From abhidon at gmail.com Thu May 11 13:39:13 2006 From: abhidon at gmail.com (don) Date: 11 May 2006 10:39:13 -0700 Subject: Reg Ex help Message-ID: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> I have a string from a clearcase cleartool ls command. /main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4 I want to write a regex that gives me the branch the file was checkedout on ,in this case - 'dbg_for_python' Also if there is a better way than using regex, please let me know. Thanks in advance, Don From onurb at xiludom.gro Thu May 4 04:26:02 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 10:26:02 +0200 Subject: This coding style bad practise? In-Reply-To: References: <44591463$0$31639$e4fe514c@news.xs4all.nl> <44591be3$0$2626$636a55ce@news.free.fr> Message-ID: <4459baf6$0$14029$626a54ce@news.free.fr> Carl Friedrich Bolz wrote: > Bruno Desthuilliers wrote: > >> Martin P. Hellwig a ?crit : >> >>> I created a class which creates a relative unique id string, now my >>> program just works fine and as expected but somehow I get the feeling >>> that I misused the __repr__ since I guess people expect to 'execute' >>> a function in an instance instead of using it's representation string >>> of the instance itself, could you elaborate whether you find this bad >>> practice and if yes what would have been a better way to do it? >> >> >> Why not just use the call operator instead ? ie: >> >> >>> id = IDGenerator(...) >> >>> id() >> 01_20060424_151903_1 >> >>> id() >> 01_20060424_151905_2 > > > because that shadows a builtin? oops :( > sorry, could not resist :-) idgen = IDGenerator(...) idgen() -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From timothy.grant at gmail.com Wed May 31 12:41:59 2006 From: timothy.grant at gmail.com (Timothy Grant) Date: Wed, 31 May 2006 09:41:59 -0700 Subject: Best Python Editor In-Reply-To: References: Message-ID: On 5/31/06, Manoj Kumar P wrote: > > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- > > > "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" > > SASKEN BUSINESS DISCLAIMER > This message may contain confidential, proprietary or legally Privileged information. In case you are not the original intended Recipient of the message, you must not, directly or indirectly, use, Disclose, distribute, print, or copy any part of this message and you are requested to delete it and inform the sender. Any views expressed in this message are those of the individual sender unless otherwise stated. Nothing contained in this message shall be construed as an offer or acceptance of any offer by Sasken Communication Technologies Limited ("Sasken") unless sent with that express intent and with due authority of Sasken. Sasken has taken enough precautions to prevent the spread of viruses. However the company accepts no liability for any damage caused by any virus transmitted by this email > -- > http://mail.python.org/mailman/listinfo/python-list > If you're on OSX you might take a look at both TextMate or TextWrangler or BBEdit. Best advice I can give is find one that works for you. -- Stand Fast, tjg. From sjmachin at lexicon.net Thu May 18 13:50:19 2006 From: sjmachin at lexicon.net (John Machin) Date: 18 May 2006 10:50:19 -0700 Subject: Which is More Efficient? In-Reply-To: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> Message-ID: <1147974619.413812.112780@i39g2000cwa.googlegroups.com> 1. Think about it. The first case will make a new list and copy "size" *objects. When the assignment happens, the old list has its reference count decremented. Not very memory-friendly. The second case merely truncates the existing list in situ. Bit hard to imagine how the first case could ever be faster than the second case. You might like to read the source code. The file that you are looking for is listobject.c. 2. Measure it. 3. Unless you are deliberately parodying b1ff at aol.com, don't use "L".lower() as a variable name. 4. Try reading this list / newsgroup more often -- (a) this topic (or a closely related one) was covered within the last week or so (b) you might notice abuse like (3) above being hurled at others and avoid copping your share. HTH, John From nobody at 127.0.0.1 Thu May 18 21:15:58 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 19 May 2006 01:15:58 GMT Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> Message-ID: Terry Hancock wrote: > But the real point is that no one here can make > any reasonably objective assessment of whether your "data" is > meaningful unless you post examples. That's what creates the > hostility, I think. Fair enough. But see my other posts on why I'm not interested in objective assessments of my code. For inquiries into real-world code, it's enough to believe that I'm not lying, e.g. that I have the programs and ran the tests described. The actual file contents are almost irrelevant. Nothing one can say about my code tells us anything about typical code in the wild. Producing more data points _will_ tell us that. If my data are an outlier, they may be worthless anyway. That's what I'm interested in. Others are interested in analyzing my code. Which is fine, it's just not what I'm after. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From antroy at gmail.com Fri May 26 07:38:58 2006 From: antroy at gmail.com (Ant) Date: 26 May 2006 04:38:58 -0700 Subject: Parsing python dictionary in Java using JPython In-Reply-To: <1148633923.428032.294760@y43g2000cwc.googlegroups.com> References: <1148633923.428032.294760@y43g2000cwc.googlegroups.com> Message-ID: <1148643538.507376.3240@j73g2000cwa.googlegroups.com> This will work fine in simple cases and if the dictionaries are passed around in repr() form. If they are being passed pickled in some way, or the values in the dictionary are anything other than strings, lists, dictionaries or combinations of these then you will need something like Jython. From __peter__ at web.de Mon May 8 10:44:52 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 May 2006 16:44:52 +0200 Subject: which is better, string concatentation or substitution? References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <1147065351.819566.140900@j73g2000cwa.googlegroups.com> <445eeab3$0$3681$4d3efbfe@news.sover.net> <1bI7g.2054$No6.45780@news.tufts.edu> Message-ID: John Salerno wrote: > Duncan Booth wrote: > >> If you build a >> list of lines to join then you don't have to repeat '\n' on the end of >> each component line. > > How would that work? Wouldn't the last line in the list still need the > newlines? >>> chunks = ["alpha", "beta", "gamma"] >>> "\n".join(chunks) 'alpha\nbeta\ngamma' You mean a '\n' after 'gamma'? >>> chunks.append("") >>> "\n".join(chunks) 'alpha\nbeta\ngamma\n' Peter From grante at visi.com Tue May 30 14:09:49 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 30 May 2006 18:09:49 -0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> Message-ID: <127p2jdgjcucc50@corp.supernews.com> On 2006-05-30, Cameron Laird wrote: >>If you feel like building a kernel, adding a few printk() calls >>to either the low-level serial driver or the tty >>line-discipline layer might do what you want. > . > . > . > !? I hadn't realized there's no such monitor ... What do you > think of ? It's yet another a terminal program (written in TCL). _If_ the pty device didn't force parity=None and bits=8, and _if_ it implemented the modem control/status ioctl() calls, and _if_ it went through the line discipline layer like a real serial port does, then something like slsnif would be workable for "real" serial port applications. In a more general sense, it would mean you could actually simulate a serial port with user-space code. That allows you to do cool stuff like create virtual serial ports in user-space that are connected via Ethernet to physical (or virtual) serial ports on other hosts. [OK, I admit there are only a few of us who think that's a cool thing to do.] Currently, if you want to create a virtual serial port under Linux you have to write a kernel-mode device driver. The only practical way to do that is to write a virtual "low level" serial driver that uses the line-discipline layer in the normal manner. And that's a real bitch to maintain because the API between the line-discipline layer and the driver you've just written is constantly changing (it seems to get major overhauls even between minor versions of a "stable" kernel). Someday I'll write a pty driver that actually allows simulation of a serial port... -- Grant Edwards grante Yow! .. My pants just went at on a wild rampage through a visi.com Long Island Bowling Alley!! From larry.bates at websafe.com Mon May 22 09:47:04 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 22 May 2006 08:47:04 -0500 Subject: newbie: windows xp scripting In-Reply-To: <1148242942.228863.97090@j73g2000cwa.googlegroups.com> References: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> <1148239856.998371.160700@u72g2000cwu.googlegroups.com> <1148242942.228863.97090@j73g2000cwa.googlegroups.com> Message-ID: oscartheduck wrote: > For completeness' sake, this is the new script I came up with: > > import os > > dirfrom = 'C:\\test' > dirto = 'C:\\test1\\' > makedir = 'mkdir "%s"' % dirto > copy_command = 'copy "%s" "%s"' % (dirfrom, dirto) > > if os.system(copy_command) == 0: > print "yay" > else: > if os.system(makedir) == 0: > if os.system(copy_command) == 0: > print 'yay!' > else: > print 'WTF mate?' > > > Is there a more efficient way of doing this? > Suggested changes: import os import glob import shutil dirfrom = 'C:\\test' dirto = 'C:\\test1' if not os.path.exists(dirto): os.makedirs(dirto) for src in glob.glob(os.path.join(dirfrom, "*.*")): dst=os.path.join(dirto, os.path.basename(src)) #print "Copying %s->%s" % (src, dst) shutil.copyfile(src, dst) -Larry Bates From n.estner at gmx.de Tue May 30 18:13:53 2006 From: n.estner at gmx.de (nikie) Date: 30 May 2006 15:13:53 -0700 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> Message-ID: <1149023817.833829.143790@u72g2000cwu.googlegroups.com> xkenneth wrote: > Hi, > > I'm writing a couple python applications that use the serial port > (RS-232) quite extensively. Is there any way I can monitor all activity > on the serial port and have it printed as the transactions occur? I'm > trying to reverse engineer a microcontroller serial routine and I'd > like to see any response the chip sends back. I've done similar things in the past, and the best tools I found at that time were: - Serial Port sniffer from www.hhdsoftware.com Similar to portmon, but (in my experience) more stable. Windows only, though. - VMWare You can run your serial port app in a VMWare and connect the virtual serial port to a file or named pipe on the host system. But this won't help you if the app uses serial commands not available for files/pipes. - Hardware cable If you know how to use a soldering iron, this might be the best way: a serial cable has an RX and a TX wire, connect each of them to the RX wires of two separate serial cables, that way you can "wiretap" the whole communication to two different serial ports (e.g. on your laptop) in a running system. Dead useful for debugging! From donald.welch at hp.com Wed May 31 13:17:28 2006 From: donald.welch at hp.com (dwelch91) Date: Wed, 31 May 2006 10:17:28 -0700 Subject: Best Python Editor In-Reply-To: References: Message-ID: <447dcf5e$1@usenet01.boi.hp.com> Maric Michaud wrote: > Le Mercredi 31 Mai 2006 12:03, Manoj Kumar P a ?crit : >> Hi, >> >> Can anyone tell me a good python editor/IDE? >> It would be great if you can provide the download link also. > > I didn't see on this list much PyQT users, is there a consensus about it ? > > I vote for linux+kdevelop for a good IDE (didn't try Pydev). > Eric3 From ms4720 at sdf.lonestar.org Thu May 25 00:11:09 2006 From: ms4720 at sdf.lonestar.org (marc spitzer) Date: Thu, 25 May 2006 04:11:09 +0000 (UTC) Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <1hfv0or.1krs4uf1704ou8N%wrf3@stablecross.com> Message-ID: On 2006-05-25, John Bokma wrote: > wrf3 at stablecross.com (Bob Felts) wrote: > >> Count me among the clueless, then. I just wrote to DreamHost and asked >> that they reverse their decision to terminate his account. > > I am sure that DreamHost has quite a nice /dev/null for clueless idiots > like you and your sock puppets :-D. > point of order, rudness is always off topic. Since you want to have such high standards for others you might want to start applying them to your self as well. marc -- ms4720 at sdf.lonestar.org SDF Public Access UNIX System - http://sdf.lonestar.org From ask at me Wed May 24 22:42:37 2006 From: ask at me (AndyL) Date: Wed, 24 May 2006 22:42:37 -0400 Subject: how to "normalize" indentation sources In-Reply-To: <447525b7$1@news.eftel.com> References: <447525b7$1@news.eftel.com> Message-ID: John Machin wrote: > On 25/05/2006 12:00 PM, AndyL wrote: > >> Hi, >> >> I have a lot of sources with mixed indentation typically 2 or 4 or 8 >> spaces. Is there any way to automatically convert them in let's say 4 >> spaces? >> > > Yup. Right under your nose: > > C:\junk>\python24\tools\scripts\reindent.py --help > reindent [-d][-r][-v] [ path ... ] > > -d (--dryrun) Dry run. Analyze, but don't make any changes to, files. > -r (--recurse) Recurse. Search for all .py files in subdirectories too. > -v (--verbose) Verbose. Print informative msgs; else no output. > -h (--help) Help. Print this usage information and exit. > > Change Python (.py) files to use 4-space indents and no hard tab > characters. > Also trim excess spaces and tabs from ends of lines, and remove empty lines > at the end of files. Also ensure the last line ends with a newline. > [snip] > > thx a lot, A. From alf at merlin.fayauffre.org Mon May 22 07:19:33 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Mon, 22 May 2006 11:19:33 +0000 (UTC) Subject: string.count issue (i'm stupid?) References: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> Message-ID: Le 22-05-2006, Matteo nous disait: > Hi all, > > i've noticed a strange beaviour of string.count: > > in my mind this code must work in this way: > > str = "a_a_a_a_" > howmuch = str.count("_a_") > print howmuch -> 3 > > but the count return only 2 > > Ok this can be fine, but why? The doc string tell that count will > return the number of substring in the master string, if we spoke about > substring i count 3 substring... > > Can someone explain me this? And in which way i can count all the > occurrence of a substring in a master string? (yes all occurrence > reusing already counter character if needed) Use the optional start argument of find or index in a loop, such as: >>> def count_all(string, substring): ... index = 0 ... count = 0 ... while True: ... index = string.find(substring, index) ... if index < 0: ... return count ... else: ... count += 1 ... index += 1 ... >>> count_all("a_a_a_a_", '_a_') 3 -- Alexandre Fayolle 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 beliavsky at aol.com Mon May 8 11:16:48 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 May 2006 08:16:48 -0700 Subject: connect file object to standard output? Message-ID: <1147101408.320069.12780@g10g2000cwb.googlegroups.com> I want to write a function that writes to an output file if specified and otherwise to standard output. How can I connect a file object to standard output in the code below? I could use an if statement to choose between print and print>>fp throughout the function, but this seems awkward. I think there is a way to connect standard output to a file, but I'd prefer not to do that, since I want to use plain print statements to warn about errors in the function and have their output appear on the screen. Thanks. def write_data(data,out_file=""): if (out_file != ""): fp = open(out_file,"w") else fp = # how to connect standard output to fp? print>>fp,data # more print>>fp statements follow From conanelbarbaro at gmail.com Sun May 28 07:28:39 2006 From: conanelbarbaro at gmail.com (conan) Date: 28 May 2006 04:28:39 -0700 Subject: unexpected behaviour for python regexp: caret symbol almost useless? Message-ID: <1148815719.082410.313870@38g2000cwa.googlegroups.com> This regexp '' works well with 'grep' for matching lines of the kind on a XML .glade file However that's not true for the re module in python, since this one takes the regexp as if were specified this way: '^' For some reason regexp on python decide to match from the start of the line, no matter if you used or not the caret symbol '^'. I have a hard time to note why this regexp wasn't working: regexp = re.compile(r'') The solution was to consider spaces: regexp = re.compile(r'\s*\s*') To reproduce behaviour just take a .glade file and this python script: import re glade_file_name = 'some.glade' bad_regexp = re.compile(r'') good_regexp = re.compile(r'\s*\s*') for line in open(glade_file_name): if bad_regexp.match(line): print 'bad:', line.strip() if good_regexp.match(line): print 'good:', line.strip() The thing is i should expected to have to put caret explicitly to tell the regexp to match at the start of the line, something like: r'^' however python regexp is taking care of that for me. This is not a desired behaviour for what i know about regexp, but maybe i'm missing something. From felipe.lessa at gmail.com Sun May 21 14:46:21 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 21 May 2006 15:46:21 -0300 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <200605211711.25043.me+python@modelnine.org> References: <200605211711.25043.me+python@modelnine.org> Message-ID: <1148237181.3355.5.camel@kenshin.CASA> Em Dom, 2006-05-21 ?s 17:11 +0200, Heiko Wundram escreveu: > for node in tree if node.haschildren(): > > > as syntactic sugar for: > > for node in tree: > if not node.haschildren(): > continue > Today you can archive the same effect (but not necessarily with the same performance) with: for node in (x for x in tree if x.haschildren()): But that's ugly... -- Felipe. From daniel.dittmar at sap.corp Tue May 30 05:41:24 2006 From: daniel.dittmar at sap.corp (Daniel Dittmar) Date: Tue, 30 May 2006 11:41:24 +0200 Subject: Is anybody knows about a linkable, quick MD5/SHA1 calculator library ? In-Reply-To: References: Message-ID: DurumDara wrote: > Hi ! > > I need to speedup my MD5/SHA1 calculator app that working on > filesystem's files. You could try using threads. This would allow the CPU and the disk to work in parallel. The sha/md5 modules don't seem to release the global interpreter lock, so you won't be able to use multiple CPUs/cores yet. Daniel From paddy3118 at netscape.net Mon May 1 17:31:26 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 May 2006 14:31:26 -0700 Subject: An Atlas of Graphs with Python References: <4455e186$0$14794$4fafbaef@reader4.news.tin.it> Message-ID: <1146519086.248221.37740@i40g2000cwc.googlegroups.com> A little off topic I'm afraid Giandomenico, But I had to smile. Here is someone working in the field of linguistics, who wants a programming solution, in the language Python. (It's Larry Wall, creator of Perl that cites his linguistic foundations). -- Pad. From jjl at pobox.com Fri May 5 13:47:26 2006 From: jjl at pobox.com (John J. Lee) Date: 05 May 2006 18:47:26 +0100 Subject: unittest.main-workalike that runs doctests too? References: Message-ID: Jay Parlar writes: > On May 5, 2006, at 6:35 AM, John J. Lee wrote: [...] > > I know about nose, but it seems just a little too magical for my > > tastes, and includes stuff I don't really need. [...] > nose actually has very little magic, its operation is quite > straightforward. I've played with its codebase before, and it's quite > clean. Maybe (but note I *was* talking about what it does, not the implementation of same). > And the new 0.9 branch uses a plugin system for some of the extra > functionality, so you don't even have to install all the things it's > capable of doing. Still seems a little OTT to require another library just to find the tests. John From esj at harvee.org Mon May 8 11:40:30 2006 From: esj at harvee.org (Eric S. Johansson) Date: Mon, 08 May 2006 11:40:30 -0400 Subject: converting to scgi Message-ID: I'm looking for a scgi modules that make it easy to convert a CGI using the standard Python CGI module. I'm hoping for something that will run my program either as scgi or cgi. I did find something called paste which purports to be some sort of CGI Bridge framework but from the documentation, it appears that the flexibility has eliminated the simplicity. From gmc at serveisw3.net Sun May 21 15:22:32 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Sun, 21 May 2006 21:22:32 +0200 Subject: Python update trouble (2.3 to 2.4): x< References: <1148197232.312628.255650@i39g2000cwa.googlegroups.com> <1148209690.978989.65430@j55g2000cwa.googlegroups.com> Message-ID: <4470BDF8.2050103@serveisw3.net> Thank you for all the suggestions! :-) The C routine is almost -changing data type long for word- a copy of the function given by a hardware manufacturer, the same code used in their firmware to calc the checksum of every piece of data sent or received, and that data is somewhat special: it does not contain only plain ascii character data (only 0x01 - 0x09 as delimiters) and every data set ends with a 0x00 null byte so its fine to calculating checksum until "\x00" is reached. And I must get the same crc calculations. That C routine (and a very similar PHP one too) are tested for months and work smoothly. And of course I should use integer not long!!... we aren't anymore in the 8 bit computer era... ;-) original code from hardware manufacturer use words by the way. And now really don't know why I used long. I thought I did that way 'cause see pyrex C generated glue code always using PyInt_FromLong so thought would use the same type. I changed the C function to use integer, and it is performing a little bit slowly than using longs (best with long: 0.614us, best with int: 0.629us), that is maybe as I said due pyrex glueing always the return values with PyObject* PyInt_FromLong for all kind of short int to long data types? Anyway both results are fine, and the timming gap is insignificant (int: 1580403 loops -> 0.973 secs, long: 1601902 loops -> 1.01 secs) as i usually never have to call more than 100,000 times when loading a full file data backup. As a note for the checksum algorithm used here, I thought the hardware manufacturer implemented this some years ago for serial data transmission, but later attached some ethernet ports and they wanted to have the protocol compatible. Anyway as I see in the link you reply, it seems to be based in CCITT CRC-16, but they adapted to their own requirements -performace issues for the hardware unit?- (never 0x00, etc.) Regards, Gonzalo. John Machin escribi?: >Gonzalo wrote: >""" >I missed the point to add the *and* to workaround the long result >issue! >I think I understand it now. > >I am timing the code once translated, so here are the results for the >crc calculation function. >""" > >Yes, and both of us were missing the point that the "16" means 16 bits >wide!! It is carrying an extra 16 redundant bits that don't contribute >to the checking ability. > >If your software *needs* to generate/check the exact same 32-bit-wide >CRC as calculated by that C routine, then what I gave you should be OK. > Do you have any more test values? In particular test an empty string >and say "\x00" * 8 -- sometimes a CRC specification will do something >special with short strings e.g. pad them put with null bytes. > >That C routine is actually, on further reading, mind-boggling!! It >stops on a null byte, rather than working on a given length. A CRC is >normally expected to work on any data (including binary data) whether >it contains \x00 or not. What are you using it for?? > >If you don't have to interface with other software, AND a 16-bit check >is adequate, then at the end of this message is a 16-bit version which >will use only ints and therefore may run faster. > >However you may wish to use a CRC32 which is supplied with Python (in >the binascii module). > >A further note: what we have so far seems not to be the CCITT aka X.25 >standard CRC-16 , but a reflection. See >http://www.joegeluso.com/software/articles/ccitt.htm >and also if you have the time and the determination, the article by >Ross Williams that it refers to. > >Cheers, >John > >=== 16-bit version === >gCRC16Table = [] > >def InitCRC16(): > global gCRC16Table > for i in xrange(0,256): > crc = i << 8 > for j in xrange(0,8): > if (crc & 0x8000) != 0: > tmp = 0x1021 > else: > tmp = 0 > crc = (crc << 1) ^ tmp > crc &= 0xFFFF > gCRC16Table.append(crc) > >def CalcCRC16(astr): > crc = 0xFFFF > for c in astr: > crc = gCRC16Table[((crc >> 8) & 255)] ^ ((crc & 0xFF) << 8) ^ >ord(c) > assert 0 <= crc <= 0xffff # remove when doing timings :-) > return crc > >test = "123456asdfg12345123" >InitCRC16() >result = CalcCRC16(test) >print result, hex(result) >====== > > > From bignose+hates-spam at benfinney.id.au Fri May 5 20:57:54 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 06 May 2006 10:57:54 +1000 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Message-ID: <87lktgrmul.fsf@benfinney.id.au> "Xah Lee" writes: > Python, Lambda, and Guido van Rossum Which one is the "critic"? Or is your subject field an indication that you continue not to learn from responses to your previous posts? > is first of all, the title ?Language Design Is Not Just Solving > Puzzles?. In the outset, and in between the lines, we are told that > ?I'm the supreme intellect, and I created Python?. Would that all of the ramblings in your posts was in between the lines. -- \ "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 nobody at 127.0.0.1 Wed May 3 15:42:35 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 19:42:35 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> <4457fc52$0$31159$636a55ce@news.free.fr> <4458ef17$0$24993$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > Technically, they are still function objects. They are later wrapped > into method descriptor objects (at lookup time IIRC, but ask a guru or > read the doc to know for sure). And don't forget the case of nested > functions... I don't see how nested functions change anything. If they're nested in a method, they can access self, but the name mapping is done at runtime. Unless you mean a nested fucntion which is dynamically added as a method, but that's the same case as the next one. >> If you're declaring >> methods outside the class and adding them dynamically, I think you would >> need to declare 'self' explicitly. > > Of course. Virtually *any* function can be set as a method[1] outside > the class statement scope, either directly on the class object or - with > manual wrapping - on an individual instance. And it's important to keep > this feature. I wouldn't dream otherwise. >> Well I'm assuming the rules for when to put 'self' in the parameter list >> are simple enough to be automated. > > They are still complex enough to require a real parser. And anyway, > since this is a syntax change, this should be handled by the parser IMHO. I agree, but it's good to keep options in mind. > Honestly, I don't think it has much chance. I barely even notice typing > 'self' or 'cls', and I guess it's the same for most Python programmers > - those who can't stand it probably use another language... And FWIW, I > still prefer to keep consistency in functions definitions. I have no doubt that's true for a lot of people. Hell I probably prefer the current approach because 1) it's not a big deal in practice, and 2) I can use the shorter 'me' or 's' in place of self in my own code, which I couldn't do under the change (well, I could add 'me = self' as the first statement of any method, but that's clumsy). My objections stem more from an elegance standpoint. Of course elegance is in the eye of the beholder. From maric at aristote.info Wed May 31 05:42:08 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 31 May 2006 11:42:08 +0200 Subject: An algorithm problem In-Reply-To: <447D3E9F.4010008@gmail.com> References: <447D3E9F.4010008@gmail.com> Message-ID: <200605311142.08932.maric@aristote.info> Le Mercredi 31 Mai 2006 08:58, Bo Yang a ?crit?: > RuntimeError: maximum recursion depth exceeded It's tied to the recursive call to the ring function, python raises a limit to recursive calls to avoid infinite recursion. You can just adjust the limit using these two lines when you call the function ring : import sys sys.setrecursionlimit(10000) # or whatever, the default is 1000 and set back the limit to its default after the call. Note that function calls are memory expensive and the recursive implementation of an algorithm must be considered (in particular in python) as an "elegant but not optimized" one. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From nicogrubert at gmail.com Wed May 24 10:29:27 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Wed, 24 May 2006 16:29:27 +0200 Subject: How to find out a date/time difference In-Reply-To: References: Message-ID: <44746DC7.9080509@gmail.com> > I use datetime class in my program and now > I have two fields that have the datetime format like this > datetime.datetime(2006, 5, 24, 16, 1, 26) > How can I find out the date/time difference ( in days) of such two > fields? Hi Lad, you could do this: >>> a = datetime.datetime(2006, 5, 24, 16, 1, 26) >>> b = datetime.datetime(2006, 5, 20, 12, 1, 26) >>> a-b datetime.timedelta(4) # 4 days >>> b = datetime.datetime(2006, 5, 20, 12, 1, 26) >>> x = a-b >>> x datetime.timedelta(4, 14400) >>> str(x) '4 days, 4:00:00' Regards, Nico From kentilton at gmail.com Mon May 8 14:29:38 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 08 May 2006 14:29:38 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1heyrbd.4ug6sg7cgci5N%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <87mzducj27.fsf@rpi.edu> <1heyrbd.4ug6sg7cgci5N%aleaxit@yahoo.com> Message-ID: [Sorry, i was just reading comp.lang.lisp, missed the following till someone mentioned it in email. k] Alex Martelli wrote: > Carl Friedrich Bolz wrote: > ... > >>>an extension that allows the programmer to specify how the value of >>>some slot (Lisp lingo for "member variable") can be computed. It >>>frees the programmer from having to recompute slot values since Cells > > ... > >>I have not looked at Cells at all, but what you are saying here sounds >>amazingly like Python's properties to me. You specify a function that >>calculates the value of an attribute (Python lingo for something like a > > > You're right that the above-quoted snipped does sound exactly like > Python's properties, but I suspect that's partly because it's a very > concise summary. A property, as such, recomputes the value each and > every time, whether the computation is necessary or not; in other words, > it performs no automatic caching/memoizing. Right, and the first thing we did was simply that, no memoizing. The second thing we did was memoize without tracking dependencies, updating everything on each pass thru the eventloop. We knew both would not (uh-oh) scale, but we wanted to see if the approach solved the computational problem that started the whole research programme. Soon enough we were tracking dependencies. > > A more interesting project might therefore be a custom descriptor, one > that's property-like but also deals with "caching wherever that's > possible". This adds interesting layers of complexity, some of them not > too hard (auto-detecting dependencies by introspection), others really > challenging (reliably determining what attributes have changed since > last recomputation of a property). Intuition tells me that the latter > problem is equivalent to the Halting Problem -- if somewhere I "see" a > call to self.foo.zap(), even if I can reliably determine the leafmost > type of self.foo, I'm still left with the issue of analyzing the code > for method zap to find out if it changes self.foo on this occasion, or > not -- there being no constraint on that code, this may be too hard. "no constraint on the code" is a sufficient objection but also: if the rule for the code is (in neutral pseudo-code) if a is true then return b else return c ..you only want to depend on one of b or c at a time. (also, not do the internal dependency tracking on, say, b if it happens to hold an immutable value (part of the Cells API). Nice performance win, it turns out. I just keep what I call a "datapulse ID", sequentially growing from zero, in a global variable. Each ruled Cell keeps track of its memoized value, datapulse stamp, and whether it in fact changed value in reaching its current datapulse stamp. (I can reach the current datapulse stamp by determining no dependency (direct or indirect recursively down the dependency graph) is both more current than me /and/ in fact changed in value getting there.[1] If not, I take on the current datapulse but never run my rule. Or, if yes, I run my rule but might compute the same value as last time. Either way, I can flag myself as current but not-actually-changed.) So we have push and pull. The whole thing gets kicked off by a setting operation on some slot, who notifies dependents that they should recompute. This is a cascade of further notifications if anyone notified recomputes and in fact computes a different value. The pull comes in while rules are running to make sure no obsolete value gets used. So the dependency graph gets updated JIT during rule evaluations, possively recursively so. > > The practical problem of detecting alterations may be softened by > realizing that some false positives are probably OK -- if I know that > self.foo.zap() *MAY* alter self.foo, I might make my life simpler by > assuming that it *HAS* altered it. This will cause some recomputations > of property-like descriptors' values that might theoretically have been > avoided, "ah well", not a killer issue. Perhaps a more constructive > approach would be: start by assuming the pseudoproperty always > recomputes, like a real property would; then move toward avoiding SOME > needless recomputations when you can PROVE they're needless. You'll > never avoid ALL needless recomputations, but if you avoid enough of them > to pay for the needed introspection and analysis, it may still be a win. > As to whether it's enough of a real-world win to warrant the project, I > pass -- in a research setting it would surely be a worthwhile study, in > a production setting there are other optimizations that look like > lower-hanging fruits to me. But, I'm sure the Cells people will be back > with further illustrations of the power of their approach, beyond mere > "properties with _some_ automatic-caching abilities". Who knows, maybe something like that lies in the future of cells. It would not be because of the need for update being undecidable, it would be because the decision somehow would be too expensive compared to "Just Run the Rule!"[2] It seems every new application brings up interesting new requirements where Cells can usefully be extended with new capabilities. But over time the code has gotten simpler and simpler, so I think we are headed in the right direction. kenny [1] Aha! I see a flaw. Arises if two datapulses pass before I (a cell ) get read and must determine if my cache is obsolete, and some dependency changed in the first datapulse but not the second. I have to enhance regression test suite and cure. One possible cure is akin to your thinking: if I missed a generation, I have to assume it changed in the missed generation. The alternatives are keeping a history of my datapulses going back no further than the last true change, or having a Cell keep a separate record of the last value used from each dependency. The second could get expensive if I consult a lot of other cells, while the first ... ah wait, I do not need a history, I just need one new attribute: datapulse-of-latest-actual change. Sweet. [2] I am making a mental note to look into that optimization. From digitalorganics at gmail.com Tue May 23 14:27:56 2006 From: digitalorganics at gmail.com (Cloudthunder) Date: Tue, 23 May 2006 14:27:56 -0400 Subject: Accessing object parent properties In-Reply-To: References: Message-ID: In the example: class Boo: def __init__(self, parent): self.parent = parent print self.parent.testme def run(): print "Yahooooo!" class Foo: testme = "I love you!" def __init__(self): test = Boo(self) A = Foo() How can I set up method delegation so that I can do the following: A.run() and have this call refer to the run() method within the boo instance? Also, what if I have tons of functions like run() within the boo instance and I want all them to be directly accessible as if they were part of their parent (the Foo instance)? Thanks! On 5/23/06, Max Erickson wrote: > > One way: > > class Boo: > def __init__(self, parent): > self.parent=parent > > > class Foo: > X=1 > def __init__(self): > self.test=boo(self) > > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From godoy at ieee.org Wed May 24 02:10:49 2006 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 24 May 2006 03:10:49 -0300 Subject: NEWB: how to convert a string to dict (dictionary) References: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> Message-ID: <1753262.ZebZmd9R9q@jupiter.g2ctech> manstey wrote: > Hi, > > How do I convert a string like: > a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}" > > into a dictionary: > b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'} > > Thanks, Matthew > > PS why in Python is it so often easy to convert one way but not the > other? I don't belive it is Python's fault. In fact, you're going from a data structure that contains enough information to be converted to a string in one way -- dict to string -- while you're going from another data structure that has no information at all about its contents on the other way -- string to dict/list/whatever. Anyway: In [1]:a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}" In [2]:type(a) Out[2]: In [3]:b = eval(a) In [4]:type(b) Out[4]: In [5]:b Out[5]:{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'} Be seeing you, -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From onurb at xiludom.gro Thu May 4 09:18:50 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 15:18:50 +0200 Subject: Python function returns: In-Reply-To: References: Message-ID: <4459ff96$0$21105$626a54ce@news.free.fr> Michael Yanowitz wrote: > I am still new to Python but have used it for the last 2+ months. > One thing I'm still not used to is that functions parameters can't > change as expected. > > For example in C, I can have > status = get_network_info (strIpAddress, &strHostname, &nPortNumber) You have to understand that Python and C are totally different beasts. A C variable is mostly symbolic name for a memory address, tagged with type infos. Assigning to a variable means storing a value at this address. Reading a variable means retrieving whatever value is stored at this memory address. Python does not in fact have a concept of "variables". It has names and objects. A binding is the association (in a hash table) of a symbolic name (which is nothing more than a name) and a reference (read: something like a smart pointer) to an object (which is itself a complex data structure). So-called "assignement" (correct term is "binding") 'binds' together a name and a reference to an object. Except for some special cases (mainly objects - which are they're own namespaces - and when using the 'global' statement), this creates an entry in the current namespace. Also, rebinding a name has no effect on other names bound to the same object. Function's params are bindings in the function's local namespace. This means that the params *names* are local to the function. So rebinding a param in a function won't have no effect on bindings in the caller's namespace. *But* - since many names can refer to the same object - *modifying* the object referenced by a name will, well, modify this object, so this modification will be visible everywhere. ie (dummy example): def appendToList(alist, what): alist.append(what) mylist = [] appendToList(mylist, 42) print mylist What doesn't work as you'd expect is: def failsToHaveSideEffects(alist, anything): print "before rebinding : alist = ", alist, " - anything = ", anything alist = anything print "after rebinding: alist = ", alist mylist = [] print "before function call, mylist = ", mylist failsToHaveSideEffects(mylist, 42) print "after function call, mylist = ", mylist So as you can see, it's quite possible for a function to *modify* it's params - it's just rebindings of params that won't have side effects outside the function's namespace. Now, there is the case of immutable types (int, strings, tuples, ....). As implied, one cannot modify objects of these types - just create them. So in order to have a function that "change the value" of an immutable object, you have to wrap it into a mutable object, ie: def getAnswer(alist): alist[0] = "42" answer = ["answer is ?"] getAnswer(answer) print "answer is : ", answer[0] (snip) > In Python, there does not seem to be an easy way to have functions return > multiple values except it can return a list such as: > strHostname, nPortNumber, status = get_network_info (strIpAddress, > strHostname, > nPortNumber) > Am I missing something obvious? Is there a better, or more standard way > to return values from functions? This *is* the 'standard' (ie: idiomatic) way to return multiple values from a function. The C idiom of passing pointers to variables that are to be modified comes from C's limitations, namely no exception handling and only one return value[1], which leads to using the return value as a status report and relying on side effect for useful values. [1] To be pedantic, Python only allows one return value too - but this value can be a tuple or list, and then one can take advantage of tuple/list expansions that allows multiple assignment... HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From steven.bethard at gmail.com Mon May 22 15:37:29 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 May 2006 13:37:29 -0600 Subject: Using metaclasses to inherit class variables In-Reply-To: <1148321972.467689.148900@j73g2000cwa.googlegroups.com> References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> <1148315581.385405.204750@i40g2000cwc.googlegroups.com> <1148321972.467689.148900@j73g2000cwa.googlegroups.com> Message-ID: telesphore4 at gmail.com wrote: > Oops! This isn't working. As the sequence I'm trying for is.... >>>> def set_classvars(**kwargs): > ... def __metaclass__(name, bases, classdict): > ... for name, value in kwargs.iteritems(): > ... if name not in classdict: > ... classdict[name] = value > ... return type(name, bases, classdict) > ... return __metaclass__ > ... >>>> class C(object): > ... __metaclass__ = set_classvars(name='foo', desc='bar', list=[]) > ... name = 'not foo' > ... >>>> C.name, C.desc, C.list > ('not foo', 'bar', []) >>>> class D(C): > ... pass #<<<<<< Use Super's metaclass > ... >>>> D.name, D.desc, D.list, D.list is C.list > ('not foo', 'bar', [], True) What should the "right" answer be here? Maybe ('foo', 'bar', [], False) or ('not foo', 'bar', [], False) or something else? STeVe From ilias at lazaridis.com Fri May 5 09:36:59 2006 From: ilias at lazaridis.com (lazaridis_com) Date: 5 May 2006 06:36:59 -0700 Subject: PUDGE - Colored Code Blocks / Mailing List Access Message-ID: <1146836219.788379.151450@i40g2000cwc.googlegroups.com> Colored Code Blocks Pudge generated documentation can contain colored code blocks, using the rst directive "..code-block:: Python" (an other languages supported by SilverCity). http://pudge.lesscode.org/trac/ticket/21 http://pudge.lesscode.org/trac/changeset/126 - Mailing List The Pudge Mailing List seems to be down since the change of the server: http://news.gmane.org/gmane.comp.python.pudge.general Possibly someone can notify some of the project admins. From aaronwmail-usenet at yahoo.com Wed May 10 14:16:33 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 10 May 2006 11:16:33 -0700 Subject: Python's DSLs (was: A critic of Guido's blog on Python's lambda) In-Reply-To: <3mh4j3-9pm.ln1@lairds.us> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <3mh4j3-9pm.ln1@lairds.us> Message-ID: <1147284993.932694.32770@j33g2000cwa.googlegroups.com> Cameron Laird wrote: > In article <1hewvsx.11x9f301gbjrhqN%aleaxit at yahoo.com>, > Alex Martelli wrote: ... . > >Of course, the choice of Python does mean that, when we really truly > >need a "domain specific little language", we have to implement it as a > >language in its own right, rather than piggybacking it on top of a > >general-purpose language as Lisp would no doubt afford; see > > for such a DSLL developed > >at Google. However, I think this tradeoff is worthwhile, and, in > >particular, does not impede scaling.... > > ....I'm confused, Alex: I sure > think *I* have been writing DSLs as specializations of Python, > and NOT as "a language in its own right".... I think Alex is suggesting that if they used, for example, a version of scheme with a good optimizing compiler they could implement sawzall like convenience with almost the same performance, including startup, etc. whereas even a highly optimized python based approach would at least have a comparatively large startup penalty. For an environment like Google where they scrape thru their logs of various sorts doing lots of trivial scans you can probably save a lot of money and time on lots of machines by optimizing such scrapes (but keep your bactine handy). And as the sawzall paper pointed out, even static type checks can prevent a lot of wasted machine bandwidth by avoiding dumb errors. But the real question for someone like Rob Pike is why use scheme when you can invent another little language instead, I suspect :). -- Aaron Watters === Stop procrastinating soon. From jimlewis at miclog.com Sun May 21 18:41:15 2006 From: jimlewis at miclog.com (Jim Lewis) Date: 21 May 2006 15:41:15 -0700 Subject: Pyrex installation on windows XP: step-by-step guide References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> Message-ID: <1148251275.211468.221460@g10g2000cwb.googlegroups.com> > and change "-lmsvcrt" to "-lmsvcr71". But then I get this error: Python was built with version 7.1 of Visual Studio, and extensions need to be built with the same version of the compiler, but it isn't installed. I want to use mingw. From bdesth.quelquechose at free.quelquepart.fr Thu May 11 20:38:53 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 May 2006 02:38:53 +0200 Subject: calling perl modules from python In-Reply-To: <1690502.fNiZoSDNhf@teancum> References: <1690502.fNiZoSDNhf@teancum> Message-ID: <4463aa2b$0$287$626a54ce@news.free.fr> David Bear a ?crit : > I have a hash function written by another organization that I need to use. > It is implemented in perl. I've been attempting to decode what they are > doing in their hash function and it is taking way too long. No comment... > I've > identified two functions in a perl module that I would like to 'call' from > a python program. I found the following: > http://www.annocpan.org/~GAAS/pyperl-1.0/perlmodule.pod > > and wondered if anyone had any comments. This thing implements a perl > interpreter inside python. That seems like overkill to me. > I wonder what wisdom this group can offer. What about writeing a small perl script that let you call the needed functions from the commandline, then calling this script from Python ? From nobody at nowhere.non Thu May 4 12:57:10 2006 From: nobody at nowhere.non (nick) Date: Thu, 04 May 2006 16:57:10 GMT Subject: problem with reload(sys) (doing reload on the sys module) References: <1146676364.470772.232350@y43g2000cwc.googlegroups.com> Message-ID: Looks like a bug (probably in IDLE): when I start IDLE from the command line, it pops up its interaction window and here is what it says about stdout: IDLE 1.1.2 >>> import sys >>> sys.stdout Then I try the reload and I get no output in the interaction window: >>> reload(sys) >>> sys.stdout >>> After the reload, stdout has been changed to the terminal from which IDLE got started, so I see the messages there: ', mode 'w' at 0xb7b67068> As you can see, stdout has been redefined (back to the way it would be if you started Python from the command line, with no IDLE involved). -- nick (nicholas dot dokos at hp dot com) From pjm at spe.com Sun May 7 15:49:58 2006 From: pjm at spe.com (Patrick May) Date: Sun, 07 May 2006 20:49:58 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: >> >> In my opinion (and that of several others), the best way for >> >> Python to grow in this regard would be to _lose_ lambda >> >> altogether, since named functions are preferable >> > >> > Why? I find the ability to create unnamed functions on the >> > fly to be a significant benefit when coding in Common Lisp. >> >> 1. They don't add anything new to the language semantically >> i.e. you can always used a named function to accomplish the same >> task as an unnamed one. Sure, but it won't necessarily be as expressive or as convenient. >> 2. Giving a function a name acts as documentation (and a named >> function is more likely to be explicitly documented than an >> unnamed one). This argument is pragmatic rather than >> theoretical. Using lambda in an expression communicates the fact that it will be used only in the scope of that expression. Another benefit is that declaration at the point of use means that all necessary context is available without having to look elsewhere. Those are two pragmatic benefits. >> 3. It adds another construction to the language. That's a very minimal cost relative to the benefits. You haven't made your case for named functions being preferable. Regards, Patrick ------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm at spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML) From hslee911 at yahoo.com Tue May 9 15:17:34 2006 From: hslee911 at yahoo.com (James) Date: 9 May 2006 12:17:34 -0700 Subject: How to recast integer to a string Message-ID: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> How to recast an integer to a string? something like n = 5 str = str + char(n) J.L From nobody at 127.0.0.1 Thu May 11 20:39:10 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 00:39:10 GMT Subject: python equivalent of the following program References: <24-dnWcg5IQETf7ZnZ2dnUVZ_tKdnZ2d@comcast.com> Message-ID: AndyL wrote: > Edward Elliott wrote: >> And if the script runs somewhere that stderr is likely to disappear: >> >> prog1 = subprocess.Popen(['prog1'], stdout=file1, >> stderr=subprocess.STDOUT) > > Forgot to mention before that the main motivation is to have the same > code on bot Linux and M$ platforms. > > Does subprocess work well on both? yes > Also how to find out that the 'prog1' e.g. has exited and it is done? prog1.wait() or prog1.poll(). look at the subprocess docs. From johnjsal at NOSPAMgmail.com Tue May 2 14:24:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 18:24:09 GMT Subject: using ftplib In-Reply-To: <44579f60$0$2576$ed2619ec@ptn-nntp-reader02.plus.net> References: <4456743d$0$2563$ed2619ec@ptn-nntp-reader02.plus.net> <44579f60$0$2576$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Dave Hughes wrote: > As far as I recall your speculation is indeed correct: a TYPE command > is only necessary before a transfer (it's only used to transform data > passing over the secondary data connection). I'm reasonably certain you > don't need *anything* before a SITE command (like SITE CHMOD), not even > PORT or PASV (unless the specific SITE command being invoked requires a > data transfer, which CHMOD shouldn't). But as Steve suggests, the best > way to know for sure is to give it a whirl and see what happens :-) Thanks. I sometimes forget I can experiment with the interactive interpreter, but I also didn't want to screw up anything on my server space by doing something weird! :) From sjmachin at lexicon.net Tue May 16 19:10:20 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 May 2006 16:10:20 -0700 Subject: Unable to extract Python source code using Windows References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> <446a0229$1@nntp0.pdx.net> <1147803594.844448.271640@i39g2000cwa.googlegroups.com> Message-ID: <1147821020.587483.294360@i39g2000cwa.googlegroups.com> Elric02 wrote: """ I tried downloading for different archives, (different versions of Python) I can't believe they are all garbled. But they all don't work with WinZip. """ I can't believe that they're all garbled either. The likelihood of that is small. Further, the probablility that all-pervasive garbling of tgz files would go unnoticed is about three-tenths of five-eighths of an extremely small number. Reminds me of the story of the proud mother watching her son's regiment on parade: "Look, everybody, my Tommy's the only one marching in step!". Let's rewrite your last sentence as "My copy of WinZip v10 doesn't work with any of them", and go with the most plausible explanation. HTH, John From nnorwitz at gmail.com Sat May 13 15:00:29 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 13 May 2006 12:00:29 -0700 Subject: SystemError: ... cellobject.c:22: bad argument to internal ? In-Reply-To: References: Message-ID: <1147546829.738347.16630@d71g2000cwd.googlegroups.com> robert wrote: > From the trace of a 2.3.5 software i got: > > \'SystemError: > C:\\\\sf\\\\python\\\\dist23\\\\src\\\\Objects\\\\cellobject.c:22: bad > argument to internal > function\\n\'] ... > Will there be another bug-fix release of Python 2.3 ? No, is this still a problem in 2.4? 2.4.4 is planned to be released this summer. Can you post the entire code (that doesn't reference anything outside the stdlib) that causes this problem? n From peace.is.our.profession at gmx.de Mon May 22 04:01:54 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Mon, 22 May 2006 10:01:54 +0200 Subject: Software Needs Philosophers In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: after all, somebody dumped some backup of his brain to use-net: > Software Needs Philosophers > by Steve Yegge, 2006-04-15. including lots of personal details. So what I basically took from it is written in this paragraph: > I was born and raised a Roman Catholic, and I renounced it when I was > thirteen years old, after my Uncle Frank (a devout terrorist Catholic > if there ever was one) told me to stop reading the Bible, that it would > ?really screw a person up? to do that, that you needed someone to > interpret it for you. That wasn't the only reason I renounced it, but > it'll suffice for our purposes. Under 'best effort interpretation', one could see the whole thing in the light of the small thing: he's rescuing 'us' by telling us: - to think rational, - to de-construct our beliefs and - don't put that much personal sympathy into 'subculture group pseudoreligion', the latter is what he thinks 'computer language culture' really is today. I can't see what's wrong with these hypotheses (besides he got some terms wrong); he describes things we most probably are already aware of (in our own context of notions) - but wouldn't bother to fill the communication lines of the world with it (wouldn't give a damn about ...) (my ?0.05) Mirco f'up ==> c.l.p.m From bjourne at gmail.com Tue May 9 17:57:54 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Tue, 9 May 2006 23:57:54 +0200 Subject: Incrementally converting a C app to Python Message-ID: <740c3aec0605091457x69d5313bp2e1ed60672cf0391@mail.gmail.com> Hello. At work I'm the sole maintainer and developer of a medium sized ~50k line C application. The lion share of this app was written before my time so it is pretty hard to read and also contain lots of bugs. I'm contemplating converting the project to Python because I think that, in the long run, maintenance will become much easier. And also because is so much more fun than C. The app is to big to be rewritten from scratch so I'm thinking of a way to rewrite it "incrementally." Something like one module, or file, at a time. Using tools like SWIG, Pyrex or embedding Python in C it seems like this would be possible. My question is what tools should I apply and what strategy should I use? Would it be best to use a top-down approach and rewrite the main files first and work my way down wrapping the remaining C files using SWIG? Or should I convert the isolated code files to Python and then embedd it in the C code? Maybe Pyrex help me with this task? Any insight on this matter is greatly appreciated. Surely someone has done the exact same thing as me before. -- mvh Bj?rn From python.list at tim.thechases.com Thu May 4 11:09:34 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 May 2006 10:09:34 -0500 Subject: Tuple assignment and generators? Message-ID: <445A192E.8090209@tim.thechases.com> Just as a pedantic exercise to try and understand Python a bit better, I decided to try to make a generator or class that would allow me to unpack an arbitrary number of calculatible values. In this case, just zeros (though I just to prove whatever ends up working, having a counting generator would be nice). The target syntax would be something like >>> a,b,c = zeros() >>> q,r,s,t,u,v = zeros() where "zeros()" returns an appropriately sized tuple/list of zeros. I've tried a bit of googling, but all my attempts have just ended up pointing to pages that blithly describe tuple assignment, not the details of what methods are called on an object in the process. My first thought was to get it to use a generator: def zeros(): while 1: yield 0 However, I get back a "ValueError: too many values to unpack" result. As a second attempt, I tried a couple of attempts at classes (I started with the following example class, only derived from "object" rather than "list", but it didn't have any better luck): >>> class zeros(list): ... def __getitem__(self,i): ... return 0 ... >>> z = zeros() >>> a,b,c = z Traceback (most recent call last): File "", line 1, in ? ValueError: need more than 0 values to unpack It looks like I need to have a pre-defined length, but I'm having trouble figuring out what sorts of things need to be overridden. It seems like I sorta need a def __len__(self): return INFINITY so it doesn't choke on it. However, how to dupe the interpreter into really believing that the object has the desired elements is escaping me. Alternatively if there was a "doYouHaveThisManyElements" pseudo-function that was called, I could lie and always return true. Any hints on what I'm missing? Thanks, -tkc From incall at msn.com Tue May 23 13:15:16 2006 From: incall at msn.com (Pablo) Date: 23 May 2006 10:15:16 -0700 Subject: Use of lambda functions in OOP, any alternative? In-Reply-To: References: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> Message-ID: <1148404515.849457.249880@y43g2000cwc.googlegroups.com> The reason i would like a different approach to the lambda function is just a question of personal taste... i dont really like it. thanx! From gry at ll.mit.edu Tue May 2 09:50:43 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 2 May 2006 06:50:43 -0700 Subject: --version? In-Reply-To: <4bp35kF12517kU1@individual.net> References: <4bp06lF1276vvU1@individual.net> <4bp35kF12517kU1@individual.net> Message-ID: <1146577843.571921.261910@y43g2000cwc.googlegroups.com> I agree. The "--version" option has become quite a de-facto standard in the linux world. In my sys-admin role, I can blithely run initiate_global_thermonuclear_war --version to find what version we have, even if I don't know what it does... python --version would be a very helpful addition. (Keep the "-V" too, if you like it :-) -- George From onurb at xiludom.gro Thu May 18 14:03:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 20:03:11 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147972445.573698.54080@i40g2000cwc.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147947048.303912.109150@38g2000cwa.googlegroups.com> <446c5a80$0$7024$636a55ce@news.free.fr> <1147958226.200557.264850@j33g2000cwa.googlegroups.com> <446c7b51$0$7040$636a55ce@news.free.fr> <1147972445.573698.54080@i40g2000cwc.googlegroups.com> Message-ID: <446cb747$0$6811$636a55ce@news.free.fr> glomde wrote: > I'm answering two of you posts here... > > >>Sweet Lord, have mercy ! >> >> > Which should create myList = [[0..9], {0:0, ... 9:9}] >> >>myList = [ >> range(10), >> dict((i, i) for i in range(10)) >>] > > >>Let's talk about readability.... > > > My code was just to show that the proposal is not only for HTML > generation but could be used whenever you want to create COMPLEX > hierarcical datastructures. It's enough to see why no-one in it's own mind would ever want to use such a syntax. > Do I need to show you a example where you cant use the style you > showed? Please, don't. Let's protect innocent eyes. > >>Strange enough, working with trees is nothing new, and it seems that >>almost anyone managed to get by without cryptic 'operators' stuff. > > Strange enough once almost anyone managed to get by without Python... > :-) > >>>I used HTML as example since it is a good >>>example and >>>most people would understand the intention. >> >>Sorry for being dumb. > > It not your fault :-) > > >>>But could you elaborate on your comment that it is unusable. >> >>Ask all the coders that switched from Perl to Python why they did so... > > > You seem to really have a thing for Perl... Yes : readability. Being dumb, I need a readable, cryptic-operator free language. >>From what you written I assume you mean that it is no good because you > find the syntax cryptic. cryptic *and* utterly ugly FWIW. Also, you failed to address the fact that there may be much better ways to do so, even probably without syntax change. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From emami at knmi.nl Tue May 16 09:17:09 2006 From: emami at knmi.nl (Nader Emami) Date: Tue, 16 May 2006 14:17:09 +0100 Subject: which one? Message-ID: L.S., I have read your replay about web development with python. I would agree with you that web design is depends on specific requirements. I would like to develop some in which the animation is well important. It will be an animation of a radar file. I have looked for a lot of alternative but I do not which of them I can choose for my application. I will appreciate you if you would give me some advice in this case. With regards, Nader From me at modelnine.org Sun May 14 17:59:32 2006 From: me at modelnine.org (Heiko Wundram) Date: Sun, 14 May 2006 23:59:32 +0200 Subject: help using smptd In-Reply-To: References: Message-ID: <200605142359.32870.me@modelnine.org> Am Sonntag 14 Mai 2006 23:47 schrieb Dennis Lee Bieber: > On Sun, 14 May 2006 20:47:33 GMT, Edward Elliott > > declaimed the following in comp.lang.python: > > class SMTPProxy (smtpd.SMTPServer): > > Don't you need to have an __init__() that invokes SMTPServer's > __init__()? If you don't define an __init__() yourself (as it seems to be the case here), MRO (and the rules associated with class methods) will take care that the base class' __init__() gets called automatically. --- Heiko. From rNOSPAMon at flownet.com Thu May 18 17:49:25 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 May 2006 14:49:25 -0700 Subject: WTF? Printing unicode strings References: Message-ID: In article , Fredrik Lundh wrote: > Ron Garret wrote: > > >>>> u'\xbd' > > u'\xbd' > >>>> print _ > > Traceback (most recent call last): > > File "", line 1, in ? > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > > position 0: ordinal not in range(128) > > so stdout on your machine is ascii, and you don't understand why you > cannot print a non-ascii unicode character to it? wtf? > > I forgot to mention: >>> sys.getdefaultencoding() 'utf-8' >>> print u'\xbd' Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 0: ordinal not in range(128) >>> From python-url at phaseit.net Tue May 30 14:05:22 2006 From: python-url at phaseit.net (Cameron Laird) Date: Tue, 30 May 2006 18:05:22 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 30) Message-ID: QOTW: "Making a user class work anywhere you can put a mapping in Perl is deep magic, but easy in Python. Creating types that act like files and can be used wherever a file is used is SOP in Python; I'm not even sure it's possible in Perl (probably is, but it's again deep magic)." - Mike Meyer "... I don't bother with classes unless I'm going to end up with multiple instances (or I'm pushed into a corner ..." - Dan Sommers Over TWO DOZEN Python-based projects have been accepted for the 2006 Summer of Code: http://wiki.python.org/moin/SummerOfCode While waiting for more polished summaries from the Iceland Sprint, admire a few of the incidental photographs: http://www.flickr.com/photos/tags/pyneedforspeed/ http://www.flickr.com/photos/30842681 at N00/ John Machin and others stride throught the periods of sequences: http://groups.google.com/group/comp.lang.python/msg/74c81885d7dd4b0e http://groups.google.com/group/comp.lang.python/msg/b9d10df764bdd3df Under-invested desiderata: documentation, regression tests, marketing, serenity, and, as Steve Holden recently discovered, *benchmarks*: http://groups.google.com/group/comp.lang.python/msg/903d5ba9745bad5b Fuzzyman advertises yet another convenience of Movable Python: http://groups.google.com/group/comp.lang.python/msg/35baaa3af891c12f Gonzalo Monzon and others discuss the circumstances of Pyrex applicability: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b051c5ae05517e3e/ Zlatko Matic, Gerard Flanagan, and others work out C# invocations for launching an out-of-process Python application: http://groups.google.com/group/comp.lang.python/browse_thread/thread/b051c5ae05517e3e/ Computing stuff is categorically hard because of the combinatorics and scales which arise naturally. Grant Edwards details a true-life example, which happened to be about numeric interpolation, of how problems ("debugging") are dramatically superlinear: http://groups.google.com/group/comp.lang.python/msg/9a78b5d34db196b4 ======================================================================== 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, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python 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!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From kak at purdue.edu Mon May 8 10:22:40 2006 From: kak at purdue.edu (Avi Kak) Date: 8 May 2006 07:22:40 -0700 Subject: Retrieving event descriptors in Tkinter Message-ID: <1147098160.527716.100700@y43g2000cwc.googlegroups.com> Does Tkinter provide a function that returns all the event descriptors for a given widget class? I am looking for something similar to what you get in Perl/Tk when you call bind() with a single explicit argument. For example, in Perl/Tk, $widget->bind( Tk::Button ) returns a list like .... Is it possible to do the same in Tkinter? I have looked through Fredrik Lundh's on-line reference and also the one by John Shipman. I am unable to locate the function I need. Perhaps I have not looked hard enough. Any help would be much appreciated. Thanks. Avi Kak kak at purdue.edu From __peter__ at web.de Tue May 16 04:33:14 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 May 2006 10:33:14 +0200 Subject: Python and Combinatorics References: <44697b5c$0$14794$4fafbaef@reader4.news.tin.it> <44698bc0$0$14791$4fafbaef@reader4.news.tin.it> Message-ID: Nic wrote: >> PS: Please don't top-post. You probably overlooked that :-) Here's a naive implementation: from itertools import izip def unique(items, N): assert N > 0 if N == 1: for item in items: yield item, else: for index, item in enumerate(items): for rest in unique(items[index+1:], N-1): yield (item,) + rest def repeat(*items): assert len(items) if len(items) == 1: for item in items[0]: yield item, else: for item in items[0]: for rest in repeat(*items[1:]): yield (item,) + rest def render(): pairs = list(unique(range(1, 4), 2)) for item in unique(pairs, 3): for suffix in repeat(*["ab"]*3): yield tuple((a, b, s) for (a, b), s in izip(item, suffix)) if __name__ == "__main__": for item in render(): print " ".join("%s%s%s" % t for t in item) Peter From paddy3118 at netscape.net Tue May 9 02:23:07 2006 From: paddy3118 at netscape.net (Paddy) Date: 8 May 2006 23:23:07 -0700 Subject: Import data from Excel In-Reply-To: References: Message-ID: <1147155787.055054.52150@i40g2000cwc.googlegroups.com> The CSV module? From admin.cluster at gmail.com Tue May 30 04:17:15 2006 From: admin.cluster at gmail.com (Anthony) Date: Tue, 30 May 2006 10:17:15 +0200 Subject: os.time() Message-ID: <447BFF8B.2070500@gmail.com> i have a problem with the os.times() command, on different Python versions, i get different printout: Server1# python Python 2.3.4 (#1, Feb 2 2005, 11:44:13) [GCC 3.4.3 20041212 (Red Hat 3.4.3-9.EL4)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> import os >>> >>> print os.times()[4] 4880406.62 ---------------------------------- Server2% python Python 2.3.2 (#4, Sep 14 2004, 09:41:45) [C] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> import os >>> >>> print os.times()[4] -21464227.74 --------------- Server3% python Python 2.4.1 (#1, May 16 2005, 15:19:29) [GCC 4.0.0 20050512 (Red Hat 4.0.0-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import time >>> import os >>> >>> print os.times()[4] 18390711.21 and on the 3 servers, the linux command: $date returns the same value..... any suggestions??? what is the command that gives me the actual time? From duncanm255 at hotmail.com Thu May 18 11:21:39 2006 From: duncanm255 at hotmail.com (D) Date: 18 May 2006 08:21:39 -0700 Subject: Python Install In-Reply-To: References: <1147962608.945821.226220@i40g2000cwc.googlegroups.com> Message-ID: <1147965699.246345.302860@38g2000cwa.googlegroups.com> Thanks, Paul - do you know where I can get the RPM? I only see the source on the Python website. Thanks. From virgil.green at gmail.com Mon May 22 14:08:23 2006 From: virgil.green at gmail.com (vjg) Date: 22 May 2006 11:08:23 -0700 Subject: Software Needs Philosophers In-Reply-To: <1148254714.668727.298420@y43g2000cwc.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148254714.668727.298420@y43g2000cwc.googlegroups.com> Message-ID: <1148321303.525258.180590@j55g2000cwa.googlegroups.com> nikie wrote: > > (BTW: Have you ever considered the possibility that philosophers might > not be interested in tab-versus-spaces-debates in the first place? > Maybe they have more interesting matters to discuss. Just like the rest > of us.) Debate? There's no valid dabate. Tabs bad. Spaces good. From olanglois at quazal.com Tue May 23 19:23:37 2006 From: olanglois at quazal.com (Olivier Langlois) Date: Tue, 23 May 2006 19:23:37 -0400 Subject: Problem with installing MySQL-python-1.2.1_p2 Message-ID: <400BDC416E2A0042AA35DF3919BB8A5123ABD6@mail.mtl.proksim.com> Hi, I have tried to install MySQL-python-1.2.1_p2 under Windows XP with Python 2.4.3 and I get some problems. 1- I get this warning when I run setup.py build: C:\tools\Python\lib\distutils\extension.py:133: UserWarning: Unknown Extension options: 'mysql_root' warnings.warn(msg) 2- When I compile _mysql.c, there are errors in the file: DL_EXPORT(void) init_mysql(void) { ... if (PyDict_SetItemString(dict, "version_info", PyRun_String(version_info, Py_eval_input, dict, dict))) goto error; if (PyDict_SetItemString(dict, "__version__", PyString_FromString(__version__))) PyRun_String parameter version_info and PyString_FromString parameter __version__ are not defined. I suspect that they should be surrounded by double quotes but if I do that and compile _mysql.pyd. When that module is initialized, python is crashing because PyRun_String returns a NULL pointer instead of the expected valid PyObject pointer. Is there anybody that can help me? Thank you, Olivier Langlois http://www3.sympatico.ca/olanglois From aleaxit at yahoo.com Sun May 7 14:57:56 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 11:57:56 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <87mzducj27.fsf@rpi.edu> Message-ID: <1heyrbd.4ug6sg7cgci5N%aleaxit@yahoo.com> Carl Friedrich Bolz wrote: ... > > an extension that allows the programmer to specify how the value of > > some slot (Lisp lingo for "member variable") can be computed. It > > frees the programmer from having to recompute slot values since Cells ... > I have not looked at Cells at all, but what you are saying here sounds > amazingly like Python's properties to me. You specify a function that > calculates the value of an attribute (Python lingo for something like a You're right that the above-quoted snipped does sound exactly like Python's properties, but I suspect that's partly because it's a very concise summary. A property, as such, recomputes the value each and every time, whether the computation is necessary or not; in other words, it performs no automatic caching/memoizing. A more interesting project might therefore be a custom descriptor, one that's property-like but also deals with "caching wherever that's possible". This adds interesting layers of complexity, some of them not too hard (auto-detecting dependencies by introspection), others really challenging (reliably determining what attributes have changed since last recomputation of a property). Intuition tells me that the latter problem is equivalent to the Halting Problem -- if somewhere I "see" a call to self.foo.zap(), even if I can reliably determine the leafmost type of self.foo, I'm still left with the issue of analyzing the code for method zap to find out if it changes self.foo on this occasion, or not -- there being no constraint on that code, this may be too hard. The practical problem of detecting alterations may be softened by realizing that some false positives are probably OK -- if I know that self.foo.zap() *MAY* alter self.foo, I might make my life simpler by assuming that it *HAS* altered it. This will cause some recomputations of property-like descriptors' values that might theoretically have been avoided, "ah well", not a killer issue. Perhaps a more constructive approach would be: start by assuming the pseudoproperty always recomputes, like a real property would; then move toward avoiding SOME needless recomputations when you can PROVE they're needless. You'll never avoid ALL needless recomputations, but if you avoid enough of them to pay for the needed introspection and analysis, it may still be a win. As to whether it's enough of a real-world win to warrant the project, I pass -- in a research setting it would surely be a worthwhile study, in a production setting there are other optimizations that look like lower-hanging fruits to me. But, I'm sure the Cells people will be back with further illustrations of the power of their approach, beyond mere "properties with _some_ automatic-caching abilities". Alex From jmdeschamps at gmail.com Tue May 23 15:12:41 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 23 May 2006 12:12:41 -0700 Subject: dynamic drawing in web page References: <1148245752.728480.238540@u72g2000cwu.googlegroups.com> Message-ID: <1148411561.547990.93000@j55g2000cwa.googlegroups.com> barbaros wrote: > Hello everybody, > > I need to put some dynamic drawings on my web page. More precisely, I > need to draw a number of geometric figures (circles, rectangles) which > evolve into a graphics windows according to some law (a little bit like > the solar system). I need also to have several fields aside the window, > where the visitor can change values for several significant parameters > (like the mass of each body). > > Could you please suggest a solution (preferably not involving hundreds > of lines of code) ? The computations should be performed on the client > machine. > > Thank you. Cristian Barbarosie http://cmaf.fc.ul.pt/~barbaros with this you can. http://www.walterzorn.com/jsgraphics/jsgraphics_e.htm It's javascript and it's not the fastest thing on earth, but it works and its client-side... JM From acatejr at gmail.com Mon May 22 18:17:19 2006 From: acatejr at gmail.com (acatejr at gmail.com) Date: 22 May 2006 15:17:19 -0700 Subject: File attributes Message-ID: <1148336239.342164.285680@j73g2000cwa.googlegroups.com> I know how to "walk" a folder/directory using Python, but I'd like to check the archive bit for each file. Can anyone make suggestions on how I might do this? Thanks. From tim.leeuwvander at nl.unisys.com Fri May 12 08:27:32 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 12 May 2006 05:27:32 -0700 Subject: New tail recursion decorator In-Reply-To: References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> Message-ID: <1147436852.364490.99440@u72g2000cwu.googlegroups.com> [...] > > > I'm not convinced by this. You have to recognise that the function is using > tail recursion, and then you have to modify the code to know that it is > using tail recursion. This is not always trivial. For example, the given > example is: > > @tail_recursion > def factorial(n, acc=1): > "calculate a factorial" > if n == 0: > return acc > res = factorial(n-1, n*acc) > return res > > but a more common way to write the function would be: > > @tail_recursion > def factorial(n): > "calculate a factorial" > if n == 0: > return 1 > return n * factorial(n-1) > > which won't work because it isn't actually tail recursion, but it looks > sufficiently close to tail recursion that it would probably mislead a lot > of people into expecting it will work. If you are going to have to rewrite > functions in a stilted manner, and they use simple tail recursion, then why > not just factor out the tail recursion in the first place. > [...] Hi Duncan, I don't know why it wouldn't work this way, or why it isn't tail-recursion? I tried the tail_recursion decorator from the cookbook-recipe with both definitions of factorial, and I tried both definitions of the factorial function with and without tail_recursion decorator. In all four cases I get the same results, so it does work with both definitions of factorial(), even if (according to you) the second definition is not proper tail-recursion. Using the tail-recursion decorator (the version that does not inspect the stackframes) I get a small performance-increase over using the factorial-function undecorated. However, calculating factorial(1000) with the factorial-function as defined in the cookbook-recipe is much much faster than calculating the same factorial(1000) with the factorial-function you gave! I cannot yet explain why the first function has so much better performance than the second function - about a factor 10 difference, in both python2.4.3 and python 2.5a2 Cheers, --Tim From rpdooling at gmail.com Thu May 4 16:41:28 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 4 May 2006 13:41:28 -0700 Subject: Can I use python for this .. ?? References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146774288.904851.278130@i39g2000cwa.googlegroups.com> Message-ID: <1146775288.873572.69220@j73g2000cwa.googlegroups.com> For starters, you need the os and webbrowser modules import os import webbrowser webbrowser.open("http://mail.google.com/mail") # need to know the shell keyword for starting the app os.system('start ' + 'Winword') # the equivalent of double-clicking on the doc or file os.startfile("c:/MyFiles/MyTextFile.txt") If you actually want to log onto password-protected sites it gets gnarly fast (beyond me). You can read about by perusing the urllib2 module or search this list at groups.google.com/group/comp.lang.python Hope this helps. rick From alengarbage at yahoo.com Fri May 19 18:34:27 2006 From: alengarbage at yahoo.com (Lenny G.) Date: 19 May 2006 15:34:27 -0700 Subject: hidden file detection Message-ID: <1148078067.570279.116300@j33g2000cwa.googlegroups.com> What's the best way to do cross-platform hidden file detection? I want to do something like weed-out the files that should be 'hidden' from os.listdir() (which would be files that start with '.' under Unix, files that have the hidden attribute set on windows, and whatever it is that makes Mac files hidden). Is there a util or lib that does this for me? Thanks, Gary From jantod at gmail.com Mon May 29 04:41:57 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 29 May 2006 01:41:57 -0700 Subject: itertools.count() as built-in References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> <1148860241.048549.269330@j73g2000cwa.googlegroups.com> <447A5028.9070203@lexicon.net> Message-ID: <1148892117.161079.133720@u72g2000cwu.googlegroups.com> Oops. The messed-up version wasn't supposed to be messed-up. Two mistakes on one line. Which kinda proves my point :) I'd much rather use the count version than (1) or (2). (1) has the problem of having "incorrect" values the rest of the time in the loop and (2) is going to an extreme just to avoid an import of count. Your zipwithcount doesn't look as obvious as for n, a, b in zip(count(), A, B) but is still easier to read than for n, (a, b) in enumerate(zip(A, B)) -Janto From onurb at xiludom.gro Thu May 18 05:31:59 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 11:31:59 +0200 Subject: Process forking on Windows - or what is MQSeries In-Reply-To: <126n8g6669ml2b6@corp.supernews.com> References: <126mgi2j7fl4b4b@corp.supernews.com> <446b45b1$0$7132$636a55ce@news.free.fr> <126mi8q1t31r9e0@corp.supernews.com> <126n8g6669ml2b6@corp.supernews.com> Message-ID: <446c3f77$0$7699$626a54ce@news.free.fr> Andrew Robert wrote: > Gary Herron wrote: > >>Andrew Robert wrote: >> > > > >>The windows CreateProcess call has many of the same semantics as the >>Unix fork, i.e., a new process is created sharing all the resources of >>the original process. The "subprocess" modules uses CreateProcess, but >>if that does not give you sufficient control over the process creation, >>you can call CreateProcess directly via the "win32process" module in the >>win32all package. >> >>However, I still don't understand *what* the "MQSeries trigger monitor" >>is or *how* it would create the need for such a solution. >> >>Gary Herron >> >> > > MQSeries is a rather interesting piece of middle-ware offered by IBM > that allows you to link disparate hosts/applications together via XML > messaging and application specific queues. > > In the broadest sense, think of MQSeries like a large switchboard > connecting everything together. > > Message queues can be programmed to do something via a mq application > process such as a rule to take action when first, 5th, etc message arrives. > > The state of queues and their linked processes are controlled by the > trigger monitor. > > The trigger monitor can only deal with one running process at a time. > > In this situation, it is possible for a process(my python program) to > monopolize and block other processes from being triggered. > > Ideally, this needs to be avoided through the use of a fork. Since there's no fork() on Windows, how do other programs working with MQSeries deal with this situation ? How does it comes that your program 'monopolize' the monitor, while other don't ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ptmcg at austin.rr._bogus_.com Sun May 14 14:26:13 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 14 May 2006 18:26:13 GMT Subject: do/while structure needed References: <4466bddd$0$18984$c3e8da3@news.astraweb.com> Message-ID: <9DK9g.28631$CH2.28363@tornado.texas.rr.com> "Ten" wrote in message news:mailman.5677.1147617486.27775.python-list at python.org... > On Sunday 14 May 2006 06:17, John Salerno wrote: > > 1 random.shuffle(letters) > > 2 trans_letters = ''.join(letters)[:len(original_set)] > > 3 trans_table = string.maketrans(original_set, trans_letters) > > > > So what I'd like to do is have lines 1 and 2 run once, then I want to do > > some comparison between original_set and trans_letters before running > > line 3. If the comparison passes, line 3 runs; otherwise, lines 1 and 2 > > run again. > > > > A do/while would be good for this, but perhaps I'm looking at it in the > > wrong way? Or is there some kind of do/while type of idiom that I could > > use? > > > > Thanks. > > while not comparison(original_set, trans_letters): > random.shuffle(letters) > trans_letters = ''.join(letters)[:len(original_set)] > > trans_table = string.maketrans(original_set, trans_letters) > I don't think the OP wants to call comparison until after the first pass through the loop. Here's a modification to your version that skips the comparison test on the first pass: first = True while first or not comparison(original_set, trans_letters): first = False random.shuffle(letters) trans_letters = ''.join(letters)[:len(original_set)] trans_table = string.maketrans(original_set, trans_letters) -- Paul From robert.kern at gmail.com Tue May 9 17:09:28 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 May 2006 16:09:28 -0500 Subject: installing numpy In-Reply-To: <8764kfkkhb.fsf@localhost.localdomain> References: <877j4v5ukc.fsf@localhost.localdomain> <6Y%7g.11622$EC.10694@tornado.rdc-kc.rr.com> <8764kfkkhb.fsf@localhost.localdomain> Message-ID: Gary Wessle wrote: > "Raymond L. Buvel" writes: >>When installing from source on a Debian system, you want the installed >>package to wind up in /usr/local/lib/python2.x/site-packages (where x >>represents the version of Python you are running the installer from). >>This allows you to keep it separate from the apt managed directories and >>allows for easy removal/upgrade. So the command you want to execute >>from root is >> >>python setup.py install --prefix=/usr/local > > sorry if this is boring since I am not a seasoned Linux user. > > setup.py isn't located at the root, do you mean, execute the command above > from root, as to do this > :~$ cd / > :/$ python setup.py install --prefix=/usr/local > or > :/$ python home/fred/numpy-0.9.6/setup.py install --pref... > or AS root > :/# python setup.py install --prefix=/usr/local > or > :/# python home/fred/numpy-0.9.6/setup.py install --pref... I think he meant "as the root user". You will probably want to build numpy as a regular user and then only install as the root user. You will probably want to use sudo(1) to gain root privileges. You can read the sudo man-page for more information on how to do that. ~$ cd numpy-0.9.6 ~/numpy-0.9.6$ python setup.py build ~/numpy-0.9.6$ sudo python setup.py install --prefix=/usr/local However, instead of setting --prefix every time you execute setup.py for every Python package, it will be easier for you to create the file ~/.pydistutils.cfg with the contents [install] prefix=/usr/local See http://docs.python.org/inst/config-syntax.html for more information. Then, you can just do ~$ cd numpy-0.9.6 ~/numpy-0.9.6$ python setup.py build ~/numpy-0.9.6$ sudo python setup.py install >>By the way, to get NymPy to use the high-performance libraries, you must >>install these libraries and the associated -dev packages before running >>the Python install. > > I wish to know the debian names for those packages, my first guess > would be refblas3 under testing since blas is not available for > debian/testing, there is also > refblas3-dev Basic Linear Algebra Subroutines 3, static library > which I don't have installed. > > would refblas3 be all what NymPy need to the high-performance? No. refblas3 provides the reference (unoptimized) implementation of the BLAS. In Ubuntu (a Debian-based distribution) the package that you would want is atlas3-base-dev. It should have a similar name in your version of Debian (possibly atlas-dev or atlas3-dev or some other variant). If you need more help, you will probably get more focused help on the numpy-discussion mailing list. http://lists.sourceforge.net/lists/listinfo/numpy-discussion -- 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 mik3l3374 at hotmail.com Thu May 25 08:43:57 2006 From: mik3l3374 at hotmail.com (mik3) Date: 25 May 2006 05:43:57 -0700 Subject: a good explanation In-Reply-To: <4dlmsqF1abojeU1@uni-berlin.de> References: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> <4dlmsqF1abojeU1@uni-berlin.de> Message-ID: <1148561036.982387.316920@j33g2000cwa.googlegroups.com> wow!...thanks for both replies..and yes you are right, he comes from a world of C and java...i have successfully "brainwashed" him to try out coding in python...haha. So he has written his first program in python and i have roughly toook a glance at it and saw what he did.. i pointed out his "mistakes" but couldn't convince him otherwise. Anyway , i am going to show him your replies.. thanks again. From ask at me Wed May 24 22:00:25 2006 From: ask at me (AndyL) Date: Wed, 24 May 2006 22:00:25 -0400 Subject: how to "normalize" indentation sources Message-ID: Hi, I have a lot of sources with mixed indentation typically 2 or 4 or 8 spaces. Is there any way to automatically convert them in let's say 4 spaces? Thx, A. From bborcic at gmail.com Wed May 24 17:51:07 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 24 May 2006 23:51:07 +0200 Subject: Python keywords vs. English grammar In-Reply-To: References: Message-ID: <4474d559$1_4@news.bluewin.ch> Roy Smith wrote: > I noticed something interesting today. In C++, you write: > > try { > throw foo; > } catch { > } > > and all three keywords are verbs, so when you describe the code, you can > use the same English words as in the program source, "You try to execute > some code, but it throws a foo, which is caught by the handler". Not convincing at all, since the *explicit* throw/raise lexically inside a try block with a catch/except clause that's *predetermined* to catch it... is the exception rather than the rule. Normally you'd use another form of block exit. Or is the case different in C++ by any chance ? > > In Python, you write: usually, you don't write something similar to that, and neither in C++ I guess. > > try: > raise foo > except: > > and now you've got a mix of verbs and (I think), a preposition. You can't > say, "You try to execute some code, but it raises a foo, which is excepted > by the handler". It just doesn't work grammatically. > > Sigh. From larry.bates at websafe.com Mon May 22 18:50:18 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 22 May 2006 17:50:18 -0500 Subject: File attributes In-Reply-To: <1148336239.342164.285680@j73g2000cwa.googlegroups.com> References: <1148336239.342164.285680@j73g2000cwa.googlegroups.com> Message-ID: <4472402A.6080000@websafe.com> acatejr at gmail.com wrote: > I know how to "walk" a folder/directory using Python, but I'd like to > check the archive bit for each file. Can anyone make suggestions on > how I might do this? Thanks. > You must have Mark Hammond's win32 package installed, then you can (barely tested): import win32api import win32con fattrs=win32api.GetFileAttributes(filename) if fattrs & win32con.FILE_ATTRIBUTE_ARCHIVE: # # Archive bit set # -Larry Bates From deets at nospam.web.de Mon May 15 15:07:02 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 21:07:02 +0200 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> Message-ID: <4cs1qgF17ee24U1@uni-berlin.de> Maric Michaud schrieb: > Le Lundi 15 Mai 2006 19:24, Roy Smith a ?crit : >> d = {} >> d.reserve (10*1000*1000) > > d={}.fromkeys(xrange(5*10**6)) ? That is a totally different beast. You don't want to insert arbitrary keys, you want the internal hash-array to be of the right size. Diez From malvert at telenet.be Wed May 3 07:02:28 2006 From: malvert at telenet.be (malv) Date: 3 May 2006 04:02:28 -0700 Subject: Binary File Reading : Metastock In-Reply-To: <1146615474.410864.52950@g10g2000cwb.googlegroups.com> References: <1146615474.410864.52950@g10g2000cwb.googlegroups.com> Message-ID: <1146654147.955416.9420@j73g2000cwa.googlegroups.com> Jack wrote: > Hi > > I am having a little trouble trying to read a binary file, I would like > to write an ascii to Metastock converter in python but am not having a > lot of success. > > The file formats are > > http://sf.gds.tuwien.ac.at/00-pdf/m/mstockfl/MetaStock.pdf > > > If any one can point me in the right direction it would be much > appreciated. > > So far I have tried opening file "rb" then trying to use struct and > then binascii but I am not too sure what I should be doing and fuction > I should be using in binascii ? > > > > TIA Jack, What you may not realize is that Metastock is using an oddball floating point format. I have not looked at this for many years now but remember using a small VB-callable dll with functions BasicToIEEE and IEEEToBasic. This may help you in recoding conversions into Python. float BasicToIEEE (unsigned char *value) { float result; unsigned char *msbin = (unsigned char *) value; unsigned char *ieee = (unsigned char *) &result; unsigned char sign = 0x00; unsigned char ieee_exp = 0x00; int i; /* MS Binary Format */ /* byte order => m3 | m2 | m1 | exponent */ /* m1 is most significant byte => sbbb|bbbb */ /* m3 is the least significant byte */ /* m = mantissa byte */ /* s = sign bit */ /* b = bit */ sign = msbin[2] & 0x80; /* 1000|0000b */ /* IEEE Single Precision Float Format */ /* m3 m2 m1 exponent */ /* mmmm|mmmm mmmm|mmmm emmm|mmmm seee|eeee */ /* s = sign bit */ /* e = exponent bit */ /* m = mantissa bit */ for (i=0; i<4; i++) ieee[i] = 0; /* any msbin w/ exponent of zero = zero */ if (msbin[3] == 0) return 0; ieee[3] |= sign; /* MBF is bias 128 and IEEE is bias 127. ALSO, MBF places */ /* the decimal point before the assumed bit, while */ /* IEEE places the decimal point after the assumed bit. */ ieee_exp = msbin[3] - 2; /* actually, msbin[3]-1-128+127 */ /* the first 7 bits of the exponent in ieee[3] */ ieee[3] |= ieee_exp >> 1; /* the one remaining bit in first bin of ieee[2] */ ieee[2] |= ieee_exp << 7; /* 0111|1111b : mask out the msbin sign bit */ ieee[2] |= msbin[2] & 0x7f; ieee[1] = msbin[1]; ieee[0] = msbin[0]; return (result); } bool IEEEToBasic (float *value, unsigned char *result) { unsigned char *ieee = (unsigned char *) value; unsigned char *msbin = (unsigned char *) result; unsigned char sign = 0x00; unsigned char msbin_exp = 0x00; int i; /* See _fmsbintoieee() for details of formats */ sign = ieee[3] & 0x80; msbin_exp |= ieee[3] << 1; msbin_exp |= ieee[2] >> 7; /* An ieee exponent of 0xfe overflows in MBF */ if (msbin_exp == 0xfe) return (FALSE); msbin_exp += 2; /* actually, -127 + 128 + 1 */ for (i=0; i<4; i++) msbin[i] = 0; msbin[3] = msbin_exp; msbin[2] |= sign; msbin[2] |= ieee[2] & 0x7f; msbin[1] = ieee[1]; msbin[0] = ieee[0]; return (TRUE); } Good luck, malv From grflanagan at yahoo.co.uk Thu May 18 04:37:57 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 18 May 2006 01:37:57 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <1147941477.650222.318420@38g2000cwa.googlegroups.com> glomde wrote: > i I would like to extend python so that you could create hiercical [...] > # build a tree structure > root = ET.Element("html") > *!*root: > *!*head("head"): > *!*title("title): > *=*text = "Page Title" > *!*body("body"): > *=*bgcolor = "#ffffff" > *=*text = "Hello, World!" > > > > I think that with the added syntax you get better view of the html > page. > Repeating things dissapears and you get indentation that corresponds to > the tree. > I think it is very pythonic IMHO. > > It could be done quite generic. If the variable, object after '*!*' > must support append > method and if you use '*=*' it must support __setitem__ > > Any comments? I personally dislike the nested-indented-brackets type of code given in other replies, and i think your suggestion has a certain appeal - 'What you see is what you mean' . But it's not Python. You also repeat yourself: head("head"), title("title"), body("body") What about this: # build a tree structure root = ET.Element("html") !root !head !title if A is True: &text = "Page A" else: &text = "Page B" !body &bgcolor = "#ffffff" &text = "Hello, World!" mmm...yamlthon? yython...:-) All the best Gerard From bborcic at gmail.com Mon May 29 10:40:31 2006 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 29 May 2006 16:40:31 +0200 Subject: Ricerca Programmatore Python In-Reply-To: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> References: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> Message-ID: <447b07eb$1_3@news.bluewin.ch> Nic wrote: > Please accept my apologies for the use of the Italian language. accepted From rpdooling at gmail.com Tue May 16 23:51:45 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 16 May 2006 20:51:45 -0700 Subject: Help System For Python Applications In-Reply-To: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> References: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> Message-ID: <1147837905.880754.145450@u72g2000cwu.googlegroups.com> At the commandline, run: pydoc -g In the interpreter: help("modulename") or help () for interactive. Are you on Windows? Using ActivePython? Or the Python.org download? rd From thomas at eforms.co.nz Tue May 2 20:58:17 2006 From: thomas at eforms.co.nz (Thomas Thomas) Date: Wed, 3 May 2006 12:58:17 +1200 Subject: Reading XST file Message-ID: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz> Hi All, I need extract the content of an XST file to dictionary object.. below is content of that file ---------------------------------------------------------------------------------------- from work centre XST [description XRX_DSCRPT_METADATA] field_0{ string MetaDataFieldName = "title"; string MetaDataPrompt = "Title"; string MetaDataType = "string"; string MetaDataValue = "Student Letter"; } field_1{ string MetaDataFieldName = "collectionname"; string MetaDataPrompt = "CollectionName"; string MetaDataType = "string"; string MetaDataValue = "999888777666"; } field_2{ string MetaDataFieldName = "summary"; string MetaDataPrompt = "Summary"; string MetaDataType = "string"; string MetaDataValue = "newman"; } [description xrx_dscrpt_metadata] entry_1{ string MetaDataFieldName = "Job Reference"; string MetaDataPrompt = "Job Reference"; string MetaDataDefaultValue = ""; string MetaDataValue = "jgutbcfrvewf"; } entry_2{ string MetaDataFieldName = "Price Text"; string MetaDataPrompt = "Price Text"; string MetaDataDefaultValue = ""; string MetaDataValue = "758bf6"; } --------------------------------------------------------------------------- I want a hash to be build based on the content like resulthash ={1:{"MetaDataFieldName" :"Price Text","MetaDataPrompt":"Price Text","MetaDataDefaultValue" :"","MetaDataValue":"758bf6",}, and so on for all ocuurences..} I started using file objects ..and was thinking is a better way to approach this scenario from os.path import * filename="c:\sxtfile.xst"; if exists(filename): if isfile(filename): f = open(filename, "rb") for line in f.readlines(): print line else: print "I cannot see a file of this name" cheers ----------------------------------------------------- Thomas Thomas phone +64 7 855 8478 fax +64 7 855 8871 -------------- next part -------------- An HTML attachment was scrubbed... URL: From andrew.arobert at gmail.com Wed May 24 12:52:27 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 24 May 2006 12:52:27 -0400 Subject: how to change sys.path? In-Reply-To: <532972pkqut50suspvi4qhmkkeporlcopv@4ax.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <5aGcg.2150$No6.46806@news.tufts.edu> <532972pkqut50suspvi4qhmkkeporlcopv@4ax.com> Message-ID: <12793r793v9to76@corp.supernews.com> Dennis Lee Bieber wrote: > On Wed, 24 May 2006 14:45:55 GMT, John Salerno > declaimed the following in comp.lang.python: > >> I just right-clicked on My Computer --> Properties --> Advanced --> >> Environment Variables, and added a new one called PYTHONPATH. I don't >> know if that edits the registry, but you don't *manually* have to edit >> the registry if you do it that way...unless of course you aren't >> supposed to be doing it that way! But it worked anyway. :) > > I may have gotten slightly confused -- I had an impression that, at > least one poster in the thread, wanted to do this from within a Python > program. That does go into registry modifications. > > For example, look at the entries under: > > (system environment, I believe) > HKEY_LOCAL_MACHINE\SYSTEM\CurrentControlSet\Control\Session > Manager\Environment > > (user specific environment) > HKEY_CURRENT_USER\Environment > > Though in the case of PYTHONPATH, the core value seems to be in (for > my install) > > HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.3\PythonPath > > which also has subkeys for Pythonwin, win32, and win32com > Instead of messing with the registry, wouldn't it be easier to just add a line similar to this within your code? sys.path.append(r'\\mynetwork\share') I use something similar so that all my scripts can locate the same home-grown modules no matter where they are run from. From 2006 at jmunch.dk Sun May 7 07:25:51 2006 From: 2006 at jmunch.dk (Anders J. Munch) Date: Sun, 07 May 2006 13:25:51 +0200 Subject: Newbie question on code vetting In-Reply-To: References: <_%w6g.44217$C63.42016@trnddc06> Message-ID: <445dd968$0$12401$ba624c82@nntp02.dk.telia.net> william.boquist at gte.net wrote: > As it is now, > one is pretty much left to rummage around on project web sites trying to get > a gut feel for what is going on. Asking the higher-ups at work to reach > technology management decisions based on my gut feel is an uphill climb. So what you need is a document that more or less formalises what you already know from rummaging around. The place for such a document would be the meta-PEP section at http://python.org/peps/. If the information you seek is in none of the existing meta-PEPs, that's probably because noone has yet felt the need for such a document bad enough to make the effort and write one. Until you came along, that is. So why don't you write a new PEP (or suggest changes to an existing PEP) with the information you need? You may not have all the answers, but if you have good questions that's a pretty good start. From an earlier post: > Is there any use of tools like BlackDuck ProtexIP or the > competing Palamida product to scan for matches to code that is already > licensed elsewhere? If you have access to such tools, why don't you just scan the CPython sources yourself? And make the results available to the community, of course. - Anders From nick.smallbone at gmail.com Thu May 25 18:31:43 2006 From: nick.smallbone at gmail.com (Nick Smallbone) Date: 25 May 2006 15:31:43 -0700 Subject: __getattr__ and functions that don't exist In-Reply-To: <44762cf8$1@nntp.zianet.com> References: <44762cf8$1@nntp.zianet.com> Message-ID: <1148596303.833301.15190@g10g2000cwb.googlegroups.com> Erik Johnson wrote: > Maybe I just don't know the right special function, but what I am wanting to > do is write something akin to a __getattr__ function so that when you try to > call an object method that doesn't exist, it get's intercepted *along with > it's argument*, in the same manner as __getattr__ intercepts attributes > references for attributes that don't exist. > > > This doesn't quite work: > > >>> class Foo: > ... def __getattr__(self, att_name, *args): > ... print "%s%s" % (att_name, str(tuple(*args))) > ... > >>> f = Foo() The problem is that the call to f.bar happens in two stages: the interpreter calls getattr(f, "foo") to get a function, and then it calls that function. When __getattr__ is called, you can't tell what the parameters of the function call will be, or even if it'll be called at all - someone could have run "print f.bar". Instead, you can make __getattr__ return a function. Then *that* function will be called as f.bar, and you can print out its arguments there: class Foo: def __getattr__(self, attr): def intercepted(*args): print "%s%s" % (attr, args) return intercepted From fredrik at pythonware.com Mon May 29 16:12:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 May 2006 22:12:53 +0200 Subject: create a text file In-Reply-To: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> References: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> Message-ID: Stan Cook wrote: > I'm writing a script to list all of my music files' id3 tags > to a comma delimited file. The only part I'm missing seems > like it should be the simplest. I haven't used Python for > the last couple of years. My question is this: > > When I use os.open(,"w"), I get an error > message, TypeError: an integer is required. Has > something changed? Did I miss something??? the function is called "open", not "os.open". there's an open function in the os module, but that's doing something slightly different (see the library reference documentation for details if you're curious). From grante at visi.com Fri May 5 17:46:05 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 05 May 2006 21:46:05 -0000 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> <125ir8gpofq3i1c@corp.supernews.com> <1146798159.209695.4190@j33g2000cwa.googlegroups.com> Message-ID: <125nhstg576mu62@corp.supernews.com> On 2006-05-05, Marc 'BlackJack' Rintsch wrote: > In <1146798159.209695.4190 at j33g2000cwa.googlegroups.com>, OlafMeding > wrote: > >>> IIRC it was something like an NTP daemon that caused the clock >>> to "jump" a little and (Window's) sleep was confused. >> >> The problem is not a "jump" but a permanet lockup of the sleep >> statement. > > The "jump" of the system clock might confuse the systems > `sleep` implementation. I wouldn't be a bit surprised if MS write code to wake up a task when the currentTime == task.wakeupTime instead of when currentTime >= task.wakeupTime. If the system time jumps past the "wakeup" point without ever passing through it, the task sleeps forever. Microsoft's bungling of simple things like timer ticks is legend in some circles: http://www.embedded.com/showArticle.jhtml?articleID=57703680 http://www.embedded.com/showArticle.jhtml?articleID=159902113 -- Grant Edwards grante Yow! I'm young... I'm at HEALTHY... I can HIKE visi.com THRU CAPT GROGAN'S LUMBAR REGIONS! From jdsalt_AT_gotadsl.co.uk Tue May 23 16:14:18 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Tue, 23 May 2006 15:14:18 -0500 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> Message-ID: "John A. Bailo" wrote in news:WOadnW-sRKmdoe7Z4p2dnA at speakeasy.net: [Snips] > What exciting new ideas exist in software that are both important and > cannot be traced back to Doug Engbart's 1968 presentation at Xerox > Parc? The only two I would think worth mentioning are Nygaard et al's ideas on patterns as embodied in Mjolner Beta, and Colmerauer's on logic programming as embodied in Prolog. And maybe pi calculus, if only for sticking the formal foundation in where it was missing from under O-O. But Prolog and pi calculus are regarded as marginal activities, and most software people have stil contrived never to have heard of Nygaard, despite his being the inventor (with Ole-Johan Dahl) of O-O in 1967. All the best, John. From bucodi at yahoo.fr.invalid Fri May 5 03:37:33 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Fri, 05 May 2006 09:37:33 +0200 Subject: Job opportunity in France Message-ID: We have a vacancy for a python programmer for a 6 months assignement. If interested, please visit www.bucodi.com And don't worry we speak english :) R_ -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From oscartheduck at gmail.com Sun May 21 16:22:22 2006 From: oscartheduck at gmail.com (oscartheduck) Date: 21 May 2006 13:22:22 -0700 Subject: newbie: windows xp scripting In-Reply-To: <1148239856.998371.160700@u72g2000cwu.googlegroups.com> References: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> <1148239856.998371.160700@u72g2000cwu.googlegroups.com> Message-ID: <1148242942.228863.97090@j73g2000cwa.googlegroups.com> For completeness' sake, this is the new script I came up with: import os dirfrom = 'C:\\test' dirto = 'C:\\test1\\' makedir = 'mkdir "%s"' % dirto copy_command = 'copy "%s" "%s"' % (dirfrom, dirto) if os.system(copy_command) == 0: print "yay" else: if os.system(makedir) == 0: if os.system(copy_command) == 0: print 'yay!' else: print 'WTF mate?' Is there a more efficient way of doing this? From jdsalt_AT_gotadsl.co.uk Tue May 16 12:45:35 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Tue, 16 May 2006 11:45:35 -0500 Subject: [silly] Does the python mascot have a name ? References: Message-ID: Steve wrote in news:e4c59e$tqg$1 at emma.aioe.org: > umm, was just wondering, does the python mascot have a name ? I always assumed it was Monty, but I confess to not having the slightest factual basis for this belief. All the best, John. From h.b.furuseth at usit.uio.no Mon May 8 05:38:00 2006 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Mon, 08 May 2006 11:38:00 +0200 Subject: Dispatching operations to user-defined methods References: <1146733381.556818.121600@u72g2000cwu.googlegroups.com> Message-ID: Michele Simionato writes: > Apparently Guido fell in love with generic functions, so > (possibly) in future Python versions you will be able to > solve dispatching problems in in an industrial strenght way. Looks interesting, I'll keep an eye on that. > Sometimes however the simplest possible way is enough, and you > can use something like this : > > class SimpleDispatcher(object): > (...) That doesn't make use of any subclass hierarchies the user defines though. But maybe it's just as well to scan his class for names once he has defined it, and build the dispatch table myself. -- Hallvard From aleaxit at yahoo.com Sun May 7 15:34:37 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 12:34:37 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <1vspxcmldcqa5.t1b4abyraqom.dlg@40tude.net> <1heytyi.lope5l1p029gfN%aleaxit@yahoo.com> <19qhkvgj0bdmg.1ex2haasqrgrj.dlg@40tude.net> Message-ID: <1heyw5k.1997033mne3xrN%aleaxit@yahoo.com> Frank Buss wrote: > Alex Martelli wrote: > > > Sorry, but I just don't see what lambda is buying you here. Taking just > > one simple example from the first page you quote, you have: > > > > (defun blank () > > "a blank picture" > > (lambda (a b c) > > (declare (ignore a b c)) > > '())) > > You are right, for this example it is not useful. But I assume you need > something like lambda for closures, e.g. from the page Wrong and unfounded assumption. > http://www.frank-buss.de/lisp/texture.html : > > (defun black-white (&key function limit) > (lambda (x y) > (if (> (funcall function x y) limit) > 1.0 > 0.0))) > > This function returns a new function, which is parametrized with the > supplied arguments and can be used later as building blocks for other > functions and itself wraps input functions. I don't know Python good > enough, maybe closures are possible with locale named function definitions, > too. They sure are, I gave many examples already all over the thread. There are *NO* semantic advantages for named vs unnamed functions in Python. Not sure what the &key means here, but omitting that def black_white(function, limit): def result(x,y): if function(x, y) > limit: return 1.0 else: return 0.0 return result Alex From tbrkic at yahoo.com Tue May 9 18:03:24 2006 From: tbrkic at yahoo.com (glomde) Date: 9 May 2006 15:03:24 -0700 Subject: What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY? References: <1147175821.309279.271730@j33g2000cwa.googlegroups.com> Message-ID: <1147212204.424499.260890@i39g2000cwa.googlegroups.com> Thanks, but the thing is that I want to have the syntactical sugar. And I think that you could use elementtree or xist or any other python tree structure module at the bottom. It could be quite generic. And with the syntactical sugar I find it a lot more readable. A little bit like yaml, but you have the power of python aswell. For example with syntactical sugar: # build a tree structure root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): *=*text = "Page Title" *!*body("body"): *=*bgcolor = "#ffffff" *=*text = "Hello, World!" This would then be this with element tree package. # build a tree structure root = ET.Element("html") head = ET.SubElement(root, "head") title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ffffff") body.text = "Hello, World!" I find it a lot more readable with the syntactical sugar. So I would really like to add this syntax. /T From bram at geenspam.sara.nl Thu May 11 05:44:54 2006 From: bram at geenspam.sara.nl (Bram Stolk) Date: Thu, 11 May 2006 11:44:54 +0200 Subject: releasing interpreter lock in custom code? Message-ID: <1147340518.685734@blaat.sara.nl> Hello, I've implemented, in C, a function that does a lot of I/O, and thus can block for a long time. If I execute this function in my Python script, it does not relinquish the global interpreter lock, like Python's native blocking functions do, like I/O funcs, and time.sleep() func. How can I have my func release the lock? thanks! Bram Stolk From p.r.hariram at gmail.com Mon May 8 06:18:32 2006 From: p.r.hariram at gmail.com (Hari) Date: 8 May 2006 03:18:32 -0700 Subject: How to get a part of string which follows a particular pattern using shell script Message-ID: <1147083512.620270.231680@j73g2000cwa.googlegroups.com> Hi all, I need to get a part of string which follows a pattern 'addr=' For example: a)test="192.168.1.17:/home/ankur/nios_fson/mnt/tmptype nfs(rw,addr=192.168.1.17)" b)test="/dev/root on / typr nfs (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93)" I need to get the ipaddress from the above two strings a and b which follows 'addr='. I tried to use cut, but it accepts only single charter as delimiter. If I give delimiter as 'addr=' for cut command it gives me a error. So please help me. A bunch of thanks in advance. Regards, P.R.Hariram From diffuser78 at gmail.com Wed May 10 19:26:25 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 10 May 2006 16:26:25 -0700 Subject: Memory leak in Python In-Reply-To: <1147252803.325579.151510@j33g2000cwa.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> <1147252803.325579.151510@j33g2000cwa.googlegroups.com> Message-ID: <1147303585.301968.270590@i39g2000cwa.googlegroups.com> I ran simulation for 128 nodes and used the following oo = gc.get_objects() print len(oo) on every time step the number of objects are increasing. For 128 nodes I had 1058177 objects. I think I need to revisit the code and remove the references....but how to do that. I am still a newbie coder and every help will be greatly appreciated. thanks From nobody at 127.0.0.1 Thu May 11 17:30:01 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 11 May 2006 21:30:01 GMT Subject: python equivalent of the following program References: Message-ID: Steven Bethard wrote: > import subprocess > > file1 = open('file1', 'w') > prog1 = subprocess.Popen(['prog1'], stdout=file1) And if the script runs somewhere that stderr is likely to disappear: prog1 = subprocess.Popen(['prog1'], stdout=file1, stderr=subprocess.STDOUT) From siona at chiark.greenend.org.uk Fri May 19 10:33:14 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 May 2006 15:33:14 +0100 (BST) Subject: memory error with zipfile module References: Message-ID: Hari Sekhon wrote: >import zipfile >zip=zipfile.ZipFile('d:\somepath\cdimage.zip') >zip.namelist() >['someimage.iso'] [ ... ] >B) content=zip.read('someimage.iso') > >Traceback (most recent call last): > File "", line 1, in ? > File "D:\u\Python24\lib\zipfile.py", line 357, in read > bytes = dc.decompress(bytes) >MemoryError > >I thought python was supposed to handle memory for you? Yes, but it can't handle more memory than the operating system is prepared to give it. How big is cdimage.zip? How big is the uncompressed someimage.iso? How much memory do you have? >The python zipfile module is obviously broken... This isn't at all obvious to me. -- \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 antroy at gmail.com Thu May 18 12:31:16 2006 From: antroy at gmail.com (Ant) Date: 18 May 2006 09:31:16 -0700 Subject: how to make the program notify me explicitly In-Reply-To: References: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> Message-ID: <1147969876.113740.107660@u72g2000cwu.googlegroups.com> > > I don't know whether python can warn me through beeping like C > > program(e.g.:printf("%c", '\07');) > > This is information that is easily lost; what if no-one is in hearing > range when the beep occurs? Indeed, *does* it still beep if there is no-one around to hear it? From maric at aristote.info Wed May 24 18:25:45 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 25 May 2006 00:25:45 +0200 Subject: Why can't timedeltas be divided? In-Reply-To: <1148508445.853563.170030@i39g2000cwa.googlegroups.com> References: <1148508445.853563.170030@i39g2000cwa.googlegroups.com> Message-ID: <200605250025.46476.maric@aristote.info> Le Jeudi 25 Mai 2006 00:07, Dan Bishop a ?crit?: > If I try to write something like: > > ? ? num_weeks = time_diff / datetime.timedelta(days=7) because it has no meaning, what you want is : num_weeks = time_diff.days / 7 or num_weeks = (time_diff / 7).days -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From kbk at shore.net Fri May 19 23:24:26 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 19 May 2006 23:24:26 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200605200324.k4K3OQR1004951@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 378 open ( +0) / 3238 closed (+22) / 3616 total (+22) Bugs : 907 open (+13) / 5831 closed (+20) / 6738 total (+33) RFE : 218 open ( +2) / 217 closed ( +2) / 435 total ( +4) New / Reopened Patches ______________________ Patch fixing #1481770 (wrong shared lib ext on hpux ia64) (2006-05-07) CLOSED http://python.org/sf/1483325 opened by David Everly Add new top-level domains to cookielib (2006-05-07) CLOSED http://python.org/sf/1483395 reopened by jjlee Add new top-level domains to cookielib (2006-05-07) CLOSED http://python.org/sf/1483395 opened by John J Lee Wave.py support for ulaw and alaw audio (2006-05-07) http://python.org/sf/1483545 opened by Eric Woudenberg tarfile.py fix for #1471427 and updates (2006-05-09) CLOSED http://python.org/sf/1484695 opened by Lars Gust?bel cookielib: reduce (fatal) dependency on "beta" logging? (2006-05-09) CLOSED http://python.org/sf/1484758 opened by kxroberto urllib2: resolves extremly slow import (of "everything") (2006-05-09) CLOSED http://python.org/sf/1484793 opened by kxroberto HTMLParser : A auto-tolerant parsing mode (2006-05-11) http://python.org/sf/1486713 opened by kxroberto Patches and enhancements to turtle.py (2006-05-11) CLOSED http://python.org/sf/1486962 opened by Vern Ceder MacOSX: distutils support for -arch and -isysroot flags (2006-05-13) http://python.org/sf/1488098 opened by Ronald Oussoren Memory alignment fix on SPARC (2006-05-14) CLOSED http://python.org/sf/1488312 opened by Jan Palus tarfile.py: support for file-objects and bz2 (cp. #1488634) (2006-05-15) CLOSED http://python.org/sf/1488881 opened by Lars Gust?bel Updates to syntax rules in reference manual (2006-05-16) http://python.org/sf/1489771 opened by ?iga Seilnacht Patch for the urllib2 HOWTO (2006-05-16) CLOSED http://python.org/sf/1489784 opened by Mike Foord fix typo in os.utime() docstring (2006-05-17) CLOSED http://python.org/sf/1490189 opened by M. Levinson add os.chflags() and os.lchflags() where available (2006-05-17) http://python.org/sf/1490190 opened by M. Levinson time.altzone does not include DST offset on Cygwin (2006-05-17) CLOSED http://python.org/sf/1490224 opened by Christian Franke PC new-logo-based icon set (2006-05-17) http://python.org/sf/1490384 opened by Andrew Clover Describe Py_DEBUG and friends... (2006-05-18) http://python.org/sf/1490989 opened by Skip Montanaro IDLE L&F on MacOSX (2006-05-19) http://python.org/sf/1491759 opened by Ronald Oussoren Simple slice support for list.sort() and .reverse() (2006-05-19) http://python.org/sf/1491804 opened by Heiko Wundram Complex representation (2006-05-19) http://python.org/sf/1491866 opened by Heiko Wundram Fix for bug #1486663 mutable types check kwargs in tp_new (2006-05-20) http://python.org/sf/1491939 opened by ?iga Seilnacht Patches Closed ______________ applesingle endianness issue (2004-06-30) http://python.org/sf/982340 closed by gbrandl Patch fixing #1481770 (wrong shared lib ext on hpux ia64) (2006-05-07) http://python.org/sf/1483325 closed by loewis Add new top-level domains to cookielib (2006-05-07) http://python.org/sf/1483395 closed by gbrandl Add new top-level domains to cookielib (2006-05-07) http://python.org/sf/1483395 closed by gbrandl Heavy revisions to urllib2 howto (2006-05-01) http://python.org/sf/1479977 closed by akuchling Make urllib2 digest auth and basic auth play together (2006-04-30) http://python.org/sf/1479302 closed by gbrandl Take advantage of BaseException/Exception split in cookielib (2006-04-29) http://python.org/sf/1478993 closed by gbrandl tarfile.py fix for #1471427 and updates (2006-05-09) http://python.org/sf/1484695 closed by gbrandl cookielib: reduce (fatal) dependency on "beta" logging? (2006-05-09) http://python.org/sf/1484758 closed by gbrandl urllib2: resolves extremly slow import (of "everything") (2006-05-09) http://python.org/sf/1484793 closed by gbrandl Fix doctest nit. (2006-04-28) http://python.org/sf/1478292 closed by tim_one Remote debugging with pdb.py (2003-04-14) http://python.org/sf/721464 closed by gbrandl urllib2: better import ftplib and gopherlib etc late (2004-10-24) http://python.org/sf/1053150 closed by loewis detect %zd format for PY_FORMAT_SIZE_T (2006-04-22) http://python.org/sf/1474907 closed by bcannon Patches and enhancements to turtle.py (2006-05-11) http://python.org/sf/1486962 closed by gbrandl Improve docs for tp_clear and tp_traverse (2006-04-19) http://python.org/sf/1473132 closed by tim_one Memory alignment fix on SPARC (2006-05-14) http://python.org/sf/1488312 closed by nnorwitz tarfile.py: support for file-objects and bz2 (cp. #1488634) (2006-05-15) http://python.org/sf/1488881 closed by gbrandl Add copy() method to zlib's compress and decompress objects (2006-02-20) http://python.org/sf/1435422 closed by gbrandl Patch for the urllib2 HOWTO (2006-05-16) http://python.org/sf/1489784 closed by gbrandl fix typo in os.utime() docstring (2006-05-17) http://python.org/sf/1490189 closed by gbrandl time.altzone does not include DST offset on Cygwin (2006-05-17) http://python.org/sf/1490224 closed by gbrandl great improvement for locale.py formatting functions (2005-04-10) http://python.org/sf/1180296 closed by gbrandl New / Reopened Bugs ___________________ docs for 'profile' should refer to pstats.Stats (2006-05-06) CLOSED http://python.org/sf/1482988 opened by Ori Peleg Objects/genobject.c:53: gen_iternext: Assertion `f->f_back ! (2006-05-07) http://python.org/sf/1483133 opened by svensoho Add set.member() method (2006-05-07) CLOSED http://python.org/sf/1483384 opened by Michael Tsai Doctest bug (2006-05-08) CLOSED http://python.org/sf/1483785 opened by stnsls struct.unpack problem with @, =, < specifiers (2006-05-08) http://python.org/sf/1483963 opened by Christian Hudon pydoc doesn't create html-file (2006-05-08) CLOSED http://python.org/sf/1483997 opened by Gregor Lingl hyper-threading locks up sleeping threads (2006-05-08) http://python.org/sf/1484172 opened by Olaf Meding Output of KlocWork on Python2.4.3 sources (2006-05-09) http://python.org/sf/1484556 opened by Miki Tebeka ctypes documenation obscure and incomplete (2006-05-09) http://python.org/sf/1484580 opened by Nicko van Someren Doc for new_panel() missing scope info (2006-05-09) CLOSED http://python.org/sf/1484978 opened by Troels Therkelsen The name is qmail, not Qmail (2006-05-09) CLOSED http://python.org/sf/1485280 opened by David Phillips subprocess.Popen + cwd + relative args[0] (2006-05-10) CLOSED http://python.org/sf/1485447 opened by Mark Sheppard httplib: read/_read_chunked failes with ValueError sometime (2006-05-11) http://python.org/sf/1486335 opened by kxroberto Over-zealous keyword-arguments check for built-in set class (2006-05-11) http://python.org/sf/1486663 opened by dib OS X framework build for python 2.5 fails, configure is odd (2006-05-11) http://python.org/sf/1486897 opened by Christopher Knox No examples or usage docs for urllib2 (2004-04-29) CLOSED http://python.org/sf/944394 reopened by fresh 2.5 rev 45972 fails build on Mac-Intel (2006-05-12) http://python.org/sf/1487105 opened by Alex Martelli datetime.time and datetime.timedelta (2006-05-12) http://python.org/sf/1487389 opened by Chris Withers can't pickle slice objects (2006-05-12) http://python.org/sf/1487420 opened by ganges master Could BIND_FIRST be removed on HP-UX? (2006-05-12) http://python.org/sf/1487481 opened by G?ran Uddeborg SystemError with conditional expression in assignment (2006-05-13) CLOSED http://python.org/sf/1487966 opened by ?iga Seilnacht tarfile.TarFile.open can might incorrectly raise ValueError (2006-05-15) CLOSED http://python.org/sf/1488634 opened by Andrew Bennetts appended file on Windows reads arbitrary data (2006-05-15) CLOSED http://python.org/sf/1488717 opened by muimi appended file on Windows reads arbitrary data (2006-05-15) CLOSED http://python.org/sf/1488779 opened by muimi endless loop in PyCFunction_Fini() (2006-05-15) http://python.org/sf/1488906 opened by Matejcik Multiple dots in relative import statement raise SyntaxError (2006-05-15) http://python.org/sf/1488915 opened by ?iga Seilnacht file.write + closed pipe (2006-05-15) http://python.org/sf/1488934 opened by Erik Demaine difflib.Differ() doesn't always add hints for tab characters (2006-05-16) http://python.org/sf/1488943 opened by Henry keyword and topic help broken in Pythonwin IDE (2006-05-15) http://python.org/sf/1489051 opened by BartlebyScrivener 2.4.3 fails to find Tcl/Tk on Solaris 10 x86_64 (2006-05-15) http://python.org/sf/1489246 opened by Tim Mooney time module missing from global mod index (2006-05-16) http://python.org/sf/1489648 opened by Skip Montanaro %g incorrect conversion (2006-05-18) CLOSED http://python.org/sf/1490688 opened by paul rubin urllib.retrieve's reporthook called with non-helpful value (2006-05-18) http://python.org/sf/1490929 opened by Sidnei da Silva glob_to_re problems (2006-05-19) http://python.org/sf/1491431 opened by Wayne Davison argvemulator doesn't work on intel mac (2006-05-19) http://python.org/sf/1491468 opened by Ronald Oussoren distutils adds (unwanted) -xcode=pic32 in the compile comman (2006-05-19) http://python.org/sf/1491574 opened by Toon Knapen Pickle & schizofrenic classes don't match (2006-05-19) CLOSED http://python.org/sf/1491688 opened by Ronald Oussoren Bugs Closed ___________ asyncore is not listed in test_sundry (2006-05-05) http://python.org/sf/1482746 closed by gbrandl docs for 'profile' should refer to pstats.Stats (2006-05-06) http://python.org/sf/1482988 closed by gbrandl tarfile.py chokes on long names (2006-04-16) http://python.org/sf/1471427 closed by gbrandl hpux ia64 shared lib ext should be ".so" (2006-05-04) http://python.org/sf/1481770 closed by nnorwitz Doctest bug (2006-05-08) http://python.org/sf/1483785 deleted by stnsls pydoc doesn't create html-file (2006-05-08) http://python.org/sf/1483997 closed by gbrandl ctypes extension does not compile on Mac OS 10.3.9 (2006-03-29) http://python.org/sf/1460514 closed by theller Doc for new_panel() missing scope info (2006-05-09) http://python.org/sf/1484978 closed by gbrandl Python does not check for POSIX compliant open() modes (2006-03-31) http://python.org/sf/1462152 closed by gbrandl Building without C++ should not fail. (2005-12-26) http://python.org/sf/1390321 closed by loewis The name is qmail, not Qmail (2006-05-10) http://python.org/sf/1485280 closed by gbrandl subprocess.Popen + cwd + relative args[0] (2006-05-10) http://python.org/sf/1485447 closed by gbrandl urllib2: better import ftplib and gopherlib etc late (2004-10-13) http://python.org/sf/1046077 closed by loewis No examples or usage docs for urllib2 (2004-04-29) http://python.org/sf/944394 closed by loewis No examples or usage docs for urllib2 (04/29/04) http://python.org/sf/944394 closed by sf-robot long path support in win32 part of os.listdir(posixmodule.c) (2006-02-14) http://python.org/sf/1431582 closed by loewis SystemError with conditional expression in assignment (2006-05-13) http://python.org/sf/1487966 closed by nnorwitz subprocess _active.remove(self) self not in list _active (05/10/05) http://python.org/sf/1199282 closed by sf-robot tarfile.TarFile.open can might incorrectly raise ValueError (2006-05-15) http://python.org/sf/1488634 closed by gbrandl appended file on Windows reads arbitrary data (2006-05-15) http://python.org/sf/1488717 closed by tim_one appended file on Windows reads arbitrary data (2006-05-15) http://python.org/sf/1488779 closed by gbrandl %g incorrect conversion (2006-05-18) http://python.org/sf/1490688 closed by gbrandl non-keyword argument following keyword (2006-04-22) http://python.org/sf/1474677 closed by nnorwitz Pickle & schizofrenic classes don't match (2006-05-19) http://python.org/sf/1491688 closed by ronaldoussoren New / Reopened RFE __________________ Backwards compatibility support for Py_ssize_t (2006-05-10) http://python.org/sf/1485576 opened by Konrad Hinsen str.startswith/endswith could take a tuple? (2006-05-19) http://python.org/sf/1491485 opened by Tom Lynn RFE Closed __________ Add set.member() method (2006-05-07) http://python.org/sf/1483384 closed by rhettinger Drop py.ico and pyc.ico (2006-04-27) http://python.org/sf/1477968 closed by loewis From almer.maria at gmail.com Sat May 27 05:18:54 2006 From: almer.maria at gmail.com (maria) Date: 27 May 2006 02:18:54 -0700 Subject: CMFBoard Message-ID: <1148721534.535888.21460@y43g2000cwc.googlegroups.com> Hi everybody! I use CMFBoard 2.2.1 as a discussion board on my website. I want to open the forum to all users, anonymous and registred users! But my problem is, that whenever an ano user posts a topic, the overview doesn't display the message correctly. Instead of a table containing topic-title, short description, last reply, user...... there is only some text shown, like this: {'last_reply_created': '2006-05-27 09:36', 'msgIcon': ' ', 'Title': 'test', 'actions': {'reply': 'http:/..../forumfolder.2006-05-27.1751137831/public/0002/forum_reply_form', 'delete': 'http:/..../forumfolder.2006-05-27.1751137831/public/0002/forum_message_delete_form'}, 'topic': , 'last_user': 'Anonymous User', 'topicIcon': u'', 'Description': '', 'creator': 'admin', 'replyCount': 1, 'msg': , 'review_state': 'published', 'topicId': '0002', 'last_reply_title': '', 'topicDesc': u'', 'pages_links': [], 'view_mode': 'flat', 'last_reply_topic': 0, 'anonymous': 1, 'last_user_isanon': 1, 'icon': 'Normal topic ', 'hits': 1, 'created': '2006-05-27 09:35', 'url': 'http://..../forumfolder.2006-05-27.1751137831/public/0002', 'sticky_flag': 1, 'last_reply_link': 'http:/..../forumfolder.2006-05-27.1751137831/public/0002/0002'} I would be very happy, if anyone can help me!! Best regards, Maria From luismgz at gmail.com Fri May 19 14:28:23 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 19 May 2006 11:28:23 -0700 Subject: combining a C# GUI with Python code? In-Reply-To: <3Dnbg.2135$No6.46516@news.tufts.edu> References: <3Dnbg.2135$No6.46516@news.tufts.edu> Message-ID: <1148063303.620372.281600@j55g2000cwa.googlegroups.com> Now that I think about it, I'm not sure if Visual Studio can create GUIs with ironpython already. I guess that at this moment, its integration is as a text editor only (I may be wrong though). I almost forgot it, but someone was working in a little tool that converts C# forms into python classes (for being used with ironpython). Check it out: http://www.digitalfanatics.org/e8johan/projects/cs2py/ From kentilton at gmail.com Fri May 12 17:38:39 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 12 May 2006 17:38:39 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Alexander Schmolck wrote: > Ken Tilton writes: > > >>In Common Lisp we would have: >> >> (defvar *x*) ;; makes it special >> (setf *x* 1) >> (print *x*) ;;-> 1 >> (let ((*x* 2)) >> (print *x*)) ;; -> 2 >> (print *x*) ;; -> 1 > > > You seem to think that conflating special variable binding and lexical > variable binding is a feature and not a bug. What's your rationale? Transparency. That is where power comes from. I did the same things with Cells. Reading a slot with the usual Lisp reader method transparently creates a dependency on the variable. To change a variable and have it propagate throughout the datamodel, Just Change It. Exposed wiring means more work and agonizing refactoring. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From jorge.vargas at gmail.com Fri May 5 08:18:06 2006 From: jorge.vargas at gmail.com (jorge.vargas at gmail.com) Date: 5 May 2006 05:18:06 -0700 Subject: ConfigParser and multiple option names In-Reply-To: References: Message-ID: <1146831486.852415.5070@i39g2000cwa.googlegroups.com> that will break horribly in windows, remenber it install all it's crap in c:\Program Files From oweston at earthlink.net Mon May 22 14:45:38 2006 From: oweston at earthlink.net (wes weston) Date: Mon, 22 May 2006 18:45:38 GMT Subject: Class probkem - getting msg that self not defined In-Reply-To: <12740frcoaju883@corp.supernews.com> References: <12740frcoaju883@corp.supernews.com> Message-ID: Andrew Robert wrote: > Hi Everyone, > > I am having a problem with a class and hope you can help. > > When I try to use the class listed below, I get the statement that self > is not defined. > > test=TriggerMessage(data) self is not known here; only inside the class. > var = test.decode(self.qname) > > I would have thought that self would have carried forward when I grabbed > an instance of TriggerMessage. > > Any ideas on this? > > > > The class in question is: > > > class TriggerMessage(object): > > def __init__(self,data): > """ > Unpacks the passed binary data based on the MQTCM2 format dictated in > the MQ Application Programming Reference > """ > > self.data=data > self.structid=None > self.version=None > self.qname=None > self.procname=None > self.trigdata=None > self.appltype=None > self.applid=None > self.envdata=None > self.userdata=None > self.qmgr=None > > > def decode(self): > import struct > format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' > size=struct.calcsize(format) > self.data=data > self.structid, self.version, self.qname, self.processname, \ > self.triggerdata, self.appltype, self.applid, \ > self.envdata, self.userdata, self.qmgr \ > = struct.unpack(format,self.data) From dadapapa at googlemail.com Fri May 19 11:16:25 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 19 May 2006 08:16:25 -0700 Subject: Feature request: sorting a list slice In-Reply-To: References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> Message-ID: <1148051785.512160.58300@g10g2000cwb.googlegroups.com> Fredrik Lundh wrote: > George Sakkis wrote: > > > It would be useful if list.sort() accepted two more optional > > parameters +1 > useful for what? what's the use case ? Actually, I was in need of such a construct only few weeks ago. The task was to organize playlists of an mp3 player. I wanted to sort future entries but not past ones (according to an index in the list that seperates past from future). I can imagine many more situations in which sorting part of a list is usefull. While I agree that the improvement of the additional keywords is minor, I think that the additional load they impose on the sort function is also minor. In my oppinion, this is a straight-forward extension of what we already find in other places in the library. I would like to see it in a future version. - harold - From bdesth.quelquechose at free.quelquepart.fr Fri May 19 23:00:54 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 May 2006 05:00:54 +0200 Subject: altering an object as you iterate over it? In-Reply-To: <446e1def$0$6919$626a54ce@news.free.fr> References: <1Mobg.2139$No6.46432@news.tufts.edu> <446e1def$0$6919$626a54ce@news.free.fr> Message-ID: <446e573a$0$4960$626a54ce@news.free.fr> bruno at modulix a ?crit : (snip) (responding to myself) (but under another identity - now that's a bit schizophrenic, isn't it ?-) > For the general case, the best way to go would probably be an iterator: > > def iterfilter(fileObj): > for line in fileObj: > if line.strip(): > yield line > > > f = open(path, 'r') > for line in iterfilter(f): > doSomethingWith(line) Which is good as an example of simple iterator, but pretty useless since we have itertools : import itertools f = open(path, 'r') for line in itertools.ifilter(lambda l: l.strip(), f): doSomethingWith(line) f.close() From micklee74 at hotmail.com Thu May 11 11:20:57 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 11 May 2006 08:20:57 -0700 Subject: find all index positions Message-ID: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> hi say i have string like this astring = 'abcd efgd 1234 fsdf gfds abcde 1234' if i want to find which postion is 1234, how can i achieve this...? i want to use index() but it only give me the first occurence. I want to know the positions of both "1234" thanks From nobody at 127.0.0.1 Wed May 17 14:37:06 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 18:37:06 GMT Subject: python vs perl lines of code References: Message-ID: John Bokma wrote: > Edward Elliott wrote: >> Evaluating my experiences yes, relating your own no. > > What would the point be? Most important to me would be: am I happy with > the result? And that rarely has to do with the number of lines of actual > code or the programming language. A language is just a tool. The point is knowing how to pick the right tool for the right job. Anecdotes aren't the answer but they can be the beginning of the question. Besides, whatever happened to pursuing knowledge for its own sake? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From Patrick.John.Wheeler at gmail.com Sun May 14 19:30:16 2006 From: Patrick.John.Wheeler at gmail.com (pjw) Date: 14 May 2006 16:30:16 -0700 Subject: any plans to make pprint() a builtin? In-Reply-To: <44669e46$0$5337$c3e8da3@news.astraweb.com> References: <44669e46$0$5337$c3e8da3@news.astraweb.com> Message-ID: <1147649416.553657.238010@j73g2000cwa.googlegroups.com> It has been proposed to replace the current print statement with a print function for python 3.0. http://www.python.org/dev/peps/pep-3100/ >From BDFL state of the python union: " print x, y, x becomes print(x, y, z) print >>f, x, y, z becomes print(x, y, z, file=f) " From martin at v.loewis.de Tue May 30 02:13:54 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 30 May 2006 08:13:54 +0200 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> Message-ID: <447BE2A2.80000@v.loewis.de> Roy Smith wrote: > My guess would be that each resize grows the table by a constant > factor, which IIRC, works out to amortized O(n). Right. For <50000 entries, the size is multiplied by 4 each time, and doubled each time for large dictionaries. > It's not as good as > creating the dict the right size in the first place, but it's really > not that bad. Somewhat more troubling is that it can lead to memory > fragmentation problems. Depends on your operating system, of course. You get over a page size fairly quickly, and then many systems use anonymous mappings, where a range of pages gets mapped from swap on allocation, and unmapped on deallocation. So while this can cause address space fragmentation, it doesn't cause memory fragmentation (i.e. memory that is allocated by the process but can't be used). > I don't understand why Python doesn't have a way to give a size hint > when creating a dict. It seems so obvious to be able to say "d = dict > (size=10*1000*1000)" if you know beforehand that's how many keys > you're going to add. There is no need for it. If dicts don't work well in some cases, these cases should be investigated and fixed, instead of working around the problem by loading the problem onto the developer. As you said, it *should* have linear time, with the number of insertions. If it doesn't (and it appears not to), that may be due to hash collisions, or due to the time for computing hashes not being constant. Regards, Martin From robert.kern at gmail.com Thu May 11 16:02:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 15:02:08 -0500 Subject: segmentation fault in scipy? In-Reply-To: <1147376927.857632.310430@j33g2000cwa.googlegroups.com> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> <1147373294.235202.188220@y43g2000cwc.googlegroups.com> <1147376927.857632.310430@j33g2000cwa.googlegroups.com> Message-ID: py_genetic wrote: >>No! matrix objects use matrix multiplication for *. You seem to need elementwise >>multiplication. > > No! when you mult a vector with itself transposed, the diagonal of the > resulting matrix is the squares of each error (albeit you do a lot of > extra calc), then sum the squares, ie trace(). Its a nifty trick, if > you don't have too much data 25000x25000 matrix in mem and youre using > matricies ie. batch learning. The actual equation includes multiply by > 1/2*(sum of the squares), but mean squared error can be more telling > about error and cross entropy is even better, becuase it tells you how > well youre predicting the posterior probabilies... Now I'm even more confused. What kind of array is "error" here? First you tell me it's a (25000, 80) array and now you are telling me it is a (25000,) array. Once you've defined what "error" is, then please tell me what the quantity is that you want to calculate. I think I told you several different wrong things, previously, based on wrong assumptions. -- 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 luis_lupe2XXX at netvisaoXXX.pt Tue May 9 07:56:10 2006 From: luis_lupe2XXX at netvisaoXXX.pt (Luis P. Mendes) Date: Tue, 09 May 2006 12:56:10 +0100 Subject: ascii to latin1 In-Reply-To: References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> Message-ID: <4460831e$0$15794$14726298@news.sunsite.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Richie Hindle escreveu: > [Serge] >> def search_key(s): >> de_str = unicodedata.normalize("NFD", s) >> return ''.join(cp for cp in de_str if not >> unicodedata.category(cp).startswith('M')) > > Lovely bit of code - thanks for posting it! > > You might want to use "NFKD" to normalize things like LATIN SMALL > LIGATURE FI and subscript/superscript characters as well as diacritics. > Thank you very much for your info. It's a very good aproach. When I used the "NFD" option, I came across many errors on these and possibly other codes: \xba, \xc9, \xcd. I tried to use "NFKD" instead, and the number of errors was only about half a dozen, for a universe of 600000+ names, on code \xbf. It looks like I have to do a search and substitute using regular expressions for these cases. Or is there a better way to do it? Luis P. Mendes -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEYINaHn4UHCY8rB8RAqLKAJ0cN7yRlzJSpmH7jlrWoyhUH1990wCgkxCW 9d7f/FyHXoSfRUrbES0XKvU= =eAuO -----END PGP SIGNATURE----- From onurb at xiludom.gro Wed May 24 08:41:28 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 24 May 2006 14:41:28 +0200 Subject: Best way to handle exceptions with try/finally In-Reply-To: References: Message-ID: <447454e4$0$23689$626a54ce@news.free.fr> Carl J. Van Arsdall wrote: (snip) Not an answer to your question, just a few comments on your code: > class Shared: class Shared(object): > def __init__(self): > self.__userData= {} > self.__mutex = threading.Lock() #lock object Don't use __names unless you have a *really* strong reason to do so. 'protected' attributes are usually noted as _name. > def getVar(self, variableName): > temp = None > error = 0 > self.__mutex.acquire() #accessing shared dictionary > try: > try: > temp = self.__userData[variableName] > except: Don't use bare except clauses. Specify the exceptions you intend to handle, let the other propagate. I once spent many hours trying to debug a badly written module that has such a catch-all clause with a misleading error message saying some file could not be opened when the actual problem was with a wrong login/pass for a connection. > print "Variable doesn't exist in shared > space" stdout is for normal program outputs. Error messages should go to stderr. > raise ValueError Should be a LookupError subclass. And the message should go with the exception: raise MyLookupErrorSubclass("Variable '%s' doesn't exist in shared space" % variableName) > finally: > self.__mutex.release() > return temp > > def putVar(self, variableName, value): > self.__mutex.acquire() #accessing shared dictionary > try: > self.__userData[variableName] = value > finally: > self.__mutex.release() > return The return statement is useless here. 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 max at alcyone.com Fri May 19 15:17:00 2006 From: max at alcyone.com (Erik Max Francis) Date: Fri, 19 May 2006 12:17:00 -0700 Subject: Why does the _winreg module start with an underscore In-Reply-To: References: Message-ID: 3c273 wrote: > Does it signify something? Just curious. Dear quasar, Typically an identifier starting with an underscore signifies something that is not intended to be exposed as part of a public API. In other words, it's an implementation detail in whatever you're using and as such you probably shouldn't use it or rely on it, unless you know the internal details very well. An identifier starting with _two_ underscores is automatically mangled in a way that makes it more difficult (but not impossible) for external clients to accidentally use them. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis I wonder if heaven got a ghetto -- Tupac Shakur From nospam at nospam.nospam Mon May 15 04:59:30 2006 From: nospam at nospam.nospam (Nic) Date: Mon, 15 May 2006 10:59:30 +0200 Subject: List and order Message-ID: <446842f7$0$14785$4fafbaef@reader4.news.tin.it> Hello, I'm using the NetworkX Python package (https://networkx.lanl.gov/). Through this package I wrote the following code: import networkx as NX G=NX.Graph() G.add_edge(1,2) G.add_edge(2,3) G.add_edge(3,4) ddeg=G.degree(with_labels=True) for (u,v) in G.edges(): print ddeg[u],ddeg[v] As result, I have: 12 22 21 I'd like to order the numbers included in the couples in a decrescent way: 12 12 22 And then to write the couples on a single line, always in a decrescent way: 12 12 22 I'm not able to do this operation. Can you help me please? Thanks a bunch, Nic From gandalf at designaproduct.biz Fri May 26 11:58:59 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 26 May 2006 17:58:59 +0200 Subject: Running Python scripts under a different user In-Reply-To: <4dolv4F1b8m87U1@uni-berlin.de> References: <4dolv4F1b8m87U1@uni-berlin.de> Message-ID: <447725C3.2000901@designaproduct.biz> Hello Diez, Please see below. > And as you refrain form telling us which OS you are running under one > can only be very vague on what to suggest - UNIXish OSes have for > example the setguid-bit, sudo springs to mind and under certain desktops > there are ways to acquire root-settings (but you need a password then I > guess) > > Windows I don't know so much - but there exist the possibility to make a > program run under a different user-account. > For Windows, you can use the 'runas.exe' program. But it requires a password too. From what you wrote, I think that you need to change architecture. You should write your own service rather than write tricky programs. This way you can develop your own security system, and restrict access to specific files/programs. You can write tools that can connect to your service. The service program can be ran on the background, with sufficient privileges. How does it sound? Best, Laszlo From eligottlieb at gmail.com Tue May 23 10:12:23 2006 From: eligottlieb at gmail.com (Eli Gottlieb) Date: Tue, 23 May 2006 14:12:23 GMT Subject: Software Needs Philosophers In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> Message-ID: John D Salt wrote: > wrote in news:4dbartF19cb9rU1 at uni-berlin.de: > > [Snips] > >>Wrong. We live in a paradise of ideas and possibilities well beyond the >>wildest dreams of only 20 years ago. > > > What exciting new ideas exist in software that are both important and > cannot be traced back to 1986 or earlier? > > I'd like to believe that there are some, but I can't think of any at the > moment. > > All the best, > > John. I correct: We live in a paradise where we finally have to processing power to realize all those ideas that were too inefficient 20 years ago. -- The science of economics is the cleverest proof of free will yet constructed. From nnorwitz at gmail.com Tue May 9 01:28:04 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 8 May 2006 22:28:04 -0700 Subject: python 2.5a2, gcc 4.1 and memory problems In-Reply-To: References: <1146969449.567022.245750@u72g2000cwu.googlegroups.com> Message-ID: <1147152484.680747.20000@i39g2000cwa.googlegroups.com> Michele Petrazzo wrote: > nnorwitz at gmail.com wrote: > > Michele Petrazzo wrote: > >> I haven't tried to recompile py 2.4 myself with gcc 4.1 because it > >> is already compiled with it (4.0.3), so I think (only think) that > >> is a py 2.5 problem. I'm right? or I have to compile it with > >> something other switches? > > > > Sounds like a gcc problem to me. Try adding --with-pydebug in the > > configure options. My guess is that it will work. This option > > enables asserts, but more importantly disables optimization. > > Yes, with this option it work, but has very bad performances. Sure, you didn't say if you tried just disabling optimization. That is often a problem. configure normally, but change the optimization from -O3 to -O0, -O1, and -O2. My guess is that -O1 will work and -O2 won't. Even -O0 will be faster than --with-pydebug since assertions won't be enabled (you may need to pass --without-pydebug to disable the option). n From keir.robinson at gmail.com Wed May 3 17:13:28 2006 From: keir.robinson at gmail.com (keirr) Date: 3 May 2006 14:13:28 -0700 Subject: This coding style bad practise? References: <44591463$0$31639$e4fe514c@news.xs4all.nl> Message-ID: <1146690808.394459.278670@g10g2000cwb.googlegroups.com> Martin P. Hellwig wrote: > Hi all, > > I created a class which creates a relative unique id string, now my > program just works fine and as expected but somehow I get the feeling > that I misused the __repr__ since I guess people expect to 'execute' a > function in an instance instead of using it's representation string of > the instance itself, could you elaborate whether you find this bad > practice and if yes what would have been a better way to do it? > > TIA > Rather than comment on the style of using a class, I'll just suggest an alternative. You can use a generator function, which yields the next id when called; at least that's how I'd implement an IDgenerator. Cheers, Keir. From none at bno.be Thu May 18 12:36:12 2006 From: none at bno.be (of) Date: Thu, 18 May 2006 18:36:12 +0200 Subject: Complex evaluation bug Message-ID: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> a = 1+3j complex(str(a)) Why does this not work ? It should From brochu121 at gmail.com Tue May 2 16:06:21 2006 From: brochu121 at gmail.com (brochu121 at gmail.com) Date: 2 May 2006 13:06:21 -0700 Subject: Check IE toolbar visible Message-ID: <1146600381.860698.129260@g10g2000cwb.googlegroups.com> I have to install a toolbar and by default make it visible in IE..any idea how i would do that? From meyer.p at gmail.com Wed May 17 13:10:43 2006 From: meyer.p at gmail.com (Pierre) Date: 17 May 2006 10:10:43 -0700 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <9bKdnakiGs9Cy_bZRVn-qw@comcast.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> <9bKdnakiGs9Cy_bZRVn-qw@comcast.com> Message-ID: <1147885843.162424.133030@i40g2000cwc.googlegroups.com> Nop I get the same AttributeError when I try to access to the property "c"... From sybrenUSE at YOURthirdtower.com.imagination Wed May 31 03:54:00 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 31 May 2006 09:54:00 +0200 Subject: An algorithm problem References: Message-ID: Bo Yang enlightened us with: > I have writen a python program to slove a problem described as > below: Please post again, but then leaving indentation intact, since this is unreadable. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From fredrik at pythonware.com Thu May 18 10:24:22 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 16:24:22 +0200 Subject: Question about exausted iterators In-Reply-To: <446c7f44$0$7128$626a54ce@news.free.fr> References: <446b48e2$0$5293$626a54ce@news.free.fr> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <446c7f44$0$7128$626a54ce@news.free.fr> Message-ID: Christophe wrote: >>> Because I'm still waiting for a valid answer to my question. The >>> answer "Because it has been coded like that" or is not a valid one. >> >> it's been coded like that because that's what the specification says: >> >> http://www.python.org/dev/peps/pep-0234/ > > I didn't though I had to mention that "Because the spec has been writen > like that" wasn't a valid answer either. so what is a valid answer? From Avizoa at gmail.com Sun May 21 19:29:42 2006 From: Avizoa at gmail.com (Avizoa at gmail.com) Date: 21 May 2006 16:29:42 -0700 Subject: performance difference between OSx and Windows In-Reply-To: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> Message-ID: <1148254182.824583.195370@i40g2000cwc.googlegroups.com> Brian wrote: > I have been a Mac and linux guy since 1998 and except for a handful of > times, have not touched a MS box since then. This changes a few days > ago when I needed to get a MS box for another project. This leads me > to my question... > > A while ago, I borrowed a python script from someone's blog that showed > some interesting profiling schemes. I made some modifications to it, > ran it and until I got this new machine forgot about it. Just for > kicks I ran it again on both boxes to see what the differences were. > To say I was surprised is an understatement. Here is the code: *snip* > > While the CPU speed on the G5 was faster the total execution time was > much quicker on the MS box. Can anyone give some suggestions as to why > this is? > > Thanks, > Brian 1. Your test only makes use of one core. So it's a comparison between a G5 and an Athlon 64. Which brings us to... 2. The K8 architecture is, in most operations, far superior to the G5 architecture, Apple's benchmarks notwithstanding. You see, the way IBM cut down its Power 4 to make the PPC970 left it a bit weak it the heavy lifting ability. The K8, however, is heir to the amazing Alpha architecture's legacy. While the G5 has no problems beating out the marketing-driven P4 architecture, it can't compete clock for clock with the K8. From tim.peters at gmail.com Sat May 20 15:04:49 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 20 May 2006 15:04:49 -0400 Subject: Decimal and Exponentiation In-Reply-To: <1qHbg.4012$8T4.2045@tornado.rdc-kc.rr.com> References: <1148060287.088387.41150@j55g2000cwa.googlegroups.com> <1qHbg.4012$8T4.2045@tornado.rdc-kc.rr.com> Message-ID: <1f7befae0605201204r2e209982odb936f6f97884acb@mail.gmail.com> [Raymond L. Buvel, on http://calcrpnpy.sourceforge.net/clnumManual.html ] >>> The clnum module handles this calculation very quickly: >>> >>> >>> from clnum import mpf >>> >>> mpf("1e10000") ** mpf("3.01") >>> mpf('9.9999999999999999999999932861e30099',26) [Tim Peters] >> That's probably good enough for the OP's needs -- thanks! >> >> OTOH, it's not good enough for the decimal module: >> >> (10**10000)**3.01 = >> 10**(10000*3.01) = >> 10**30100 >> >> exactly, and the proposed IBM standard for decimal arithmetic requires >> error < 1 ULP (which implies that if the mathematical ("infinite >> precision") result is exactly representable, then that's the result >> you have to get). It would take some analysis to figure out how much >> of clnum's error is due to using binary floats instead of decimal, and >> how much due to its pow implementation. [Raymond] > Indeed, it is not clear where the error is comming from especially since > you can increase the precision of the intermediate calculation and get > the exact result. > > >>> mpf(mpf("1e10000",30) ** mpf("3.01",30), 20) > mpf('1.0e30100',26) > > Is this the kind of thing you will need to do in the Decimal module to > meet the specification? It will vary by function and the amount of effort people are willing to put into implementations. Temporarily (inside a function's implementation) increasing working precision is probably the easiest way to get results provably suffering less than 1 ULP error in the destination precision. The "provably" part is the hardest part under any approach ;-) From clpy at russellsalsbury.com Thu May 4 20:46:11 2006 From: clpy at russellsalsbury.com (Russ Salsbury) Date: 4 May 2006 17:46:11 -0700 Subject: Swaying A Coder Away From Python In-Reply-To: <1146758592.602133.51630@g10g2000cwb.googlegroups.com> References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <1146758592.602133.51630@g10g2000cwb.googlegroups.com> Message-ID: <1146789970.966185.167520@j33g2000cwa.googlegroups.com> Adam Jones: """ User error, evidently. Sometimes the interface is more intelligent than its user, and every time this happens the interface is the one that gets the bad rap. """ Well that certainly explains my problems with Eclipse. From bignose+hates-spam at benfinney.id.au Wed May 17 19:25:33 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 09:25:33 +1000 Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> Message-ID: <871wusnsia.fsf@benfinney.id.au> "Michael Tobis" writes: > "The plural of anecdote is not data." > > It's a pithy quote, but it isn't QOTW in my book, simply because it > isn't true in general. Talk to some paleoclimatologists. > > There is no way to get uniform measures of ancient climate. What > should we do then? Should we ignore the information we have? Are the > fortuitously preserved fossils of the very deep past to be ignored > just because we can't get an unbiased sample? Those samples can be independently verified by any skilled observer at another time. This is what distinguishes them from anecdotes, and breaks your analogy. -- \ "I know you believe you understood what you think I said, but I | `\ am not sure you realize that what you heard is not what I | _o__) meant." -- Robert J. McCloskey | Ben Finney From kentilton at gmail.com Fri May 12 20:12:45 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 12 May 2006 20:12:45 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <7xy7x7m0wn.fsf@ruckus.brouhaha.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <7xy7x7m0wn.fsf@ruckus.brouhaha.com> Message-ID: <1w99g.54$vH7.47@fe09.lga> Paul Rubin wrote: > Alexander Schmolck writes: > >>> (defvar *x*) ;; makes it special >>> (setf *x* 1) >>> (print *x*) ;;-> 1 >>> (let ((*x* 2)) >>> (print *x*)) ;; -> 2 >>> (print *x*) ;; -> 1 >> >>You seem to think that conflating special variable binding and lexical >>variable binding is a feature and not a bug. What's your rationale? > > > I thought special variables meant dynamic binding, i.e. > > (defvar *x* 1) > (defun f () > (print *x*) ;; -> 2 > (let ((*x* 3)) > (g))) > (defun g () > (print *x*)) ;; - > 3 > > That was normal behavior in most Lisps before Scheme popularlized > lexical binding. IMO it was mostly an implementation convenience hack > since it was implemented with a very efficient shallow binding cell. > That Common Lisp adapted Scheme's lexical bindings was considered a > big sign of CL's couthness. So I'm a little confused about what Ken > Tilton is getting at. Paul, there is no conflict between your example and mine, but I can see why you think mine does not demonstrate dynamic binding: I did not demonstrate the binding applying across a function call. What might be even more entertaining would be a nested dynamic binding with the same function called at different levels and before and after each binding. I just had the sense that this chat was between folks who fully grokked special vars. Sorr if I threw you a curve. kenny From john at castleamber.com Tue May 16 09:24:25 2006 From: john at castleamber.com (John Bokma) Date: 16 May 2006 13:24:25 GMT Subject: Google-API Bad-Gateway-Error References: <1147783046.944898.43470@i39g2000cwa.googlegroups.com> <1147784189.292674.145010@i39g2000cwa.googlegroups.com> Message-ID: DierkErdmann at mail.com wrote: > It's quite strange, after calling the script several times it started > to work; but sometimes the error occurs again. Maybe google has > technical probs. Yup, I've seen exactly the same behavoir. So now I do several retry - sleep - retry steps before giving up. -- 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 sjmachin at lexicon.net Tue May 16 02:23:11 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2006 23:23:11 -0700 Subject: using target words from arrays in regex, pythons version of perls 'map' In-Reply-To: <1147760335.159838.146390@v46g2000cwv.googlegroups.com> References: <44691fc2$0$61162$ae4e5890@news.nationwide.net> <41mi62hih1d3i53nnhdkfi9tpil77bfdp7@4ax.com> <1147760335.159838.146390@v46g2000cwv.googlegroups.com> Message-ID: <1147760591.524083.21330@j55g2000cwa.googlegroups.com> Would you believe "steps 3 & 4"? From robin.meier at gmail.com Wed May 31 11:46:26 2006 From: robin.meier at gmail.com (robin) Date: 31 May 2006 08:46:26 -0700 Subject: problem with google api / xml In-Reply-To: <1149081715.924998.46430@f6g2000cwb.googlegroups.com> References: <1149066648.521045.152480@h76g2000cwa.googlegroups.com> <1149081715.924998.46430@f6g2000cwb.googlegroups.com> Message-ID: <1149090385.875462.172500@g10g2000cwb.googlegroups.com> hi kent, thanks for your reply. in fact it was me who put "pathtomy" into the path and exchanged my apikey with "...." i prefer not everyone to know the name of my directories and even less my apikey. so the problem isn't there :-( hope to find some other solution.... thanks!! robin Mike Kent wrote: > robin wrote: > > > from SOAPpy import WSDL > > WSDLFILE = '/pathtomy/googleapi/GoogleSearch.wsdl' > > APIKEY = '....' > > _server = WSDL.Proxy(WSDLFILE) > > Robin, note this part of the URI set in WSDLFILE: > '/pathtomy/googleapi'. Get it? 'path to my google api'. You must set > this part to the actual path where the file 'GoogleSearch.wsdl' is > found. In addition, doesn't APIKEY = '....' look a bit odd to you? > Hmm, what could this mean. APIKEY. Perhaps you need to get an API key > from Google in order to use their search API, and fill it in there? > > ;-) From luismgz at gmail.com Wed May 10 01:26:33 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 9 May 2006 22:26:33 -0700 Subject: Is PythonCard dead? In-Reply-To: <1147228229.133910.118410@g10g2000cwb.googlegroups.com> References: <1147228229.133910.118410@g10g2000cwb.googlegroups.com> Message-ID: <1147238793.364423.3800@g10g2000cwb.googlegroups.com> 18 months? Wow!.. time flies... Anyway, PythonCard is a fine product, and it's very good just the way it is. It would be great if a new release comes up though... From george.sakkis at gmail.com Wed May 24 12:00:30 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 24 May 2006 09:00:30 -0700 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148484597.410529.219960@j33g2000cwa.googlegroups.com> Message-ID: <1148486430.501620.175320@i39g2000cwa.googlegroups.com> Robert Boyd wrote: > On 24 May 2006 08:29:57 -0700, Rune Strand wrote: > > > > > I can just declare my support. Reading Mr. Bokmas comments below [*] > > certainly makes my suport stronger. > > > > I sent an email in support of Xah, which I wouldn't have bothered to > do had I not read the rapid-fire posts from Bokma which were abusive, > insulting, and arrogant. Xah's posts often make me roll my eyes, or I > skip them, but sometimes (and more so lately) they have been > intriguing and foster thought-provoking replies. I'd prefer debate and > discussion be fostered, rather than squelched. But what does this > clueless sock-puppet know? ;) It's funny how a single obnoxious self-righteous usenet-nazi can make a slightly annoying loonie look good. I'm sure Bokma's ISP will get some unfriendly emails about him soon, if this hasn't started happening already. From cvanarsdall at mvista.com Fri May 5 15:06:13 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 05 May 2006 12:06:13 -0700 Subject: easy way to dump a class instance? In-Reply-To: <8SL6g.73271$H71.63860@newssvr13.news.prodigy.com> References: <8SL6g.73271$H71.63860@newssvr13.news.prodigy.com> Message-ID: <445BA225.5090902@mvista.com> Mark Harrison wrote: > Is there a way to automatically print all the instance > data in a class? This is for debugging, I would like > to do something like dump(self) to snapshot the state > of the object. > > > Would something like cPickle work? That allows you to dump objects into files as they are and read them again as they were. Its fairly easy to use and might work well for you. HTH -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From songyi012133 at gmail.com Sat May 6 01:04:47 2006 From: songyi012133 at gmail.com (hankssong) Date: 5 May 2006 22:04:47 -0700 Subject: how to construct a binary-tree using python? References: <1146879397.871842.183790@u72g2000cwu.googlegroups.com> Message-ID: <1146891887.841835.159970@u72g2000cwu.googlegroups.com> I use google and get some detailed info in the page: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/286239 Carl J. Van Arsdall ,vdrab, thank for your help! From possibilitybox at gmail.com Wed May 24 15:43:31 2006 From: possibilitybox at gmail.com (possibilitybox at gmail.com) Date: 24 May 2006 12:43:31 -0700 Subject: Finding Upper-case characters in regexps, unicode friendly. Message-ID: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> I'm trying to make a unicode friendly regexp to grab sentences reasonably reliably for as many unicode languages as possible, focusing on european languages first, hence it'd be useful to be able to refer to any uppercase unicode character instead of just the typical [A-Z], which doesn't include, for example ?. Is there a way to do this, or do I have to stick with using the isupper method of the string class? From prinster at mail.com Fri May 5 22:06:11 2006 From: prinster at mail.com (Stephen Prinster) Date: Sat, 06 May 2006 02:06:11 GMT Subject: (question) How to use python get access to google search without query quota limit In-Reply-To: <1146829024.301402.282540@e56g2000cwe.googlegroups.com> References: <1146829024.301402.282540@e56g2000cwe.googlegroups.com> Message-ID: Per wrote: > I am doing a Natural Language processing project for academic use, > > I think google's rich retrieval information and query-segment might be > of help, I downloaded google api, but there is query limit(1000/day), > How can I write python code to simulate the browser-like-activity to > submit more than 10k queries in one day? Would Yahoo's API work for you? IIRC, it allows 5000 queries per day and up to 100 results per query. It also includes some easy-to-use Python examples. Or, if you are willing to pay for it, you can get as many queries as you want from Alexa. HTH, Steve P. From http Fri May 12 21:37:36 2006 From: http (Paul Rubin) Date: 12 May 2006 18:37:36 -0700 Subject: Python Translation of C# DES Encryption References: Message-ID: <7xac9mzov3.fsf@ruckus.brouhaha.com> Gary Doades writes: > http://twhiteman.netfirms.com/des.html I'm not sure if that's the same DES lib that I used in a project last year but as I remember, the lib I used had a bug in 3DES CBC mode that made it give answers incompatible with the NIST test vectors. It took considerable head scratching to figure out that the library was causing the problem. I ended up switching to a different library. Anyway, be careful. The library that I used did handle the 1DES CBC and 3DES ECB correctly, fwiw. From phddas at yahoo.com Mon May 8 01:49:43 2006 From: phddas at yahoo.com (Gary Wessle) Date: 08 May 2006 15:49:43 +1000 Subject: reading a column from a file Message-ID: <87y7xd83rc.fsf@localhost.localdomain> Hi I have a file with data like location pressure temp str floot floot I need to read pressure and temp in 2 different variables so that I can plot them as lines. is there a package which reads from file with a given formate and returns desired variables? or I need to open, while not EOF read, parse, build list, return? thanks From johnjsal at NOSPAMgmail.com Tue May 2 13:12:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 17:12:46 GMT Subject: simultaneous assignment In-Reply-To: <445792a3$1_2@news.bluewin.ch> References: <8dM5g.2031$No6.43874@news.tufts.edu> <445792a3$1_2@news.bluewin.ch> Message-ID: Boris Borcic wrote: > >>> w == x > False > >>> w is x > True > >>> That's the opposite of what I want to happen. From barberomarcelo at gmail.com Wed May 17 11:06:54 2006 From: barberomarcelo at gmail.com (barberomarcelo at gmail.com) Date: 17 May 2006 08:06:54 -0700 Subject: List behaviour Message-ID: <1147878414.819145.88580@i40g2000cwc.googlegroups.com> Maybe I'm missing something but the latter is not the behaviour I'm expecting: >>> a = [[1,2,3,4], [5,6,7,8]] >>> b = a[:] >>> b [[1, 2, 3, 4], [5, 6, 7, 8]] >>> a == b True >>> a is b False >>> for i in range(len(b)): ... for x in range(4): ... b[i][x] = b[i][x] + 10 ... >>> b [[11, 12, 13, 14], [15, 16, 17, 18]] >>> a [[11, 12, 13, 14], [15, 16, 17, 18]] >>> ActivePython 2.4.2 Build 248 (ActiveState Corp.) based on Python 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] on win32 Windows XP Marcelo From jjl at pobox.com Mon May 22 16:35:53 2006 From: jjl at pobox.com (John J. Lee) Date: 22 May 2006 20:35:53 +0000 Subject: ftplib.ftpcp(), undocumented function? References: <1148028935.558821.198210@j33g2000cwa.googlegroups.com> Message-ID: <877j4dajbp.fsf@pobox.com> swordsp at gmail.com writes: > Hi all, > I found this function recently when I read the source code of ftplib > module, I almost omit it at all and have tried to write it myself for > FXP work. > It seems exist long long ago, but never appeared in any document, > anyone knows why? > Is its implementation broken or planed to be removed from standard > library? Probably the only ways to find out are: 1. studying the code and relevant standards carefully, 2. file a patch that documents it, and see if people pop up to complain that it shouldn't be documented. John From phddas at yahoo.com Wed May 3 17:02:43 2006 From: phddas at yahoo.com (Gary Wessle) Date: 04 May 2006 07:02:43 +1000 Subject: scope of variables Message-ID: <874q06bz4c.fsf@localhost.localdomain> Hi is the code below correct? b = 3 def adding(a) print a + b it seams not to see the up-level scope where b is defined. thanks From beliavsky at aol.com Mon May 8 18:45:44 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 8 May 2006 15:45:44 -0700 Subject: Econometrics in Panel data? References: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1147128344.645205.310000@v46g2000cwv.googlegroups.com> DeepBlue wrote: > Hi all, > > I am new to Python. Just wondering can Python able to do econometric > regression in either Time-series or pooled (panel) data? As well as test > for hetero, autocorrelation, or endogeneity? > Thank you! NumPy can do linear regression, and one can certainly program any statistical algorithm in it. For the fairly advanced statistical methods you are interested in, however, it may be easiest to call R from Python using the methods described at http://www.omegahat.org/RSPython/index.html . From bignose+hates-spam at benfinney.id.au Wed May 3 18:57:13 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 May 2006 08:57:13 +1000 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: <87zmhybtti.fsf@benfinney.id.au> Edward Elliott writes: > Marc 'BlackJack' Rintsch wrote: > > Edward Elliott wrote: > >> I can prove that assertion too: make a simple text processor that > >> reads Python source code and outputs the same source code with > >> only one change: insert the string 'self" as the first parameter > >> of every "def somemethod". Next run the output source code with > >> the normal Python > > > > Okay, let's start with writing a simple text processor for this > > little mess:: > > I didn't even try to wade through that morass of monocharacter > variables. Anyone wanna summarize the point of that code? As I understand it, the point was not what the code does, but to give a sample input (a Python program) for the "simple text processor" you described to wade through. -- \ "I always had a repulsive need to be something more than | `\ human." -- David Bowie | _o__) | Ben Finney From Serge.Orlov at gmail.com Wed May 24 00:45:05 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 23 May 2006 21:45:05 -0700 Subject: NEWB: reverse traversal of xml file References: <1148344898.351787.159540@i40g2000cwc.googlegroups.com> <1148348572.610824.137750@j33g2000cwa.googlegroups.com> <1148422499.812056.134120@u72g2000cwu.googlegroups.com> Message-ID: <1148445905.374059.261750@g10g2000cwb.googlegroups.com> manstey wrote: > But will this work if I don't know parts in advance. Yes it will work as long as the highest part number in the whole file is not very high. The algorithm needs only store N records in memory, where N is the highest part number in the whole file. > I only know parts > by reading through the file, which has 450,000 lines. Lines or records? I created a sequence of 10,000,000 numbers which is equal to your ten million records like this: def many_numbers(): for n in xrange(1000000): for part in xrange(10): yield part parts = many_numbers() and the code processed it consuming virtually no memory in 13 seconds. That is the advantage of iterators and generators, you can process long sequences without allocating a lot of memory. From tim.leeuwvander at nl.unisys.com Wed May 31 09:55:59 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 31 May 2006 06:55:59 -0700 Subject: Variable name has a typo, but code still works. Why? In-Reply-To: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> Message-ID: <1149083759.510994.222810@f6g2000cwb.googlegroups.com> Hi Mateus, We'd need to see more code then just this snippet. It looks like the name 'session' is used elsewhere in the code, and is in scope for the showReport() method. But without seeing a bit more code of this class, and possibly global variables / code, it's not possible to say this. There's definately no rules in Python that allow you to 'abbreviate' variable names. Cheers, --Tim mateus wrote: > print "hello world" > > I have a nested loop where the outer loop iterates over key value pairs > of a dictionary and the inner loop iterates over a list each list of > which is a mapped value from the dictionary > > def showReport(self): > for dev, sessions in self.logger.items(): > for tree in session: > self.addTestItem(self, tree) > > What I don't understand is why this executes w/o any problems when > "sessions" was spelled as plural (sessionS) while later being spelled > in the singular (session). > > Is there some type of name resolution of local variables where Python > makes assumptions? From ptmcg at austin.rr._bogus_.com Fri May 19 15:08:41 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 19:08:41 GMT Subject: Request for comments on python distributed technologies References: Message-ID: "Carl J. Van Arsdall" wrote in message news:mailman.5972.1148064796.27775.python-list at python.org... > Hey everyone, another question for the list. In particular i'm looking > for comments on some of the distributed technologies supported in > python. Specifically, I'm looking at XML-RPC, RPyC, CORBA, and Twisted. > What you describe sounds very much like pyro, which should probably be added to your list. BTW, distributed frameworks are not inherently more robust or more easily maintained than monolithic systems. Unless you establish dynamic replication and/or relocation of services, you can easily end up with one or more single points of failure. Services should be self-registering in order to make finding them an automatic process, without having to maintain global configuration/locator files or services (which themselves can become bottlenecks), or distributed lookup files that must be propagated when changes occur (with appropriate change collision management). You also want to incorporate some form of isolation in your framework, to try to avoid permitting ill-behaved clients from crashing services. A global logging service for all services is handy - its a bear traipsing through and interleaving among log files from each separate service node - but this too can be a drag on performance and robustness. And also, don't forget admin and monitoring utilities - some op center somewhere is going to have to monitor this whole mess^H^H^H^Hsystem, and would like an early warning before the one critical bottleneck resource decides to croak at 2a.m. on a Sunday. -- Paul From fredrik at pythonware.com Wed May 31 17:05:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 31 May 2006 23:05:14 +0200 Subject: shuffling elements of a list In-Reply-To: <1149105576.321676.131600@j55g2000cwa.googlegroups.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <1149105576.321676.131600@j55g2000cwa.googlegroups.com> Message-ID: Roger Miller wrote: > DSU seems like a lot of trouble to go through in order to use an O(n > log n) sorting algorithm to do what can be done in O(N) with a few > lines of code. The core code of random.shuffle() shows how easy it is > to do it right: > > for i in reversed(xrange(1, len(x))): > # pick an element in x[:i+1] with which to exchange x[i] > j = int(random() * (i+1)) > x[i], x[j] = x[j], x[i] easy to do it right? you know, the main reason for adding shuffle to the standard library was that its way too easy to get it wrong. see e.g. this thread: http://tinyurl.com/ppgzq From tim.peters at gmail.com Fri May 19 11:59:22 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 19 May 2006 11:59:22 -0400 Subject: Reference Counts In-Reply-To: <1148012327.849813.282080@i39g2000cwa.googlegroups.com> References: <1147933695.752344.195350@u72g2000cwu.googlegroups.com> <1147937632.918370.300350@j55g2000cwa.googlegroups.com> <1148012327.849813.282080@i39g2000cwa.googlegroups.com> Message-ID: <1f7befae0605190859j30b9ca09u228d2b766f3bbd48@mail.gmail.com> [raghu, on Heiko Wundram's test program: import sys x = {} i = 0 def test(): global x, i x[i] = "test" i += 1 del x[i-1] # Properly clean up x. for j in xrange(10000): print "Before", j, ":", sys.gettotalrefcount() test() print "After", j, ":", sys.gettotalrefcount() ] > Hmm... > > I tried the gc.collect(). It aint helping. The reference count still > keeps growing till 5 after it which it drops. As you said, it is not > gonna hurt right away. > > The only downside in that mysterious up and down thingie is that , we > could get to a wrong conclusion about a leak, if we ran the algo for > say 3 times. Right ? > > Thanks Heiko for all the help. And in case, you get to decode the > mystery behind the increase before the decrease ..kindly let me know. It has nothing to do with cyclic gc. It has to do with this: del x[i-1] # Properly clean up x. When you remove a dictionary key, under the covers the dictionary slot that contained the deleted pair has its value portion set to a special "dummy" object. This is invisible from the Python level (there's no way you can get at this object), but the dummy object is a real Python object, and like all Python objects has a refcount. Each time the dummy object gets used, its refcount is bumped, and that shows up in gettotalrefcount(). From time to time the dict resizes, and then the number of references to the dummy dict value changes sharply. Except in the upcoming 2.5 release. The refcount on the dummy dict value (and the similar dummy set value) confuses people so much that gettotalrefcount() has been changed in 2.5 to subtract the refcounts on the dummy dict and set values. As a result, running under current 2.5 trunk Heiko's program is steady as a rock: Before 0 : 25632 After 0 : 25632 Before 1 : 25632 After 1 : 25632 Before 2 : 25632 After 2 : 25632 Before 3 : 25632 After 3 : 25632 Before 4 : 25632 After 4 : 25632 Before 5 : 25632 After 5 : 25632 Before 6 : 25632 After 6 : 25632 Before 7 : 25632 After 7 : 25632 Before 8 : 25632 After 8 : 25632 Before 9 : 25632 After 9 : 25632 Before 10 : 25632 After 10 : 25632 ... From conor.robinson at gmail.com Thu May 11 14:48:14 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 11 May 2006 11:48:14 -0700 Subject: segmentation fault in scipy? In-Reply-To: References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> Message-ID: <1147373294.235202.188220@y43g2000cwc.googlegroups.com> >I'm afraid you're using terminology (and abbreviations!) that I can't follow. >Let me try to restate what's going on and you can correct me as I screw up. You >have a neural net that has 80 output units. You have 25000 observations that you >are using to train the neural net. Each observation vector (and consequently, >each error vector) has 80 elements. First, sorry for not quoting and using abbreviations. Second, your obsevation is correct, except that I have *one* output unit, not 80. I have ~80 input units + bias (for each of the 25000 observations), x + bias number of hidden units and one output unit leaving me with an output array/matrix of shape =(25000,), as well as my desired output having the same shape. RPROP = Resilliant BackPropogation, uses chages in the error gradiant ignores the magnitude of the gradiant, which can be harmful. See "A Direct Adaptive Method for Faster Backpropogation Learning: The RPROP Algorithm" -Martin Riedmiller and Heinrich Braun, just google it and read Section D, it's well written. tanh = hyperbolic tangent function [-1, 1] y vals, often times better for its steeper derivative and wider range. sigmoid function = popular for its [0,1] range and can calculate posterior probabilities when using a the cross entropy error function which I have commented out since it takes more time to process and I'm not using my error function in this specific case at this point in time, thus SSE is not really needed, however I'd like use it as a check. Also, popular for its easily calculatable derivative. >The answer I gave also used the wrong name for the result. It seems that you >want the sum of the squared errors across all of the observations. In this case, >you can use axis=None to specify that every element should be summed: > > SSE = sum(multiply(error, error), axis=None) > >trace(dot(error, transpose(error))) wastes a *huge* amount of time and memory >since you are calculating (if your machine was capable of it) a gigantic matrix, >then throwing away all of the off-diagonal elements. The method I give above >wastes a little memory; there is one temporary matrix the size of error. This is great advise and much appreciated. It was the answer to my problem, thank you. However, isn't this faster... scipy.sum(scipy.array(scipy.matrix(error)*scipy.matrix(error)), axis = None) as we you explained in my other posting? Thanks again. From robert.kern at gmail.com Fri May 12 12:41:16 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 12 May 2006 11:41:16 -0500 Subject: which windows python to use? In-Reply-To: References: Message-ID: Robert Kern wrote: > James Stroud wrote: > >>Robert Kern wrote: >> >>>James Stroud wrote: >>> >>>>Enthought does not play well with cygwin, I've noticed. >>> >>>In what way? Does the mingw gcc that we distribute interfere with Cygwin's gcc? >> >>One can not run the enthought python interactive interpreter from a >>cygwin x-window session, it locks up. > > Interesting. I've seen the same thing with MSYS's rxvt ("native", not X). I > presumed it was a strange interaction between bash and (any) Python. Looks like > it may just be our Python, then. I'll enter a ticket on our Trac. Thank you! My officemate notes that we ship readline. It is possible that readline is expecting CMD.EXE not a decent terminal. -- 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 alisonken1 at gmail.com Thu May 11 12:04:07 2006 From: alisonken1 at gmail.com (alisonken1) Date: 11 May 2006 09:04:07 -0700 Subject: find all index positions In-Reply-To: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> Message-ID: <1147363447.657331.224450@i40g2000cwc.googlegroups.com> micklee74 at hotmail.com wrote: > hi > say i have string like this > astring = 'abcd efgd 1234 fsdf gfds abcde 1234' > if i want to find which postion is 1234, how can i achieve this...? i > want to use index() but it only give me the first occurence. I want to > know the positions of both "1234" > thanks ========== def getAllIndex(aString=None, aSub=None): t=dict() c=0 ndx=0 while True: try: ndx=aString.index(aSub, ndx) t[c]=ndx ndx += 1 c += 1 except ValueError: break return t =========== This will return a dictionary of what was found; i.e., >>> getAllIndex('abcd 1234 efgh 1234 ijkl', '1234') {0: 5, 1: 15} From wuwei23 at gmail.com Sun May 21 22:08:05 2006 From: wuwei23 at gmail.com (alex23) Date: 21 May 2006 19:08:05 -0700 Subject: Software Needs Philosophers In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <1148263685.895961.245310@38g2000cwa.googlegroups.com> As a professionally trained "philosopher" and "programmer", I'm perfectly well aware that the onus is on _me_ to make others respect & appreciate my skills and what they offer. Posting to usenet about how others just don't "get it" is, in fact, not "getting it". Even further, using "religion" as the antithesis to the glorious philosophy which produces only truth makes this little more than the standard net rant of "your way is different from mine and therefore wrong". I can just as easily use "philosophy" to mean "the pointless rantings of obsessed individuals"... Seriously, this fails on every single level it aims at. - alex23 From adonisv at DELETETHISTEXTearthlink.net Tue May 2 08:14:11 2006 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Tue, 02 May 2006 12:14:11 GMT Subject: --version? In-Reply-To: <4bp06lF1276vvU1@individual.net> References: <4bp06lF1276vvU1@individual.net> Message-ID: Paul Watson wrote: > Is there any chance that Python would support the --version command line > parameter? It seems that many open source programs use this switch to > report their version number. try at a command prompt: python -V Hope this helps. Adonis From dacut at kanga.org Sat May 20 03:19:24 2006 From: dacut at kanga.org (David Cuthbert) Date: Sat, 20 May 2006 00:19:24 -0700 Subject: Using python for a CAD program In-Reply-To: <446C8950.3070107@anansispaceworks.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <446C8950.3070107@anansispaceworks.com> Message-ID: Terry Hancock wrote: > I disagree that transactions are bad for CAD -- they may have > a different semantic role and the needed granularity may be > different, but the need to roll data back to an earlier revision > is just as present in drawings as it is for code or financial > transactions. Sure, but that's called source control. So you do need transactions, but for the entire database state, not on database operations. (This was certainly true at Cadence -- there was a thriving third-party market for handling source control on CDBA databases, and I never encountered any code which operated on the database in a transactional manner. OpenAccess did have some basic support for transactions, but I never heard of anyone using them.) Some kind of transactionality is needed for undo/redo, but this is usually done in a different (some might say "more efficient", others might say "hackier") method than how transactions are implemented for RDBMS (that I've dealt with, anyway). I suspect this can be attributed to two major factors: concurrent access is never an issue in such systems, and the number of database objects representing a given state is far larger than in, say, e-commerce. From me+python at modelnine.org Sun May 21 17:01:35 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 21 May 2006 23:01:35 +0200 Subject: Slicing Issues In-Reply-To: References: Message-ID: <200605212301.35778.me+python@modelnine.org> Am Sonntag 21 Mai 2006 22:52 schrieb BJ Swope: > district_combo=line[85:3] This returns the slice from character 85 to character 3 in the string, read forwards. Basically, as Python slices are forgiving (because the borders are actually "illogical"), this amounts to nothing, but could also amount to: "your indexing boundaries are invalid." Basically, what you want is: district_combo = line[85:88] where 88 = 85 + 3 (3 being the length). Read up on Python slices... --- Heiko. From sam at nuevageorgia.com Thu May 18 10:09:20 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 18 May 2006 07:09:20 -0700 Subject: Python - Web Display Technology In-Reply-To: References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> Message-ID: <1147961360.404525.203520@j55g2000cwa.googlegroups.com> I guess there isn't much to understand. If you are satisfied with a text based, static image web, that is light on artistic possabilities, all that HTML stuff is acceptable. Perhaps the HTML/JS group will even get off their rear ends and bring some decent cross platform graphics capabilities to the web one decade? Perhaps even bring some 90's style graphics to the browser one decade? WC3 at Work - Beware Falling Luddites From c.gillespie at ncl.ac.uk Fri May 5 12:40:19 2006 From: c.gillespie at ncl.ac.uk (Colin Gillespie) Date: Fri, 05 May 2006 17:40:19 +0100 Subject: Drop Down Menus... In-Reply-To: References: Message-ID: bruce wrote: > Hi... > > Never used python, but I have a question regarding Drop Down Menus. Does > Python allow me to create a website, that will permit the user to create > Drop Down menus that can be initiated with the right mouse click? If it can, > is it fairly easy to implement? > > Thanks > > -Bruce > No you wouldn't use python for this. Look at javascript & CSS. e.g. http://www.youngpup.net/2004/transmenus/examples and http://www.robocup2004.pt/ Colin From pthibault33 at yahoo.ca Wed May 3 14:27:22 2006 From: pthibault33 at yahoo.ca (Pierre Thibault) Date: 3 May 2006 11:27:22 -0700 Subject: Mutable String Message-ID: <1146680841.991313.248410@i40g2000cwc.googlegroups.com> I would like to know if there are modules offering a mutable version of strings in Python? From aylwyn at cantab.net Wed May 17 17:15:08 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 14:15:08 -0700 Subject: python vs perl lines of code References: Message-ID: <1147900508.423650.155470@i40g2000cwc.googlegroups.com> It probably says something about your coding style, particularly in perl. I've found (anecdotally of course) that while perl is potentially the more economical language, writing *legible* perl takes a lot more space. From me+python at modelnine.org Wed May 3 15:57:27 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 3 May 2006 21:57:27 +0200 Subject: OT: SourceForge Tracker offline? Message-ID: <200605032157.27574.me+python@modelnine.org> Is anybody else also experiencing the SourceForge tracker to be offline? I can't log in at the moment, and can't view any tracker items... --- Heiko. From bill.pursell at gmail.com Thu May 18 18:27:17 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 18 May 2006 15:27:17 -0700 Subject: number of different lines in a file In-Reply-To: References: Message-ID: <1147991237.732146.29350@j55g2000cwa.googlegroups.com> r.e.s. wrote: > I have a million-line text file with 100 characters per line, > and simply need to determine how many of the lines are distinct. > > On my PC, this little program just goes to never-never land: > > def number_distinct(fn): > f = file(fn) > x = f.readline().strip() > L = [] > while x<>'': > if x not in L: > L = L + [x] > x = f.readline().strip() > return len(L) > > Would anyone care to point out improvements? > Is there a better algorithm for doing this? Have you tried cat file | sort | uniq | wc -l ? sort might choke on the large file, and this isn't python, but it might work. You might try breaking the file into smaller peices, maybe based on the first character, and then process them seperately. The time killer is probably the "x not in L" line, since L is getting very large. By subdividing the problem initially, that time constraint will be better. From george.sakkis at gmail.com Sun May 14 01:43:42 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 May 2006 22:43:42 -0700 Subject: do/while structure needed In-Reply-To: <4466bddd$0$18984$c3e8da3@news.astraweb.com> References: <4466bddd$0$18984$c3e8da3@news.astraweb.com> Message-ID: <1147585422.693953.292480@u72g2000cwu.googlegroups.com> John Salerno wrote: > 1 random.shuffle(letters) > 2 trans_letters = ''.join(letters)[:len(original_set)] > 3 trans_table = string.maketrans(original_set, trans_letters) > > So what I'd like to do is have lines 1 and 2 run once, then I want to do > some comparison between original_set and trans_letters before running > line 3. If the comparison passes, line 3 runs; otherwise, lines 1 and 2 > run again. > > A do/while would be good for this, but perhaps I'm looking at it in the > wrong way? Or is there some kind of do/while type of idiom that I could use? > > Thanks. I guess you want something like: while True: random.shuffle(letters) trans_letters = ''.join(letters)[:len(original_set)] if some_compatison(original_set,trans_letters): trans_table = string.maketrans(original_set, trans_letters) break HTH, George From chuangwoo at gmail.com Wed May 17 12:13:52 2006 From: chuangwoo at gmail.com (CC) Date: 17 May 2006 09:13:52 -0700 Subject: How to add columns to python arrays Message-ID: <1147882432.166728.207820@j55g2000cwa.googlegroups.com> Hi there, I wanna compile a 6000x1000 array with python. The array starts from 'empty', each time I get a 6000 length list, I wanna add it to the exist array as a column vector. Is there any function to do so? Or, I can add the list as a rows, if this is easier, and transpose the whole array after all the rows are setup. Thanks so much. From doug.bromley at gmail.com Fri May 5 11:50:11 2006 From: doug.bromley at gmail.com (Doug Bromley) Date: Fri, 5 May 2006 16:50:11 +0100 Subject: Best IDE for Python? In-Reply-To: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> Message-ID: <288425520605050850i6f94518nafd34adb6ae6581e@mail.gmail.com> I have a Python IDE review I did a few months back you may want to view: http://www.straw-dogs.co.uk/blog/python-ide-review Hope that helps. Doug On 5 May 2006 08:28:00 -0700, Saurabh Sardeshpande wrote: > > Pardon if this is already discussed extensively. But what is the best > IDE for Python for a newbie? I have experience in C++ and Java and this > is the first time I am learning a scripting language. > Thanks in advance > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From bborcic at gmail.com Wed May 10 06:00:36 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 10 May 2006 12:00:36 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <0UG7g.8$u17.6@fe08.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <1147068524.966560.52210@y43g2000cwc.googlegroups.com> <0UG7g.8$u17.6@fe08.lga> Message-ID: <4461b9d5_3@news.bluewin.ch> Ken Tilton wrote: > "Now if you are like most > people, you think that means X. It does not." As far as natural language and understanding are concerned, "to mean" means conformity to what most people understand, Humpty Dumpties notwithstanding. Cheers. From onurb at xiludom.gro Tue May 16 11:37:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 16 May 2006 17:37:11 +0200 Subject: what is the difference between tuple and list? In-Reply-To: <1147791654.513678.309360@i39g2000cwa.googlegroups.com> References: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> <1147791654.513678.309360@i39g2000cwa.googlegroups.com> Message-ID: <4469f20d$0$7052$636a55ce@news.free.fr> infidel wrote: >>is there any typical usage that shows their difference? > > > I think the general idea is to use lists for homogenous collections and > tuples for heterogenous structures. > > I think the database API provides a good usage that shows their > differences. When you do cursor.fetchall() after executing a query, > you get back a list of tuples. Each tuple is one "record" from the > cursor. "tuple" is even the term used in relational database theory > when talking about a table row. You shouldn't be able to add or remove > fields from a query result, so using a tuple is a perfect match for > this. On the other hand, you can certainly add, delete, or replace > entire tuples in the result set, so it makes sense to use a list to > hold the set of tuples. > I think you can remove the 'I think' !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From __peter__ at web.de Fri May 12 00:58:04 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 12 May 2006 06:58:04 +0200 Subject: Threads References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> Message-ID: placid wrote: > I have a thread that has a job Queue, it continuosly polls this queue > to see if there are any jobs for it, what i really wont to be able to > do is, when the queue is empty, i want the thread to pause (or more > technical, i want the thread to block) until the queue gets populated > again. Is this possible ? Isn't that the default behaviour of Queue.get()? Peter From nobody at 127.0.0.1 Fri May 12 15:04:44 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 19:04:44 GMT Subject: How to get a part of string which follows a particular pattern usingshell script References: <1147083512.620270.231680@j73g2000cwa.googlegroups.com> Message-ID: Anthra Norell wrote: > This is the third problem today which I propose to solve with my stream > editor SE. If the group thinks it could be useful I would submit it the > moment I'm done with the doc, which is in the final stage. You keep saying that and getting no response, so I'll take a stab at telling you why. I take it that when you say 'propose it to the group' and 'submit it for distribution', you mean include it in the standard library. My impression (and fervent hope) is that nobody's gonna throw a new, unfamiliar module straight into the standard library. Put it up somewhere like the cheese shop and let people kick the tires for a few months/years. Then if it solves a real need, works well, is sufficiently general, and isn't handled better by another module, it might be eligible for consideration for inclusion in the standard library. New modules aren't just thrown in there willy-nilly. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From nobody at 127.0.0.1 Sun May 21 17:16:11 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 21:16:11 GMT Subject: Iterators: Would "rewind" be a good idea? References: <4470C2E5.1020004@earthlink.net> Message-ID: Heiko Wundram wrote: > But, think of the following: what if the iterator computes the values at > runtime, and you're not iterating over a "predefined" list of some sort? > Do you want the machinery to store the state of the iterator at every > earlier point in time (sometimes this may not even be possible, think of > socket communication handled by iterators, or of some state being kept in > a C extension outside of the grasp of the Python interpreter), and to > restore the iterator to this point? This is why the C++ STL has independent forward and backward iterator types. Iterating over containers in memory generally supports both. Iterating over stdin or a socket would only support forward iteration. I can't recall any examples of backwards-only iteration atm... maybe popping values off a stack. My STL's a bit rusty. Anyway, python iterators could provide a prev() method to go with next(). If the iterator doesn't support backwards iteration (sockets, generators), it could raise an exception. Then you could implement rewind as: def rewind (iter) try: while iter.prev(): pass except StopIteration: pass There's no faster way in general to rewind an iterator (think linked lists), just like there's no fast_forward() to automatically jump current iterators to the end of the sequence (which may not terminate anyway, a la itertools.count). Note that backwards iterators are different from iterating in reverse. Namely, the former let's you move back and forth at will in a sequence, while the latter is just a one-way street from back to front. My knowledge of Python's iterators is kind of sketchy, so I may have missed something. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From steve at hastings.org Wed May 3 13:40:52 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 03 May 2006 10:40:52 -0700 Subject: what is the 'host' for SMTP? References: <44581205$0$25583$c3e8da3@news.astraweb.com> Message-ID: On Wed, 03 May 2006 16:10:16 +0000, John Salerno wrote: > If all I > put in is, for example, smtp.gmail.com, how is that directed to my own > email address? The address of the SMTP server does not specify where the email will go. SMTP is a protocol, and when you are talking SMTP to the server, part of what the conversation includes will be to whom you wish to send the email. Please Google for information on SMTP. You can also start here: http://en.wikipedia.org/wiki/SMTP -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From mivabe at nospam.invalid Wed May 17 06:31:28 2006 From: mivabe at nospam.invalid (Mivabe) Date: Wed, 17 May 2006 12:31:28 +0200 Subject: Python script windows servcie References: Message-ID: Mivabe formulated the question : > > Google helped me discovering that it has something to do something with > 'CTRL_LOGOFF_EVENT'. I know what it means but i don't know how to solve it. > Is that something i have to configure in the script? > > I'n totally new to Python so maybe someone can point me to the right > direction? :D > > Regards, Mivabe No-one who can help me or did i visit the wrong group for this 'problem'? -- No line here today .... Posted by news://news.nb.nu From a.schmolck at gmail.com Sat May 6 11:36:33 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 06 May 2006 16:36:33 +0100 Subject: NaN handling References: <125hplqmppfeq29@corp.supernews.com> <01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> Message-ID: Felipe Almeida Lessa writes: > Em Sex, 2006-05-05 ?s 16:37 -0400, Ivan Vinogradov escreveu: > > This works to catch NaN on OSX and Linux: > > > > # assuming x is a number > > if x+1==x or x!=x: > > #x is NaN > > This works everywhere: > > nan = float('nan') > > . > . > . > > if x == nan: > # x is not a number No it doesn't. 'as From me+python at modelnine.org Fri May 5 07:50:09 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Fri, 5 May 2006 13:50:09 +0200 Subject: (question) How to use python get access to google search without query quota limit In-Reply-To: <1146829024.301402.282540@e56g2000cwe.googlegroups.com> References: <1146829024.301402.282540@e56g2000cwe.googlegroups.com> Message-ID: <200605051350.09765.me+python@modelnine.org> Am Freitag 05 Mai 2006 13:37 schrieb Per: > I think google's rich retrieval information and query-segment might be > of help, I downloaded google api, but there is query limit(1000/day), > How can I write python code to simulate the browser-like-activity to > submit more than 10k queries in one day? How about asking them for a "license" which doesn't have this restriction before taking the trouble to work around a limit they don't impose for nothing? Anything else might be considered text-/email-grabbing, and can get you into serious trouble... --- Heiko. From None at none.none Mon May 29 21:24:05 2006 From: None at none.none (WIdgeteye) Date: Mon, 29 May 2006 20:24:05 -0500 Subject: TIming Message-ID: HI, I am trying to write a little program that will run a program on scedule. I am having trouble understanding the datetime, time, sched modules. What I would like is something like this: If date&time = 06-13-2006:18:00:00 Then run this program I am not sure how to enter a future date in this equation using any of the modules mentioned above. I have figured out how to get the date and time from the modules above but not the future and then compare the two. Any help appreciated. Thanks From mystilleef at gmail.com Sat May 6 04:34:45 2006 From: mystilleef at gmail.com (mystilleef) Date: 6 May 2006 01:34:45 -0700 Subject: Best IDE for Python? In-Reply-To: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> Message-ID: <1146904485.740385.228520@y43g2000cwc.googlegroups.com> What OS? IDEs are overkill, bloated, complex and slow for agile languages like Python. You need an editor that is nimble, fast, simple, powerful and doesn't get in your way. For linux, I suggest Scribes. http://scribes.sf.net http://scribes.sf.net/snippets.htm (Flash Demo) http://www.minds.nuim.ie/~dez/images/blog/scribes.html (GIF Demo) From iddw at hotmail.com Fri May 19 10:15:36 2006 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 19 May 2006 09:15:36 -0500 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: On 19 May 2006 07:18:03 GMT in comp.lang.python, Duncan Booth wrote: [...] >My experience of programming with either spaces or tabs has taught me >that tabs are evil not for themselves, but simply because no matter how >hard you try they always end up being mixed with spaces. That's been my experience as well. At least on projects with more than one programmer. And more than once with single-programmer projects where the programmer changed or updated his editor in the middle... Regards, -=Dave -- Change is inevitable, progress is not. From tim.peters at gmail.com Tue May 2 13:30:14 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 2 May 2006 13:30:14 -0400 Subject: bug in modulus? In-Reply-To: References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> <4450928c$0$21107$626a54ce@news.free.fr> Message-ID: <1f7befae0605021030r458a371fm54f263cfaf9c90cf@mail.gmail.com> [Andrew Koenig, on the counter intuitive -1e-050 % 2.0 == 2.0 example] >> I disagree. For any two floating-point numbers a and b, with b != 0, it >> is always possible to represent the exact value of a mod b as a >> floating-point number--at least on every floating-point system I have ever >> encountered. The implementation is not even that difficult. [also Andrew] > Oops... This statement is true for the Fortran definition of modulus (result > has the sign of the dividend) but not the Python definition (result has the > sign of the divisor). In the Python world, it's true only when the dividend > and divisor have the same sign. Note that you can have it in Python too, by using math.fmod(a, b) instead of "a % b". IMO, it was a mistake (and partly my fault cuz I didn't whine early) for Python to try to define % the same way for ints and floats. The hardware realities are too different, and so are the pragmatics. For floats, it's actually most useful most often to have both that a % b is exact and that 0.0 <= abs(a % b) <= abs(b/2). Then the sign of a%b bears no relationship to the signs of a and b, but for purposes of modular reduction it yields the result with the smallest possible absolute value. That's often valuable for floats (e.g., think of argument reduction feeding into a series expansion, where time to convergence typically depends on the magnitude of the input and couldn't care less about the input's sign), but rarely useful for ints. I'd like to see this change in Python 3000. Note that IBM's proposed standard for decimal arithmetic (which Python's "decimal" module implements) requires two operations here, one that works like math.fmod(a, b) (exact and sign of a), and the other as described above (exact and |a%b| <= |b/2|). Those are really the only sane definitions for a floating point modulo/remainder. From http Mon May 15 17:31:45 2006 From: http (Paul Rubin) Date: 15 May 2006 14:31:45 -0700 Subject: my cryptogram program References: Message-ID: <7xodxzrn3y.fsf@ruckus.brouhaha.com> John Salerno writes: > def convert_quote(quote): > coded_quote = make_code(quote) > author = coded_quote.split('|')[1] > quote = coded_quote.split('|')[0] > return quote, author I think it's a little bit ugly (plus inefficient) to split the quote twice. You can use: def convert_quote(quote): coded_quote = make_code(quote) author, quote = coded_quote.split('|') return quote, author > def make_code(original): > original_letters = make_set(original) > new_letters = list(string.ascii_uppercase) > while True: > random.shuffle(new_letters) > trans_letters = ''.join(new_letters)[:len(original_letters)] > if test_code(original_letters, trans_letters): > trans_table = string.maketrans(original_letters, trans_letters) > break > return original.translate(trans_table) You're trying to make sure that no character maps to itself in the cryptogram. I'm not sure if that's one of the "rules". If not, you might like to know that it's a cryptographic weakness, not that you're attempting strong cryptography ;-). But the WW2 Enigma machine had that characteristic as part of its design, and that was used to break it. It also looks like upper and lower case letters in the input are treated as separate. For example, "George" become "abcdef" while "george" becomes "abcde". Did you want that? I don't think it can be right, because "trans_letters" has at most 26 characters, but there can be 52 separate original letters (26 upper and 26 lower). As for the efficiency of the above algorithm, well, look at what happens after you shuffle the alphabet: the probability that any given character maps to something other than itself is 25/26. That means the probability that N letters all map to something other than themselves is (25/26)**N. If N=26, this is about 0.36, so on average you'll shuffle about three times, which is not too bad, if you're just doing something casual. Note that this is close to 1/e. I'll let you figure out the reason. Of course there is a chance you'll have to shuffle 4 times, 10 times, 1000 times, etc. You might like to calculate those probabilities and decide whether it's worth thinking up a more efficient algorithm, that's possibly more complex and therefore more likely to have bugs, to burn additional development time, etc. How bad is it if occasional instances take a long time to generate? This is the kind of tradeoff you always have to spend time pondering if you're doing a large scale application. > def make_set(original): > original_set = set(original) > punc_space = string.punctuation + string.whitespace > for char in punc_space: > if char in original_set: > original_set.remove(char) > return ''.join(original_set) I think I'd write something like: def make_set(original): return set(strings.ascii_uppercase) & set(original.upper()) That is, convert the original string to uppercase, make a set from it, and then intersect that set with the set of uppercase letters. This seems more direct. From bdesth.quelquechose at free.quelquepart.fr Thu May 4 17:56:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 May 2006 23:56:58 +0200 Subject: __getattr__ for global namespace? In-Reply-To: <1146743418.248566.241890@e56g2000cwe.googlegroups.com> References: <1146743418.248566.241890@e56g2000cwe.googlegroups.com> Message-ID: <445a49ea$0$30163$636a55ce@news.free.fr> Harold Fellermann a ?crit : > Hi, > > I am writing an application that initializes the global namespace, and > afterwards, leaves the user with the python prompt. Now, I want to > catch NameErrors in user input like e.g. > > >>>>some_name > > Traceback (most recent call last): > File "", line 1, in ? > NameError: name 'some_name' is not defined > > For classes, there are the __getattr__ and __getattribute__ functions. > I wonder if there is some related function for (failed) global > attribute > lookup that is invoked with name as its argument instead. > > I consulted the docs, but could not find anything. Any ideas? http://docs.python.org/lib/module-sys.html """ excepthook( type, value, traceback) This function prints out a given traceback and exception to sys.stderr. When an exception is raised and uncaught, the interpreter calls sys.excepthook with three arguments, the exception class, exception instance, and a traceback object. In an interactive session this happens just before control is returned to the prompt; in a Python program this happens just before the program exits. The handling of such top-level exceptions can be customized by assigning another three-argument function to sys.excepthook. """ >>> import sys >>> def myhook(type, value, tb): ... print "got ", type, value, tb ... ... >>> sys.excepthook = myhook >>> toto got exceptions.NameError name 'toto' is not defined >>> HTH From mwilson-to at sympatico.ca Fri May 19 15:21:24 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 19 May 2006 15:21:24 -0400 Subject: [silly] Does the python mascot have a name ? In-Reply-To: References: <_s2bg.8867$aa4.296233@news20.bellglobal.com> Message-ID: John D Salt wrote: > Mel Wilson wrote in news:_s2bg.8867$aa4.296233 > @news20.bellglobal.com: > > [Snips] >> Just reinforces the central truth. The mascot doesn't >> *have* a name. Most things don't. > > Most things don't have names? > > I'll believe you if you can give me a list of ten things that don't have > names. > > ;-) !!! [object() for i in xrange(10)] > > All the best, > > John. Likewise, Mel. From johnjsal at NOSPAMgmail.com Tue May 23 12:39:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 16:39:39 GMT Subject: question about shadowing built-in names In-Reply-To: References: Message-ID: Dennis Lee Bieber wrote: >> import MySQLdb >> >> db = connect(blah blooh blee) > > Actually, the above has already failed Should be > MySQLdb.connect... Heh heh, yeah, I totally meant to do that on purpose. ;) > Well, if you have a habit of doing > from module import * > and later rebind one of the imported names... I see. So doing a regular import statement keeps the namespace confined to that module, right? So I would be able to create my own variable with the same name as a name in the imported module, and this wouldn't be a problem as long as I didn't import with *? From olsongt at verizon.net Thu May 18 11:50:26 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 18 May 2006 08:50:26 -0700 Subject: Windows Registry Dump In-Reply-To: <1147964415.540190.47480@i40g2000cwc.googlegroups.com> References: <1147964415.540190.47480@i40g2000cwc.googlegroups.com> Message-ID: <1147967425.773885.227230@u72g2000cwu.googlegroups.com> Dirk Hagemann wrote: > Hi! > > Does someone know how I can make a Text-Dump-File of a remote > Windows-Computer's Registry (not the whole registry - only a part of > it)? > > Thanks a lot for some code or a helpful link! > > regards > Dirk the win32api module has a bunch of Reg* functions that let you do this. From bignose+hates-spam at benfinney.id.au Wed May 17 21:15:24 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 11:15:24 +1000 Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> Message-ID: <87sln8m8ur.fsf@benfinney.id.au> Edward Elliott writes: > Ben Finney wrote: > > > Those samples can be independently verified by any skilled > > observer at another time. This is what distinguishes them from > > anecdotes, and breaks your analogy. > > Anyone who has my source files can run the same tests. Which we don't. Currently all we have is an anecdote. I'm making no comment on the veracity or interest of the anecdote, but currently that's all we have. I responded to a post that seemed to claim that anecdotes about events can be treated as data about events. They can't; that's what I'm arguing. -- \ "It is hard to believe that a man is telling the truth when you | `\ know that you would lie if you were in his place." -- Henry L. | _o__) Mencken | Ben Finney From roman.bischoff at googlemail.com Mon May 15 18:16:52 2006 From: roman.bischoff at googlemail.com (Roman) Date: 15 May 2006 15:16:52 -0700 Subject: How to guess the language of a given textstring? Message-ID: <1147731412.848833.225910@j55g2000cwa.googlegroups.com> Does anybody know an easy way (or tool) to guess the language of a given text string? e.g. Feeding in "This is an example." --> should return "english" or ISO code Feeding in "Das ist ein Beispiel." --> should return "german" or ISO code Feeding in "Esto es un ejemplo." --> should return "spanish" or ISO code I would prefer something more lightweight than using nltk/corpus/... And it's ok if the success ratio is just about 90% or so. Roman From herraotic at googlemail.com Wed May 24 12:27:18 2006 From: herraotic at googlemail.com (herraotic at googlemail.com) Date: 24 May 2006 09:27:18 -0700 Subject: Python Programming Books? In-Reply-To: References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> <1148483986.822220.287590@i39g2000cwa.googlegroups.com> Message-ID: <1148488038.055267.174810@j33g2000cwa.googlegroups.com> If you don't mind could you send me an email to my address, John Salerno, and tell me whether "Python Programming: An Introduction to Computer Science" was good. Email preferably because it will take you a while to finish the book >500 pages and I probably won't look back on this topic. Thanks! From onurb at xiludom.gro Mon May 15 04:45:38 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 15 May 2006 10:45:38 +0200 Subject: Web framework to recommend In-Reply-To: References: Message-ID: <44684017$0$5312$626a54ce@news.free.fr> Jacky wrote: > Hi all, > > I just started learning Python and would like to starting writing some > web-based applications with Python. > > I did have pretty much experience with doing so with PHP and Java, but > Python seems a bit different for me. > > Do you guys have some good web framework to recommend? (I don't want to > use CGI mode) There's quite a lot of (good) web frameworks for Python, and choosing the right one depends a lot on specific requirements you didn't express... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ask at me Thu May 11 08:16:04 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 08:16:04 -0400 Subject: redirecting print to a a file In-Reply-To: References: <7JudnYwllewrrv7ZRVn-vA@comcast.com> <1147352171.658508.187490@y43g2000cwc.googlegroups.com> Message-ID: Sybren Stuvel wrote: > AndyL enlightened us with: > >>And what if I want to still send the output to stdout and just a log >>it in the file as well? > > > $ python some_program.py | tee output.log > > Or write a class that has a write() function and outputs to a file and > to the original value of sys.stdout (IIRC that's in sys.__stdout__) > > Sybren Thx again. Python is cool, do that in C++ or Java :-) A. From john at castleamber.com Wed May 17 19:50:08 2006 From: john at castleamber.com (John Bokma) Date: 17 May 2006 23:50:08 GMT Subject: python vs perl lines of code References: <1147900508.423650.155470@i40g2000cwc.googlegroups.com> Message-ID: Edward Elliott wrote: > But again, the interesting thing to me isn't what could one do, it's > what are people actually doing in the real world? In that case: there is probably more Perl out there that makes us cry compared to Python :-D. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From 123 at 321.com Fri May 12 20:49:56 2006 From: 123 at 321.com (DeepBlue) Date: Sat, 13 May 2006 08:49:56 +0800 Subject: How to install pyTrix? Message-ID: <44652d37$0$15982$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi all, can any1 please tell me how to install pyTrix? thx! From dooscape at gmail.com Fri May 5 11:57:33 2006 From: dooscape at gmail.com (dooscape at gmail.com) Date: 5 May 2006 08:57:33 -0700 Subject: Best IDE for Python? References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> Message-ID: <1146844653.466812.44190@j73g2000cwa.googlegroups.com> >> Pardon if . . . already discussed Here is a link searching comp.lang.python for "best ide" http://tinyurl.com/qqtaf From noway at sorry.com Sun May 7 20:21:15 2006 From: noway at sorry.com (Giovanni Bajo) Date: Mon, 08 May 2006 00:21:15 GMT Subject: python 2.5a2, gcc 4.1 and memory problems References: Message-ID: <%9w7g.401$b5.20892@twister2.libero.it> Michele Petrazzo wrote: > Then I execute my test. The memory usage of 2.5a2 and gcc 3.3 that I > see with "top", is the same (about VIRT: 260 MB and RES: 250MB ) that > with the py 2.3 and 2.4, but then I recompile with 4.1 and execute > the same test, my system "stop to work"... with "top" I can see that > it use VIRT: 2440 MB and RES: 640MB RAM (I think all that I have into > my pc) > > I haven't tried to recompile py 2.4 myself with gcc 4.1 because it is > already compiled with it (4.0.3), so I think (only think) that is a py > 2.5 problem. > I'm right? or I have to compile it with something other switches? Make sure -fno-strict-aliasing is specified. Python does not conform to ISO C type aliasing rules. -- Giovanni Bajo From franz.steinhaeusler at gmx.at Wed May 31 09:21:17 2006 From: franz.steinhaeusler at gmx.at (Franz Steinhaeusler) Date: Wed, 31 May 2006 15:21:17 +0200 Subject: Best Python Editor References: Message-ID: <6t5r72h9b8aie8njcd9j79j4p27eh6uhqb@4ax.com> On Wed, 31 May 2006 15:33:29 +0530, "Manoj Kumar P" wrote: > >Hi, > >Can anyone tell me a good python editor/IDE? >It would be great if you can provide the download link also. > For a simple start: Scite is small, good, cross platform, free and open source and you can launch the program easy hitting F5 (run). Of course there are more powerful editors as vim, (x)emacs, jedit, ... but that depends on your intentions. From my_email_is_posted_on_my_website at munged.invalid Fri May 26 12:55:20 2006 From: my_email_is_posted_on_my_website at munged.invalid (Roedy Green) Date: Fri, 26 May 2006 16:55:20 GMT Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: On 21 May 2006 02:15:31 -0700, "Xah Lee" wrote, quoted or indirectly quoted someone who said : >FACT: Java has no first-class functions and no macros. This results in >warped code that hacks around the problem, and as the code base grows, >it takes on a definite, ugly shape, one that's utterly unique to Java. You need to back up a sweeping statement like that with an least an example code showing how it could much better be handled with macros. Java has lots of macro languages, including C++'s preprocessor. What it does not have is a sanctioned one. It has instead on-the-fly code generation. See http://mindprod.com/jgloss/onthefly.html -- Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching. From claudio.grondi at freenet.de Tue May 16 04:39:43 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 16 May 2006 10:39:43 +0200 Subject: IDLE confusion In-Reply-To: <1147767977.928350.261650@i39g2000cwa.googlegroups.com> References: <1147767977.928350.261650@i39g2000cwa.googlegroups.com> Message-ID: MrBlueSky wrote: > Hi, I'm trying to use IDLE to develop My First Python App and my head > hurts... > > I've a file called spalvi.py with this in it: > from Test import * > firstTest("Mike") > > And a file called Test.py with this in it: > def firstTest(name): > print "Yo",name > > I open spalvi.py with IDLE and Run it. It says "Yo Mike". > I use the File menu to open Test.py and change the message from "Yo" to > "Hi". > I Run it again.... it still says "Yo Mike" :-( > I close everything down, open spalvi.py with IDLE and Run it again. It > says "Hi Mike". > > So I'm obviously not using IDLE in the "right" way. But what *is* the > "right" way, when you're trying to develop using several source files? > > John > You need some deeper understanding of what import does and what happens when you import again (after the library files have changed). Try in the IDLE menu [Shell] "Restart Shell" (Ctrl+F6) each time you have changed something in your files - this "resets" anything previously imported, which stays the same way otherwise. Claudio From jared at hpalace.com Thu May 11 01:57:48 2006 From: jared at hpalace.com (M Jared Finder) Date: Wed, 10 May 2006 22:57:48 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <4461c69d$0$647$bed64819@news.gradwell.net> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <44606502$2$645$bed64819@news.gradwell.net> <4461c69d$0$647$bed64819@news.gradwell.net> Message-ID: Chris Uppal wrote: > E.g. can you add three-way comparisons (less-than, same-as, greater-than to, > say, Python with corresponding three-way conditional control structures to > supplement "if" etc ? Are they on a semantic and syntactic par with the > existing ones ? In Smalltalk that is trivial (too trivial to be particularly > interesting, even), and I presume the same must be true of Lisp (though I > suspect you might be forced to use macros). As an illustration, here's the definition and usage of such a numeric-if in Lisp. Using raw lambdas, it's ugly, but doable: (defun fnumeric-if (value lt-body eq-body gt-body) (cond ((< value 0) (funcall lt-body)) ((= value 0) (funcall eq-body)) ((> value 0) (funcall gt-body)))) (fnumeric-if (- a b) (lambda () (print "a < b")) (lambda () (print "a = b")) (lambda () (print "a > b"))) A macro helps clean that up and make it look prettier: (defmacro numeric-if (value lt-body eq-body gt-body) `(fnumeric-if ,value (lambda () ,lt-body) (lambda () ,eq-body) (lambda () ,gt-body))) (numeric-if (- a b) (print "a < b") (print "a = b") (print "a > b")) -- MJF From go at away.com Wed May 31 19:24:01 2006 From: go at away.com (3rdshiftcoder) Date: Wed, 31 May 2006 23:24:01 GMT Subject: beginner: using parameter in functions Message-ID: hi- i am having trouble using parameter values in my function and to be honest a little trouble with member variables. i am trying to pass in the argument 'd' representing delete. what the code will do is if it is 'd' it will make a delete query template string. if it is an 'i' then insert query etc. this is the results of my attempt to print the contents of the parameter values. <__main__.getQryStr instance at 0x01151D50> ('d',) me mad (and on a side note if i dont include the *args i get an invalid number of parameters supplied message.) why is it returning the value in this format ('d',) ? i cant get x == d i guess that value 'd' is stored in a tuple and i'd like to get it out of there. so basically the function returns nope as it stands python is sure different from other languages i have used. thanks for any help, jim class getQryStr: def __init__(self,op): print op self.x = 'd' def returnStr(x,*args): print '%s %s me mad' % (x,args) if x == 'd': s = Template("delete from columndef where tblid = $tblid and colname = $colname") else: return 'nope' #this else is just for illustration and testing d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) print s.substitute(d) return s def delqry(self): createfldobj = getQryStr('d') s = createfldobj.returnStr('d') From David.Squire at no.spam.from.here.au Tue May 30 05:11:52 2006 From: David.Squire at no.spam.from.here.au (David Squire) Date: Tue, 30 May 2006 10:11:52 +0100 Subject: John Bokma harassment In-Reply-To: <447bff02$0$38691$edfadb0f@dread12.news.tele.dk> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> <447bff02$0$38691$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > John Bokma wrote: >> ilitzroth at gmail.com wrote: > >> Your first question should be: Is it alright that Xah harasses 5 >> newsgroups? Or maybe work on your spelling, harass is with one r, but >> maybe you didn't read the subject, which wouldn't amaze me, since you >> sound like you should be spending time on MySpace OMG!. > > > I assume that the single l in alright is the courteous misspelling that > should allways be in a posting, when correcting other peoples speling? Nope. Oxford English Dictionary has: alright a frequent spelling of all right. And Merriam-Webster has: alright Pronunciation: (")ol-'rIt, 'ol-" Function: adverb or adjective : ALL RIGHT usage The one-word spelling alright appeared some 75 years after all right itself had reappeared from a 400-year-long absence. Since the early 20th century some critics have insisted alright is wrong, but it has its defenders and its users. It is less frequent than all right but remains in common use especially in journalistic and business publications. It is quite common in fictional dialogue, and is used occasionally in other writing . DS From gmc at serveisw3.net Mon May 15 12:45:38 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Mon, 15 May 2006 18:45:38 +0200 Subject: py on windows Mobile 5.0? In-Reply-To: <2387F0EED10A4545A840B231BBAAC722608345@slcimail1.slcgov.com> References: <2387F0EED10A4545A840B231BBAAC722608345@slcimail1.slcgov.com> Message-ID: <4468B032.2090905@serveisw3.net> Bell, Kevin escribi?: >Does anyone know if/how to go about using python on a windows mobile 5.0 >PDA? > >Kevin > > > > Hi Bell, Yes, there's PythonCE (Python 2.4.3 port) for Windows CE / ARM, and seems to run with mobile 5. Please search in the pythonce mail list and you'll got the answers about how to go. I attach here the last revision announcement in the maillist (May 1, 2006): A new bug fix release of Python for Windows CE is available. Download it here: http://sourceforge.net/project/showfiles.php?group_id=104228 The release notes are linked from this page, but a direct link is: http://sourceforge.net/project/shownotes.php?release_id=413801&group_id=104228 Luke _______________________________________________ PythonCE mailing list PythonCE at python.org http://mail.python.org/mailman/listinfo/pythonce Regards, Gonzalo Monz?n From bencvt at gmail.com Mon May 22 18:43:08 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 22 May 2006 15:43:08 -0700 Subject: File attributes References: <1148336239.342164.285680@j73g2000cwa.googlegroups.com> Message-ID: <1148337788.615072.115990@y43g2000cwc.googlegroups.com> acatejr at gmail.com wrote: > I know how to "walk" a folder/directory using Python, but I'd like to > check the archive bit for each file. Can anyone make suggestions on > how I might do this? Thanks. Since the archive bit is Windows-specific, your first place to check is Mark Hammond's Python for Windows Extensions (aka win32all). It's a quick and painless install; grab it here: http://python.net/crew/skippy/win32/ Once you have that installed, look in the PyWin32.chm help file for the function calls you need. If the documentation is too sparse, check MSDN or google it. For what you're trying to do: import win32file import win32con def togglefileattribute(filename, fileattribute, value): """Turn a specific file attribute on or off, leaving the other attributes intact. """ bitvector = win32file.GetFileAttributes(filename) if value: bitvector |= fileattribute else: bitvector &= ~fileattribute win32file.SetFileAttributes(filename, bitvector) # Sample usage: togglefileattribute('foo.txt', win32con.FILE_ATTRIBUTE_ARCHIVE, True) --Ben From duane at franz.com Sat May 13 03:55:12 2006 From: duane at franz.com (Duane Rettig) Date: Sat, 13 May 2006 00:55:12 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Alexander Schmolck writes: > I think that in most contexts lexical transparency is desirable so that > deviations from lexical transparency ought to be well motivated. I also > believe that a construct that is usually used to establish a lexically > transparent binding shouldn't be equally used for dynamic bindings so that it > isn't syntactically obvious what's going on. I've already provided some > reasons why CL's design wrt. binding special and lexical variables seems bad > to me. I don't think these reasons were terribly forceful but as I'm not aware > of any strong motivation why the current behaviour would be useful I'm > currently considering it a minor wart. > > To make things more concrete: What would be the downside of, instead of doing > something like: > > (let ((*x* ...)) [(declare (special *x*))] ...) ; where [X] denotes maybe X Let's start with this. You seem to be saying that the above construct is inferior to the alternatives you are about to suggest. Why? And since you are adding an optional form, let's break it down into its separate situations: 1. (let ((*x* ...)) (declare (special *x*)) ...) Here there is no question about the specialness of *x*; it is textually obvious what the binding is - that it is not a lexical binding but a special binding. 2. (let ((*x* ...)) ...) [where there is no special declaration for *x* within the form] Here, the issue is that it is not obvious that *x* is special (in this case, it would have to already be a dynamic variable (what we internally call "globally special"), because a special declaration within a lexical context does not affect inner bindings. Perhaps this form is the one you are really having trouble with. > doing any of the below: > > a) using a different construct e.g. (fluid-let ((*x* ...)) ...) for binding > special variables Unless you also _remove_ the #2 case above, this seems no diferent than writing a macro for the #1 case, above. > b) having to use *...* (or some other syntax) for special variables In fact, the spec does suggest precisely this (see http://www.franz.com/support/documentation/8.0/ansicl/dictentr/defparam.htm, in the Notes section), and to the extent that programmers obey the suggestion, the textual prompting is present in the name. > c) using (let ((q (special *x*) (,a ,b , at c)) (values 1 2 '(3 4 5 6))) > (list q ((lambda () (incf *x*))) a b c)) ; => (1 3 3 4 (5 6)) > > (It's getting late, but hopefully this makes some vague sense) Well, sort of; this seems simply like a sometimes-fluid-let, whose syntax could easily be established by a macro (with destructurings whose form is (special X) could be specially [sic] treated. Now if in the above example you would have trouble with (a) and/or (c) based on the absence of a "lexical" declaration (i.e. one that would undo the effect of a globally special declaration), thus guaranteeing that a fluid-let or a "sometimes-fluid-let" would work, you should know that while I was working on the Environments Access module I theorized and demonstrated that such a declaration could be easily done within a conforming Common Lisp. I leave you with that demonstration here (though it really is only for demonstration purposes only; I don't necessarily propose that CL should add a lexical declaration to the language): [This only works on Allegro CL 8.0]: CL-USER(1): (defvar pie pi) PIE CL-USER(2): (compile (defun circ (rad) (* pie rad rad))) CIRC NIL NIL CL-USER(3): (circ 10) 314.1592653589793d0 CL-USER(4): (compile (defun foo (x) (let ((pie 22/7)) (circ x)))) FOO NIL NIL CL-USER(5): (foo 10) 2200/7 CL-USER(6): (float *) 314.2857 CL-USER(7): (sys:define-declaration sys::lexical (&rest vars) nil :variable (lambda (declaration env) (declare (ignore env)) (let* ((spec '(lexical t)) (res (mapcar #'(lambda (x) (cons x spec)) (cdr declaration)))) (values :variable res)))) SYSTEM::LEXICAL CL-USER(8): (compile (defun foo (x) (let ((pie 22/7)) (declare (sys::lexical pie)) (circ x)))) ; While compiling FOO: Warning: Variable PIE is never used. FOO T NIL CL-USER(9): (foo 10) 314.1592653589793d0 CL-USER(10): -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From peace.is.our.profession at gmx.de Tue May 9 04:21:27 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Tue, 09 May 2006 10:21:27 +0200 Subject: Why 3.0/5.0 = 0.59999... In-Reply-To: <1147159404.498386.58860@g10g2000cwb.googlegroups.com> References: <1147159404.498386.58860@g10g2000cwb.googlegroups.com> Message-ID: Hi Davy > When I type 3.0/5.0, the result is 0.59999... try: >>> print (3.0/5.0) 0.6 > Is there some precision loss? And how to overcome it? Make sure the result gets piped through some floating point con- version (like print, %s etc.) BTW, the 0.59999999999999998 value is the "exact" calculated value corresponding to your floating point accuracy (34/2 digits). Regards Mirco From brian at sweetapp.com Sun May 7 06:10:26 2006 From: brian at sweetapp.com (brian at sweetapp.com) Date: 7 May 2006 03:10:26 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> Message-ID: <1146996626.037365.304750@v46g2000cwv.googlegroups.com> Patrick May wrote: > aleaxit at yahoo.com (Alex Martelli) writes: >> In my opinion (and that of several others), the best way for Python to >> grow in this regard would be to _lose_ lambda altogether, since named >> functions are preferable > > Why? I find the ability to create unnamed functions on the fly > to be a significant benefit when coding in Common Lisp. 1. They don't add anything new to the language semantically i.e. you can always used a named function to accomplish the same task as an unnamed one. 2. Giving a function a name acts as documentation (and a named function is more likely to be explicitly documented than an unnamed one). This argument is pragmatic rather than theoretical. 3. It adds another construction to the language. Cheers, Brian From tim.golden at viacom-outdoor.co.uk Thu May 18 11:30:40 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 18 May 2006 16:30:40 +0100 Subject: Python Install Message-ID: [D] | Thanks, Paul - do you know where I can get the RPM? I only see the | source on the Python website. Thanks. http://www.python.org/pyvault/ (first Google hit for site:python.org RPM) 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 siona at chiark.greenend.org.uk Thu May 4 11:27:42 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 May 2006 16:27:42 +0100 (BST) Subject: Subclassing array References: <1146747096.623101.122510@j73g2000cwa.googlegroups.com> <1heszg6.1q17bgp1jwua35N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: >TG wrote: >> When I call Vector.__init__() in Stimulus, doesn't it also call __new__ >> ? I don't understand the detail of callings to __new__ and __init__ in >> python inheritance ... >Calling a (new-style) class does __new__ first, THEN calls the class's >__init__ on the resulting instance -- and the arguments you're passing >when calling the class go to both __new__ and __init__. ... so you might want something like: class Vector(array): def __new__(cls,*args): return super(Vector,cls).__new__(cls,'f') -- \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 andy at neotitans.com Wed May 17 14:06:00 2006 From: andy at neotitans.com (Andy Sy) Date: Thu, 18 May 2006 02:06:00 +0800 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <1147885294.044080.132570@38g2000cwa.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <1147885294.044080.132570@38g2000cwa.googlegroups.com> Message-ID: achates wrote: > Andy Sy: >> Code with anything other than 8-space tabs will *NEVER* display >> properly using everyday unix utilities such as less and cat. > > less -x does what you want. > Ok, that tip certainly counts for something. This is definitely going to make viewing tabbed code suck much less (although you still have to guess the tab setting using trial and error). Next major objection then, how can one practically use 'tabs as semantic indentation' without screwing up formatting of code like the below?? def sqlcall(): cursor.execute('select id, item, amount, field4, field5, field6'+ 'from table1 where amount>100') ... if you change the tabsize then the 3rd line will no longer properly align with the start of the quote in the 2nd line. The 3rd line makes use of _arbitrary_, not semantic indentation. Because you cannot count on indentation to be semantics-driven on every single line, you _will_ end up mixing semantic and arbitrary indentation and thus the whole notion of being able to use tabs as 'semantic indentation' is *still untenable*. There is JUST NO PRACTICAL USE FOR TABS. -- It's called DOM+XHR and it's *NOT* a detergent! From mscottschilling at hotmail.com Fri May 26 19:18:39 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Fri, 26 May 2006 23:18:39 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <447479A1.8050809@hotORgooMAIL.invalid> <3j0dg.27$u4.11@newsread1.news.pas.earthlink.net> <87slmwbhx5.fsf@wolfbone.ath.cx> Message-ID: "P.L.Hayes" wrote in message news:87slmwbhx5.fsf at wolfbone.ath.cx... > > I agree. I have already written to Dreamhost and I hope more people > will do so. I have found some of what has been posted here quite > astonishing and the actions of certain people to be reprehensible: by > far the most serious violation of netiquette I see here is this > thoroughly wrong-headed campaign to try to censor Xah by appealing to > his service provider. No one that I know of is trying to censor Xah. It's the form his postings take that cause problems, not the content. > In my opinion it is that, not anything Xah has > done, which comes any where near deserving any sort of termination of > access to the Internet. Bringing facts to their attention? If Dreamhost has given him notice of termination, it's for violating their policies, not because people have told them "I don't like him". > Since Xah's website is hosted by Dreamhost, > the unwarranted censorship will be compounded by an act of gratuitous > vandalism, potentially depriving people of useful resources: He's free to find another ISP and *not* violate their rules. From spudtheimpaler at hotORgooMAIL.invalid Wed May 24 11:20:01 2006 From: spudtheimpaler at hotORgooMAIL.invalid (Mitch) Date: Wed, 24 May 2006 16:20:01 +0100 Subject: John Bokma harassment In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> Message-ID: <447479A1.8050809@hotORgooMAIL.invalid> John Bokma wrote: [...] > You're mistaken. All you need to do is report it. After some time Xah will > either walk in line with the rest of the world, or has found somewhere > else to yell. As long as it's not my back garden and not around 4AM, I am > ok with it. > Walk in line with the rest of the world? Pah. This is no-ones back garden. From fphsml at gmail.com Sat May 20 15:42:44 2006 From: fphsml at gmail.com (James) Date: 20 May 2006 12:42:44 -0700 Subject: combining a C# GUI with Python code? In-Reply-To: <3Dnbg.2135$No6.46516@news.tufts.edu> References: <3Dnbg.2135$No6.46516@news.tufts.edu> Message-ID: <1148154164.393830.276000@j73g2000cwa.googlegroups.com> Yes! It is. Just make your GUI in C# and assign event handlers using Python for .NET http://www.zope.org/Members/Brian/PythonNet/ Python for .NET is a great tool and has a minimal learning curve. Unfortunately, it hasn't attracted enough attention from the Python community. It does not have a .NET 2.0 release yet but it is in the works. Or you could use Boo with SharpDevelop. You will get Visual form design with a very Pythonic language. But you won't get to use Python libraries. IronPython is getting IDE integration in the CTP releases for Visual Studio. Maybe it will support form design in the future. I have not tried it yet. From sjmachin at lexicon.net Wed May 24 19:10:50 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 May 2006 09:10:50 +1000 Subject: Why can't timedeltas be divided? In-Reply-To: References: <1148508445.853563.170030@i39g2000cwa.googlegroups.com> Message-ID: <4474E7FA.4080001@lexicon.net> On 25/05/2006 8:25 AM, Maric Michaud wrote: > Le Jeudi 25 Mai 2006 00:07, Dan Bishop a ?crit : >> If I try to write something like: >> >> num_weeks = time_diff / datetime.timedelta(days=7) > > because it has no meaning, what you want is : > > num_weeks = time_diff.days / 7 > or > num_weeks = (time_diff / 7).days > > The ratio of two durations has no meaning??? From mramos at montevideo.com.uy Tue May 16 13:51:00 2006 From: mramos at montevideo.com.uy (Marcelo Ramos) Date: Tue, 16 May 2006 14:51:00 -0300 Subject: How to pass variables between scripts? In-Reply-To: <5290E77B1FE2FE40B82AA54158825F0602EF50F9@hqosex01.fao.org> References: <5290E77B1FE2FE40B82AA54158825F0602EF50F9@hqosex01.fao.org> Message-ID: <446A1104.5050309@montevideo.com.uy> Gross, Dorit (SDRN) escribi?: >>> #! /usr/local/bin/python >>> # test_exec.py >>> >>> import os, sys, glob >>> >>> fileList = glob.glob('/data/*.ZIP') >>> >>> for f in fileList: >>> try: >>> globvars = {'infile' : f} >>> locvars = {} >>> execfile('/scripts/second.py', globvars(), locvars) >>> except IOError: >>> exit(0) >>> print locvars >>> >>> >>> >> You are calling the dictionary globvars as a function then the error. >> The fixed line is: >> >> execfile('/scripts/second.py', globvars, locvars) >> >> >> >> What you want is the function globals(). >> Try putting this line in second.py: >> >> print globals()['infile'] >> >> Using the dictionary returned by globals() you can make second.py to >> read the contents of testexec.py's globvars dictionary. >> locvars is populated with the local variables of second.py >> and that is >> what you want. >> >> > > Marcelo, thank you! Passing the variables with dictonaries and function > globals() works fine if no other functions are defined in 'second.py'. Now > 'second.py' contains further functions and a "if __name__ = __main__" > statement and in this case it seems that 'second.py' is not fully executed > from 'test_exec.py'. For the sole purpose of testing, 'second.py' looks like > this at the moment: > > #! /usr/local/bin/python > # second.py > > import os, sys > > global zipfile > print 'Read from globals: ' + globals()['infile'] > zipfile = globals()['infile'] > print 'Read from zipfile: ' + zipfile > > if __name__ == '__main__': > > print 'Hello' > print globals()['infile'] > print zipfile > > > Calling test_exec.py results into this output: > > ./test_exec.py > Read from globals: /data/S0012230_0010.ZIP > Read from zipfile: /data/S0012230_0010.ZIP > > > It seems that the commands within the main are not executed when calling > test_exec.py!?! Is there a way to make it running? > > Regards and thank you again, > Dorit > > > If you print __name__ in second.py its value is '__builtin__', because of that your "main" doesn't execute. Try adding this to test_exec.py before the execfile() call: globvars[ '__name__' ] = '__main__' It looks like a ad hoc fix but i couldn't find any doc about the change of __name__ to 'builtin' of a python script being run from another with execfile(). Regards. -- Marcelo Ramos Fedora Core 5 | 2.6.16 Socio UYLUG Nro 125 From martin at v.loewis.de Fri May 19 10:42:38 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 19 May 2006 16:42:38 +0200 Subject: Encode exception for chinese text In-Reply-To: <1148042447.460782.156990@j73g2000cwa.googlegroups.com> References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> <1148037335.595690.49030@g10g2000cwb.googlegroups.com> <1148039249.873491.234770@38g2000cwa.googlegroups.com> <1148042447.460782.156990@j73g2000cwa.googlegroups.com> Message-ID: <446DD95E.4080802@v.loewis.de> John Machin wrote: > 1. *By definition*, you can encode *any* Unicode string into utf-8. > Proves nothing. > 2. \u00a0 [no-break space] has no equivalent in gb2312, nor in the > later gbk alias cp936. It does have an equivalent in the latest Chinese > encoding, gb18030. Also, *by definition*, though :-) For those that have not followed encodings too closely: gb18030 is to gb2312 what UTF-8 is to ASCII. Both encode the entire Unicode in an algorithmic way, and provide byte-for-byte identical encodings for the for their respective subset. Regards, Martin From phil at riverbankcomputing.co.uk Mon May 8 10:11:49 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Mon, 8 May 2006 15:11:49 +0100 Subject: Scaled Vector Graphics In-Reply-To: <57aa55060605080658p48c6ddd0g71bc88201909e867@mail.gmail.com> References: <57aa55060605080658p48c6ddd0g71bc88201909e867@mail.gmail.com> Message-ID: <200605081511.49754.phil@riverbankcomputing.co.uk> On Monday 08 May 2006 2:58 pm, Greg Lindstrom wrote: > I have been asked to write a routine to merge documents in pfd and svg > formats into a single file (preferably pfd format). Currently we send the > pdf image to the printer followed by the svg image (a scan of a health care > claim) but this is not a satisfactory solution. We have as many as 3000 > document pairs daily (another project in development will send all the > information to out clients electronically via EDI X12 format). > > Does Python offer support for working with svg files? I've looked at the > PIL and Reportlab packages and Googled around but have not found anything. > My other option is to snag one of the routines I've found that claim to > convert scg to pdf and then merge them as pdf files. > > Any help or suggestions you may supply will be greatly appreciated, PyQt4 supports the rendering of SVG images onto PDF via the QSvgRenderer and QPrinter classes. Phil From steve at hastings.org Fri May 5 23:56:03 2006 From: steve at hastings.org (Steve R. Hastings) Date: Fri, 05 May 2006 20:56:03 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> Message-ID: On Fri, 05 May 2006 21:16:50 -0400, Ken Tilton wrote: > The upshot of > what he wrote is that it would be really hard to make semantically > meaningful indentation work with lambda. Pretty much correct. The complete thought was that it would be painful all out of proportion to the benefit. See, you don't need multi-line lambda, because you can do this: def make_adder(x): def adder_func(y): sum = x + y return sum return adder_func add5 = make_adder(5) add7 = make_adder(7) print add5(1) # prints 6 print add5(10) # prints 15 print add7(1) # prints 8 Note that make_adder() doesn't use lambda, and yet it makes a custom function with more than one line. Indented, even. You could also do this: lst = [] # create empty list def f(x): return x + 5 lst.append(f) del(f) # now that the function ref is in the list, clean up temp name print lst[0](1) # prints 6 Is this as convenient as the lambda case? lst.append(lambda x: x + 7) print lst[1](1) # prints 8 No; lambda is a bit more convenient. But this doesn't seem like a very big issue worth a flame war. If GvR says multi-line lambda would make the lexer more complicated and he doesn't think it's worth all the effort, I don't see any need to argue about it. > But the key in the whole thread is simply that indentation will not > scale. Nor will Python. This is a curious statement, given that Python is famous for scaling well. I won't say more, since Alex Martelli already pointed out that Google is doing big things with Python and it seems to scale well for them. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From bdesth.quelquechose at free.quelquepart.fr Sat May 27 15:40:22 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 27 May 2006 21:40:22 +0200 Subject: dynamic type changing In-Reply-To: <1148740408.226975.318050@u72g2000cwu.googlegroups.com> References: <1148740408.226975.318050@u72g2000cwu.googlegroups.com> Message-ID: <44787bc6$0$19572$636a55ce@news.free.fr> andychambers2002 at yahoo.co.uk a ?crit : > I'm working on a "TempFile" class that stores the data in memory until > it gets larger than a specified threshold (as per PEP 42). Whilst > trying to implement it, I've come across some strange behaviour. Can > anyone explain this? > > The test case at the bottom starts a TempFile at size 50 and prints its > type. It then increases the size to the threshold at which point > "self" is changed to being a TemporaryFile. Changed how ?-) > It seems that the next > call correctly uses the write() method of TemporaryFile (since we don't > see "changing type" in the output). However, type(tmp) still equals > TempFile. Not only that, tmp can still access the method dummy() that > exists only in TempFile. > > #!/usr/bin/env python > from StringIO import StringIO > import tempfile > > class TempFile(StringIO, object): > """A temporary file implementation that uses memory unless > either capacity is breached or fileno is requested, at which > point a real temporary file will be created and the relevant > details returned > """ > def __init__(self, buffer, capacity): > """Creates a TempFile object containing the specified buffer. > If capacity is specified, we use a real temporary file once the > > file gets larger than that size. Otherwise, the data is stored > > in memory. > """ > self.capacity = capacity > if len(buffer) > capacity: > self = tempfile.TemporaryFile() assigning to 'self' in a method doesn't impact the object itself - it only rebinds the *local* name 'self' for the rest of the block. If you want to change the class of an object, you must assign to self.__class__ - but, while perfectly legal (and in fact the simplest possible implementation of the state pattern in Python), it may be somewhat risky. (snip) > def write(self, str): > self.seek(0, 2) # find end of file > if((self.tell() + len(str)) >= self.capacity): > print "changing type" > flo = tempfile.TemporaryFile() > flo.write(self.getvalue()) > self = flo > print type(self) Same comment here. (snip) Now for a practical solution : what you want is the strategy pattern. from StringIO import StringIO from tempfile import TemporaryFile import sys class TempFile(object): """A temporary file implementation that uses memory unless either capacity is breached or fileno is requested, at which point a real temporary file will be created and the relevant details returned """ _strategies = (StringIO, TemporaryFile) def __init__(self, buffer, capacity): """Creates a TempFile object containing the specified buffer. If capacity is specified, we use a real temporary file once the file gets larger than that size. Otherwise, the data is stored in memory. """ self.capacity = capacity self._delegate = self._strategies[len(buffer) > self.capacity]() self.write(buffer) def write(self, value): print >> sys.stderr, \ "about to write %d more characters" % len(value) if isinstance(self._delegate, self._strategies[0]): len_value = len(value) if len_value >= self.capacity: needs_new_strategy = True else: self.seek(0, 2) # find end of file needs_new_strategy = \ self.tell() + len_value >= self.capacity if needs_new_strategy: print >> sys.stderr, "changing strategy" new_delegate = self._strategies[1]() new_delegate.write(self.getvalue()) self._delegate = new_delegate self._delegate.write(value) def __getattr__(self, name): # Takes care of automatic delegation, # customize this according to your needs. # Hint : this will only be called if normal lookup # failed, so to control access to any _delegate's method, # just implement a method with same name try: return getattr(self._delegate, name) except AttributeError: # hide the delegation e = "object '%s' has no attribute '%s'" \ % (self.__class__.__name__, name) raise AttributeError(e) if __name__ == "__main__": print "testing tempfile:" tmp = TempFile("", 100) ten_chars = "1234567890" tmp.write(ten_chars * 5) print "tmp < 100: ", tmp._delegate.__class__.__name__ tmp.write(ten_chars * 5) print "tmp == 100: " , tmp._delegate.__class__.__name__ tmp.write("the last straw") print "tmp > 100: " , tmp._delegate.__class__.__name__ From john at castleamber.com Wed May 17 18:05:38 2006 From: john at castleamber.com (John Bokma) Date: 17 May 2006 22:05:38 GMT Subject: [silly] Does the python mascot have a name ? References: Message-ID: John D Salt wrote: > Andy Sy wrote in > news:mailman.5791.1147860411.27775.python-list at python.org: > >> http://mail.python.org/pipermail/python-list/2003-September/185612.html > > "Odi" must be the Dutch for "Monty". Nope. If it was Dutch it would probably be Odie -- 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 rpdooling at gmail.com Fri May 26 14:59:20 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 26 May 2006 11:59:20 -0700 Subject: Python for my mum In-Reply-To: <5opjk3-dam.ln1@lairds.us> References: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> <1148644991.633948.32260@j55g2000cwa.googlegroups.com> <5opjk3-dam.ln1@lairds.us> Message-ID: <1148669959.938843.177550@j73g2000cwa.googlegroups.com> Cameron, The "7 Minutes To Hello World" IS the ActiveState distribution. It's just hand-holding, click here, click there, for the person who doesn't know what "Windows/x86" means on the install page, or perhaps doesn't know what to do with the interpreter once it's installed. From andy at neotitans.com Wed May 17 10:43:22 2006 From: andy at neotitans.com (Andy Sy) Date: Wed, 17 May 2006 22:43:22 +0800 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: Peter Decker wrote: > On 5/17/06, Andy Sy wrote: >> Peter Decker wrote: >>> On 5/17/06, Andy Sy wrote: >>> >>>> If tabs are easily misunderstood, then they are a MISfeature >>>> and they need to be removed. >>> I don't seem to understand your point in acting as a dictator. >>> Therefore, you are a MISfeature and need to be removed. >> Is the above an example of how a tab-user exercises 'logic'...? > > Uh, I should know better than to try to educate, but FYI: using the > same argument construction and having it reach an invalid conclusion > suffices to show that the original construction is invalid, and thus > the original conclusion is suspect. I guess this *REALLY* is how a misguided tab user exercises his 'logic': Syntax replication (e.g. so-called 'argument construction') is enough, semantics don't matter. ROTFLMAO! -- It's called DOM+XHR and it's *NOT* a detergent! From penneys at bigfoot.com Tue May 16 04:26:18 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 16 May 2006 01:26:18 -0700 Subject: IDLE confusion Message-ID: <1147767977.928350.261650@i39g2000cwa.googlegroups.com> Hi, I'm trying to use IDLE to develop My First Python App and my head hurts... I've a file called spalvi.py with this in it: from Test import * firstTest("Mike") And a file called Test.py with this in it: def firstTest(name): print "Yo",name I open spalvi.py with IDLE and Run it. It says "Yo Mike". I use the File menu to open Test.py and change the message from "Yo" to "Hi". I Run it again.... it still says "Yo Mike" :-( I close everything down, open spalvi.py with IDLE and Run it again. It says "Hi Mike". So I'm obviously not using IDLE in the "right" way. But what *is* the "right" way, when you're trying to develop using several source files? John From duncan.booth at invalid.invalid Fri May 12 16:02:53 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 May 2006 20:02:53 GMT Subject: New tail recursion decorator References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> <1147437656.779139.54840@d71g2000cwd.googlegroups.com> <1147441799.331677.88460@d71g2000cwd.googlegroups.com> <1147452169.797342.43740@g10g2000cwb.googlegroups.com> Message-ID: Kay Schluehr wrote: > Duncan Booth wrote: > >> The decorator also fails for functions which are tail-recursive but >> which contain other non-tail recursive calls within themselves. For >> example I would be pretty sure you couldn't write a working >> implementation of Ackermann's function using the decorator: >> >> def Ack(M, N): >> if (not M): >> return( N + 1 ) >> if (not N): >> return( Ack(M-1, 1) ) >> return( Ack(M-1, Ack(M, N-1)) ) > > Definitely. The translation into a proper tail-recursive form is > non-trivial but nevertheless possible as demonstrated by the following > Ackermann implementation: > > @tail_recursion > def ack(m,n,s=[0]): # use a stack-variable s as "accumulator" > if m==0: > if s[0] == 1: > return ack(s[1]-1,n+1,s[2]) > elif s[0] == 0: > return n+1 > elif n==0: > return ack(m-1,1,s) > else: > return ack(m,n-1,[1,m,s]) > Very clever, although simulating a stack isn't exactly eliminating recursion. Any idea how long I have to wait to find ack(4,1)? From danmcleran at yahoo.com Sat May 6 20:28:44 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 6 May 2006 17:28:44 -0700 Subject: Splice two lists Message-ID: <1146961724.195038.18680@u72g2000cwu.googlegroups.com> Is there a good way to splice two lists together without resorting to a manual loop? Say I had 2 lists: l1 = [a,b,c] l2 = [1,2,3] And I want a list: [a,1,b,2,c,3] as the result. I've been searching around but I can't seem to find a good example. Thanks, Dan McLeran From fredrik at pythonware.com Fri May 19 09:51:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 15:51:40 +0200 Subject: Which is More Efficient? References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com><1147974619.413812.112780@i39g2000cwa.googlegroups.com><1147990753.406649.80150@y43g2000cwc.googlegroups.com><1147991742.990761.144730@j73g2000cwa.googlegroups.com> <1148036087.843911.307990@u72g2000cwu.googlegroups.com> Message-ID: Dustan wrote: > The task manager says "CPU Usage: 100%" when the program is running, > and only when the program is running. > > Efficiency is a measure of 2 things: CPU usage and time. If you measure > just time, you're not necessarily getting the efficiency. are you for real? From alikakakhel at yahoo.com Tue May 30 23:18:19 2006 From: alikakakhel at yahoo.com (greenflame) Date: 30 May 2006 20:18:19 -0700 Subject: shuffling elements of a list Message-ID: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> I would like to make a function that takes a list, more specificaly a list of strings, and shuffles its elements, like a pile of cards. The following is a script I tryed to make that implements pile shuffling. ---------- testdeck = list('qwertyuiop') def pileshuffle(DECK, NUMPILES): """Split the deck given into NUMPILES piles. Then also put the piles""" \ """ together to make the deck again.""" # Define a list of lists which is the piles PILES = [[]] * NUMPILES card = 0 pilenum = 0 while card < len(DECK): PILES[pilenum].append(DECK[card]) card += 1 if pilenum < NUMPILES: pilenum += 1 else: pilenum = 0 print PILES ---------- First of all, this script tells me that an index is out of range. I cannot see why this would be so. Second of all, I would like to have other methods of shuffling, prefererably riffle shuffling and just plain randomly arranging the elements of the list. I very much appreciate any help. Thank you. From john at castleamber.com Wed May 24 12:05:08 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 16:05:08 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <1148485967.164221.304310@y43g2000cwc.googlegroups.com> Message-ID: fup-to poster "Ant" wrote: > John Bokma wrote: >> That's because you're clueless. > > Well argued. No really. Not quite sure what you base the allegations > on of course. Like I said, clueless. > John, you're well out of order getting this guy into problems with his > ISP. Based on what "order"? The law of the Usenet Kook? > Ken Tilton has it spot on - if everyone who wasn't interested in > what he had to say ignored it, then it would make it far easier for > those actually interested in the topic to reply, without a tirade of > off topic abuse to filter through. If Xah posts to just one group, on topic, the problem is gone. But Xah is spamvertizing his website, and hence posts to 5 groups (since I guess that's a limit GG sets, not Xah), so he doesn't care that a post on whitespace in Python ends up in a group on Java or Perl. > I'm not a particular Xah fan, but I do find some of the threads > provoked by his posts interesting. What is more of a concern to me is > that he should have freedom to post on relevant newsgroups. He has. > Take a look > at his site. You'll find that he is actually interested in the 5 or so > newsgroups he cross-posts to, and his posts are general enough to > apply to each of them. In that very rare case he should pick a single group that matches his diatribe the best. And in the very rare case that 3 groups are on topic, he could set a follow up to. > In short, get off of your soap box - if you don't like what the guy > has to say then *ignore it*. No, that's the joke. I won't ignore it. And you're mistaken to think I am the only one that has reported Xah. It's simple: Xah has to stick to the netiquette, or complaints will go to his next hosting provider. In the end Xah either pays quite some money for bullet proof hosting (since that is what a host that offers a safe haven to spammers is called), or he goes yelling somewhere else. > FYI - I have written in support of Xah Lee to the ISP simply because I > don't see why your personal problem with the guy should cost him > money. So you waste money of an ISP... The decision has been made, a few days ago even. -- 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 me+python at modelnine.org Sun May 14 08:39:04 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 14 May 2006 14:39:04 +0200 Subject: send an email with picture/rich text format in the body In-Reply-To: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> Message-ID: <200605141439.04567.me+python@modelnine.org> Am Sonntag 14 Mai 2006 13:24 schrieb anya: > I want to send an email message with picture in it. This... > I dont want to put > it as > attachment but make it in the body of the mail, so every one who open > the email will see the picture.. will... > (it is possible that the solution will > be in any other format that will be opened i.e pdf, doc and I will put > this in the body ) never... > Neither in MimeWriter nor using the definition of MymeTypes I was able > to do it .. work. That is, unless you design your own MIME standard, and get all email clients out there to read your type of "structured document," which you inherently need for including pictures directly in an email (body), as MIME (as we know it today) only knows about stacked message parts, not about message content and higher level formatting. Basically, to include a picture in a body today, there's concensus that you insert a HTML-document into one MIME part, and an link refers to the attachment that comes in another MIME part (by the filename, which is the same as for the attached MIME part). But, as you see, this specifically requires that the recipient is able to view HTML mails (which quite a lot of people, even those using M$ Outlook, have turned off by default). Anyway, read Ben Finney's response carefully. If you're trying to send out commercial email, I'll be the first person to dump your mail if it doesn't at least come in a format I can read (and understand!) text-only. --- Heiko. From iddw at hotmail.com Wed May 10 10:07:36 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 10 May 2006 09:07:36 -0500 Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <44605c5f$0$7085$626a54ce@news.free.fr> Message-ID: On Wed, 10 May 2006 06:44:27 GMT in comp.lang.python, Edward Elliott wrote: > >Would I recommend perl for readable, maintainable code? No, not when better >options like Python are available. But it can be done with some effort. I'm reminded of a comment made a few years ago by John Levine, moderator of comp.compilers. He said something like "It's clearly possible to write good code in C++. It's just that no one does." Regards, -=Dave -- Change is inevitable, progress is not. From newsgroup at farc-ep.com Thu May 25 19:15:21 2006 From: newsgroup at farc-ep.com (Sender) Date: 25 May 2006 16:15:21 -0700 Subject: Survey on open-source software for the desktop Message-ID: <1148598921.493413.79580@38g2000cwa.googlegroups.com> I just submit the questionnaire to Digg, you can digg for it here: http://digg.com/software/Survey_on_open-source_software_for_the_desktop And if you want to fill out the questionnaire, here it is: http://freeonlinesurveys.com/rendersurvey.asp?sid=iegzi2sbv9j9g8h195091 Thanks for your contribution! From apardon at forel.vub.ac.be Wed May 10 07:25:09 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 May 2006 11:25:09 GMT Subject: Proposal: Base variables Message-ID: When you want to specify a location or moment, it sometimes is easier to do so in an absolute way and sometimes it is easier to do so relative to some kind of base. Examples of this are the Scheduler objects with the enter and enterabs methods and the seek method of files. However python has no unified approach for handling these cases. In the case of Schedular objects the choice was made to have two methods. In one method (enterabs) the "time" is interpreted as an absolute time. In the other method (enter) the "time" is interpreted relative to the moment of the call. With seeking in files the choice was made to use an extra parameter. The second parameter of the seek method determines relative to what the where parameter is to be interpreted. My idea is a third approach which (would it be accepted) should replace the other two so we would have one obvious way to do this in Python The idea is to to use symbolic bases when you want to specify a time or location relatice to something else. The standard bases would be among the following: Front, Rear, Position, Now So if you want to seek 90 bytes from the end, you use: Rear - 90 If you want something to happen 900 second from now you use: Now + 900. So we would have the following calls: fl.seek(Rear - 90) shed.enter(Now + 90) The adavantages: One unified approach, that doesn't require extra methods or extra parameters. By using appropiate symbolic names the code is also more clear about what it does. The disadvantages: functions that use these variables as argument may be a bit more complicated to write. The Base variables can't be combined. Writing fl.seek((Front + Rear) / 2) wont work A sample implementation of these variables and a seek function using them is below, any comments? --------------------------------------------------------------------- def NewBase(): class Base(object): def __init__(self, offset = 0): self.offset = offset def __add__(self, term): return Base(self.offset + term) def __sub__(self, term): return Base(self.offset - term) def __repr__(self): if self.offset < 0: return "< * - %s >" % abs(self.offset) else: return "< * + %s >" % self.offset return Base FrontType = NewBase() NowType = NewBase() RearType = NewBase() PosType = NewBase() Front = FrontType(0) Now = NowType(0) Rear = RearType(0) Pos = PosType(0) def seek(fl, where): if type(where) == RearType: return fl.seek(where.offset, 2) elif type(where) == PosType: return fl.seek(where.offset, 1) elif type(where) == FrontType: return fl.seek(where.offset, 0) return fl.seek(where, 0) fl = file('test') seek(fl, Rear - 90) fl.read() -- Antoon Pardon From michele.simionato at gmail.com Thu May 25 03:42:17 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 25 May 2006 00:42:17 -0700 Subject: How does a generator object refer to itself? In-Reply-To: <1148311069.417177.254550@y43g2000cwc.googlegroups.com> References: <1148311069.417177.254550@y43g2000cwc.googlegroups.com> Message-ID: <1148542937.078674.223580@i40g2000cwc.googlegroups.com> Why don't you use a class ? class MyGen(object): def __iter__(self): for i in range(2): yield "I know who I am %s" % self gen_obj = MyGen() for x in gen_obj: print x For language lawyers: strictly speaking gen_obj is not a generator object (since it is restartable) but it may work for you anyway. Michele Simionato From onurb at xiludom.gro Wed May 3 05:15:14 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 11:15:14 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <4457fc52$0$31159$636a55ce@news.free.fr> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> <4457fc52$0$31159$636a55ce@news.free.fr> Message-ID: <445874fe$0$12865$626a54ce@news.free.fr> Bruno Desthuilliers wrote: (snip) > Since Python 3K is supposed to be the 'clean the warts and don't bother > breaking compat' rewrite of Python, you may as well propose a PEP on > this. You'll have to really prove it doesn't break anything else in the > object model, have strong and articulate arguments to support your point > (like proving this is really a common source of confusion for newbies), And of course propose an implementation - perhaps the compiler.ast could be useful ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From OlafMeding at gmail.com Tue May 30 16:08:32 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 30 May 2006 13:08:32 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1149019712.662721.77450@g10g2000cwb.googlegroups.com> Update The problem turned out to be the BIOS of the PC we were using. The Python test program has been running fine for 5 days now (after we upgraded the system BIOS) and is still running fine. Sorry, I do not have any information as to what was fixed in the BIOS. Also, I do not know exactly who made the motherboard or the BIOS. I will post another update if this information becomes available. This was sure a strange bug! Olaf From eadmund42 at NOSPAMgmail.com Wed May 10 13:53:26 2006 From: eadmund42 at NOSPAMgmail.com (Robert Uhl) Date: Wed, 10 May 2006 11:53:26 -0600 Subject: A critic of Guido's blog on Python's lambda References: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> Message-ID: Ken Tilton writes: > > Set Kelvin, and make Celsius and Fahrneheit functions of that. Or Rankine:-) -- Robert Uhl Brought to you by 'Ouchies', the sharp, prickly toy you bathe with... From rupole at hotmail.com Thu May 4 01:56:06 2006 From: rupole at hotmail.com (Roger Upole) Date: Thu, 4 May 2006 01:56:06 -0400 Subject: Playability of a file in windows media player References: <1146660038.890159.167130@j73g2000cwa.googlegroups.com> Message-ID: <1146721959_1203@sp6iad.superfeed.net> The below code will catch the OnError event that's triggered when you specify a bad URL. import win32com.client class wmpevents: def OnOpenStateChange(self, NewState): """Sent when the control changes OpenState""" print 'OnOpenStateChange', NewState if NewState==win32com.client.constants.wmposMediaOpen: print "Media successfully opened" def OnError(self): """Sent when the control has an error condition""" print 'OnError' print self.Error.Item(0).errorCode, self.Error.Item(0).errorDescription self.Error.clearErrorQueue() win32com.client.gencache.EnsureDispatch('WMPlayer.OCX',0) w=win32com.client.DispatchWithEvents('WMPlayer.OCX', wmpevents) w.URL='some bad URL' Roger "sri2097" wrote in message news:1146660038.890159.167130 at j73g2000cwa.googlegroups.com... > Basically, > I want to check if a URL is playable or not (without actually playing > it). > i.e. given a URL I want to write an automation script to figure it out > for me > if it's playable or not. If you give a bad/invalid URL for windows > media > player to play a pop-up window shows us that it cannot be played. So > I would want to catch that event. > > I have found 2 ways to do this - > > 1) > > import win32com.client, win32api, sre, time > > data = file("webclips.txt") > web_clips = data.readlines () > > shell = win32com.client.Dispatch("WScript.Shell") > shell.Run("wmplayer.exe") > shell.AppActivate("Windows Media Player") > win32api.Sleep(100) > > print "Total :", len(web_clips) > > for webclip in web_clips: > shell.SendKeys("^u", 0) > shell.AppActivate("Open URL") > > shell.SendKeys("{DEL}") > shell.SendKeys(webclip) > shell.SendKeys("~") > time.sleep(25) > > if shell.AppActivate("Windows Media Player"): > webclip = webclip > not_there.append(webclip) > shell.SendKeys("~") > > print len(not_there) > print "Not here: ", not_there > ~ > > In this way I manually fire Windows media player and do the checking. > But It's a brute force way of solving the problem (since for every URL > I keep a > time-out of 25 seconds). As a result it takes a lot of time.I had to > look for a > better solution. My second solution uses Windows much hyped ActiveX > controls. > > 2) > > from win32com.client import Dispatch,DispatchWithEvents > > class WMPEvents: > def OnVisible(self,evt): > print "OnVisible changed:",evt > def OnError(self,evt=None): > print "OnError",evt > def OnMediaError(self,evt=None): > print "OnMediaError",evt > def OnDisconnect(self,evt): > print "OnDisconnect",evt > def OnStatusChange(self): > print "OnStatusChange" > def OnDisconnect(self,evt): > print "Disconnect",evt > def OnBuffering(self,evt): > print "OnBuffering changed:",evt > def OnOpenStateChange(self,evt=None): > print "OnOpenStateChange" ,evt > > mp = DispatchWithEvents("WMPlayer.OCX", WMPEvents) > mp.settings.autoStart = True > webclip_playlist = mp.newPlaylist('Web_Clips', "") > > raw_web_clips = [] > data = file("webclips.txt") > web_clips = data.readlines() > > for url in web_clips: > tune = mp.newMedia(url) > mp.currentPlaylist.appendItem(tune) > mp.controls.playItem (tune) > mp.controls.play() > mp.controls.stop() > > raw_input("Press enter to stop playing") > mp.controls.stop() > mp.close() > > This solution is much faster. But still I'm not able to solve it. > Initially I had > planned to use the "OnOpenStateChange" event to detect if a given URL > is in > a state just about to be opened. That's good enough for me to declare > that a > URL can be played. But as written in MSDN, they suggest not to rely on > state > changes as a definitive way to find details. So, I had to find an > alternative. > There is an event called "OnBuffering", i.e. when a link is found and > is just > about to be buffered this event (Boolean value) is triggered. But it > never seem > to happen. > > I would be truly grateful if you can help in any way. > From sjmachin at lexicon.net Thu May 18 13:51:36 2006 From: sjmachin at lexicon.net (John Machin) Date: 18 May 2006 10:51:36 -0700 Subject: Feature request: sorting a list slice In-Reply-To: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> Message-ID: <1147974696.448816.119100@i39g2000cwa.googlegroups.com> Use case? From cfbolz at gmx.de Sun May 21 09:03:06 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 21 May 2006 15:03:06 +0200 Subject: misleading prefix ++ In-Reply-To: References: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> Message-ID: Edward Elliott wrote: > Peter Otten wrote: [snip] > > Now that is absolutely lovely. Looks like it's time to join the ranks of > Perl and C with an Obfuscated Python Contest. ;) > yes, please! and you get special points for programs that seem to do one thing but do something totally entirely different :-). Cheers, Carl Friedrich From umut.tabak at gmail.com Mon May 8 10:37:07 2006 From: umut.tabak at gmail.com (utab) Date: 8 May 2006 07:37:07 -0700 Subject: Python Graphics Library Message-ID: <1147099026.983602.148160@v46g2000cwv.googlegroups.com> Dear all, Could you please recommend me a graphics library for python. I saw PYX which has nice screenshots on the webpage. My first ambition is to be able to draw 2D or 3D graphs for my mathematical results. Maybe later, I can handle other types of graphical operations. Regards. From bj_666 at gmx.net Fri May 26 17:51:13 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 26 May 2006 23:51:13 +0200 Subject: write() vs. writelines() References: <1148667630.902170.310930@i40g2000cwc.googlegroups.com> <1148669055.390737.57050@j33g2000cwa.googlegroups.com> Message-ID: In <1148669055.390737.57050 at j33g2000cwa.googlegroups.com>, Gregory Petrosyan wrote: > Thanks for your reply. I understand this fact, but I wonder why > writelines() works slowly -- I think C code can be optimised to work > faster than Python one. Is it correct that writelines(...) is just a > shorthand for > > for ch in ...: > file.write(ch) > ? Depends on `...`. If it's a string then yes because a string is a sequence of characters. But `writelines()` is ment for a sequence of strings. It's the counterpart of `readlines()`. Then it's just a shorthand for:: for line in lines: file.write(line) Ciao, Marc 'BlackJack' Rintsch From tim.leeuwvander at nl.unisys.com Wed May 24 04:06:39 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 24 May 2006 01:06:39 -0700 Subject: documentation for win32com? In-Reply-To: <1148444403_20939@sp6iad.superfeed.net> References: <1148444403_20939@sp6iad.superfeed.net> Message-ID: <1148457999.379337.19910@j55g2000cwa.googlegroups.com> Roger Upole wrote: > The Excel docs are your best bet. The examples they give > are all MS-specific languages like VB, but most translate > fairly easily to Python. > > You can also run makepy on the Excel typelib, which will > generate a file with all the methods, events etc available > thru the Excel object model. > You should definately run makepy, it will be a great help, but there are objects for which you can still not get any 'help' from your IDE's autocompletion... In those cases you'll just have to wing it, and indeed refer to the Excel helpfiles for VBA methods/objects/etc. Look at some samples on the web, and experiment a lot (using the PythonWin IDE seems to work quite well for this kind of experimenting, perhaps IDLE would also do it quite well. Due to the dynamic nature of this kind of explorations, the pydev Eclipse plugin doesn't work well for it). > Also, searching this group and the pywin32 mailing list > for "excel.application" turns up a bunch of sample code. > > hth > Roger > > Cheers, --Tim From me+python at modelnine.org Sun May 21 16:53:08 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 21 May 2006 22:53:08 +0200 Subject: getattr for modules not classes In-Reply-To: <5f56302b0605211252k79b642efl5ff4653fe7d17768@mail.gmail.com> References: <5f56302b0605211252k79b642efl5ff4653fe7d17768@mail.gmail.com> Message-ID: <200605212253.08081.me+python@modelnine.org> Am Sonntag 21 Mai 2006 21:52 schrieb Daniel Nogradi: > Is there something analogous to __getattr__ for modules? > > I know how to create a class that has attributes from a list and > nothing else by overloading __getattr__ and making sure that the > accessed attribute appears in my list. Now I would like to do the same > with a module, say x.py, in which I have a list, say mylist, and after > importing x from another module I would like to be able to say x.one( > ) or x.two( ) if 'one' and 'two' are in mylist and raise an exception > if they aren't. Is this possible? Not really. But, why not create an instance of some custom type in x.py, and import that instance into the current namespace? Just as convenient. x.py ---- mylist = {"one":1,"two":2} class test(object): def __getattr__(self,name): return mylist.get(name,None) test = test() --- y.py --- from x import test print test.one print test.two print test.three --- --- Heiko. From gherron at islandtraining.com Thu May 11 13:05:38 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 11 May 2006 10:05:38 -0700 Subject: find all index positions In-Reply-To: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> Message-ID: <44636EE2.2030109@islandtraining.com> micklee74 at hotmail.com wrote: >hi >say i have string like this >astring = 'abcd efgd 1234 fsdf gfds abcde 1234' >if i want to find which postion is 1234, how can i achieve this...? i >want to use index() but it only give me the first occurence. I want to >know the positions of both "1234" >thanks > > > The regular expression module (called re) has a function (named finditer) that gives you what you want here. The finditer function will find all matches of a pattern in a string and return an iterator for them. You can loop through the iterator and do what you want with each occurrence. >>> import re >>> astring = 'abcd efgd 1234 fsdf gfds abcde 1234' >>> pattern = '1234' Perhaps just find the starting point of each match: >>> for match in re.finditer(pattern,astring): ... print match.start() ... 10 31 Or the span of each match: >>> for match in re.finditer(pattern,astring): ... print match.span() ... (10, 14) (31, 35) Or use list comprehension to build a list of starting positions: >>> [match.start() for match in re.finditer(pattern,astring)] [10, 31] And so on .... Of course, if you wish, the re module can work with vastly more complex patterns than just a constant string like your '1234'. Gary Herron From deets at nospam.web.de Tue May 30 07:32:40 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 May 2006 13:32:40 +0200 Subject: saving settings References: <4e07c8F1c7r6jU1@uni-berlin.de> <127m9nbemdmsha2@corp.supernews.com> Message-ID: <4e2ou0F1cbvi3U1@uni-berlin.de> Grant Edwards wrote: > Documents and settings aren't quite the same thing, but it's a > valid point. > >> Especially not the ones you wrote on that other machine. >> >> Seriously: Who is going to copy a executable around? > > I do. I copy putty.exe around all of the time. I download it every time, and if I didn't, I'd be pretty annoyed if I'd copy it to a friends machine containing ALL MY KEYS embedded into it. >> Do you know of any other program that behaves like that? > > Back in the day, that used to be fairly common under > DOS/Windows. Not that it's still not a really bad idea. Back in the day self-modifying code was the craze too. And _some_ people even do it in python :) Diez From mc_anjo at tamu.edu Mon May 22 23:48:41 2006 From: mc_anjo at tamu.edu (Chris Smith) Date: Mon, 22 May 2006 22:48:41 -0500 Subject: Includeing Python in text files In-Reply-To: <4ddilkF18fs7bU1@uni-berlin.de> References: <4ddilkF18fs7bU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Paolo Pantaleo wrote: > > >>I am working on this: >> >>I have a text file, containig certain section in the form >>> python code here >>py?> >> >>I parse the text file and substitute the python code with its result >>[redirecting sys.stdin to a StringIO]. It something like php or >>embedded perl. >> >>So my little toy works not bad, but I was wondering if such a feature >>already existed, if yes, can you point me out some links? > > > Its a templating system, and there are a gazillion out there. Some of them > are listed here: > > http://www.cherrypy.org/wiki/ChoosingATemplatingLanguage > > > Diez > > > I'm just getting into programming so this may be a dumb question...but why would you want to do this? What is templating good for? Chris From lrasinen at iki.fi Sun May 14 14:30:52 2006 From: lrasinen at iki.fi (Lasse Rasinen) Date: 14 May 2006 21:30:52 +0300 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> Message-ID: Ken Tilton writes: > ps. flaming aside, PyCells really would be amazingly good for Python. And > so Google. (Now your job is on the line. ) k Here's something I wrote this week, mostly as a mental exercise ;-) The whole code is available at , I'll include a test example below. Feel free to flame away ;-) (As for background: I like CL better as a language, but I also like Python a lot. However, I was employed for 3 years as a developer and maintainer in a Python data mining application, so I'm more fluent in Python than CL.) The code is mostly based on Kenny's descriptions of Cells in the following messages: <0mp7g.600$4q2.70 at fe12.lga> In addition, I have looked at the CL source code briefly, but I'm not sure if any concepts have survived to the Python version. Since Python's object model is sufficiently different, the system is based on rules being defined per-class (however, if you define a rule by hand in the __init__ function, it'll work also. I think; haven't tested). I can possibly be persuaded to fix bugs in the code and/or to implement new features ;-) Features: - Tracks changes to input cells dynamically (normal attributes are not tracked) - Callbacks for changes (see caveats) - Requires Python 2.4 for the decorator syntax (@stuff) - Should calculate a cell only once per change (haven't tested ;-) Caveats: - The input cell callbacks are not called with the class instance as the first argument, while the rule cell callback are. This is mostly due to laziness. - There is no cycle detection. If you write cyclic dependencies, you lose. - There is very little error checking. Example follows: def x_callback(oldval, newval): print "x changed: %s => %s" % (oldval, newval) class Test(cellular): def __init__(self): self.x = InputCell(10, callback=x_callback) def y_callback(self, oldval, newval): print "y changed: %s => %s" %(oldval, newval) def a_callback(self, oldval, newval): print "a changed: %s => %s" %(oldval, newval) def g_callback(self, oldval, newval): print "g changed: %s => %s" %(oldval, newval) @rule(callback=y_callback) def y(self): return self.x ** 2 @rule(callback=a_callback) def a(self): return self.y + self.x @rule(callback=g_callback) def g(self): if self.x % 2 == 0: return self.y else: return self.a $ python cells.py y changed: __main__.unbound => 100 a changed: __main__.unbound => 110 g changed: __main__.unbound => 100 ============= x changed: 10 => 4 y changed: 100 => 16 a changed: 110 => 20 g changed: 100 => 16 ============= x changed: 4 => 5 y changed: 16 => 25 a changed: 20 => 30 g changed: 16 => 30 -- Lasse Rasinen lrasinen at iki.fi From brochu121 at gmail.com Tue May 2 15:45:51 2006 From: brochu121 at gmail.com (david brochu jr) Date: Tue, 2 May 2006 15:45:51 -0400 Subject: making IE toolbars visible Message-ID: <9583ed900605021245m2fadcc3av5c81322f76e486bb@mail.gmail.com> Anyone know how if there is a module out there or some way to automate making an IE toolbar visible in IE? Thanks, Dave -------------- next part -------------- An HTML attachment was scrubbed... URL: From Matthias.Weber at faps.uni-erlangen.de Mon May 1 03:19:34 2006 From: Matthias.Weber at faps.uni-erlangen.de (Weber Matthias) Date: Mon, 1 May 2006 09:19:34 +0200 Subject: using break in exec() Message-ID: <7CF2534088731741A719AB7F5ED036F61144C7@moritz.faps.uni-erlangen.de> Hi, has anybody a suggestion to get this example to work? I have the need to jump out of the loop within the exec statement. while True: exec("break") Thanks Matthias -------------- next part -------------- An HTML attachment was scrubbed... URL: From kent at kentsjohnson.com Tue May 30 22:41:31 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 30 May 2006 22:41:31 -0400 Subject: genexp performance problem? In-Reply-To: References: Message-ID: <447d016a$1_1@newspeer2.tds.net> Delaney, Timothy (Tim) wrote: > python -mtimeit "sum(int(L) for L in xrange(3000))" > 100 loops, best of 3: 6.76 msec per loop > > python -mtimeit -s "g = (int(L) for L in xrange(3000))" "sum(g)" > 1000000 loops, best of 3: 1.09 usec per loop > > The generator comprehension needs to create a new generator each time > around. Reusing the generator doesn't give a correct answer; after the first sum() the generator is exhausted: In [1]: g=(int(L) for L in xrange(10)) In [2]: sum(g) Out[2]: 45 In [3]: sum(g) Out[3]: 0 Kent From onurb at xiludom.gro Tue May 9 04:46:01 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 10:46:01 +0200 Subject: utility functions within a class? In-Reply-To: <445ebacc$0$5345$c3e8da3@news.astraweb.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> Message-ID: <44605729$0$14042$626a54ce@news.free.fr> John Salerno wrote: > John Salerno wrote: > >> jeffshannon at gmail.com wrote: >> >>> Even if you don't end up referring to self or any instance >>> attributes within the method >> >> >> Hmm, follow-up: I *do* plan to refer to instance attributes inside >> these methods (self.something), but does that require that they be >> instance methods, or can they still reference 'self' since they are >> inside the class? >> >> They won't be called directly from an instance, which is why I >> wondered about making them static or class methods, but can static or >> class methods use self, or does it have to be an instance method in >> that case? > > > Ugh, sorry about another post, but let me clarify: In these utility > functions, I need to refer to an attribute of an instance, So you want ordinary methods. > but these > functions will be called from another method in the class, not from the > instance itself. yes, they will: class Parrot(object): def _func1(self, whatever): print whatever def talk(self): self._func1('vroom') > Is this even possible, or would 'self' have no meaning > when used this way? You probably noticed that 'self' (or whatever you name it - but better to stick to convention) *must* be defined as the first param of a 'method'. The reason for it is that what we commonly call 'methods' are in fact plain Python functions. It's only when they are looked up on an instance that they are wrapped into a 'method' object (read about the descriptor protocol to learn how...), that in turn calls the function, passing it the instance as first param. For saying it short (warning: over-simplification ahead), the usual method call idiom: myObj.myMethod(arg) is syntactic sugar for: myObj.__class__.myMethod(myObj, arg) HTH. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From george.sakkis at gmail.com Mon May 22 23:55:03 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 22 May 2006 20:55:03 -0700 Subject: groupby References: Message-ID: <1148356503.165982.247800@y43g2000cwc.googlegroups.com> Bryan wrote: > can some explain why in the 2nd example, m doesn't print the list [1, 1, 1] > which i had expected? > > > >>> for k, g in groupby([1, 1, 1, 2, 2, 3]): > ... print k, list(g) > ... > 1 [1, 1, 1] > 2 [2, 2] > 3 [3] > > > >>> m = list(groupby([1, 1, 1, 2, 2, 3])) > >>> m > [(1, ), (2, at 0x00AAC5A0>), (3, )] > >>> list(m[0][1]) > [] > >>> > > > thanks, > > bryan I've tripped on this more than once, but it's in the docs (http://docs.python.org/lib/itertools-functions.html): "The returned group is itself an iterator that shares the underlying iterable with groupby(). Because the source is shared, when the groupby object is advanced, the previous group is no longer visible. So, if that data is needed later, it should be stored as a list" George From penneys at bigfoot.com Wed May 10 04:22:03 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 10 May 2006 01:22:03 -0700 Subject: Redirecting unittest output to a Text widget In-Reply-To: References: <1147244476.396761.36600@i40g2000cwc.googlegroups.com> Message-ID: <1147249323.758783.303820@e56g2000cwe.googlegroups.com> Excellent, that seems to have done the trick! FWIW: I should admit that I haven't really taken the time to properly understand unittest... I'm too eager to get my tests written :-) So for reasons I do not as yet understand Peter's suggestion above didn't quite work for me but the following did.... testSuite = unittest.makeSuite(testX) testSuite = unittest.makeSuite(testY) testRunner = unittest.TextTestRunner(stream=myTextWindow, verbosity=2) testRunner.run(testSuite) I'm only mentioning this in case it's relevant to others. Thanks, Peter! From nospam at nospam.nospam Mon May 29 06:58:01 2006 From: nospam at nospam.nospam (Nic) Date: Mon, 29 May 2006 12:58:01 +0200 Subject: Ricerca Programmatore Python Message-ID: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> Please accept my apologies for the use of the Italian language. ************* Salve a tutti, Scrivo per informarvi di una proposta di collaborazione. Sto cercando un programmatore per la realizzazione di un mini-software utile per analizzare e rappresentare multigrafi. Si richiede una ottima competenza nell'utilizzo di Python con i relativi pacchetti di rappresentazione matematica (es. matplotlib). Per la nozione di grafo si rimanda alle seguenti pagine: http://it.wikipedia.org/wiki/Teoria_dei_grafi (italiano). http://en.wikipedia.org/wiki/Graph_theory (inglese). ? preferibile la residenza in provincia di Milano, in vista di un possibile incontro. Si tratta di una collaborazione esterna retribuita. Gli interessati possono contattarmi direttamente ai recapiti presenti in coda all'e-mail, inviando il relativo curriculum vitae. Spero di avere fatto cosa gradita postando questo annuncio. In caso contrario, mi scuso per il disturbo. Saluti, Giandomenico Sica Polimetrica Onlus Corso Milano 26 20052 Monza Mi Italia Tel/Fax: 039.2301829 E-mail: g.sica chiocciola polimetrica.org From robert.kern at gmail.com Tue May 9 15:52:58 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 May 2006 14:52:58 -0500 Subject: Econometrics in Panel data? In-Reply-To: <44606dd5$0$3285$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <07l062li47gjhuskkkqsai7kji82fpfjnq@4ax.com> <44606dd5$0$3285$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: DeepBlue wrote: > so are you saying that Python is not an appropriate language for doing > econometrics stuff? Alan Isaac certainly thinks it is appropriate and lists many Python resources for econometrics: http://www.american.edu/econ/pytrix/pytrix.htm You may also want to look at QuantLib, which has a Python interface via SWIG. http://www.quantlib.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 __peter__ at web.de Tue May 23 02:52:18 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 May 2006 08:52:18 +0200 Subject: Short and simple functions (was: Re: Dr. Dobb's Python-URL! - weekly Python news and links (May 22)) References: Message-ID: Ben Finney wrote: > "Andy Salnikov" writes: >> "Too many" is always opposite to "hard to make a mistake", at least >> in my mind. > > I parsed the assertion as: > > (It's hard to > (make a mistake > (by having > (too many > (short and simple) > functions)))) > > In other words, it's not that he's saying "having too many short and > simple functions" is difficult, nor that it's not a mistake; he's > saying that it's difficult to get into a situation where that is the > cause of one's mistake. I completely agree -- and incidentally you helped me understand Andy's statement. Thanks. Peter From devlai at gmail.com Fri May 26 00:29:31 2006 From: devlai at gmail.com (Devan L) Date: 25 May 2006 21:29:31 -0700 Subject: Creating instances of untrusted new-style classes References: <1148605569.607231.41640@j73g2000cwa.googlegroups.com> Message-ID: <1148617771.003397.277520@u72g2000cwu.googlegroups.com> Ben Finney wrote: > "Devan L" writes: > > > Is there any safe way to create an instance of an untrusted class > > Why are you instantiating classes you don't trust? > > > without consulting the class in any way? > If you don't "consult the class", how can the instance be created > properly? > When my program runs (CGI), the following happens: * User enters source, which is executed in a restricted environment, which unserializes a previously serialized environment if there is one. * The restricted environment is serialized, including any instances they may have instantiated. So when I unserialize their instances, I have to recreate them, but without calling any of their code (I can't run the unserializing code in a restricted environment). Instances of old-style classes can be created without touching the actual old-style class code, but I'm not sure how, if it's possible, to do the same with new-style classes - Devan From jmcmonagle at velseis.com.au Tue May 30 02:15:44 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Tue, 30 May 2006 16:15:44 +1000 Subject: TIming In-Reply-To: References: Message-ID: <1148969744.27134.13.camel@kuepper.vels-int.com.au> Tue, 2006-05-30 at 00:23 -0500, WIdgeteye wrote: > On Tue, 30 May 2006 04:34:03 +0000, Tim Roberts wrote: > > > WIdgeteye wrote: > >>HI, > >>I am trying to write a little program that will run a program on scedule. > >>I am having trouble understanding the datetime, time, sched modules. What > >>I would like is something like this: > >> > >>If date&time = 06-13-2006:18:00:00 > >>Then run this program > >> > >>I am not sure how to enter a future date in this equation using any of > >>the modules mentioned above. I have figured out how to get the date and > >>time from the modules above but not the future and then compare the two. > > > > What operating system are you using? Both Linux and Windows have commands > > that can do this for you. It's more efficient to use existing operating > > system services than to invent your own. > > > > Also, remember to take into account the possibility that your program > > might not check the time at the exact second. In your example, you need > > to be prepared to start your app if the time is just PAST 6 PM on June 13. > > I am using Linux and could use cron. But I want to be able to > schedule and record television shows on her. And yeah I know about > freevo but it's way to complicated than it needs to be. > > So back to the question: How can I get a 9 position tuple from > the time functions in Python based on a future date. Tim Roberts is right. As you are on linux, I suggest you investigate the at command - very user friendly and not at all complicated. -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From python.list at tim.thechases.com Sun May 7 12:35:24 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 07 May 2006 11:35:24 -0500 Subject: printing list In-Reply-To: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> References: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> Message-ID: <445E21CC.6050706@tim.thechases.com> compboy wrote: > How do you print elements of the list in one line? > > alist = [1, 2, 5, 10, 15] > > so it will be like this: > 1, 2, 5, 10, 15 >>> print ', '.join(alist) 1, 2, 5, 10, 15 -tkc From joel.hedlund at gmail.com Thu May 11 13:16:57 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Thu, 11 May 2006 19:16:57 +0200 Subject: logging module: add client_addr to all log records In-Reply-To: <1147214957.960232.300860@g10g2000cwb.googlegroups.com> References: <1147125271.065354.66180@j73g2000cwa.googlegroups.com> <1147214957.960232.300860@g10g2000cwb.googlegroups.com> Message-ID: > See a very similar example which uses the new 'extra' keyword argument: Now that's brilliant! Exactly what I need. But unfortunately, it's also unavailable until 2.5 comes out. Until then I'm afraid I'm stuck with my shoddy hack... but it's always nice to know the time will come when I can finally throw it out! Thanks for taking the time! Cheers! /Joel From danb_83 at yahoo.com Mon May 1 05:06:24 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 1 May 2006 02:06:24 -0700 Subject: returning none when it should be returning a list? References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> <5Dh5g.71445$H71.59445@newssvr13.news.prodigy.com> Message-ID: <1146474384.336062.223870@y43g2000cwc.googlegroups.com> Edward Elliott wrote: [in reponse to some prime-number code] > 5. you can do better than checking every odd number (next+2) to find the > next prime, but I'm too tired to look into it right now. it may require > more complex machinery. You only need to check the prime numbers up to sqrt(n). If you're calculating primes in sequential order, this is easy. Otherwise, you can remove a third of the odd divisors by considering only odd numbers of the form 6k?1 (because 6k?3 is divisible by 3). def potential_primes(): yield 2 yield 3 i = 6 while True: yield i - 1 yield i + 1 i += 6 From fredrik at pythonware.com Fri May 19 15:47:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 21:47:24 +0200 Subject: Why does the _winreg module start with an underscore In-Reply-To: References: Message-ID: 3c273 wrote: > Does it signify something? Just curious. from the module documentation: This module exposes a very low-level interface to the Windows registry; it is expected that in the future a new winreg module will be created offering a higher-level interface to the registry API. From jkgunjal at gmail.com Thu May 25 01:19:56 2006 From: jkgunjal at gmail.com (jkgunjal at gmail.com) Date: 24 May 2006 22:19:56 -0700 Subject: how to change sys.path? In-Reply-To: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> Message-ID: <1148534396.032281.79320@j55g2000cwa.googlegroups.com> sys.append() Bye. From harry.g.george at boeing.com Tue May 2 08:33:25 2006 From: harry.g.george at boeing.com (Harry George) Date: Tue, 2 May 2006 12:33:25 GMT Subject: An Atlas of Graphs with Python References: <4455e186$0$14794$4fafbaef@reader4.news.tin.it> <1146519086.248221.37740@i40g2000cwc.googlegroups.com> Message-ID: "Paddy" writes: > A little off topic I'm afraid Giandomenico, > But I had to smile. Here is someone working in the field of > linguistics, who wants a programming solution, in the language Python. > (It's Larry Wall, creator of Perl that cites his linguistic > foundations). > > -- Pad. > I used Python for computational linguistics coursework, but not since. Google for "nlp python". E.g.: http://nltk.sourceforge.net/ http://www.logilab.org/projects/hmm http://www.cs.berkeley.edu/~russell/aima/python/nlp.html -- Harry George PLM Engineering Architecture From ptmcg at austin.rr._bogus_.com Fri May 19 15:25:37 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 19:25:37 GMT Subject: number of different lines in a file References: <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> <1148063935.859890.173230@u72g2000cwu.googlegroups.com> <126s5l24kd7u19a@corp.supernews.com> Message-ID: "Grant Edwards" wrote in message news:126s5l24kd7u19a at corp.supernews.com... > > Why would the second running of uniq remove any additional lines that > > weren't removed in the first pass? > > Because uniq only removes _adjacent_ identical lines. > Thanks, guess my *nix ignorance is showing (this doesn't sound very "uniq" to me, tho). -- Paul From python at codeforge.ch Thu May 11 14:29:57 2006 From: python at codeforge.ch (pydev) Date: Thu, 11 May 2006 18:29:57 -0000 Subject: multi-threaded c++ callback problem Message-ID: <20060511182956.E14641E4008@bag.python.org> hi all, i'm building a wrapper for a multi-threaded c++ library to use it in python. everything works fine except the callback. the c++ code to call the python function: //-----------------------------------------------------------// void pyCallEventCallback( CALL hCall, LINE hLine, CALLSTATE_MAJOR eMajor, CALLSTATE_MINOR eMinor, PyObject* def ) { if( !PyCallable_Check( def ) ) { PyErr_SetString( PyExc_TypeError, "Need a callable object!" ); return; } printf( "EventCallback hCall: %i, hLine: %i, eMajor: %i, eMinor: %i\n", hCall, hLine, eMajor, eMinor); PyObject* arglist = Py_BuildValue("(iiii)", hCall, hLine, eMajor, eMinor); // if i comment out next line it works! PyEval_CallObject( def, arglist ); Py_XDECREF(arglist); } //-----------------------------------------------------------// the python callback function looks like this: //-----------------------------------------------------------// def callback( *args ): print "callback:", args //-----------------------------------------------------------// the soutput i get looks like this: EventCallback hCall: 1, hLine: 1, eMajor: 2000, eMinor: 2001 callback: ( 1, 1, 2000, 2001 ) EventCallback hCall: 1, hLine: 1, eMajor: 2500, eMinor: 2501 callback: ( 1, 1, 2500, 2501 ) EventCallback hCall: 1, hLine: 1, eMajor: 8000, eMinor: 8001 an then instead of: callback: ( 1, 1, 8000, 8001) it crashes there are no other python interactions between the callback calls. From sjmachin at lexicon.net Wed May 31 04:29:32 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 May 2006 18:29:32 +1000 Subject: An algorithm problem In-Reply-To: References: Message-ID: <447D53EC.2070100@lexicon.net> On 31/05/2006 4:58 PM, Bo Yang wrote: > Hi , > I have writen a python program to slove a problem described as below: > > (Forgive my poor English !) > > Put the 2^n 0 or 1 to form a ring , Sorry, I can't understand that. It would be very helpful if you wrote out (for example, when n == 3) what the "0-1 ring" looks like. Do you mean ring as in a circular buffer, or do you mean ring as in "groups, rings, and fields"? > and we can select any continuous n > ones from > the ring to constitute a binary number . And obviously we can get 2^n > selections , > so the question is : > Given a number n and you must > Povide an algorithm by which the 0-1 ring is produced , and the 2^n > number we get > are just from 0 to 2^n-1 uniquely and entirely . > > So I write the following program to slove the question , and it works > well for the n below 10 > > > flag = 0 > input = 10 Problem! See below. > number = 2**input > set = set() Problem!! > list = [] Problem!!! It is a very bad habit to re-use or "shadow" the names of built-in functions (input, set, list). Please stop now. Try to think of meaningful names for your input number, your set and your list. What do you think would happen if your code needed a second set and you wrote: set2 = set() ? > > def list2int(l , n ): Please don't use "l" (that's "L".lower()) as an identifier. It is far too easily confused with the digit "1" in many fonts. > ret = 0 > for x in l : > if( n == 0 ): Please lose the (); they are redundant. Please read http://www.python.org/dev/peps/pep-0008/ in particular the section on whitespace. (Please forgive my exceedingly poor putonghua!) Dui bu qi, women shi laowai -- we can't read our characters easily without the customary spacing. > break [snip] Your code appears without any indentation in the two newsreaders that I tried. As a result, I (and I presume others interested in helping you) can't read your code without a lot of guesswork, and certainly can't run it. Try changing leading tabs to spaces, and sending it again. Alternatively attach it as a file. Regards, John From bborcic at gmail.com Tue May 2 09:52:01 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 15:52:01 +0200 Subject: set partitioning In-Reply-To: <44574755$1_5@news.bluewin.ch> References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> <1146522121.798317.206180@i39g2000cwa.googlegroups.com> <1146523373.778624.142510@y43g2000cwc.googlegroups.com> <1146530789.867089.75160@i39g2000cwa.googlegroups.com> <44574755$1_5@news.bluewin.ch> Message-ID: <44576404$1_5@news.bluewin.ch> I wrote: > > def pickk(k,N,m=0) : > if k==1 : > return ((n,) for n in range(m,N)) > else : > return ((n,)+more for more in pickk(k-1,N,m+1) > for n in range(m,more[0])) > > def partitionN(k,N) : > subsets = [frozenset(S) for S in pickk(k,N)] while it doesn't otherwise change results, changing this line to subsets = [frozenset(S) for S in sorted(pickk(k,N))] provides everything nicely ordered (e.g. lexicographically) > def exhaust(rest,bound=0) : > if len(rest) < k : > if rest : > yield [sorted(rest)] > else : > yield [] > for newbound in range(bound,len(subsets)) : > S = subsets[newbound] > if rest >= S : > sS = [sorted(S)] > for restpart in exhaust(rest-S,newbound+1) : > yield sS+restpart > return exhaust(set(range(N))) > > partition = lambda k,S : [[[S[j] for j in S0] for S0 in P0] > for P0 in partitionN(k,len(S))] > > >>> partition(2,[1,2,3,4]) > [[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[2, 3], [1, 4]]] > >>> partition(3,[1,2,3,4]) > [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 3, 4], [2]], [[2, 3, 4], [1]]] > > > CAVEAT : insufficiently tested, not proved correct, uncommented, > provided as is From max at alcyone.com Mon May 22 17:04:54 2006 From: max at alcyone.com (Erik Max Francis) Date: Mon, 22 May 2006 14:04:54 -0700 Subject: Includeing Python in text files In-Reply-To: References: Message-ID: <5N-dneBDUcnruu_ZRVn-sg@speakeasy.net> Paolo Pantaleo wrote: > I am working on this: > > I have a text file, containig certain section in the form > python code here > py?> > > I parse the text file and substitute the python code with its result > [redirecting sys.stdin to a StringIO]. It something like php or > embedded perl. > > So my little toy works not bad, but I was wondering if such a feature > already existed, if yes, can you point me out some links? Another standalone templating system is EmPy: http://www.alcyone.com/software/empy/ -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis What would physics look like without gravitation? -- Albert Einstein From john at castleamber.com Wed May 17 18:02:48 2006 From: john at castleamber.com (John Bokma) Date: 17 May 2006 22:02:48 GMT Subject: Time to bundle PythonWin References: <1147388148.406918.76040@q12g2000cwa.googlegroups.com> <1147855659.304748.189690@j73g2000cwa.googlegroups.com> Message-ID: "Tim N. van der Leeuw" wrote: > > John Bokma wrote: >> "Robert Hicks" wrote: >> >> > No it isn't. >> >> Learn to quote when you use Google's Usenet garbage. >> > > I don't know why you consider it 'garbage', How many people use GG without quoting, annoying plenty of people on Usenet a day? (Well, the answer is probably less and less since GG is in general added to quite some kill files). > using it myself for this > 'contribution', but quoting isn't hard using google groups. Just > clicking the right links instead of the 'reply' link beneath the > message. Yet its well enough hidden for people to use it, or so it seems. -- 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 Thu May 18 19:56:36 2006 From: john at castleamber.com (John Bokma) Date: 18 May 2006 23:56:36 GMT Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: Edward Elliott wrote: > corroborations. It's like a guy saying he saw a cloud that looks like > a python. The cloud's gone now, but other people can watch other > clouds and report what they see. Good comparison, now does the cloud gazing make them better programmers? -- 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 simon at brunningonline.net Fri May 19 04:38:10 2006 From: simon at brunningonline.net (Simon Brunning) Date: Fri, 19 May 2006 09:38:10 +0100 Subject: who can give me the detailed introduction of re modle? In-Reply-To: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: <8c7f10c60605190138g1a7f0c53n10cf7533e23e8599@mail.gmail.com> On 18 May 2006 22:50:24 -0700, softwindow wrote: > the re module is too large and difficult to study > > i need a detaild introduction. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From michele.petrazzo at TOGLIunipex.it Fri May 26 11:46:34 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 26 May 2006 15:46:34 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1148655611.990937.322350@j73g2000cwa.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> <1148655611.990937.322350@j73g2000cwa.googlegroups.com> Message-ID: Iain King wrote: > Michele Petrazzo wrote: > > I downloaded and installed 0.9.9.3, and it now works. Thanks! > I advice you to don't use that ctypes version... Better is to use the newest one and update freeimagepy! > Iain > Michele From rasmussen.bryan at gmail.com Thu May 4 08:14:22 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Thu, 4 May 2006 14:14:22 +0200 Subject: refactoring question Message-ID: <3bb44c6e0605040514i50a34306l47808f50f56c140d@mail.gmail.com> Hi, I'm doing a sort of symbolic linking app in Windows for my own enjoyment, and figured I would do it in python for the same reason + learning the language. The following functions could obviously do with some refactoring. One obvious thing would be to make wordsetter and wordsforfolder more generic, and just pass a few extra parameters. But that seems sort of stupid. Any suggestions on refactoring here? other improvements? def getwordslist(word): thisword = wordpath + word + ".xml" if exists(thisword): doc = xml.dom.minidom.parse(thisword) loc = doc.childNodes[0] for i in range(0, len(loc.childNodes)): if (loc.childNodes[i].firstChild.data == thispath): break else: wordsetter(thisword,doc,loc) else : doc = xml.dom.minidom.Document() loc = doc.createElementNS("", "locations") doc.appendChild(loc) wordsetter(thisword,doc,loc) return None def getfolderwords(word): if exists(normpath(folderwords)): doc = xml.dom.minidom.parse(folderwords) loc = doc.childNodes[0] wordsforfolder(word,doc,loc) else : doc = xml.dom.minidom.Document() loc = doc.createElementNS("", "wordlist") doc.appendChild(loc) xml.dom.ext.PrettyPrint(doc, open(normpath(folderwords), "w")) wordsforfolder(word,doc,loc) return None def wordsetter(word,doc,loc): thisloc = doc.createElementNS("", "location") xexpr= "//location[.='" + thispath + "']" xp = Evaluate(xexpr,doc.documentElement) if len(xp) < 1: loc.appendChild(thisloc) text = doc.createTextNode(thispath) thisloc.appendChild(text) fi = open(word, "w") fi.write(doc.toxml()) def wordsforfolder(word,doc,loc): thisloc = doc.createElementNS("", "word") xexpr= "//word[.='" + word + "']" xp = Evaluate(xexpr,doc.documentElement) if len(xp) < 1: loc.appendChild(thisloc) text = doc.createTextNode(word) thisloc.appendChild(text) fi = open(folderwords, "w") fi.write(doc.toxml()) Cheers, Bryan Rasmussen From alastair at gotadsl.co.uk Mon May 22 13:26:54 2006 From: alastair at gotadsl.co.uk (Alastair Alexander) Date: Mon, 22 May 2006 18:26:54 +0100 Subject: COM Server crashing when returning large arrays Message-ID: Hi ... I'm using pythoncom to create a python COM server application that needs to be able to return large arrays to COM client apps. For example, I need to be able to return an array to Excel that is 500 by 10, with each element of the array holding a 32 byte string. If I run the code for smaller arrays, say 10 by 10, it works fine. If I allow the server to try to return the entire 500 by 10 array, pythonw.exe causes a memory access violation and dies and I get an "automation exception" error message in the client app. I assume I'm violating some upper limit for data transfer from pythoncom into COM. Anyone know if such limitations exist? Is there a way around them? Can anyone point me in the right direction? Thanks Alastair p.s. 1st message on comp.lang.python, indeed 1st message on any news group From bdesth.quelquechose at free.quelquepart.fr Tue May 2 20:32:12 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 02:32:12 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> Message-ID: <4457cb5b$0$16422$626a54ce@news.free.fr> tsaar2003 at yahoo.com a ?crit : > Hi Pythonians, > > To begin with I'd like to apologize that I am not very experienced > Python programmer so please forgive me if the following text does not > make any sense. > > I have been missing constants in Python language. Why so ? I guess you're talking about named (symbolic) constants ? If so, just follow the convention : a name in ALL_UPPERCASE is a constant (or at least will be treated as such by anyone not wanting to mess with your package's implementation). No need to add extra syntax here IMHO. From aum at spam.me.please Sun May 28 16:17:16 2006 From: aum at spam.me.please (aum) Date: Mon, 29 May 2006 08:17:16 +1200 Subject: q - including manpages in setup.py Message-ID: Hi, What is the best way to incorporate manpages in a distutils setup.py script? Is there any distro-independent way to find the most appropriate place to put the manpages? For instance, /usr/man/? /usr/share/man? /usr/local/man? /usr/local/share/man? Also - I've got .html conversions of the manpages, for the benefit of OSs such as Windows which don't natively support manpages. What's the best place to put these? -- Cheers aum From runlevelten at gmail.com Sun May 14 10:38:03 2006 From: runlevelten at gmail.com (Ten) Date: Sun, 14 May 2006 15:38:03 +0100 Subject: do/while structure needed In-Reply-To: <4466bddd$0$18984$c3e8da3@news.astraweb.com> References: <4466bddd$0$18984$c3e8da3@news.astraweb.com> Message-ID: <200605141538.03457.runlevelten@gmail.com> On Sunday 14 May 2006 06:17, John Salerno wrote: > 1 random.shuffle(letters) > 2 trans_letters = ''.join(letters)[:len(original_set)] > 3 trans_table = string.maketrans(original_set, trans_letters) > > So what I'd like to do is have lines 1 and 2 run once, then I want to do > some comparison between original_set and trans_letters before running > line 3. If the comparison passes, line 3 runs; otherwise, lines 1 and 2 > run again. > > A do/while would be good for this, but perhaps I'm looking at it in the > wrong way? Or is there some kind of do/while type of idiom that I could > use? > > Thanks. while not comparison(original_set, trans_letters): random.shuffle(letters) trans_letters = ''.join(letters)[:len(original_set)] trans_table = string.maketrans(original_set, trans_letters) HTH, Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. From mahs at telcopartners.com Fri May 26 00:50:58 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Thu, 25 May 2006 21:50:58 -0700 Subject: Creating instances of untrusted new-style classes In-Reply-To: <1148605569.607231.41640@j73g2000cwa.googlegroups.com> References: <1148605569.607231.41640@j73g2000cwa.googlegroups.com> Message-ID: Devan L wrote: > Is there any safe way to create an instance of an untrusted class > without consulting the class in any way? With old-style classes, I can > recreate an instance from another one without worrying about malicious > code (ignoring, for now, malicious code involving attribute access) as > shown below. > >>>> import types >>>> class Foo: > ... def __init__(self, who, knows, what, args): > ... self.mystery_args = (who, knows, what, args) > ... print "Your code didn't expect the Spanish inquisition!" > ... >>>> f = Foo('spam','eggs','ham','bacon') # This would be in a restricted environment, though. > Your code didn't expect the Spanish inquisition! >>>> types.InstanceType(Foo, f.__dict__) # This wouldn't, but we never run that code, anyways. > <__main__.Foo instance at 0x008B5FD0> > > I'm not sure how to do the same for new-style classes, if it's at all > possible to do from within Python. Is there any way to accomplish this, > or is there no practical way to do so? > > Thanks, > - Devan > >>> class A(object): ... def __init__(self, *args): ... self.args = args ... print "Calling __init__" ... >>> a = A("new","style") Calling __init__ >>> b = object.__new__(A) >>> b.__dict__ = a.__dict__.copy() >>> b.args ('new', 'style') >>> type(a) is type(b) True >>> HTH Michael From johnjsal at NOSPAMgmail.com Fri May 19 13:54:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 17:54:07 GMT Subject: combining a C# GUI with Python code? Message-ID: <3Dnbg.2135$No6.46516@news.tufts.edu> Is it possible to construct a C# form (using Visual Studio) but write only Python code for the events? Is there some way to tell your program to run Python whenever code is run, since it will be all Python code (e.g. for button presses, etc.)? I know it's sort of silly, and it makes your program depend on .NET, but it would be a nice and easy way to create a GUI while still writing in Python, if it's possible. From manuveio at nospammers.net Sun May 7 07:32:46 2006 From: manuveio at nospammers.net (J. A. Gaeta Mendes) Date: Sun, 07 May 2006 08:32:46 -0300 Subject: ANN: eric3 3.9.0 released References: <1146969457.495258.226730@j33g2000cwa.googlegroups.com> Message-ID: Petr Jakes wrote: > I think you can get the answer on > http://www.die-offenbachs.de/detlev/eric3-mailinglist.html > rather then here. > > HTH > > Petr Jakes Thanks Petr, I've got help there. To those interested, the problem was PyKDE was missing. Best regards, -- jagm From grante at visi.com Tue May 9 15:34:41 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 09 May 2006 19:34:41 -0000 Subject: python rounding problem. References: <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> <125v9g8q00o1d52@corp.supernews.com> <125vedc9n2q3m55@corp.supernews.com> Message-ID: <1261rmhetnlbj34@corp.supernews.com> On 2006-05-09, Thomas Bartkus wrote: >>> Even base 60 makes more sense if you like it when a lot of >>> divisions come out nice and even. >> >> Did they actually have 60 unique number symbols and use >> place-weighting in a manner similar to the arabic/indian >> system we use? > > I don't know. I googled around a while last night, and they ahd sort of a hybrid notation. The Sumerians started withindividual "tic marks" up to 9, and symbols for 10, 60, 600, 3600 and so on. That evolved into the Babylonian base-60 position-weighted system (without a zero symbol) that used only the 1 symbol and the 10 symbol. http://it.stlawu.edu/%7Edmelvill/mesomath/sumerian.html http://www.ancientscripts.com/sumerian.html http://www-gap.dcs.st-and.ac.uk/~history/HistTopics/Babylonian_numerals.html > I do know that we have 360 degrees in a circle And 60 seconds in a minute, 60 minutes in a hour (for both time and angles), and 60 minutes in a degree. -- Grant Edwards grante Yow! PARDON me, am I at speaking ENGLISH? visi.com From sjmachin at lexicon.net Fri May 26 16:22:15 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 27 May 2006 06:22:15 +1000 Subject: chop() and empty() functions In-Reply-To: References: Message-ID: <44776377.7090304@lexicon.net> On 27/05/2006 2:54 AM, Jeremy L. Moles wrote: ["chop" snipped] > > Furthermore, what do people think about the idea of adding a truly > empty, no-op global lambda somewhere in Python? I use them a lot What is the use case? Why write something like """empty(foo, 42, cmd="xyzzy")""" when you could merely write "pass" or nothing at all? > (usually defining a: empty = lambda *a, **k: None somewhere at the > topmost module space), but if enough people did too, it might be worth > adding an empty() builtin to much later versions of Python. > From luismgz at gmail.com Fri May 19 14:06:54 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 19 May 2006 11:06:54 -0700 Subject: combining a C# GUI with Python code? In-Reply-To: <3Dnbg.2135$No6.46516@news.tufts.edu> References: <3Dnbg.2135$No6.46516@news.tufts.edu> Message-ID: <1148062014.928756.303380@g10g2000cwb.googlegroups.com> First of all, you should be thinking about ironpython instead of cpython. This way you can forget about c# and do it all in (iron)python. I don't know its current state, but Microsoft is working in a Visual Studio - Ironpython integration. For more info: http://lists.ironpython.com/htdig.cgi/users-ironpython.com/2006-February/001752.html From scott.daniels at acm.org Tue May 30 14:36:53 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 30 May 2006 11:36:53 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <1149009774.346691.294680@r44g2000cwb.googlegroups.com> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> Message-ID: <447c8c6e$1@nntp0.pdx.net> akameswaran at gmail.com wrote: > However, none of the algo's I have checked will work with generated > sequences, or iterable classes, as posited in my first post. > > While appropriate to the current domain, ie dice. What if you want > combinations of extrememely large lists, say 3 sets of 10 mil items. > In such a case, I really do want my sets to be generators rather than > lists or set objects. > > This is what had me stumped before, and still has me stumped. class Counter(object): def __init__(self, digits, iterable=None): self.digits = digits self.iterable = iterable def __iter__(self): for digit in self.digits: single = digit, if self.iterable is None: yield single else: for rest in self.iterable: yield single + rest for v in Counter('ab', Counter('cd', Counter('ef', Counter('gh')))): print v This works with "iterables" (and produces), rather than "iterators", which is vital to the operation. --Scott David Daniels scott.daniels at acm.org From fredrik at pythonware.com Sat May 27 11:37:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 27 May 2006 17:37:46 +0200 Subject: PIL problem with biprocessor hardware In-Reply-To: <1148671774.185653.234650@j55g2000cwa.googlegroups.com> References: <1148661656.407762.147020@j73g2000cwa.googlegroups.com> <1148663531.254814.301790@i40g2000cwc.googlegroups.com> <1148665221.735821.211520@y43g2000cwc.googlegroups.com> <1148670754.148116.23950@y43g2000cwc.googlegroups.com> <1148671774.185653.234650@j55g2000cwa.googlegroups.com> Message-ID: danmcleran at yahoo.com wrote: > oops. lost my train of thought. I was gonna say, I wonder if some of > these image manipulation routines are using multiple threads? PIL doesn't use threading by itself, and I know of quite a few PIL-based systems running on multi-processor hardware (not to mention multi-core and hyper-threading systems). if the posted snippet is all there is, I'd blame it on the hardware ;-) From Serge.Orlov at gmail.com Tue May 2 08:11:02 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 2 May 2006 05:11:02 -0700 Subject: string.find first before location References: <87hd49m0xc.fsf@localhost.localdomain> <87zmi0emhd.fsf@localhost.localdomain> Message-ID: <1146571862.234132.8670@u72g2000cwu.googlegroups.com> Peter Otten wrote: > Gary Wessle wrote: > > >> These days str methods are preferred over the string module's functions. > >> > >> >>> text = "abc abc and Here and there" > >> >>> here_pos = text.find("Here") > >> >>> text.rfind("abc", 0, here_pos) > >> 4 > >> > >> Peter > > > > and what about when python 3.0 is released and those depreciated > > functions like find and rfind are not supported. is there another > > solution which is more permanent? > > I think the functions may go away, the methods will stay; so I'm confident > the above will continue to work. find and rfind methods are in danger too. AFAIR they are to be replaced by partion and rpartition methods. People who are worried about future can continue to use index and rindex From claird at lairds.us Fri May 19 10:41:13 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 19 May 2006 14:41:13 +0000 Subject: Exception style (was: calling python functions using variables) References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <446da180$0$10184$636a55ce@news.free.fr> <126rjus43k450df@corp.supernews.com> Message-ID: <9121k3-hjm.ln1@lairds.us> In article <126rjus43k450df at corp.supernews.com>, Grant Edwards wrote: >On 2006-05-19, bruno at modulix wrote: > >>> Either deal with the resulting NameError exception (EAFP[0]) >> >> try: >> getattr(commands, VARIABLE)() >> except NameError: >> print >> sys.stderr, "Unknown command", VARIABLE >> >>> or test >>> first whether the attribute exists (LBYL[1]). >> >> command = getattr(commands, VARIABLE, None) >> if command is None: >> print >> sys.stderr, "Unknown command", VARIABLE >> else: >> command() >> >> I'd go for the first solution. > >Me too. Assuming the user isn't clueless, the normal case is >where the command exists. Write code for the normal case and >use the exception that occurs for exceptional cases. . . . Guys, I try--I try *hard*--to accept the BetterToAskForgiveness gospel, but this situation illustrates the discomfort I consistently feel: how do I know that the NameError means VARIABLE didn't resolve, rather than that it did, but that evaluation of commands.VARIABLE() itself didn't throw a NameError? My usual answer: umm, unless I go to efforts to prevent it, I *don't* know that didn't happen. From duncan.booth at invalid.invalid Thu May 11 13:20:38 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2006 17:20:38 GMT Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> <1147333696.789718.189050@v46g2000cwv.googlegroups.com> <1147366331.637492.129980@i39g2000cwa.googlegroups.com> Message-ID: Kaz Kylheku wrote: > Duncan Booth wrote: >> One big problem with this is that with the decorator the function has >> a name but with a lambda you have anonymous functions so your >> tracebacks are really going to suck. > > Is this an issue with this particular design that is addressed by > other designs? Yes. Decorators don't interfere with the name of the underlying function displayed in tracebacks. > > Are the existing one-line lambdas free from this problem? No, but since a single line lambda does virtually nothing it isn't as serious. Decorators are useful enough that in some situation you might decorate every method in a class (e.g. for a web application you might apply security settings with decorators). In that situation you have just messed up every stack frame in every traceback. > > Is there really a problem? The Python tracebacks identify every frame > by file and line number, as well as name, if one is available. Great, and I suppose that if they printed out the line numbers in binary that wouldn't make it harder to understand the traceback either. I end up reading tracebacks quite a lot, and it is the sequence of the function names which matter first, I don't usually need to go and look at the file and code lines. > > Let me make the observation that name of an inner function is, alone, > insufficient to identify that function in a debugging scenario. If you > have some inner function called I, defined within function F, you need > to know that it's the I inside F, and not some other I. > If the stack frame shows I called from F then it is usually a pretty good guess that it means the I inside F. Besides, I don't usually name all my inner functions I; I find that giving them meaningful names tends to help. From scott.daniels at acm.org Tue May 16 13:04:27 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 16 May 2006 10:04:27 -0700 Subject: Unable to extract Python source code using Windows In-Reply-To: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> Message-ID: <446a0229$1@nntp0.pdx.net> Elric02 at rogers.com wrote: > I'm currently trying to get access to the Python source code, however > whenever I try to extract the files using the latest version of WinZip > (version 10) I get the following error "error reading header after > processing 0 entries" > I was under the impression that I could (from reading the various posts > on this group) that I could simply extract the tar ball, using WinZip. Perhaps you pulled the file as a non-binary (and so got LFs turned to CRLFs). You should be able to use a recent Python to read the archive as well. First, I'd do: import md5 BLOCK_SIZE = 4096 * 8 # or whatever accumulator = md5.new() source = open('whatever.tar.gz', 'rb') try: while True: data = source.read(BLOCK_SIZE) if data: accumulator.update(data) else: break finally: source.close() print 'md5 checksum =', accumulator.hexdigest() Compare that result to the published checksum for the archive to make sure you don't have a garbled archive. --Scott David Daniels scott.daniels at acm.org From 123 at 321.com Tue May 9 06:24:11 2006 From: 123 at 321.com (DeepBlue) Date: Tue, 09 May 2006 18:24:11 +0800 Subject: Econometrics in Panel data? In-Reply-To: <07l062li47gjhuskkkqsai7kji82fpfjnq@4ax.com> References: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <07l062li47gjhuskkkqsai7kji82fpfjnq@4ax.com> Message-ID: <44606dd5$0$3285$5a62ac22@per-qv1-newsreader-01.iinet.net.au> so are you saying that Python is not an appropriate language for doing econometrics stuff? Dennis Lee Bieber wrote: > On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <123 at 321.com> declaimed the > following in comp.lang.python: > >> Hi all, >> >> I am new to Python. Just wondering can Python able to do econometric >> regression in either Time-series or pooled (panel) data? As well as test >> for hetero, autocorrelation, or endogeneity? > > Can you do such in FORTRAN, COBOL, SNOBOL, APL, C, Matlab, Maple, > Excel, Turing Machine? Most likely... > > Is there a pre-built library to compute such? No idea... > From python.list at tim.thechases.com Fri May 12 08:29:54 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 12 May 2006 07:29:54 -0500 Subject: deleting texts between patterns In-Reply-To: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> Message-ID: <44647FC2.704@tim.thechases.com> > I wish to delete lines that are in between 'abc' and > 'xyz' and print the rest of the lines. Which is the best > way to do it? While this *is* the python list, you don't specify whether this is the end goal, or whether it's part of a larger program. If it *is* the end goal (namely, you just want the filtered output someplace), and you're not adverse to using other tools, you can do something like sed -n -e'1,/abc/p' -e'/xyz/,$p' file.txt which is pretty straight-forward. It translates to -n don't print each line by default -e execute the following item 1,/abc/ from line 1, through the line where you match "abc" p print each line and also -e execute the following item /xyz/,$ from the line matching "abc" through the last line p print each line It assumes that 1) there's only one /abc/ & /xyz/ in the file (otherwise, it defaults to the first one it finds in each case) 2) that they're in that order (otherwise, you'll get 2x each line, rather than 0x each line) However, it's a oneliner here, and seems to be a bit more complex in python, so if you don't need to integrate the results into further down-stream python processing, this might be a nice way to go. If you need the python, others on the list have offered a panoply of good answers already. -tkc From softwindow at gmail.com Fri May 19 00:57:30 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 21:57:30 -0700 Subject: Script to make Windows XP-readable ZIP file In-Reply-To: References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> <1148011001.613000.294750@g10g2000cwb.googlegroups.com> Message-ID: <1148014650.844340.212540@38g2000cwa.googlegroups.com> Carl Banks is right From exarkun at divmod.com Thu May 25 17:02:49 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 25 May 2006 17:02:49 -0400 Subject: Secure Pickle-like module In-Reply-To: <1148588541.444993.115600@u72g2000cwu.googlegroups.com> Message-ID: <20060525210249.28682.366403425.divmod.quotient.5310@ohm> On 25 May 2006 13:22:21 -0700, jiba at tuxfamily.org wrote: >Hi all, > >I'm currently working on a secure Pickle-like module, Cerealizer, >http://home.gna.org/oomadness/en/cerealizer/index.html >Cerealizer has a pickle-like interface (load, dump, __getstate__, >__setstate__,...), however it requires to register the class you want >to "cerealize", by calling cerealizer.register(YourClass). >Cerealizer doesn't import other modules (contrary to pickle), and the >only methods it may call are YourClass.__new__, YourClass.__getstate__ >and YourClass.__setstate__ (Cerealizer keeps it own reference to these >three method, so as YourCall.__setstate__ = cracked_method is >harmless). >Thus, as long as __new__, __getstate__ and __setstate__ are not >dangerous, Cerealizer should be secure. > >The performance are quite good and, with Psyco, it is about as fast as >cPickle. However, Cerealizer is written in less than 300 lines of >pure-Python code. > >I would appreciate any comments, especially if there are some security >gurus here :-) There are a couple factual inaccuracies on the site that I'd like to clear up first: Trivial benchmarks put cerealizer and banana/jelly on the same level as far as performance goes: $ python -m timeit -s 'from cereal import dumps; L = ["Hello", " ", ("w", "o", "r", "l", "d", ".")]' 'dumps(L)' 10000 loops, best of 3: 84.1 usec per loop $ python -m timeit -s 'from twisted.spread import banana, jelly; dumps = lambda o: banana.encode(jelly.jelly(o)); L = ["Hello", " ", ("w", "o", "r", "l", "d", ".")]' 'dumps(L)' 10000 loops, best of 3: 89.7 usec per loop This is with cBanana though, which has to be explicitly enabled and, of course, is written in C. So Cerealizer looks like it has the potential to do pretty well, performance-wise. Similar benchmarks show jelly/banana actually produces shorter encoded forms: >>> len(banana.encode(jelly.jelly(()))) 9 >>> len(cereal.dumps(())) 21 >>> len(banana.encode(jelly.jelly(["Hello", " ", ("w", "o", "r", "l", "d", ".")]))) 45 >>> len(cereal.dumps(["Hello", " ", ("w", "o", "r", "l", "d", ".")])) 67 I think the mistake you may have made was thinking that repr(jelly()) is the final output form, when really it's banana.encode(jelly()). You talked about _Tuple and _Dereference on the website as well. These are internal implementation details. They don't show up in the final decoded output at all: >>> from twisted.spread import jelly >>> output = jelly.unjelly(jelly.jelly([()] * 2)) >>> output [(), ()] >>> output[0] is output[1] True >>> type(output[0]) is tuple True >>> jelly also supports extension types, by way of setUnjellyableForClass and similar functions. As far as security goes, no obvious problems jump out at me, either from the API for from skimming the code. I think early-binding __new__, __getstate__, and __setstate__ may be going further than is necessary. If someone can find code to set attributes on classes in your process space, they can probably already do anything they want to your program and don't need to exploit security problems in your serializer. On the other hand, early-binding may lead to confusing bugs, albeit only in nasty cases where people are expecting changes they make to class objects to have an effect on every part of the system. Jean-Paul From chaks.yoper at gmail.com Wed May 17 07:02:10 2006 From: chaks.yoper at gmail.com (chaks.yoper at gmail.com) Date: 17 May 2006 04:02:10 -0700 Subject: how to traverse network devices in our system? In-Reply-To: References: Message-ID: <1147863730.559574.181720@i39g2000cwa.googlegroups.com> Hi Tim and all, Tim Golden wrote: > [chaks.yoper at gmail.com] > > | i would like to know whether python can help me querying the network > | devices attached to my system (ethernet,wireless) and display their > | module name and vendor name? > > Which OS? If it's windows, you can use WMI. I would > guess Linux, tho', from your mention of module name. > Yes, it is Linux. I was just googling and found that there are kudzu bindings for python. From that i can query kudzu for any configured and unconfigured device (i hope so). is there any other method available other kudzu python bindings ? thank you. Chakkaradeep > 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 OlafMeding at gmail.com Mon May 8 17:55:46 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 8 May 2006 14:55:46 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1147125346.610994.168260@u72g2000cwu.googlegroups.com> Tim Many thanks for trying and reporting the details of your environment. All our hyper-threading PC are identical. However, we identified one that is different and we are installing Windows XP on it now ... My hope is that other people will try this, too. Olaf From akameswaran at gmail.com Thu May 18 21:41:41 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 18:41:41 -0700 Subject: python vs perl lines of code In-Reply-To: References: Message-ID: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> As a coder, I wouldn't normally use the two different conventions. you show in your examples. So it does little to tell us about the importance or lack there of line count. Let me state clearly - to use line count , in absence of other considerations, IS meaningless. But if a 1 person, using 1 language, with the same set of tools withing a 3 month period implements the same algo without bugs - I'll bet you the shorter one was theone written second. The fact that you many ppl will state the shorter line count of rewrites is a sign of improving skill I think actually presents some "anecdotal" evidence that there is some truth that shorter code is better code. My skill level increases a lot faster than my coding style changes over time. So while far from conclusive, the fact that I find my code gets shorter the second time - and it is usually done more skillfully, it seems there is a correlation of some sort between lines of code and quality. From sjmachin at lexicon.net Thu May 11 05:50:07 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 11 May 2006 19:50:07 +1000 Subject: Nested loops confusion In-Reply-To: <2uCdnY7CIt9qc__ZnZ2dnUVZ8qGdnZ2d@giganews.com> References: <2uCdnY7CIt9qc__ZnZ2dnUVZ8qGdnZ2d@giganews.com> Message-ID: <446308d1$1@news.eftel.com> On 11/05/2006 5:59 PM, Matthew Graham wrote: > Thanks very much for the advice, have tidied it up and tested and seems > to be working as needed. Seems to be working? Consider where you have the expression x^2 + y^2 ... I'd like to bet that you mean "x squared" etc, not "x exclusive-or 2" etc. >>> x = 3 >>> x ^ 2 1 >>> x ** 2 9 >>> > I'm still not sure what was stopping the inner > loop from working earlier Call me crazy, but I thought you said it was the outer loop that wasn't working ... > - but removing the redundancy in "j=0" and so > on seems to have solved it. > There's that "seems" word again. Removing "j=0" should have had no effect at all, as Dennis has pointed out. What meaning do you attach to "working"? Have you written any tests? Have you contemplated dropping the size to say 5x5 instead of 100x100 and hand-calculating the expected results? From rowen at cesmail.net Mon May 22 15:22:19 2006 From: rowen at cesmail.net (Russell E. Owen) Date: Mon, 22 May 2006 12:22:19 -0700 Subject: PEP 3102 for review and comment References: <1148102845.438543.16380@38g2000cwa.googlegroups.com> Message-ID: In article <1148102845.438543.16380 at 38g2000cwa.googlegroups.com>, "Talin" wrote: > (Note: PEPs in the 3xxx number range are intended for Python 3000, > however this particular PEP may be backported if there is support for > it.) > > PEP: 3102 > Title: Keyword-Only Arguments ... > Syntactically, the proposed changes are fairly simple. The first > change is to allow regular arguments to appear after a varargs > argument: > > def sortwords(*wordlist, case_sensitive=False): > ... > > This function accepts any number of positional arguments, and it > also accepts a keyword option called 'case_sensitive'. This > option will never be filled in by a positional argument, but > must be explicitly specified by name. The following is a 2nd syntactical change, and I strongly suggest listing it as such (since the first change can be made without this change): > Keyword-only arguments are not required to have a default value. > Since Python requires that all arguments be bound to a value, > and since the only way to bind a value to a keyword-only argument > is via keyword, such arguments are therefore 'required keyword' > arguments. Such arguments must be supplied by the caller, and > they must be supplied via keyword. ...making this the third syntactical change: > The second syntactical change is to allow the argument name to > be omitted for a varargs argument. The meaning of this is to > allow for keyword-only arguments for functions that would not > otherwise take a varargs argument: > > def compare(a, b, *, key=None): Personally, my feelings are: +1 on allowing keyword arguments after *args. I have long wanted this and feel it is: - very useful (the alternative of abusing **kargs is ugly and doesn't support introspection) - an obvious and clear extension of current notation - removes an awkward limitation of current notation -1 on allowing keywords without values because: - if it is added, then it means something like the last change is required, and as I say next, I don't like it - why bother? it just makes work for the caller -1 on the use of * to mean a separator between positional args and keyword-only args because: - I think proposed syntax is confusing (there are more arguments in the argument list than the function accepts; yecch!!!) and hard to read - I don't think the added functionality is important enough to justify the awkward notation If folks are desperate enough for this last feature then please at least find a clearer notation. For example: def compare(a, b | key=None): but personally I'd rather skip it. Now if somebody could figure out a natural notation for boolean flags, *that'd* be useful (where the presence, absence or explicit negation of a keyword is all that is required to enable or disable a feature). -- Russell From kentilton at gmail.com Wed May 10 11:23:49 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 10 May 2006 11:23:49 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <4461bd09$1_6@news.bluewin.ch> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <87wtcyy5i0.fsf@rpi.edu> <4461bd09$1_6@news.bluewin.ch> Message-ID: <9An8g.3$%L2.2@fe12.lga> Boris Borcic wrote: > Bill Atkins wrote: > >> >> It's interesting how much people who don't have macros like to put >> them down and treat them as some arcane art that are too "*insane*"ly >> powerful to be used well. >> >> They're actually very straightforward and can often (shock of shocks!) >> make your code more readable, without your efficiency taking a hit. > > > Not even efficiency of debugging ? A real problem with macros is that > run-time tracebacks etc, list macro outputs and not your macro'ed source > code. And that becomes an acute problem if you leave code for somebody > else to update. Or did lisp IDEs make progress on that front ? AllegroCL now shows macros in the stack frame. Relatively recent feature, and their IDE really stands out above the rest. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From nobody at 127.0.0.1 Mon May 29 20:11:04 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 30 May 2006 00:11:04 GMT Subject: Need C# Coding for MD5 Algorithm... References: <1148884151.511656.81110@j73g2000cwa.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > As for the algorithm... http://www.faqs.org/rfcs/rfc1321.html > > Implement per that spec. It even includes a C-language > implementation that you might be able to bastardize into C# Please don't. Crypto algorithms are hard enough to implement correctly as it is. Leave it to the experts and use a library. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From manstey at csu.edu.au Wed May 24 01:52:27 2006 From: manstey at csu.edu.au (manstey) Date: 23 May 2006 22:52:27 -0700 Subject: NEWB: how to convert a string to dict (dictionary) Message-ID: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> Hi, How do I convert a string like: a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}" into a dictionary: b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'} Thanks, Matthew PS why in Python is it so often easy to convert one way but not the other? From dave at waveform.plus.com Mon May 1 15:34:25 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 01 May 2006 19:34:25 GMT Subject: returning none when it should be returning a list? References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> <5Dh5g.71445$H71.59445@newssvr13.news.prodigy.com> Message-ID: <445662c1$0$23183$ed2e19e4@ptn-nntp-reader04.plus.net> Edward Elliott wrote: > randomtalk at gmail.com wrote: > > The function basically takes in a list of all the prime number > > found, it takes the next number to be tested for (next) and the > > limit it will go up to. It divide next by the list of previous > > prime numbers if next is not bigger than lim, count up all the > > times where it's not evenly divdided, if the result is equal the > > length of prime number, then we have another prime number, lather > > rinse and repeat :) > > Your basic algorithm as described above sounds workable, but can be > made more efficient (I didn't look closely at your code for bugs). I > won't even go near the complicated number theory algorithms. > > 1. integer mod will be faster than floating point mod (unless you're > getting into numbers too large to store efficiently as ints, but > you'll probably run into other limitations before you get near that > point in this code). > > 2. you can stop as soon as you find a zero remainder, no need to keep > testing the rest of the primes in the list. > > 3. you can stop testing numbers at the halfway point. there are no > primes smaller than 2, so no number x can have a factor larger than > x/2. > > 4. in fact you can do even better. a simple proof by contradiction > shows that if primes 1..y don't divide x and y^2 > x then x must be > prime. put another way, once you test up to the square root of x, > there's no point continuing. if one factor were bigger than sqrt(x), > the other would have to be smaller than sqrt(x). but you've already > tested the factors smaller than sqrt(x), so there can't be any > factors. The Prime Number article[1] on Wikipedia has a nice little Python snippet implementing this algorithm (more or less). See the Finding Prime Numbers section. > 5. you can do better than checking every odd number (next+2) to find > the next prime, but I'm too tired to look into it right now. it may > require more complex machinery. > > Locating primes is an interesting challenge because of the seemingly > endless grades of refinements over simple brute-force search. Like I > said though, if speed and size aren't concerns, your algorithm is > fine. Further reading: the Sieve of Eratosthenes[2] is a relatively simple and fun little algorithm to implement (also has a size issue in that it requires a list of numbers from 2 up to the largest number you wish to test for primality, and I don't think it's any faster than the algorithm above). A modern refinement called the Sieve of Atkin[3] is also interesting, a bit faster, although rather more complicated. If you want to look further into the subject, see the Primality Test article[4] on Wikipedia (mentions things like probabilistic testing, the Miller-Rabin primality test, and such like). [1] http://en.wikipedia.org/wiki/Prime_number [2] http://en.wikipedia.org/wiki/Sieve_of_Eratosthenes [3] http://en.wikipedia.org/wiki/Sieve_of_Atkin [4] http://en.wikipedia.org/wiki/Primality_test Dave. -- From kentilton at gmail.com Sat May 6 11:04:15 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 11:04:15 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <445c794e$0$31647$e4fe514c@news.xs4all.nl> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> Message-ID: Martin P. Hellwig wrote: > Bill Atkins wrote: > > >> >> How do you define scalability? >> > http://www.google.com/search?hl=en&q=define%3Ascalability&btnG=Google+Search > Damn! Google can do that?! Omigod!!! Not joking, I never knew that,a lways used dictionary.com. Thx! I meant: > The ability to add power and capability to an existing system without significant expense or overhead. > www.yipes.com/care/cc_glossary.shtml The number of definitions explains why most respondents should save their breath. Natural language is naturally ambiguous. Meanwhile Usenet is the perfect place to grab one meaning out of a dozen and argue over the implications of that one meaning which of course is never the one originally intended, as any reasonable, good faith reader would admit. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From johnjsal at NOSPAMgmail.com Tue May 9 10:19:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 14:19:31 GMT Subject: utility functions within a class? In-Reply-To: <44605729$0$14042$626a54ce@news.free.fr> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <44605729$0$14042$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: >> but these >> functions will be called from another method in the class, not from the >> instance itself. > > yes, they will: > > class Parrot(object): > def _func1(self, whatever): > print whatever > > def talk(self): > self._func1('vroom') > HTH. yes, all your posts did help...this is exactly what i ended up doing, and i see now why i needed to make them regular methods, despite the fact that they weren't used outside the class (because the instance was still used *inside* the class to call them) From aleaxit at yahoo.com Sat May 6 22:23:12 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 19:23:12 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> Message-ID: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> Ken Tilton wrote: ... > Why? (symbol-name '|(|) -> "(" (No, the "s are not part of the name!) > > If you want to argue about that, I will have to bring up the Lisp > readtable. Or did you forget that, too? Mea culpa -- it wasn't in the Lisp(s) I used 25+ years ago, nor in Scheme; I've never used Common Lisp in anger, and obviously "just dabbling" gives one no good feel for how *INSANELY COMPLICATED* (or, if you prefer, "insanely extensible") it truly is. I personally think these gyrations are a good example of why Python, the language that "fits your brain" and has simplicity among its goals, is vastly superior for production purposes. Nevertheless, I admit I was wrong! Alex From johnjsal at NOSPAMgmail.com Mon May 15 10:48:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 14:48:03 GMT Subject: any plans to make pprint() a builtin? In-Reply-To: <1147680829.246867.161640@i40g2000cwc.googlegroups.com> References: <44669e46$0$5337$c3e8da3@news.astraweb.com> <446735ea$1_1@newspeer2.tds.net> <1147680829.246867.161640@i40g2000cwc.googlegroups.com> Message-ID: Ant wrote: > Considering that the current: > > import pprint > pprint.pprint(x) > > is hardly lengthy, I can't see how either of the alternatives proposed > are any better. > >> python.pprint.pprint(x) > > 6 characters shorter, but considerably more keystrokes if you are using > pprint more than once. Is it worth adding the 'python' builtin to save > an import statement? > >> import py >> py.std.pprint.pprint(x) > > Longer, messy, and what's the actual point? Wouldn't: > > import pprint as pp > pp.pprint(x) > > be better, standard *and* shorter? > I guess the idea is that you can use the import py statement to access many other modules as well, without importing them all separately. From stormtoad at gmail.com Thu May 4 16:06:50 2006 From: stormtoad at gmail.com (Stormcoder) Date: 4 May 2006 13:06:50 -0700 Subject: Swaying A Coder Away From Python In-Reply-To: References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> Message-ID: <1146773210.213607.96420@v46g2000cwv.googlegroups.com> I usually refer to it as "VILE!". As in what Vile thing do I have before me. Emacs all the way baby! From jemfinch at gmail.com Thu May 4 20:11:13 2006 From: jemfinch at gmail.com (jemfinch at gmail.com) Date: 4 May 2006 17:11:13 -0700 Subject: Tuple assignment and generators? In-Reply-To: <1146787689.113964.85810@i40g2000cwc.googlegroups.com> References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146787689.113964.85810@i40g2000cwc.googlegroups.com> Message-ID: <1146787873.310656.120810@i39g2000cwa.googlegroups.com> > Zero, in particular, is the same variable all throughout a Python interpreter. For the sake of accuracy let me note that I ought to have said, "is the same *value* all throughout a Python interpreter." Jeremy From scott.daniels at acm.org Thu May 25 17:28:24 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 25 May 2006 14:28:24 -0700 Subject: Problem with itertools.groupby. In-Reply-To: <1148591325.875006.246120@j55g2000cwa.googlegroups.com> References: <1148591325.875006.246120@j55g2000cwa.googlegroups.com> Message-ID: <44761d44$1@nntp0.pdx.net> trebucket at gmail.com wrote: > What am I doing wrong here? > >>>> import operator >>>> import itertools >>>> vals = [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), > ... (1, 16), (2, 17), (3, 18), (4, 19), (5, 20)] >>>> for k, g in itertools.groupby(iter(vals), operator.itemgetter(0)): > ... print k, [i for i in g] > ... > > What I want is tuples starting with identical numbers to be grouped. I > cannot figure out why this is not working. If anyone has any insights, > I would appreciate it. > > - Alex Ross > Sort the list before using it. >>> vals = [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), (1, 16), (2, 17), (3, 18), (4, 19), (5, 20)] >>> def first(pair): return pair[0] >>> for k, g in itertools.groupby(sorted(vals, key=first), first): print k, [i for i in g] "groupby" depends on the source stream having the clustering you need. Otherwise it could not work "on the fly" for arbitrarily large sources. Often you can arrange for your data source to be clustered; when you cannot, the groupby arg is a great sort key. --Scott David Daniels scott.daniels at acm.org From pmartin at snakecard.com Fri May 5 09:39:10 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 08:39:10 -0500 Subject: Is this a legal / acceptable statement ? Message-ID: <2AI6g.10201$9c6.5375@dukeread11> Hi, This code works, but is it "appropriate" ? l_init = False if True == l_init and 1234 = l_value: print 'l_value is initialized' I know I can do this with a try but ... Philippe From ptmcg at austin.rr._bogus_.com Fri May 12 03:42:12 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 12 May 2006 07:42:12 GMT Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> Message-ID: "Lad" wrote in message news:1147416658.204175.193480 at i39g2000cwa.googlegroups.com... > I use Python 2.3. > I have heard about decorators in Python 2.4. > What is the decorator useful for? > Thanks for reply > L. > Check out these examples on the Python wiki: http://wiki.python.org/moin/PythonDecoratorLibrary I've gotten to be a big fan of memoize. -- Paul From ianb at colorstudy.com Fri May 19 11:31:15 2006 From: ianb at colorstudy.com (Ian Bicking) Date: 19 May 2006 08:31:15 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <1148052675.065004.173390@38g2000cwa.googlegroups.com> glomde wrote: > i I would like to extend python so that you could create hiercical > tree structures (XML, HTML etc) easier and that resulting code would be > more readable than how you write today with packages like elementtree > and xist. > I dont want to replace the packages but the packages could be used with > the > new operators and the resulting IMHO is much more readable. You might want to look at PEP 359 for ideas: http://www.python.org/dev/peps/pep-0359/ From vbgunz at gmail.com Thu May 11 15:25:52 2006 From: vbgunz at gmail.com (vbgunz) Date: 11 May 2006 12:25:52 -0700 Subject: 2 books for me In-Reply-To: <87lkt9ytxx.fsf@localhost.localdomain> References: <87lkt9ytxx.fsf@localhost.localdomain> Message-ID: <1147375552.352050.5520@i40g2000cwc.googlegroups.com> The cookbook assumes you know some Python. if you know it, you're good :) If you're new to Python and programming I would recommend 'Learning Python' by Mark Lutz and David Ascher. if you're very familiar with programming but need to catch up on Python syntax, I would recommend the Python in a nutshell by Alex Martelli. I would also recommend you always keep a copy of the official Pythons docs by your side. They're priceless in my opinion. Good luck! From tim.golden at viacom-outdoor.co.uk Mon May 8 04:45:56 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 8 May 2006 09:45:56 +0100 Subject: Need to send email on HIGH Disk usage Message-ID: [C Saha] | I am looking for a py script which will send me email when | ever my disk becomes more than 90% full. By the way my OS is Win XP. | | If anybody have already has written same type of script or | something very similar kind of script will also be great. You can certainly do this with a WMI event. You might start by combining this example: http://tgolden.sc.sabren.com/python/wmi_cookbook.html#percentage_free with one like this: http://tgolden.sc.sabren.com/python/wmi_cookbook.html#monitor_error_even ts For the event type, you'll need to use "Modification". I'm happy to put together an example script for you, but I didn't want to take away the fun of learning! 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 lorenzo at excitement.com Tue May 16 01:08:30 2006 From: lorenzo at excitement.com (Lorenzo) Date: Tue, 16 May 2006 00:08:30 -0500 Subject: Aggregate funuctions broken in MySQLdb? References: <1147623011.319336.11820@v46g2000cwv.googlegroups.com> Message-ID: In article , Dennis Lee Bieber wrote: > On Mon, 15 May 2006 20:14:29 GMT, John Salerno > declaimed the following in comp.lang.python: > > > Lorenzo Thurman wrote: > > > Thanks, that was my problem. Can you point me to some documentation on > > > MySQLdb? I've been googling to get answers and that obviously has not > > > been working. > > > > I've been looking into this too lately, and finding thorough docs for it > > is hard. Have you seen these yet: > > http://sourceforge.net/docman/?group_id=22307 > > For the most part, it follows the DB-API 2 specifications. The > subject of this thread (aggregates) would have occurred with ANY db-api > compliant adapter, even plain ODBC -- since it was a misunderstanding > that xxxx.execute() returns the status code (typically # of records > affected by the query), and xxxx.fetchnnn() is needed to obtain the data > values. This misunderstanding is not specific to use of aggregates as > any "select..." statement functions this way. > > Most divergences from the db-api specifications should be > determinable by looking at the sources of the python portion of the > adapter; or by looking at the features of the underlying RDBM. Thanks, you are correct. I have done similar database things using PHP and Perl to connect to databases, and I felt like DUH, when I got my first reply, but there are times when one cannot see the forest for the trees, so to speak. Better docs can help. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From vinay_sajip at yahoo.co.uk Tue May 30 12:13:25 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 30 May 2006 09:13:25 -0700 Subject: logging In-Reply-To: References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> Message-ID: <1149005605.819519.242350@j55g2000cwa.googlegroups.com> Baurzhan Ismagulov wrote: > Hello Vinay, > Ok, here is my hierarchy: > [snip] > [handlers] > keys=console [snip] > [logger_root] > level=CRITICAL > handlers=console > > [logger_l01] > level=DEBUG > qualname=l01 > handlers=console > > [logger_l02] > level=CRITICAL > qualname=l02 > handlers=console [snip] > With the config above, I expect that zzz gets printed, and qqq doesn't. > When I run the script, zzz is printed twice, and qqq isn't. I want that > zzz is printed once. How do I do that? I can add a filter if this can't > be done otherwise, however, I'm at the moment reluctant to do that since > I don't see why CRITICAL for root passes zzz through and drops qqq > correctly for l02. Did you try removing the handler from l01, as I suggested in an earlier reply? The config above still has the console handler attached to root, l01 and l02. The reason that zzz is printed twice is that when a logger decides to process an event, it is passed to handlers attached to ancestor loggers (unless propagate is set to 0 - but this is not the normal situation). So, log1 is deciding to process the event (based on the level), and passing it to its own handlers (l01->console) and then to its ancestor loggers' handlers (root->console). Remove the handlers from l01 and l02 and try again. From floyd at apaflo.com Wed May 3 15:20:06 2006 From: floyd at apaflo.com (Floyd L. Davidson) Date: Wed, 03 May 2006 11:20:06 -0800 Subject: symbolic links, aliases, cls clear References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> <87r7430x2t.fld@apaflo.com> <1146682594.341905.187600@u72g2000cwu.googlegroups.com> Message-ID: <87odyeud95.fld@apaflo.com> af.dingo at gmail.com wrote: >it would be nice if python provided a termcap or terminfo library, >wouldn't it? Try "import curses". -- Floyd L. Davidson Ukpeagvik (Barrow, Alaska) floyd at apaflo.com From m.sloyko at gmail.com Thu May 4 07:05:33 2006 From: m.sloyko at gmail.com (Maxim Sloyko) Date: 4 May 2006 04:05:33 -0700 Subject: ZSI usage In-Reply-To: <1146739412.265658.124130@j73g2000cwa.googlegroups.com> References: <1146739412.265658.124130@j73g2000cwa.googlegroups.com> Message-ID: <1146740733.764886.69900@v46g2000cwv.googlegroups.com> There is a typo there in functions name. It is called "session_open" not "open_session", but everything else is as described From jim.lewis at miclog.com Thu May 25 19:03:01 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 25 May 2006 16:03:01 -0700 Subject: Pyrex installation on windows XP: step-by-step guide References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> <1148251275.211468.221460@g10g2000cwb.googlegroups.com> <1148344720.139905.282630@y43g2000cwc.googlegroups.com> Message-ID: <1148598181.033043.28820@38g2000cwa.googlegroups.com> Thanks but now another problem :-( Examples in books show importing a global so why does below give: AttributeError: 'module' object has no attribute 'globalvar' primes.pyx: from run import globalvar def prime(int kmax): result = [run.globalvar] ... run.py: from primes import prime globalvar = 999 while True: print prime (10) From aleax at mac.com Sun May 14 18:27:56 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 14 May 2006 15:27:56 -0700 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> Message-ID: <1hfc2sb.8hxfcv13c5v6nN%aleax@mac.com> Cameron Laird wrote: > In article <1hfarom.1lfetjc18leddeN%aleax at mac.com>, > Alex Martelli wrote: > . > . > . > >My preference would be (with the original definition for > >words_of_the_file) to code > > > > numwords = sum(1 for w in words_of_the_file(thefilepath)) > . > . > . > There are times when > > numwords = len(list(words_of_the_file(thefilepath)) > > will be advantageous. Can you please give some examples? None comes readily to mind... > For that matter, would it be an advantage for len() to operate > on iterables? It could be faster and thriftier on memory than > either of the above, and my first impression is that it's > sufficiently natural not to offend those of suspicious of > language bloat. I'd be a bit worried about having len(x) change x's state into an unusable one. Yes, it happens in other cases (if y in x:), but adding more such problematic cases doesn't seem advisable to me anyway -- I'd evaluate this proposal as a -0, even taking into account the potential optimizations to be garnered by having some iterables expose __len__ (e.g., a genexp such as (f(x) fox x in foo), without an if-clause, might be optimized to delegate __len__ to foo -- again, there may be semantic alterations lurking that make this optimization a bit iffy). Alex From johnjsal at NOSPAMgmail.com Tue May 16 23:50:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 23:50:38 -0400 Subject: help with this simple DB script In-Reply-To: <1147830177.787319.268940@i40g2000cwc.googlegroups.com> References: <446a7849$0$1901$c3e8da3@news.astraweb.com> <1147830177.787319.268940@i40g2000cwc.googlegroups.com> Message-ID: <446a9ed6$0$11709$c3e8da3@news.astraweb.com> BartlebyScrivener wrote: > Are you able to connect to the DB using MySQL administrator? > Yes, through my hosting control panel. That's how I created the DB, but I want to try to do everything else with mysqldb. From alexander.kozlovsky at gmail.com Mon May 22 04:06:38 2006 From: alexander.kozlovsky at gmail.com (Alexander Kozlovsky) Date: Mon, 22 May 2006 12:06:38 +0400 Subject: dict!ident as equivalent of dict["ident"] In-Reply-To: References: Message-ID: <1595609895.20060522120638@gmail.com> Edward Elliott wrote: >> With this suggestion, mapping!identifier >> becomes fully equivalent to mapping["identifier"] > > Penny-wise, pound-foolish. Saves 3 character strokes at the cost of a new > special-purpose operator which only works in limited circumstances. To > avoid parsing ambiguity, identifier can only contain (as the name implies) > alphanumerics and _. So your ! is limited not only to dicts but to certain > keys in certain dicts. More complicated than it's worth. Yes, it is limited use-case, but IMHO important one. The benefits are: 1. Code looks more neat, because IDE will highlight it as identifier, and not as string 2. Limited form of code completion (as in PythonWin) becomes possible 3. A bit easier to type, and to read Anyway, I don't intent strongly on this, I just like to see common attitude > So your ! is limited not only to dicts Not only to dict, but to any class with __getitem__ or __setitem__ methods -- Best regards, Alexander mailto:alexander.kozlovsky at gmail.com From sjmachin at lexicon.net Wed May 31 22:06:15 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 12:06:15 +1000 Subject: struct: type registration? In-Reply-To: References: Message-ID: <447e4b98$1@news.eftel.com> On 1/06/2006 10:50 AM, Giovanni Bajo wrote: > Hello, > > given the ongoing work on struct (which I thought was a dead module), I was > wondering if it would be possible to add an API to register custom parsing > codes for struct. Whenever I use it for non-trivial tasks, I always happen to > write small wrapper functions to adjust the values returned by struct. > > An example API would be the following: > > ============================================ > def mystring_len(): > return 20 > > def mystring_pack(s): > if len(s) > 20: > raise ValueError, "a mystring can be at max 20 chars" > s = (s + "\0"*20)[:20] Have you considered s.ljust(20, "\0") ? > s = struct.pack("20s", s) > return s I am an idiot, so please be gentle with me: I don't understand why you are using struct.pack at all: |>>> import struct |>>> x = ("abcde" + "\0" * 20)[:20] |>>> x 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>> len(x) 20 |>>> y = struct.pack("20s", x) |>>> y == x True |>>> Looks like a big fat no-op to me; you've done all the heavy lifting yourself. > > def mystring_unpack(s): > assert len(s) == 20 > s = struct.unpack("20s", s)[0] Errrm, g'day, it's that pesky idiot again: |>>> z = struct.unpack("20s", y)[0] |>>> z 'abcde\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00' |>>> z == y == x True > idx = s.find("\0") > if idx >= 0: > s = s[:idx] > return s Have you considered this: |>>> z.rstrip("\0") 'abcde' |>>> ("\0" * 20).rstrip("\0") '' |>>> ("x" * 20).rstrip("\0") 'xxxxxxxxxxxxxxxxxxxx' > > struct.register("S", mystring_pack, mystring_unpack, mystring_len) > > # then later > foo = struct.unpack("iilS", data) > ============================================ > > This is only an example, any similar API which might fit better struct > internals would do as well. > > As shown, the custom packer/unpacker can call the original pack/unpack as a > basis for their work. I guess an issue with this could be the endianess > problem: it would make sense if, when called recursively, struct.pack/unpack > used by the default the endianess specified by the external format string. From NOatkinwSPAM at rpi.edu Sat May 6 20:16:19 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 20:16:19 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> Message-ID: <87ac9ubsfg.fsf@rpi.edu> aleaxit at yahoo.com (Alex Martelli) writes: > Bill Atkins wrote: > ... >> > ``allow ( as an ordinary single-character identifier'' as for the >> > unneded feature ``allow unnamed functions with all the flexibility of >> > named ones''. >> >> Not so infeasible: >> >> (let ((|bizarrely(named()symbol| 3)) >> (+ |bizarrely(named()symbol| 4)) >> >> ;; => 7 > > Read again what I wrote: I very specifically said "ordinary > *single-character* identifier" (as opposed to "one of many characters > inside a multi-character identifier"). Why do you think I said > otherwise, when you just quoted what I had written? (Even just a > _leading_ ( at the start of an identifier may be problematic -- and just > as trivial as having to give names to functions, of course, see below). Well, the same technique can obviously be used for: (let ((|(| 3))) (+ |(| 4))) ;; => 7 The length of the identifier is irrelevant... >> And in any case, enforced indentation is a policy with vastly more >> serious consequences than the naming of identifiers. > > So far, what was being discussed here isn't -- having to use an > identifier for an object, rather than keeping it anonymous -- trivial. > Python practically enforces names for several kinds of objects, such as > classes and modules as well as functions ("practically" because you CAN > call new.function(...), type(...), etc, where the name is still there > but might e.g. be empty -- not a very practical alternative, though) -- > so what? Can you have an unnamed macro in Lisp? Is being "forced" to > name it a "serious consequence"? Pah. Common Lisp does not support unnamed macros (how would these be useful?), but nothing stops me from adding these. What use case do you envision for anonymous macros? > Anyway, I repeat: *any* design choice (in a language, or for that matter > any other artefact) has consequences. As Paul Graham quotes and > supports his unnamed friend as saying, Python lets you easily write code > that *looks* good, and, as Graham argues, that's an important issue -- > and, please note, a crucial consequence of using significant > indentation. Alien whitespace eating nanoviruses are no more of a worry > than alien parentheses eating nanoviruses, after all. It *is* an important issue, but it's also a subjective issue. I find Lisp to be far prettier than any syntax-based language, so it's far from an objective truth that Python code often looks good - or even at all. Plus, I can easily write code that looks good without using a language that enforces indentation rules. Lisp's regular syntax lets Emacs do it for me with a simple C-M-a C-M-q. What could be easier? > > > Alex -- This is a song that took me ten years to live and two years to write. - Bob Dylan From pjb at informatimago.com Thu May 18 13:24:15 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 18 May 2006 19:24:15 +0200 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> <1147796116.826750@elch.in-berlin.de> <1147905290_7@news-east.n> <87ves3wpuy.fsf@thalassa.informatimago.com> <1147963328.479963.4390@j33g2000cwa.googlegroups.com> Message-ID: <87y7wzutz4.fsf@thalassa.informatimago.com> "Jonathon McKitrick" writes: > Pascal Bourguignon wrote: >> (defun ???? (&key (????? 10) (?? 1) (???? 0)) >> (loop :for i :from ???? :to ????? :by ?? :collect i)) > > How do you even *enter* these characters? My browser seems to trap all > the special character combinations, and I *know* you don't mean > selecting from a character palette. Why? Of course! Aren't you either an emacs or a Mac user? On a Mac, you just select the input keyboad from the Input menu (the little flag on the right of the menubar, you may activate it from the International System Preference panel). On emacs, it's as simple: M-x set-input-method RET I've bound C-F9, C-F10, C-F11, and C-F12 to various input methods: (global-set-key [C-f9] (lambda()(interactive)(set-input-method 'chinese-py-b5))) (global-set-key [C-f10] (lambda()(interactive)(set-input-method 'cyrillic-yawerty))) (global-set-key [C-f11] (lambda()(interactive)(set-input-method 'greek))) (global-set-key [C-f12] (lambda()(interactive)(set-input-method 'hebrew))) C-\ is bound to toggle-input-method which allows to revert back to the usual input method. For the alphabetic scripts, there's no difficulty, it's like with roman scripts: each key is a character. For ideographic scripts, the input methods are more sophisticated. Then, you have to learn some of these strange languages. I learned several (but I forgot everything but: ???? ?? ?? ???, ???????????, ? ????? ????, ? ??, ? ? ???). For the Korean, I copy-and-pasted it from some web translation service. But keying them in is the easiest part. -- __Pascal Bourguignon__ http://www.informatimago.com/ Cats meow out of angst "Thumbs! If only we had thumbs! We could break so much!" From alanalan at newsgroup.nospam Thu May 4 08:42:25 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 4 May 2006 08:42:25 -0400 Subject: Python sample code for PLSQL REF CURSORS Message-ID: <0Cm6g.3838$ix6.280105@news20.bellglobal.com> Hi, I am having hard time to find a sample that shows me how to return an OUT REF CURSOR from my oracle stored procedure to my python program. The technique is explained here for Java and Visual Basic: http://www.oracle-base.com/articles/8i/UsingRefCursorsToReturnRecordsets.php I am looking for similar code for Python Any help would be appreciated, Alan From telesphore4 at gmail.com Mon May 22 17:27:56 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 22 May 2006 14:27:56 -0700 Subject: Using metaclasses to inherit class variables References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> <1148315581.385405.204750@i40g2000cwc.googlegroups.com> <1148321972.467689.148900@j73g2000cwa.googlegroups.com> Message-ID: <1148333276.914151.13910@j33g2000cwa.googlegroups.com> Sorry for not being clear. Fresh copies of class vars so the first one is the correct: ('foo', 'bar', [], False) >>> import copy >>> >>> class ClassVars(type): ... def __init__(cls, name, bases, dict): ... for name, value in type(cls).classVars.iteritems(): ... if name not in dict: ... setattr(cls, name, copy.copy(value)) ... >>> def are(**kwargs): ... return type('', (ClassVars,), {'classVars':kwargs}) ... >>> class C(object): ... __metaclass__ = are(name='foo', desc='bar', list=[]) ... name = 'not foo' #<<< Changing a copy only owned by this class ... >>> class D(C): ... pass ... >>> C.name, C.desc, C.list ('not foo', 'bar', []) <<<<<<<<<<<<<<<<<<<<<< Separate copy we changed >>> D.name, D.desc, D.list, D.list is C.list ('foo', 'bar', [], False) <<<<<<<<<<<<<<<<<<<< Defaults are not changed Both prints are correct here Thanks for your help btw. t4 From phoolimin at gmail.com Tue May 16 10:49:22 2006 From: phoolimin at gmail.com (Limin Fu) Date: Tue, 16 May 2006 16:49:22 +0200 Subject: questions on python script compiling for embedding Message-ID: <935fb28e0605160749o55444ea0o57522726a6371c8d@mail.gmail.com> Dear all, I am trying to embed python into another scripting language, to do this I need to solve a number of problems on importing or compiling python script. First let me state what exactly I want to do, that is, I want the following syntax to be supported in the host language which I am developing: ###################################################### # scripts in the host language routine Test() do println("printed by Test()"); end global astring = "ASTRING"; # begin python scripts: @begin(python) def PyTest( s ): print s return 1000; # access global variables from the host scripts pystring = astring; # call function defined in the host script: Test(); @end(python) # call a python function: n = PyTest( "invoke python function" ); ###################################################### So there are the following problems come out naturally: #1. can I compile a block of python script to get the list of variables, classes and functions etc. (or at least the names) without executing? Because I need the host script to see the python definitions. The Py_CompileStringFlags() seems to do the work. But it returns a code object, which I don't know exactly and if it is possible to get the list of variables, classes and functions from this kind of object. ##2. Can I pass a list global variables for such compiling? Because I need python scripts also see the variables functions etc. defined in the host scripts. ********* For these two problem, a C API like this would be pefect: PyObject* Py_CompileStringFlagsXXX( const char *str, const char *file, int start, PyObject *module, PyCompilerFlags *flags ); Different from Py_CompileStringFlags(), this function should take another parameter (Python module object), which serve as a **namespace**, to solve undefined names in the souce "str", and store global variables, functions and classes etc defined in this source string. So the third question is: ###3. Is there some way, or how to do such thing as Py_CompileStringFlagsXXX() would do??? Of course, I do not expect such API should be added soon or even added. Thanks a lot, Limin -------------- next part -------------- An HTML attachment was scrubbed... URL: From Serge.Orlov at gmail.com Thu May 11 10:35:30 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 May 2006 07:35:30 -0700 Subject: Use subprocesses in simple way... References: <1147262237.501896.177210@y43g2000cwc.googlegroups.com> Message-ID: <1147358130.354414.265440@u72g2000cwu.googlegroups.com> DurumDara wrote: > 10 May 2006 04:57:17 -0700, Serge Orlov : > > I thought md5 algorithm is pretty light, so you'll be I/O-bound, then > > why bother with multi-processor algorithm? > > This is an assessor utility. > The program's architecture must be flexible, because I don't know, > where it need to run (only I have a possibility to fix this: I write > to user's guide). > > But I want to speedup my alg. with native code, and multiprocess code. > I not tested yed, but I think that 4 subprocess quickly as one large > process. I believe you need to look at Queue module. Using Queue will help you avoid threading hell that you're afraid of (and rightly so!). Create two queues: one for jobs, another one for results, the main thread submits jobs and picks up results for results queue. As soon as number of results == number of jobs, it's time to quit. Submit N special jobs that indicate it's time to exit, where N is the number of worker threads. Then "join" the main thread with worker threads and exit the application. From pod at internode.on.net Thu May 18 03:37:44 2006 From: pod at internode.on.net (PoD) Date: Thu, 18 May 2006 16:37:44 +0900 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: On Wed, 17 May 2006 21:37:14 +0800, Andy Sy wrote: > If tabs are easily misunderstood, then they are a MISfeature > and they need to be removed. > >>From the Zen of Python: > > "Explicit is better than implicit..." > "In the face of ambiguity, refuse the temptation to guess..." > "Special cases aren't special enough to break the rules..." Exactly. How many levels of indentation does 12 spaces indicate? It could be 1,2,3,4,6 or 12. If you say it's 3 then you are _implying_ that each level is represented by 4 spaces. How many levels of indentation is 3 tabs? 3 levels in any code that you will find in the wild. From http Fri May 19 05:04:55 2006 From: http (Paul Rubin) Date: 19 May 2006 02:04:55 -0700 Subject: Segmenting a pickle stream without unpickling References: <446d8566$1_3@news.bluewin.ch> Message-ID: <7xodxu75c8.fsf@ruckus.brouhaha.com> Boris Borcic writes: > def pickles(my_stream) : > from cPickle import load,dumps > while 1 : > yield dumps(load(my_stream)) > > without the overhead associated with unpickling objects > just to pickle them again ? I think you'd have to write something special. The unpickler parses as it goes along, and all the dispatch actions build up objects. You'd have to write a set of actions that just read past the representations. I think there's no way to know where an object ends without parsing it, including parsing any objects nested inside it. From emin.martinian at gmail.com Tue May 30 16:55:17 2006 From: emin.martinian at gmail.com (emin.martinian at gmail.com) Date: 30 May 2006 13:55:17 -0700 Subject: "initializer element is not constant" Message-ID: <1149018679.330326.163720@y43g2000cwc.googlegroups.com> When trying to compile python extensions written in C using "python setup.py build" on cygwin I get the following error: foo.c: initializer element is not constant foo.c: error: (near initialization for `FooType.ob_type') I remember someone telling me a long time ago that this had something to do with declspec and how dlls are imported on cygwin/python. Can someone give me a pointer to how to build python extensions on cygwin? Thanks From manstey at csu.edu.au Wed May 17 07:07:41 2006 From: manstey at csu.edu.au (manstey) Date: 17 May 2006 04:07:41 -0700 Subject: index in for loops Message-ID: <1147864061.717315.211440@i39g2000cwa.googlegroups.com> in for loops like the following: word='abcade' for letter in word: print letter Is it possible to get the position of letter for any iteration through the loop? so for examlpe letter=='a', and I want to know if it is the first or second 'a' in 'abcade'. can i do this by looking at a property of letter? From skip at pobox.com Tue May 16 14:53:19 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 May 2006 13:53:19 -0500 Subject: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? In-Reply-To: <1147804326.793291.53410@j55g2000cwa.googlegroups.com> References: <1147657728.064817.214850@j73g2000cwa.googlegroups.com> <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> <1147804326.793291.53410@j55g2000cwa.googlegroups.com> Message-ID: <17514.8095.14185.137871@montanaro.dyndns.org> Graham> Looking up a key in a dictionary is done in constant-time, Graham> i.e. it doesn't matter how large the dictionary is. Doesn't that depend on how many keys hash to the same value? For small dictionaries keeping the max keys that hash to the same value small isn't a huge problem. For large dictionaries (millions of keys) might you have some long chains? Or in an effort to reduce the chain length, wind up using so much virtual memory that you wind up wrecking performance by swapping? Skip From vbgunz at gmail.com Fri May 26 06:31:56 2006 From: vbgunz at gmail.com (vbgunz) Date: 26 May 2006 03:31:56 -0700 Subject: how to clear up a List in python? In-Reply-To: References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148612582.510390.48040@i39g2000cwa.googlegroups.com> Message-ID: <1148639516.244264.37500@i40g2000cwc.googlegroups.com> Steve, I have no qualm with Fredrik over this '''if you don't know how to do things, you don't need to post.''' but this ''' if you know why this is about the dumbest way to do what you're doing, and you're posted this on purpose, you really need to grow up.'''. The problem was I did post it on purpose, but not with the intent to mess anyone up over it. To top it off, this thread was done and over with (the end) with Roberts reply that came in immediately after mines. I acknowledged his was best and that I *learned* from it. It just seemed Fredriks response was an attack on me and I did take it personally because I tried my best. Sometimes I try to give back but to try and make me regret it is poor communication if the best intent is to advise me on how things are done and not done around here... Its all good. I live and I learn... From onurb at xiludom.gro Tue May 23 04:14:41 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 23 May 2006 10:14:41 +0200 Subject: global name not defined In-Reply-To: <1148336761.776348.260450@j33g2000cwa.googlegroups.com> References: <1148336761.776348.260450@j33g2000cwa.googlegroups.com> Message-ID: <4472c4dc$0$25675$626a54ce@news.free.fr> NetKev wrote: (snip) > def process_log(self, logfile, offset): > if new_denied_hosts: > info("new denied hosts: %s", str(new_denied_hosts)) > [warn_Admin(ip) for ip in new_denied_hosts] This uselessly builds a list. List comprehension is meant to create lists, not to replace for loops. for ip in new_denied_hosts: warn_admin(ip) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From richie at entrian.com Fri May 19 11:46:58 2006 From: richie at entrian.com (Richie Hindle) Date: Fri, 19 May 2006 16:46:58 +0100 Subject: Exception style (was: calling python functions using variables) In-Reply-To: <9121k3-hjm.ln1@lairds.us> References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <446da180$0$10184$636a55ce@news.free.fr> <126rjus43k450df@corp.supernews.com> <9121k3-hjm.ln1@lairds.us> Message-ID: [Cameron] > try: > getattr(commands, VARIABLE)() > except NameError: > print >> sys.stderr, "Unknown command", VARIABLE > > this situation illustrates the discomfort I consistently > feel: how do I know that the NameError means VARIABLE didn't resolve, > rather than that it did, but that evaluation of commands.VARIABLE() > itself didn't throw a NameError? My usual answer: umm, unless I go > to efforts to prevent it, I *don't* know that didn't happen. The 'try' block should only include the code that you expect to fail with the given exception. Try this instead: >>> try: >>> command = getattr(commands, VARIABLE) >>> except AttributeError: >>> print >> sys.stderr, "Unknown command", VARIABLE >>> else: >>> command() (Aside: I think AttributeError is correct here, not NameError.) -- Richie Hindle richie at entrian.com From tim.peters at gmail.com Thu May 25 11:19:08 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 25 May 2006 15:19:08 +0000 Subject: how to "normalize" indentation sources In-Reply-To: References: <447525b7$1@news.eftel.com> Message-ID: <1f7befae0605250819p5c1fbb83xc7d5ae24a4885553@mail.gmail.com> [John Machin, quoting reindent.py docs] >> remove empty lines at the end of files. Also ensure the last line ends >> with a newline. [John Salerno] > don't those two things conflict with one another? No. This is the repr of a file with (3) empty lines at the end: "a file\n\n \n \t \n" reindent.py changes that to: "a file\n" This is the repr of a file with no newline at the end: "a file" reindent.py changes that to: "a file\n" > or is the newline added after empty lines are removed? False dichotomy ;-) From andreasp+python at qbcon.com Mon May 15 07:01:34 2006 From: andreasp+python at qbcon.com (Andreas Pauley) Date: Mon, 15 May 2006 13:01:34 +0200 Subject: Python Translation of C# DES Encryption In-Reply-To: <5m49g.86150$dW3.66874@newssvr21.news.prodigy.com> References: <5m49g.86150$dW3.66874@newssvr21.news.prodigy.com> Message-ID: <44685F8E.4070901@qbcon.com> Edward Elliott wrote: >You need to find the exact algorithm the DESCryptoServiceProvider uses. >CBC and CTR are common modes with IVs. Besides mode of operation, there's >the issue of how it pads the data (in the cipher, not base64). There could >also be differences in things like the key scheduling routines, but that's >less likely. Until you know exactly what the original code does, your only >option is trial and error. > > > I read some of the C# documentation on DESCryptoServiceProvider, but it was completely useless for my purpose. The documentation basically only tells you how to use the class, not what it does. I managed to *decrypt* a string encrypted by the C# method using CBC mode, as suggested by Gary (thanks). The python CBC encryption results in a different encrypted string, but decrypting both these strings returns the original plaintext value. As for padding, the C# method uses characters '\x01' to '\x07' for padding. If there are 3 padding characters needed (eg with a password of 5 chars), then three '\x03' chars will be used. Similarly, a 2-char password will be padded with '\x06' * 6 Regards, Andreas Pauley _____________________________________________________________________________________________ This e-mail contains official information from Quality Business Consultants (Pty) Ltd and is intended for use by the addressee only. Important notice: Important restrictions, qualifications and disclaimers ("the Disclaimer") apply to this email. To read this click on the following address: http://www.qbcon.com/disclaimer The Disclaimer forms part of the content of this email in terms of section 11 of the Electronic Communications and Transactions Act, 25 of 2002. If you are unable to access the Disclaimer, send a blank e-mail to disclaimer at qbcon.com and we will send you a copy of the Disclaimer. From manojk at sasken.com Wed May 24 02:25:45 2006 From: manojk at sasken.com (Manoj Kumar P) Date: Wed, 24 May 2006 11:55:45 +0530 Subject: Access C++, Java APIs from Python.. In-Reply-To: Message-ID: Hi, I'm new to python. I would like to know whether is it possible to access Java/C++ APIs from python. I have two applications written in Java and API, I wanted to call the APIs of these applications from Python. I'm developing web-based application using Zope. Thanks in advance. -Manoj- "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" SASKEN BUSINESS DISCLAIMER This message may contain confidential, proprietary or legally Privileged information. In case you are not the original intended Recipient of the message, you must not, directly or indirectly, use, Disclose, distribute, print, or copy any part of this message and you are requested to delete it and inform the sender. Any views expressed in this message are those of the individual sender unless otherwise stated. Nothing contained in this message shall be construed as an offer or acceptance of any offer by Sasken Communication Technologies Limited ("Sasken") unless sent with that express intent and with due authority of Sasken. Sasken has taken enough precautions to prevent the spread of viruses. However the company accepts no liability for any damage caused by any virus transmitted by this email From elventear at gmail.com Sun May 21 17:34:16 2006 From: elventear at gmail.com (elventear) Date: 21 May 2006 14:34:16 -0700 Subject: Question about Python on Mac References: <1148073591.308980.289300@u72g2000cwu.googlegroups.com> Message-ID: <1148247256.591585.57810@i40g2000cwc.googlegroups.com> James Stroud wrote: > I think fink is not detecting the gmp (GNU multiple precision arithmetic > library) dependency. > > Try: > > % fink install gmp > > Then try building gmpy with /sw/bin/python. I think I didn't explain myself very well. gmp is already installed in my computer; when building gmpy it links against libgmp without problems. But when doing import gmpy is that Fink's Python complains like I've mentioned before. But if I build gmpy (Using setup.py), using Python 2.4.3 works fine. Pepe From mariano.difelice at gmail.com Fri May 19 10:46:18 2006 From: mariano.difelice at gmail.com (mardif) Date: 19 May 2006 07:46:18 -0700 Subject: open file with whitespaces In-Reply-To: <446dd899$0$8108$626a54ce@news.free.fr> References: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> <446dd899$0$8108$626a54ce@news.free.fr> Message-ID: <1148049978.121892.198840@y43g2000cwc.googlegroups.com> OK OK GUYS!!!! I've found the solution: ( effectly, a friend of mine has found the solution ) import os os.spawnl(os.P_WAIT, "c:\programmi\internet explorer\iexplore.exe",'"C:\Documents and Settings\michele\Desktop\ciccio.html"','"C:\Documents and Settings\michele\Desktop\ciccio.html"') The secret are the ' simbols around arguments: ' "C:\Documents and Settings\michele\Desktop\ciccio.html" ' Without these, don't work! Very STRONG!!!!! bye and thx From steve at ferg.org Tue May 9 22:30:29 2006 From: steve at ferg.org (Steve) Date: 9 May 2006 19:30:29 -0700 Subject: Is PythonCard dead? Message-ID: <1147228229.133910.118410@g10g2000cwb.googlegroups.com> There haven't been any updates since version 0.8.1 in October 2004, almost 18 months. And the new book on wxPython doesn't say anything about PythonCard, which I find rather surprising. From deets at nospam.web.de Fri May 5 05:23:02 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 11:23:02 +0200 Subject: Tuple assignment and generators? References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <4c0hueF12dnv0U1@uni-berlin.de> <1146820171.032245.205870@i40g2000cwc.googlegroups.com> Message-ID: <4c0jsnF13feqqU1@uni-berlin.de> vdrab wrote: >> beasts. It can get even worse: I can define an object (in C++ as well as >> in python) that is not even equal to itself. Not that I felt the need for >> that so far.... > > hehe... now you've picked my curiosity... how? > > ps. > def __eq__(self, other): return False > does not count ! Sure it does! The rich comparison methods can very well be used to define whatever semantics you want. Now I agree that def __eq__(self, other): if self is other: return False ... # do something more sane doesn't make much sense usually. Or maybe even never. Still, it illustrates the point: object identity is not to be confused with two objects being part of an equality relation. Diez From conor.robinson at gmail.com Thu May 11 16:49:05 2006 From: conor.robinson at gmail.com (py_genetic) Date: 11 May 2006 13:49:05 -0700 Subject: segmentation fault in scipy? In-Reply-To: References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> <1147373294.235202.188220@y43g2000cwc.googlegroups.com> <1147376927.857632.310430@j33g2000cwa.googlegroups.com> Message-ID: <1147380545.329818.102610@i40g2000cwc.googlegroups.com> >Now I'm even more confused. What kind of array is "error" here? First you tell >me it's a (25000, 80) array and now you are telling me it is a (25000,) array. >Once you've defined what "error" is, then please tell me what the quantity is >that you want to calculate. I think I told you several different wrong things, >previously, based on wrong assumptions. > It's just in my original post I was trying to get across maximum size of the arrays I'm using. sorry for the confusion, I didn't state actual size of my output vectors. I discovered the probelm when your first stated: >If error.shape == (25000, 80), then dot(error, transpose(error)) will be >returning an array of shape (25000, 25000) Which was exactly related to the excessive calculation I was running and set off the red flags and made it very clear. Later I was somewhat confused and believed that you we were talking about two different things regarding SSE when you said: SSE = sum(multiply(error, error), axis=None) And didn't realize that multipy() was an efficient element mult method for matricies, thinking it was like matrixmultiply() and gave you back the old trace sse method but with the casting (not meaning to contradict you). However all is now very clear, and I agree with element wise mult or even squaring the output error, and have no real reason why I was using trace, except I had a faint memory of using it in a class for small experiments in matlab (i guess the idea was to keep everything in linear algebra) and I spit it up for some reason when I was doing a quicky error function. From ronnyma at math.uio.no Mon May 15 14:59:49 2006 From: ronnyma at math.uio.no (Ronny Mandal) Date: Mon, 15 May 2006 20:59:49 +0200 Subject: OOP and Tkinter References: <7gih62p25k5krj9c5l9ot6tpt01c45e723@4ax.com> <4cs113F17n5m7U1@uni-berlin.de> Message-ID: <1rjh629au1b5k1mk1trffnr97e2s61sqen@4ax.com> Thanks, but the problem was my undentation, after making one indent, it worked as expected. :) -Ronny M From me+python at modelnine.org Fri May 19 18:32:31 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sat, 20 May 2006 00:32:31 +0200 Subject: Feature request: sorting a list slice In-Reply-To: <1148073894.399040.242890@j73g2000cwa.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1148073894.399040.242890@j73g2000cwa.googlegroups.com> Message-ID: <200605200032.31573.me+python@modelnine.org> Am Freitag 19 Mai 2006 23:24 schrieb George Sakkis: > This is great, thanks Heiko ! Any idea on the chances of being > considered for inclusion in 2.5 ? Don't ask me, I'm not one of the core developers... ;-) But, anyway, the people on python-dev are doing their best to review patches. Just: I rather write them, than review them... ;-) --- Heiko. From george.sakkis at gmail.com Sun May 21 01:32:01 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 20 May 2006 22:32:01 -0700 Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> <1148172321.824018.207540@j33g2000cwa.googlegroups.com> Message-ID: <1148189521.803453.142860@j73g2000cwa.googlegroups.com> John Bokma wrote: > "George Sakkis" wrote: > > > John Bokma wrote: > > > >> "George Sakkis" wrote: > >> > >> > Not trying to be as ass, but can you take this offline or at least in > >> > a perl newsgroup ? Arguing on a particular fact or speculation about > >> > the perl community is rather unproductive and offtopic for a python > >> > newsgroup. > >> > >> Use a real Usenet client, and you can make it skip a thread. > > > > That's funny, coming from the same guy that's been harassing Xah for OT > > posts. Oh, the irony. > > Xah was harassing 5 groups with a cross post without setting a follow-up > to for the sole purpose of spamvertizing his website [1] repeatedly. And somehow this made all real usenet clients unable to skip his thread. > If you are that clueless, don't post. I will seriously ponder upon this, rest assured. > [1] He is looking for another hoster btw. This must feel really empowering huh ? George From andrew.arobert at gmail.com Wed May 17 12:02:16 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 17 May 2006 12:02:16 -0400 Subject: Process forking on Windows In-Reply-To: <446b45b1$0$7132$636a55ce@news.free.fr> References: <126mgi2j7fl4b4b@corp.supernews.com> <446b45b1$0$7132$636a55ce@news.free.fr> Message-ID: <126mi8q1t31r9e0@corp.supernews.com> bruno at modulix wrote: > Andrew Robert wrote: >> Hi everyone, >> >> >> I have a python program that will need to interact with an MQSeries >> trigger monitor. >> >> It does this fine but it hogs the trigger monitor while it executes. >> >> I'd like to fork the program off and terminate the parent process so >> that the trigger monitor frees up. > > > Is this really the solution ? > > >> Does anyone how this can be accomplished on a Windows platform? > > AFAIK, there's no fork in Windows - you might want to give a try with > CreateProcess. > http://www.byte.com/art/9410/sec14/art3.htm > http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/html/UCMGch01.asp > > HTH Unfortunately there is a real need for this. The MQSeries trigger monitor is single threaded. Because of this, my program would absorb it until it completes. The way to get around this would be to fork off and terminate the parent. Unfortunately, Windows appears to be somewhat stubborn about it. Creating a subprocess does not alleviate the need to get the originating process out of the trigger monitor. From robert.kern at gmail.com Thu May 11 16:40:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 15:40:08 -0500 Subject: which windows python to use? In-Reply-To: References: Message-ID: James Stroud wrote: > Enthought does not play well with cygwin, I've noticed. In what way? Does the mingw gcc that we distribute interfere with Cygwin's gcc? -- 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 Mon May 1 22:28:24 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 May 2006 03:28:24 +0100 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> Message-ID: Edward Elliott wrote: > Holger wrote: > >>oops, that was kinda embarrassing. > > > It's really not. You got a completely unhelpful error message saying you > passed 2 args when you only passed one explicitly. The fact the b is also > an argument to b.addfile(f) is totally nonobvious until you know that 1) b > is an object not a module*, and 2) objects pass references to themselves as > the first argument to their methods. The syntax "b." is completely > different from the syntax of any other type of parameter. > Specifically, perhaps it would be better to say "b is an instance of some Python class or type". Objects don't actually "pass references to themselves". The interpreter adds the bound instance as the first argument to a call on a bound method. I agree that the error message should probably be improved for the specific case of the wrong number of arguments to a bound method (and even more specifically when the number of arguments is out by exactly one - if there's one too many then self may have been omitted from the parameter list). > The mismatch between the number of parameters declared in the method > signature and the number of arguments actually passed is nonobvious, > unintuitive, and would trip up anybody who didn't already know what was > going on. It's ugly and confusing. It's definitely a wart on the > langauge. > Sorry, it's a wart on your brain. Read Guido's arguments in favor of an explicit self argument again before you assert this so confidently. It's certainly confusing to beginners, but there are actually quite sound reasons for it (see next paragraph). > Making people pass 'self' explicitly is stupid because it always has to be > the first argument, leading to these kinds of mistakes. The compiler > should handle it for you - and no, explicit is not *always* better than > implicit, just often and perhaps usually. While it's easy to recognize > once you know what's going on, that doesn't make it any less of a wart. > Hmm. I see. How would you then handle the use of unbound methods as first-class objects? If self is implicitly declared, that implies that methods can only be used when bound to instances. How, otherwise, would you have an instance call its superclass's __init__ method if it's no longer valid to say myClass(otherClass): def __init__(self): otherClass.__init__(self) ... > * technically modules may be objects also, but in practice you don't declare > self as a parameter to module functions The reason you don't do that is because the functions in a module are functions in a module, not methods of (some instance of) a class. Modules not only "may be" objects, they *are* objects, but the functions defined in them aren't methods. What, in Python, *isn't* an object? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From diffuser78 at gmail.com Tue May 16 09:06:26 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 16 May 2006 06:06:26 -0700 Subject: Python script for remotely shutting down Windows PC from Linux ? Message-ID: <1147784786.317200.238780@v46g2000cwv.googlegroups.com> I am a newbie in Python and want your help in writing python script. I have to remotely shut the windows px from linux box. I run OpenSSH on windows PC. I remotely connect it from Linux box using .... ssh Admin at IP_ADDR # connects me fine now without problems (LOCAL) Next, I wrote a script that would log me in and also shut the windows pc down, so I wrote a script ssh Admin at IP_ADDR # connects me fine now without problems (LOCAL) shutdown -s # This is a windows command (REMOTE) Now, when I run this script, it successfully logs me into the windows box but doesn't run the second part of the script which is to shut down the windows PC. Can you please tell me why ?? Is there a way using Python script to perform this operation ? Every help is appreciated. From rNOSPAMon at flownet.com Fri May 19 03:03:26 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 19 May 2006 00:03:26 -0700 Subject: WTF? Printing unicode strings References: <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <1147998139.268318.315250@y43g2000cwc.googlegroups.com> <1148001708.183506.296240@g10g2000cwb.googlegroups.com> Message-ID: In article <1148001708.183506.296240 at g10g2000cwb.googlegroups.com>, "Serge Orlov" wrote: > Ron Garret wrote: > > > > I'm using an OS X terminal to ssh to a Linux machine. > > > > > > In theory it should work out of the box. OS X terminal should set > > > enviromental variable LANG=en_US.utf-8, then ssh should transfer this > > > variable to Linux and python will know that your terminal is utf-8. > > > Unfortunately AFAIK OS X terminal doesn't set that variable and most > > > (all?) ssh clients don't transfer it between machines. As a workaround > > > you can set that variable on linux yourself . This should work in the > > > command line right away: > > > > > > LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > > > Or put the following line in ~/.bashrc and logout/login > > > > > > export LANG=en_US.utf-8 > > > > No joy. > > > > ron at www01:~$ LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > Traceback (most recent call last): > > File "", line 1, in ? > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > > position 0: ordinal not in range(128) > > ron at www01:~$ > > What version of python and what shell do you run? What the following > commands print: > > python -V > echo $SHELL > $SHELL --version ron at www01:~$ python -V Python 2.3.4 ron at www01:~$ echo $SHELL /bin/bash ron at www01:~$ $SHELL --version GNU bash, version 2.05b.0(1)-release (i386-pc-linux-gnu) Copyright (C) 2002 Free Software Foundation, Inc. ron at www01:~$ From just at xs4all.nl Sun May 7 06:24:50 2006 From: just at xs4all.nl (Just) Date: Sun, 07 May 2006 12:24:50 +0200 Subject: md5 from python different then md5 from command line References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> Message-ID: In article <1146996448.577162.283480 at j73g2000cwa.googlegroups.com>, "ursache.marius at gmail.com" wrote: > I noticed that the md5 computed with md5 module from python is > different then the md5 sum computed with md5sum utility (on slackware > and gentoo). > > i.e. > $echo marius|md5sum > 0f0f60ac801a9eec2163083a22307deb - > > >>> test = md5.new("marius") > >>> print test.hexdigest() > 242aa1a97769109065e3b4df359bcfc9 > > > Any idea why? and how to get the same md5 sum for both calls? echo adds a newline: >>> import md5 >>> test = md5.new("marius\n") >>> print test.hexdigest() 0f0f60ac801a9eec2163083a22307deb Just From george.sakkis at gmail.com Thu May 25 23:20:08 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 25 May 2006 20:20:08 -0700 Subject: Array? References: Message-ID: <1148613608.250998.239350@j33g2000cwa.googlegroups.com> Dr. Pastor wrote: > I need a row of 127 bytes that I will use as a > circular buffer. Into the bytes (at unspecified times) > a mark (0 After some time the "buffer" will contain the last 127 marks > and a pointer will point the next "usable" byte. > What would be the Pythonic way to do the above? > Thanks for any guidance. This will do the trick: import itertools as it from array import array class CircularBuffer(object): def __init__(self, size=128): self._buffer = array('c', it.repeat(chr(0),size)) self._next = 0 def putmark(self, mark): self._buffer[self._next] = mark self._next = (self._next+1) % len(self._buffer) def __str__(self): return '%s(%r)' % (self.__class__.__name__, self._buffer.tostring()) if __name__ == '__main__': import string b = CircularBuffer() for c in string.letters * 10: b.putmark(c) print b HTH, George From lfw at fusion.net.nz Sat May 20 23:02:22 2006 From: lfw at fusion.net.nz (Lloyd Weehuizen) Date: Sun, 21 May 2006 15:02:22 +1200 Subject: WeakrefValueDictionary of Callables? Message-ID: <446FD83E.2000007@fusion.net.nz> Hey I'm trying to set up a WeakrefValueDictionary of callables however as soon as my method that adds the callable to the dictionary exits the value is removed? Is there any way around this? Example: import weakref TEST_EVENT = 1 class TestBinder: def __init__( self ): self.entries = weakref.WeakValueDictionary() def BindFunction( self, event_id, function ): self.entries[event_id] = function def CallFunction( self, event_id, *args ): self.entries[event_id]( *args ) class TestCase: def __init__( self, binder ): binder.BindFunction( TEST_EVENT, self.TestFunction ) def TestFunction(): print "TestFunction OK" test_binder = TestBinder() test_case = TestCase( test_binder ) test_binder.CallFunction( TEST_EVENT ) This generates a KeyError: 1, if I don't use weakrefs, then the TestCase object is never cleaned up until TestBinder is destroyed. Thanks From usenet at DavidFilmer.com Wed May 24 20:30:53 2006 From: usenet at DavidFilmer.com (usenet at DavidFilmer.com) Date: 24 May 2006 17:30:53 -0700 Subject: John Bokma harassment In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <1148517053.805687.78620@u72g2000cwu.googlegroups.com> Xah Lee wrote: > I do not like to post off-topic messages Oh REALLY? That's strange, because I don't recall ever seeing an on-topic message (a Perl message in a Perl newsgroup) from Xah. Every one of the many Xah post I've ever seen (including the "Philosopher" message that this thread morphed into) was off-topic for a Perl programming newsgroup. -- http://DavidFilmer.com From aleax at mac.com Tue May 9 23:12:29 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 9 May 2006 20:12:29 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> <1147193343.140552.51470@i40g2000cwc.googlegroups.com> Message-ID: <1hf34bb.16yx7jvoisuovN%aleax@mac.com> Joe Marshall wrote: > Pisin Bootvong wrote: > > Is this a Slippery Slope fallacious argument? > > (http://c2.com/cgi/wiki?SlipperySlope) > > > > "if python required you to name every function then soon it will > > require you to name every number, every string, every immediate result, > > etc. And we know that is bad. Therefore requiring you to name your > > function is bad!!!! So Python is bad!!!!" > > No, it is a question about consistency. Why are functions singled out? They're not: packages, modules and classes also have names; as I pointed out, the common factor among these four types is that instance of these types are liable to occur in tracebacks &c, where a (good) name is particularly useful as a summary reminder of what the thing is. Alex From kadeko at gmail.com Thu May 18 07:15:56 2006 From: kadeko at gmail.com (looping) Date: 18 May 2006 04:15:56 -0700 Subject: Question about exausted iterators References: <446b48e2$0$5293$626a54ce@news.free.fr> <446c2dea$0$5306$626a54ce@news.free.fr> Message-ID: <1147950956.161966.211630@u72g2000cwu.googlegroups.com> Christophe wrote: > Ok, call me stupid if you want but I know perfectly well the "solution" > to that problem ! Come on, I was showing example code of an horrible > gotcha on using iterators. > OK, your are stupid ;-) Why asking questions when you don't want to listen answers ? > > > Instead of saying that all works as intended could you be a little > helpful and tell me why it was intended in such an obviously broken way > instead ? Why an exausted iterator must return an Exception (other than StopIteration of course) ? Well an exausted iterator could be seen like an empty string or an empty list (or tons of others things), so you expect the code for car in "": print car to return an Exception because it's empty ??? It's your job to check the iterator when it need to be. Regards. Dom From __peter__ at web.de Tue May 2 08:57:25 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 May 2006 14:57:25 +0200 Subject: Strange result with math.atan2() References: Message-ID: Vedran Fura? wrote: > I think that this results must be the same: > > In [3]: math.atan2(-0.0,-1) > Out[3]: -3.1415926535897931 > > In [4]: math.atan2(-0,-1) > Out[4]: 3.1415926535897931 > > In [5]: -0 == -0.0 > Out[5]: True Glimpsing at the hardware formats: >>> struct.pack("d", 0.0) '\x00\x00\x00\x00\x00\x00\x00\x00' >>> struct.pack("d", -0.0) '\x00\x00\x00\x00\x00\x00\x00\x80' >>> struct.pack("i", -0) '\x00\x00\x00\x00' >>> struct.pack("i", 0) '\x00\x00\x00\x00' -0 and +0 integers are identical while 0.0 and -0.0 floats are not. The negative sign is therefore lost before the int --> float conversion takes place. Peter From benkasminbullock at gmail.com Wed May 24 08:45:25 2006 From: benkasminbullock at gmail.com (Ben Bullock) Date: Wed, 24 May 2006 21:45:25 +0900 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: "Xah Lee" wrote in message news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... > If you believe this lobbying to my webhosting provider is unjust, > please write to my web hosting provider abuse at dreamhost.com Why don't you just change your provider? It would take less time than this. From __peter__ at web.de Wed May 31 03:26:31 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 31 May 2006 09:26:31 +0200 Subject: genexp performance problem? References: Message-ID: Giovanni Bajo wrote: > I found this strange: > > python -mtimeit "sum(int(L) for L in xrange(3000))" > 100 loops, best of 3: 5.04 msec per loop > > python -mtimeit "import itertools; sum(itertools.imap(int, xrange(3000)))" > 100 loops, best of 3: 3.6 msec per loop > > I thought the two constructs could achieve the same speed. I think early binding would have been preferable, but as Fredrik Lundh said, int is looked up for every iteration which accounts for the slowdown. For reference: $ python -m timeit "sum(int(i) for i in xrange(3000))" 1000 loops, best of 3: 1.92 msec per loop $ python -m timeit -s "from itertools import imap" "sum(imap(int, xrange(3000)))" 1000 loops, best of 3: 1.17 msec per loop You can shave off a few percent by turning int into a local variable: $ python -m timeit -s "int_ = int" "sum(int_(i) for i in xrange(3000))" 1000 loops, best of 3: 1.74 msec per loop On the other hand the function call overhead that imap() sometimes enforces is larger than the cost of a symbol lookup: $ python -m timeit -s"def square(i): return i*i" -s"from itertools import imap" "sum(imap(square, xrange(3000)))" 100 loops, best of 3: 2.25 msec per loop $ python -m timeit "sum(i*i for i in xrange(3000))" 1000 loops, best of 3: 1.29 msec per loop Peter From johnjsal at NOSPAMgmail.com Mon May 8 09:44:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 13:44:08 GMT Subject: which is better, string concatentation or substitution? In-Reply-To: References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> Message-ID: Roy Smith wrote: > One may be marginally faster, but they both require copying the source > string, and are thus both O(n). Sorry, I'm not familiar with the O(n) notation. > If you're just doing one or a small fixed > number of these, it really doesn't matter. Pick whichever one you think is > easier to read. Thanks guys. I have a handful of methods that each do this task once per call, so I suppose this counts as not a lot, at least not at one time. And it seems like a good point that the real problem could be constantly concatenating with self.source, rather than the smaller pieces being put together. From rpdooling at gmail.com Mon May 8 07:57:50 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 8 May 2006 04:57:50 -0700 Subject: get Windows file type Message-ID: <1147089470.336984.173510@u72g2000cwu.googlegroups.com> Using Python on Windows XP, I am able to get almost all file and path info using os.path or stat, but I don't see a way to retrieve the file type? E.g. Microsoft Word file, HTML file, etc, the equivalent of what is listed in the "Type" column in the Windows Explorer box. Thanks, rick From meyer.p at gmail.com Wed May 17 13:57:15 2006 From: meyer.p at gmail.com (Pierre) Date: 17 May 2006 10:57:15 -0700 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> <9bKdnakiGs9Cy_bZRVn-qw@comcast.com> <1147885843.162424.133030@i40g2000cwc.googlegroups.com> Message-ID: <1147888635.546162.131270@j73g2000cwa.googlegroups.com> I'm using python 2.4.3. I removed the method __getattribute__ The mistake was my 3rd underscore :S sorry for wasting your time... The problem is solved ! Thx all ! PS: Richard youre message are displayed 3 times ?! From zlatko.matic1 at sb.t-com.hr Mon May 29 16:21:25 2006 From: zlatko.matic1 at sb.t-com.hr (tatamata) Date: Mon, 29 May 2006 22:21:25 +0200 Subject: starting some Python script from C# References: <1148728940.440692.166330@i39g2000cwa.googlegroups.com> <1148815194.860060.43810@j73g2000cwa.googlegroups.com> Message-ID: Hello. It seems that the following code works. And it seems that Process object can automatically run script by using python.exe, but only if standard output is not redirected... /* * Created by SharpDevelop. * User: Zlatko * Date: 28.5.2006 * Time: 9:38 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.IO; using System.Collections.Generic; using System.Diagnostics; using System.ComponentModel; using System.Windows.Forms; namespace CS_script { class MainClass { public static void Main(string[] args) { MyProcess myProcess = new MyProcess(); myProcess.ExecuteScript(); MessageBox.Show("Continue?","Application", MessageBoxButtons.OKCancel); } } public class MyProcess { // These are the Win32 error code for file not found or access denied. const int ERROR_FILE_NOT_FOUND =2; const int ERROR_ACCESS_DENIED = 5; /// /// Executes a python script. /// public void ExecuteScript() { Process myProcess = new Process(); try { // Get the path that stores the python script. //string myDocumentsPath =Environment.GetFolderPath(Environment.SpecialFolder.Personal); //If the script is placed in the same folder as C# executable, set the path to current directory: string myDocumentsPath=Environment.CurrentDirectory; //Set the fully qualified script name myProcess.StartInfo.FileName = myDocumentsPath + "\\my_script.py"; //Execute the script: myProcess.Start(); //string output = myProcess.StandardOutput.ReadToEnd(); //Console.WriteLine(output); //Console.WriteLine(myProcess.StandardOutput.ReadToEnd()); //TextReader t = myProcess.StandardOutput; //MessageBox.Show(t.ReadToEnd()); // Wait for it to die... myProcess.WaitForExit(); MessageBox.Show ("Python script is successfully executed!"); } catch (Win32Exception e) { if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND) { Console.WriteLine(e.Message + ". Check the path."); } else if (e.NativeErrorCode == ERROR_ACCESS_DENIED) { // Note that if your word processor might generate exceptions // such as this, which are handled first. Console.WriteLine(e.Message + ". You do not have permission to print this file."); } } } } } Greetings, Zlatko "Gerard Flanagan" je napisao u poruci interesnoj grupi:1148815194.860060.43810 at j73g2000cwa.googlegroups.com... >> "Gerard Flanagan" je napisao u poruci interesnoj >> grupi:1148728940.440692.166330 at i39g2000cwa.googlegroups.com... >> > tatamata wrote: >> >> Hello. >> >> >> >> How can I run some Python script within C# program? >> >> >> > >> > --------------------------------------------------------------------------------- >> > ProcessStartInfo startInfo; >> > Process process; >> > string directory; >> > string pyArgs; >> > string script; >> > >> > startInfo = new ProcessStartInfo("python"); >> > startInfo.WorkingDirectory = directory; >> > startInfo.Arguments = script + " " + pyArgs; >> > startInfo.UseShellExecute = false; >> > startInfo.CreateNoWindow = true; >> > startInfo.RedirectStandardOutput = true; >> > startInfo.RedirectStandardError = true; >> > >> > process = new Process(); >> > process.StartInfo = startInfo; >> > process.Start(); >> > >> > string s; >> > while ((s = process.StandardOutput.ReadLine()) != null) >> > { >> > //do something with s >> > } >> > --------------------------------------------------------------------------------- >> > > > tatamata wrote: >> Hello. I tried to implement ypour suggestion, but an error apears: >> "Exception System.ComponentModel.Win32Exception was thrown in debugee: >> The specified executable is not a valid Win32 application. >> >> namespace CS_script >> { >> class MainClass >> { >> public static void Main(string[] args) >> { >> >> System.Diagnostics.ProcessStartInfo psi =new >> System.Diagnostics.ProcessStartInfo(); >> psi.FileName="my_script.py"; >> psi.WorkingDirectory=Environment.CurrentDirectory; >> psi.RedirectStandardOutput = true; >> psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; >> psi.UseShellExecute = false; >> psi.CreateNoWindow = true; >> >> System.Diagnostics.Process script; >> script = System.Diagnostics.Process.Start(psi); >> >> System.IO.StreamReader myOutput = script.StandardOutput; >> script.WaitForExit(2000); >> if (script.HasExited) >> { >> string output = myOutput.ReadToEnd(); >> //this.processResults.Text = output; >> } >> MessageBox.Show("finished!"); >> } >> } >> } >> >> When running the program, I have the following error: >> >> "Exception System.ComponentModel.Win32Exception was thrown in debugee: >> The specified executable is not a valid Win32 application. >> >> StartWithCreateProcess() >> Start() >> Start() >> Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop >> Projects\CS_script\CS_script\Main.cs:32,5 " >> > > > I have no means of running C# programs at present and can't claim much > expertise in any case. A guess is that a "valid Win32 application" > means an '.exe' file, not a '.py' file. > > You are assuming that a Process object is as smart as the command > interpreter ('cmd.exe') and will know to use 'python.exe' for a file > with a 'py' extension? > > What happens if you use 'python.exe' (or 'cmd.exe') as your file and > the script name as argument as in the code I posted? > > Gerard > > > (PS. This group prefers that one doesn't top-post) > From jjl at pobox.com Tue May 2 22:06:22 2006 From: jjl at pobox.com (John J. Lee) Date: 03 May 2006 02:06:22 +0000 Subject: Python & SSL References: Message-ID: <87slnrrhep.fsf@pobox.com> James Stroud writes: > I have been trying to make an https client with python, but it seems What exactly do you mean by "make an https client"? > that, to do this, one needs to have the socket module compiled with ssl. > This is not the default. So I have a couple of questions. > > 1. Where do I specify to compile socket with ssl? I found no > obvious option in configure or setup.py or several other > files I checked. What OS are you on? > 2. Is there a way to do this without re-compiling all of python? Are you sure it's NOT compiled in? But, if it's not compiled, it's not compiled. > Also, I have done numerous combinations of searches with ssl, https, & > python as terms, but I haven't found a page outlining the steps to make > a certificate and key that python understands. Has anyone been > successful at this? Did you use openssl? I want to make sure I am doing > this part correctly. Since you say "make a certificate", and mention "https client", it sounds like you want to authenticate yourself to an HTTP server using an SSL certificate? If so, I don't believe the issue Benji raised is relevant (that issue is relevant for fetching HTTPS URLs rather than authenticating yourself to a server using an SSL certificate, I think). urllib claims to have support for this in the form of the key_file and cert_file arguments to Urlopener constructor (UNTESTED): import urllib opener = urllib.URLopener(key_file="/path/to/my_key_file", cert_file="/path/to/my_cert_file") response = opener.open(url) I can't claim to know that it actually works, though... John From duane at franz.com Fri May 12 16:05:54 2006 From: duane at franz.com (Duane Rettig) Date: Fri, 12 May 2006 13:05:54 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Alexander Schmolck writes: > Ken Tilton writes: > >> In Common Lisp we would have: >> >> (defvar *x*) ;; makes it special >> (setf *x* 1) >> (print *x*) ;;-> 1 >> (let ((*x* 2)) >> (print *x*)) ;; -> 2 >> (print *x*) ;; -> 1 > > You seem to think that conflating special variable binding and lexical > variable binding is a feature and not a bug. What's your rationale? A bug is a non-conformance to spec. Kenny's statement was specifically about Common Lisp, which has a spec. Now, what was your rationale for it _being_ a bug? -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From john at castleamber.com Sun May 21 00:22:18 2006 From: john at castleamber.com (John Bokma) Date: 21 May 2006 04:22:18 GMT Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> <1148172321.824018.207540@j33g2000cwa.googlegroups.com> Message-ID: "George Sakkis" wrote: > John Bokma wrote: > >> "George Sakkis" wrote: >> >> > Not trying to be as ass, but can you take this offline or at least in >> > a perl newsgroup ? Arguing on a particular fact or speculation about >> > the perl community is rather unproductive and offtopic for a python >> > newsgroup. >> >> Use a real Usenet client, and you can make it skip a thread. > > That's funny, coming from the same guy that's been harassing Xah for OT > posts. Oh, the irony. Xah was harassing 5 groups with a cross post without setting a follow-up to for the sole purpose of spamvertizing his website [1] repeatedly. If you are that clueless, don't post. [1] He is looking for another hoster btw. -- 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 johnjsal at NOSPAMgmail.com Mon May 15 14:15:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 18:15:39 GMT Subject: do/while structure needed In-Reply-To: References: <4466bddd$0$18984$c3e8da3@news.astraweb.com><1147585422.693953.292480@u72g2000cwu.googlegroups.com> <4467786c$0$1956$c3e8da3@news.astraweb.com> Message-ID: Terry Reedy wrote: > "John Salerno" wrote in message > news:4467786c$0$1956$c3e8da3 at news.astraweb.com... >> Thanks, that looks pretty good. Although I have to say, a do/while >> structure is the much more obvious way. I wonder why it hasn't been >> added to the language. > > Been suggested many times, been considered, and rejected. Easily similated > with while True: ... if exit_condition: break which also solves 'loop and a > half' problem, which is more common. Requires new keyword for little gain. > Etc. I know, I remember a discussion about it a while back. But IMO, at least, a do/while structure seems much cleaner and more readable than a while loop with an embedded if and break statement. From gjzusenet at gmail.com Tue May 9 06:10:40 2006 From: gjzusenet at gmail.com (gjzusenet at gmail.com) Date: 9 May 2006 03:10:40 -0700 Subject: wxPython IEHtmlWindow mystery - dependencies? Message-ID: <1147169440.096433.288670@u72g2000cwu.googlegroups.com> Hi I've been using an IEHtmlWindow in my script with no problems, but it seems that for people with a clean installation of XP SP2 it fails like such: Traceback (most recent call last): File "htmlloader.py", line 509, in load File "PythonCard\model.pyo", line 340, in __init__ File "PythonCard\resource.pyo", line 86, in __init__ File "PythonCard\resource.pyo", line 91, in __init__ File "PythonCard\resource.pyo", line 91, in __init__ File "PythonCard\resource.pyo", line 96, in __init__ File "PythonCard\resource.pyo", line 139, in enforceSpec File "PythonCard\resource.pyo", line 30, in loadComponentModule ImportError: cannot import module 'iehtmlwindow As soon as a simple session of windowsupdate is run (with just the hotfixes etc.) the problem seems to disappear. So,do you know which update exactly is needed to prevent the error, and why does it happen in the first place anyway? Any ideas? Thanks ~G From scott.daniels at acm.org Wed May 3 13:29:46 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 03 May 2006 10:29:46 -0700 Subject: Anaglyph 3D Stereo Imaging with PIL and numpy In-Reply-To: <4bqgraF121v26U1@news.dfncis.de> References: <4bqgraF121v26U1@news.dfncis.de> Message-ID: <4458e4f6$1@nntp0.pdx.net> David Murmann wrote: > i just found some colored glass and experimented a bit with > these red/green 3d images, so i thought i'd share this simple > script i wrote to generate such images with anyone whos > interested. i also wouldn't mind some comments on the code. Check out VPython -- there you can build 3-D models and display them in real time while viewing with your glasses. See: http://www.vpython.org/FAQ.html --Scott David Daniels scott.daniels at acm.org From tjreedy at udel.edu Tue May 9 14:30:18 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 May 2006 14:30:18 -0400 Subject: clear memory? how? References: <4cb49uF15811rU1@uni-berlin.de> Message-ID: "Diez B. Roggisch" wrote in message news:4cb49uF15811rU1 at uni-berlin.de... > You don't - python does it for you. It is called garbage collection. All > you > have to to is get into granny-mode(tm): forget about things. In general, especially for beginners, this is good advice. Forget about memory management until one actually runs into a problems. >That means: once an object is not referenced by your code anymore, > it will be cleaned up. The language spec only says that it *may* be cleaned up. Even with CPython, it will not be immediately deleted if caught in a circular reference loop with other objects no longer referenced by the code. One may then want to explicitly invoke the circular ref garbage collector. And read the gc module docs for details. > For example: >>>> l = range(100000) >>>> del l > will make python garbage collect the list referred to by l. No, it only *allows* the interpreter to gc the list and (most of - depending on the implementation) the ints in the list. When, if ever, is implementation dependent. Even with CPython, ranges much larger than that are better done as xranges unless the explicit all-at-once list is really needed. > Generally speaking: don't worry. Terry Jan Reedy From tjreedy at udel.edu Tue May 30 17:28:04 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 30 May 2006 17:28:04 -0400 Subject: Strange behavior with iterables - is this a bug? References: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> Message-ID: wrote in message news:1149019886.693900.126850 at u72g2000cwu.googlegroups.com... > Ok, I am confused about this one. I'm not sure if it's a bug or a > feature.. but > >>>> ================================ RESTART >>>> f1 = open('word1.txt') >>>> f2 = open('word2.txt') >>>> f3 = open('word3.txt') >>>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in f1 for i2 in f2 >>>> for i3 in f3] > [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')] A file is something like an iterator and something like an iterable. At this point, the internal cursur for f3 points at EOF. To reiterate thru the file, you must rewind in the inner loops. So try (untest by me) def initf(fil): f.seek(0) return f and ...for i2 in initf(f2) for i3 in initf(f3) >>>> l1 = ['a\n','b\n','c\n'] >>>> l2 = ['a\n','b\n','c\n'] >>>> >>>> l3 = ['a\n','b\n','c\n'] >>>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 >>>> for i3 in l3] > [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), > ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), > ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), > ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), > ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), > ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), > ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')] > > explanation of code: the files word1.txt, word2.txt and word3.txt are > all identical conataining the letters a,b and c one letter per line. > The lists I've added the "\n" so that the lists are identical to what > is returned by the file objects. Just eliminating any possible > differences. But lists are not file objects and you did not eliminate the crucial difference in reiterability. Try your experiment with StringIO objects, which are more nearly identical to file objects. Terry Jan Reedy From kentilton at gmail.com Mon May 8 16:55:22 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 08 May 2006 16:55:22 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: References: <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> Message-ID: Thomas F. Burdick wrote: > Ken Tilton writes: > > >>No, you do not want on-change handlers propagating data to other >>slots, though that is a sound albeit primitive way of improving >>self-consistency of data in big apps. The productivity win with >>VisiCalc was that one simply writes rules that use other cells, and >>the system keeps track of what to update as any cell changes for >>you. You have that exactly backwards: every slot has to know what >>other slots to update. Ick. > > > No no, that's fine and the way it should be: when you change a slot, > it should know who to update. And that's also the way it works in > Cells. The trick is that Cells takes care of that part for you: all > the *programmer* has to care about is what values a slot depends on -- > Cells takes care of inverting that for you, which is important because > that's a job that a computer is much better at than a human. Well, as long as we are being precise, an important distinction is being obscured here: I was objecting to a slot "knowing" who to update thanks to having been hardcoded to update certain other slots. When you say "Cells takes care of that", it is important to note that it does so dynamically at runtime based on actual usage of one slot by the rule for another slot. kt -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From bill.pursell at gmail.com Tue May 23 14:29:19 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 23 May 2006 11:29:19 -0700 Subject: Guide to using python for bash-style scripting In-Reply-To: <1148405325.101047.181370@j73g2000cwa.googlegroups.com> References: <1148405239.840908.120910@j33g2000cwa.googlegroups.com> <1148405325.101047.181370@j73g2000cwa.googlegroups.com> Message-ID: <1148408959.230231.142460@i39g2000cwa.googlegroups.com> 4zumanga wrote: > Yes, there is a stupid mistake in that script, last line should be: > > diff new_out1 new_out2 > > However, this is hopefully not important, what is important is the > general kind of (very simple) things I'm trying to do. I have been hoping for a good solution to this. An easy way to handle simple commands is: #!/usr/bin/env python import os s = "echo foo | sed 's/foo/gap/' > file\n" s += "wc -c file\n" s += "cat file\n" print s, "***" os.system(s) ######## end (Apologies for the lameness of the commands above). However, I have some bash scripts that rely on things like PIPESTATUS, and I have no idea how to emulate that behavior easily. How can one most easily emulate a simple pipe as readily as in bash? I've seen a few recipes for doing something like that, but I haven't yet seen one that i really like. Is it possible to execute: os.system( " a | b | c | d | e") and retrieve the value of PIPESTATUS? From cvanarsdall at mvista.com Fri May 5 21:50:45 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 05 May 2006 18:50:45 -0700 Subject: how to construct a binary-tree using python? In-Reply-To: <1146879397.871842.183790@u72g2000cwu.googlegroups.com> References: <1146879397.871842.183790@u72g2000cwu.googlegroups.com> Message-ID: <445C00F5.3040604@mvista.com> hankssong wrote: > Hi everyone, I'm wondering whether it's possible to construct a > binary-tree using python. > Since python don't have pointer, it can't dynamically allocate memory > like C language. > But some important data structures like linked list, binary-tree and > hash table are closely linked with dynamic memory technology. > > Its actually very possible to construct a binary tree in python. If you do some googles searches you'll, in fact find, some implementations. Its important to remember that python can dynamically make objects on the fly. Objects are created as references and so you can make tree nodes whenever you want to Here are some snippets, I'm not the most advanced coder but its just to show you that it can be done. I wouldn't use this code verbatim, its taylored to a project I was doing at the time, but I hope this helps you get an idea. class TreeNode: def __init__(self, nodeData): self.left = None self.right = None [snip - stuff for my project] class Tree: def __init__(self): self.root = None #assigns the data to a new TreeNode def addNode(self, inputData): return TreeNode(inputData) #insert is recursive, so when it reaches its ending point this is called #this function traverses the tree and finds the spot to add the node def insertNode(self, inputData, root): def insertNode(self, inputData, root): if inputData.buildTag <= root.bTag: if root.left == None: root.left = self.addNode(inputData) #left is empty? add else: self.insertNode(inputData, root.left) #visit the left subtree else: if root.right == None: root.right = self.addNode(inputData) else: self.insertNode(inputData, root.right) return #root def findNode(self, nodeToFind, root): #nodeToFind is just a buildTag string if root == None: return None else: #btag is something i needed for what I was doing, ignore it #print "Comparing " + nodeToFind + " and " + root.bTag if nodeToFind == root.bTag: return root elif nodeToFind < root.bTag: return( self.findNode(nodeToFind, root.left) ) else: return( self.findNode(nodeToFind, root.right) ) -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From david.nospam.hopwood at blueyonder.co.uk Fri May 5 22:28:12 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Sat, 06 May 2006 02:28:12 GMT Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <6OS6g.78$Ey5.74@fe12.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> Message-ID: <0RT6g.83274$tc.10279@fe2.news.blueyonder.co.uk> Ken Tilton wrote: > [...] The upshot of what [Guido] wrote is that it would be really hard to make > semantically meaningful indentation work with lambda. Haskell manages it. -- David Hopwood From blair.bethwaite at gmail.com Tue May 9 00:24:04 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 8 May 2006 21:24:04 -0700 Subject: Enumerating Regular Expressions In-Reply-To: References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> Message-ID: <1147148644.762057.238640@v46g2000cwv.googlegroups.com> James Stroud wrote: > You mean like re.compile(r'.*') ? No. I mean like: >>> regex = re.compile(r'a|b') >>> regex.enumerate() a b >>> From pydecker at gmail.com Wed May 17 09:39:31 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 17 May 2006 09:39:31 -0400 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: On 5/17/06, Andy Sy wrote: > If tabs are easily misunderstood, then they are a MISfeature > and they need to be removed. I don't seem to understand your point in acting as a dictator. Therefore, you are a MISfeature and need to be removed. -- # p.d. From tbrkic at yahoo.com Fri May 12 06:28:09 2006 From: tbrkic at yahoo.com (glomde) Date: 12 May 2006 03:28:09 -0700 Subject: compiling module from string and put into namespace Message-ID: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> Hi, I want to create a function that preprocesses a file and then imports the parsed file. What I found out is that you can do something like this: def ImportFile(fileName): parsedCode = Parser(fileName).Parse() module = new.module(name) exec parsedCode in module.__dict__ sys.modules[name] = module import name But this works only if the ImportFile isnt loaded from a module. Since the import is local. So this wouldnt work: from XXX import ImportFile ImportFile(fileName) fileName.Function() Since the import in ImportFile isnt visible the module that calls it. So how do I do so that the import is visible from callers namespace? Best regards, T From grbridgeREMOVETHIS at btinternet.com Tue May 2 20:53:41 2006 From: grbridgeREMOVETHIS at btinternet.com (Gordon Rainsford) Date: Wed, 3 May 2006 01:53:41 +0100 Subject: recognize a drive as removable media (e.g. compact flash, sd card or usb drive) References: <1144523029.468368.114100@z34g2000cwc.googlegroups.com> Message-ID: <1heqnwc.1f9zrcdvxbybcN%grbridgeREMOVETHIS@btinternet.com> Tim Golden wrote: > Mike Joyce wrote: > > I am trying to write a portable script that will find removable media, > > such as compact flash, sd card, usb, etc. drive and then upload files > > from the media. I want this to be portable so that I can write and > > maintain one program for both Linux and Windows. Each platform uses > > different functions so even if I could find two platform dependent > > functions that would be fine. Basically, I would like to avoid checking > > fixed disks if possible. > > If anyone know of a good way to do this please let me know. Thanks in > > advance for any help. > > Under Windows, you can probably use WMI for this, depending on > exactly what it is you're trying to do. If I read you right, you want > to > scan all devices, determine the removable ones, and then read stuff > off them. Any suggestions as to doing this on a Mac? -- Gordon Rainsford From esj at harvee.org Fri May 5 08:45:59 2006 From: esj at harvee.org (Eric S. Johansson) Date: Fri, 05 May 2006 08:45:59 -0400 Subject: Progamming python without a keyboard In-Reply-To: References: Message-ID: <445B4907.6010101@harvee.org> Rony Steelandt wrote: > http://www.newscientisttech.com/article/dn9066 > > To nice to be true ? its early technology. It's difficult to install and it definitely need some extra horsepower because the two people developing it are also disabled (like me). The only thing I've done to support the project is host two workshops on speech driven programming and let Alain stay in our guest bedroom. As I said on another mailing list, this kind of technology is incredibly important. Depending on whose numbers you use, there are somewhere between 50,000 and 80,000 developers injured every year, most of them permanently. Those these people just leave the field because there are little or no tools to support them. Helping out on this project and making it easier to use and install may mean the difference between living a disability and earning a paycheck for a sizable number of people. I must say however that Python is one of the friendlier languages when programming by unassisted speech recognition. That is as long as you keep your symbols ordinary English words and don't try to control capitalization. The easiest symbols are_like_this the hardest are CapitalizeWithoutSpaces (six misrecognition errors generating that last bit. one is still left uncorrected) So if you want to make a serious difference in people's lives from your keyboard, you can help out in two ways. The first is helping Alain and david in the voice coder project. Second is working with probably myself and a couple of other folks in gnome at-spi land building a bridge between speech recognition on Windows and complete control of the environment on Linux. As I said above and I'm not exaggerating, this kind of assistance makes a serious, quantifiable difference in the life of people with upper extremity disabilities. I hope people can help. --- eric From alikakakhel at yahoo.com Wed May 31 00:53:32 2006 From: alikakakhel at yahoo.com (greenflame) Date: 30 May 2006 21:53:32 -0700 Subject: shuffling elements of a list In-Reply-To: References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <1149051212.139046.155340@c74g2000cwc.googlegroups.com> Thank you all for all of your help. Also I got the shuffle function to work. Do not worry I will be back soon with more shuffling! However, I do not quite understand this DSU that you mention, although it looks useful. From antroy at gmail.com Mon May 15 04:13:49 2006 From: antroy at gmail.com (Ant) Date: 15 May 2006 01:13:49 -0700 Subject: any plans to make pprint() a builtin? In-Reply-To: <446735ea$1_1@newspeer2.tds.net> References: <44669e46$0$5337$c3e8da3@news.astraweb.com> <446735ea$1_1@newspeer2.tds.net> Message-ID: <1147680829.246867.161640@i40g2000cwc.googlegroups.com> Considering that the current: import pprint pprint.pprint(x) is hardly lengthy, I can't see how either of the alternatives proposed are any better. > python.pprint.pprint(x) 6 characters shorter, but considerably more keystrokes if you are using pprint more than once. Is it worth adding the 'python' builtin to save an import statement? > import py > py.std.pprint.pprint(x) Longer, messy, and what's the actual point? Wouldn't: import pprint as pp pp.pprint(x) be better, standard *and* shorter? From gherron at islandtraining.com Fri May 19 02:31:42 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 18 May 2006 23:31:42 -0700 Subject: who can give me the detailed introduction of re modle? In-Reply-To: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: <446D664E.4000702@islandtraining.com> softwindow wrote: >the re module is too large and difficult to study > >i need a detaild introduction. > > > That's not the kind of question that's likely to get a useful response from an all volunteer newsgroup community, even one with as friendly a reputations as this one. Here's my suggestion: Read the manual page at http://docs.python.org/lib/module-re.html, then try to apply it to a specific problem you'd like to solve with regular expressions. Any problems you run into at that point will be quite specific. If you list the problem you tried to solve, your solution attempt, and what failed, you will likely get lots of useful answers here. But you have to take the first step. P.S. The re module is really not all *that* difficult. Gary Herron From bignose+hates-spam at benfinney.id.au Tue May 16 00:44:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 May 2006 14:44:20 +1000 Subject: Multiple inheritance : waht does this error mean ? References: <1147750957.673439.154420@g10g2000cwb.googlegroups.com> Message-ID: <87d5eer32z.fsf@benfinney.id.au> jnair at ensim.com writes: > >>>class K(object,list): > ...: pass > ...: > ------------------------------------------------------------ > Traceback (most recent call last): > File "", line 1, in ? > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases object, list The class 'object' is already the base class of 'list', and of every other basic type. Python is saying that you need to decide what you want; inheritance from 'object', or inheritance from something that already inherits from 'object'. -- \ "People come up to me and say, 'Emo, do people really come up | `\ to you?'" -- Emo Philips | _o__) | Ben Finney From a_salnikov at yahoo.com Mon May 22 15:24:29 2006 From: a_salnikov at yahoo.com (Andy Salnikov) Date: Mon, 22 May 2006 12:24:29 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 22) References: Message-ID: "Peter Otten" wrote in message news:e4sma5$msm$1 at lairds.us... > QOTW: "It's hard to make a mistake by having too many short and simple > functions. And much too easy to make them when you have too few ;-)" > - Thomas Bartkus > And of course there is a mathematical proof of that provided somewhere, isn't it? :) "Too many" is always opposite to "hard to make a mistake", at least in my mind. Andy. From johnjsal at NOSPAMgmail.com Wed May 31 15:48:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 31 May 2006 19:48:30 GMT Subject: using import * with GUIs? In-Reply-To: <1149104134.583234.36020@i39g2000cwa.googlegroups.com> References: <1149104134.583234.36020@i39g2000cwa.googlegroups.com> Message-ID: akameswaran at gmail.com wrote: > Personally I prefer explicit to implicit, and typing wx. is not really > that much to type is it? No, but typing "Tkinter." is! ;) From gherron at islandtraining.com Fri May 19 01:44:11 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 18 May 2006 22:44:11 -0700 Subject: import woe In-Reply-To: <1148016083.020020.40660@u72g2000cwu.googlegroups.com> References: <1148016083.020020.40660@u72g2000cwu.googlegroups.com> Message-ID: <446D5B2B.3000102@islandtraining.com> gsocks at gmail.com wrote: >hello, > >i have a problem. i would like to import python files above and below >my current directory. > >i'm working on /home/foo/bar/jar.py > >i would like to import /home/foo/car.py and > /home/foo/bar/far.py > >how can i do this? > >thank you, >bob > >ps: i want to scale, so i do not want to edit the python path > > > Work out the path name for the directory from which you'd like to import, and append it to sys.path: import sys sys.path.append('..') sys.path.append('whatever/path/absolute/or/relative') Then off you go importing as you wish. From timr at probo.com Wed May 17 02:12:29 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 17 May 2006 06:12:29 GMT Subject: A Unicode problem -HELP References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <1147839615.973950.54770@y43g2000cwc.googlegroups.com> Message-ID: "manstey" wrote: > >I have done more reading on unicode and then tried my code in IDLE >rather than WING IDE, and discovered that it works fine in IDLE, so I >think WING has a problem with unicode. Rather, its output defaults to ASCII. >So, assuming I now work in IDLE, all I want help with is how to read in >an ascii string and convert its letters to various unicode values and >save the resulting 'string' to a utf-8 text file. Is this clear? > >so in pseudo code >1. F is converted to \u0254, $ is converted to \u0283, C is converted >to \u02A6\02C1, etc. >(i want to do this using a dictionary TRANSLATE={'F':u'\u0254', etc) >2. I read in a file with lines like: >F$ >FCF$ >$$C$ etc >3. I convert this to >\u0254\u0283 >\u0254\u02A6\02C1\u0254 etc >4. i save the results in a new file > >when i read the new file in a unicode editor (EmEditor), i don't see >\u0254\u02A6\02C1\u0254, but I see the actual characters (open o, esh, >ts digraph, modified letter reversed glottal stop, etc. Of course. Isn't that exactly what you wanted? The Python string u"\u0254" contains one character (Latin small open o). It does NOT contain 6 characters. If you write that to a file, that file will contain 1 character -- 2 bytes. If you actually want the 6-character string \u0254 written to a file, then you need to escape the \u special code: "\\u0254". However, I don't see what good that would do you. The \u escape is a Python source code thing. >I'm sure this is straightforward but I can't get it to work. I think it is working exactly as you want. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From jack at performancedrivers.com Tue May 16 11:37:44 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Tue, 16 May 2006 11:37:44 -0400 Subject: Google-API Bad-Gateway-Error In-Reply-To: References: <1147783046.944898.43470@i39g2000cwa.googlegroups.com> <1147784189.292674.145010@i39g2000cwa.googlegroups.com> Message-ID: <20060516153744.GJ5767@performancedrivers.com> On Tue, May 16, 2006 at 01:24:25PM +0000, John Bokma wrote: > DierkErdmann at mail.com wrote: > > > It's quite strange, after calling the script several times it started > > to work; but sometimes the error occurs again. Maybe google has > > technical probs. > > Yup, I've seen exactly the same behavoir. So now I do several retry - > sleep - retry steps before giving up. Yup, me too. retries = 0 while (retries < 5): try: gpage = google.doGoogleSearch(keyword, start=start) break except: retries += 1 time.sleep(30) else: raise # chronic failure, reraise the last error The job runs nightly at O'Dark thirty. I get one chronic failure every few months. -Jack From me+python at modelnine.org Sun May 14 16:33:37 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 14 May 2006 22:33:37 +0200 Subject: Converting String to int In-Reply-To: <200605142123.52846.ognjen@mailshack.com> References: <44678C99.5020003@tim.thechases.com> <200605142123.52846.ognjen@mailshack.com> Message-ID: <200605142233.37897.me+python@modelnine.org> Am Sonntag 14 Mai 2006 22:23 schrieb Ognjen Bezanov: > mynums = "423.523.674.324.342.122.943.421.762.158.830" > > mynumArray = string.split(mynums,".") This is the old way of using string functions using the module string. You should only write this as: mynumArray = mynums.split(".") (using the string methods of string objects directly) > x = 0 > for nums in mynumArray: This is misleading. Rename the variable to num, as it only contains a single number. > if nums.isalnum() == true: .isalnum() checks whether the string consists of _alpha_-numeric characters only. So, in this case, it may contain letters, among digits. .isdigit() checks whether it is a (base <= 10) number. > x = x + int(nums) > else: > print "Error, element contains some non-numeric characters" As you don't know what the offending element is, insert a: print nums here. > break If you change the code as noted above, it works fine for me. --- Heiko. From kkylheku at gmail.com Thu May 11 13:57:52 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 11 May 2006 10:57:52 -0700 Subject: Multi-line lambda proposal. In-Reply-To: References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <1147366331.637492.129980@i39g2000cwa.googlegroups.com> Message-ID: <1147370272.511444.160810@v46g2000cwv.googlegroups.com> Terry Reedy wrote: > So name it err_inner. Or _err. Right. The C language approach to namespaces. From jarrod.roberson at gmail.com Tue May 2 16:43:58 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 2 May 2006 13:43:58 -0700 Subject: What is wrong with the Python home page? Message-ID: <1146602638.824774.264180@j33g2000cwa.googlegroups.com> I am using FireFox 1.5.2 on OS X 10.4.6 and the www.python.org ends up being only text with just the nasa picture with the guy in the space suit. It looks like the CSS is hosed or something. And trying to go to the module docs for the current release is broken as well From simon at brunningonline.net Mon May 22 10:08:09 2006 From: simon at brunningonline.net (Simon Brunning) Date: Mon, 22 May 2006 15:08:09 +0100 Subject: about py2exe, I installed it, but can't find py2exe.exe in my computer. In-Reply-To: <1148298814.490374.115070@j33g2000cwa.googlegroups.com> References: <1148045399.833782.106910@g10g2000cwb.googlegroups.com> <1148298814.490374.115070@j33g2000cwa.googlegroups.com> Message-ID: <8c7f10c60605220708x21231a43x3642248d0a165be5@mail.gmail.com> On 22 May 2006 04:53:34 -0700, python wrote: > it prompt: invalid command 'py2exe'. > I have import py2exe in setup.py file. Can you show us your setup.py file, the exact command that you typed, and the exact error message that you are getting? -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From __peter__ at web.de Mon May 15 10:54:07 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 May 2006 16:54:07 +0200 Subject: keyword help in Pythonwin interpreter References: <1147702380.665861.106540@g10g2000cwb.googlegroups.com> Message-ID: BartlebyScrivener wrote: > Using ActivePython 2.4.3 on Windows XP > > While in the Pythonwin IDE, if I seek keyword help by issuing the > following command: > >>>>help ('while') > > I get: > > Sorry, topic and keyword documentation is not available because the > Python HTML documentation files could not be found. If you have > installed them, please set the environment variable PYTHONDOCS to > indicate their location. > > My PYTHONDOCS variable is set to: > > c:\python24\Doc\Python-Docs-2.4.2\ref > > which appears to be correct (ie the help html files are installed > there). > > Searching this group, I found someone else complaining about the same > behavior with no clear resolution. > > http://tinyurl.com/pblev > > Any advice? Check if http://groups.google.com/group/comp.lang.python/msg/991f1d19a36b8dda applies. Peter From maric at aristote.info Tue May 23 12:18:45 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 23 May 2006 18:18:45 +0200 Subject: Use of lambda functions in OOP, any alternative? In-Reply-To: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> References: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> Message-ID: <200605231818.46426.maric@aristote.info> Le Mardi 23 Mai 2006 15:55, Pablo a ?crit?: > Question: Isn't there an *alternative* way to do it without the lambda > function? No, it's good, why shouldn't you use a lambda function ? Note you can do something like this : class _virtualgetter : def __init__(self, name) : self._n =name def _call__(self, vself) : return getattr(vself, 'get' + self._n)() def vprop(name) : return property(fget=_virtualgetter(name)) #anywhere from ... import vprop class Base(object): def __init__(self, attr): self._attr = attr def getAttribute(self): return self._attr attr = vprop('Attribute') class Derived(Base): def getAttribute(self): return 2*self._attr -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From tdw at tdw.net Sat May 6 09:15:13 2006 From: tdw at tdw.net (Tim Williams) Date: Sat, 6 May 2006 14:15:13 +0100 Subject: Replace In-Reply-To: References: Message-ID: <9afea2ac0605060615s668c434fo368a3cb18219cc6@mail.gmail.com> On 06/05/06, Eric wrote: > I have a string... > > str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" > > I want to replace the characters after each '=', what I ended up doing is > somthing like this... > > buf = list(str) > newchr = '#' > > count = 0 > for i in range(len(buf)): > if buf[count] == '=': > buf[count + 1] = newchr > count = count + 1 > else: > count = count + 1 > > newstr = ''.join(buf) > > Is there a better, faster way of doing it? Using somthing like > str.index() dosn't work because... > After you find an '=' you are updating the next chr in the list to '#' then testing the '#' to see if it is an '=' . This would be quicker as it bypasses testing your self-added '#' , and also removes a " count +1" #Untested buf = list(str) newchr = '#' count = 0 for i in range(len(buf)): if buf[count] == '=': count = count + 1 buf[count] = newchr count = count + 1 I might have done something like this (using s instead of str) #untested >>> buf = list(s) >>> newstr = '' >>> while buf: ... newstr += buf.pop(0) # get the first item in buf and append it to newstr ... if new[-1] == '=': ... newstr += '#' ... buf.pop(0) # discard the next item in buf HTH :) From bdesth.quelquechose at free.quelquepart.fr Fri May 5 19:21:05 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 May 2006 01:21:05 +0200 Subject: Is this a good use of __metaclass__? In-Reply-To: References: Message-ID: <445baf1a$0$2386$626a54ce@news.free.fr> Joel Hedlund a ?crit : > Hi! > > I need some input on my use of metaclasses since I'm not sure I'm using > them in a pythonic and graceful manner. I'm very grateful for any tips, > pointers and RTFMs I can get from you guys. > > Below, you'll find some background info and an executable code example. > > In the code example I have two ways of doing the same thing. The problem > is that the "Neat" version doesn't work, and the "Ugly" version that > works gives me the creeps. > > The "Neat" version raises a TypeError when I try the multiple > inheritance (marked with comment in the code): > > Traceback (most recent call last): > File "/bioinfo/yohell/pybox/gridjs/gridjs-2.0/test.py", line 132, in ? > class FullAPI(JobAPI, UserAPI, AdminAPI): > File "/bioinfo/yohell/pybox/gridjs/gridjs-2.0/test.py", line 43, in > __new__ > return type.__new__(cls,classname,bases,classdict) > TypeError: Error when calling the metaclass bases > metaclass conflict: the metaclass of a derived class must be a > (non-strict) subclass of the metaclasses of all its bases http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197 > In the "Ugly" version, I'm changing the metaclass in the global scope > between class definitions, Yuck. > and that gives me bad vibes. > > What should I do? Is there a way to fix my "Neat" solution? Is my "Ugly" > solution in fact not so horrid as I think it is? Or should I rethink the > whole idea? Or maybe stick with decorating manually (or in > BaseAPI.__init__)? I'd go for 'manually decorating' anyway. Metaclasses can be really handy for framework-like stuff, but for the use case you describe, I think the explicit decorator option is much more, well, explicit - and also more flexible - than metaclass black magic. This may also help you distinguish 'published' API from implementation (which is what CherryPy do). And finally, this may let you organize your code more freely - you can mix methods needing different decorators in a same class. Also, and FWIW, you may want to favor composition-delegation (which is a piece of cake in Python, see below...) over inheritance. This is more flexible. You would then have a 'server' class that just provides common services and dispatch to specialized objects. class Dispatcher(object): def __init__(self, delegates): self._delegates = delegates def __getattr__(self, name): for delegate in self._delegates: try: return getattr(delegate, name): except AttributeError: pass else: err = "object '%s' has no attribute '%s'" \ % (self.__class__.__name__, name) raise AttributeError(err) # note that you may want to reorganize your code differently # if you go for explicit decorators d = Dispatcher(JobApi, UserApi, AdminApi) My 2 cents... From iainking at gmail.com Fri May 26 11:00:12 2006 From: iainking at gmail.com (Iain King) Date: 26 May 2006 08:00:12 -0700 Subject: Trying to get FreeImagePy to work. In-Reply-To: <7fEdg.13375$cX1.201311@twister2.libero.it> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> <7fEdg.13375$cX1.201311@twister2.libero.it> Message-ID: <1148655611.990937.322350@j73g2000cwa.googlegroups.com> Michele Petrazzo wrote: > Iain King wrote: > > I've installed ctypes and FreeImagePy. When I do this: > > > >>>> import FreeImagePy f = FreeImagePy.Image() > > > > I put a 'print self._name' in the ctypes __init__ file, just before > > line 296 - it's printing out the 'find' just before the error. So, in > > what specific way have I screwed up the install? > > What's your ctypes version? Is 0.9.9.6? If yes, can you download the > last svn version, that solve that problem (I hope) and add some > functions? If you can't I'll release a new version (1.2.5) > I downloaded and installed 0.9.9.3, and it now works. Thanks! Iain From petr at tpc.cz Tue May 2 12:38:08 2006 From: petr at tpc.cz (Petr Jakes) Date: 2 May 2006 09:38:08 -0700 Subject: milliseconds are not stored in the timestamp KInterbasDB + Firebird Message-ID: <1146587888.770947.162440@v46g2000cwv.googlegroups.com> I am trying to insert "timestamp" to the Firebird database using standard library datetime module example given in the "KInterbasDB Usage Guide" http://tinyurl.com/mplo4 , section "Example Programs DATE/TIME/TIMESTAMP" Even timestamp has the correct format before inserting to the database (2006-26-2 17:25:34.940279 for example), milliseconds are not stored and the database returns (2006,26,2,17,25,34). I have made some Googling the whole afternoon to find if it is possible to configure Firebird or KInterbasDB, but no success. My environment: Fedora Core4, Firebird CS 1.5, Python 2.4.1, KInterbasDB 3.2b1 Thanks for your advices. Petr Jakes From andrew.arobert at gmail.com Mon May 22 10:27:09 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 22 May 2006 10:27:09 -0400 Subject: Testing for file type Message-ID: <1273iims70cu3e6@corp.supernews.com> Hi Everyone, Is there a way to test if a file is binary or ascii within Python? I'd prefer not to text against file extension. Any help you can provide would be greatly appreciated. Thanks, Andy From linuxnow at gmail.com Sun May 7 19:21:01 2006 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: 7 May 2006 16:21:01 -0700 Subject: why _import__ only works from interactive interpreter? In-Reply-To: <1147043686.558715.124540@j73g2000cwa.googlegroups.com> References: <1147041996.232232.165820@i39g2000cwa.googlegroups.com> <1147043686.558715.124540@j73g2000cwa.googlegroups.com> Message-ID: <1147044060.998898.140740@i40g2000cwc.googlegroups.com> It's not that, it looks like __import__looks into sys.path, so if use an absolute path it cannot work. I found this thread and it seems they are right: http://groups.google.com/group/comp.lang.python/browse_thread/thread/6eed0025488bf130/637790b4ed62771b?lnk=st&q=__import__+ImportError+interpreter&rnum=1#637790b4ed62771b So, if this is right, I need to put the .py file to be imported inside sys.path!! And the relative path will be usedto find the module. Can I __import__ providing the absolute path? Thanks Pau From john at castleamber.com Wed May 17 17:59:48 2006 From: john at castleamber.com (John Bokma) Date: 17 May 2006 21:59:48 GMT Subject: python vs perl lines of code References: Message-ID: Edward Elliott wrote: > John Bokma wrote: > >> Edward Elliott wrote: >>> Evaluating my experiences yes, relating your own no. >> >> What would the point be? Most important to me would be: am I happy >> with the result? And that rarely has to do with the number of lines >> of actual code or the programming language. A language is just a >> tool. > > The point is knowing how to pick the right tool for the right job. True, and I don't think that the number of lines is going to be a good guideline. > Anecdotes aren't the answer but they can be the beginning of the > question. Besides, whatever happened to pursuing knowledge for its own > sake? Sure, but research without being able to peer review the set up is a bit difficult. If you want an anecdote: three years ago my Perl coding was different from now, and I am sure that my Python coding (when I get there), will be different compared to if I had learned the language 3 years ago. Mind, I am not saying that I am going to program Python the Perl way, just that in 3 years I have learned stuff I can use in other languages as well. -- 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 Serge.Orlov at gmail.com Tue May 9 09:06:54 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 9 May 2006 06:06:54 -0700 Subject: ascii to latin1 References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <4460831e$0$15794$14726298@news.sunsite.dk> Message-ID: <1147180014.685659.325830@i39g2000cwa.googlegroups.com> Luis P. Mendes wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Richie Hindle escreveu: > > [Serge] > >> def search_key(s): > >> de_str = unicodedata.normalize("NFD", s) > >> return ''.join(cp for cp in de_str if not > >> unicodedata.category(cp).startswith('M')) > > > > Lovely bit of code - thanks for posting it! > > > > You might want to use "NFKD" to normalize things like LATIN SMALL > > LIGATURE FI and subscript/superscript characters as well as diacritics. > > > > Thank you very much for your info. It's a very good aproach. > > When I used the "NFD" option, I came across many errors on these and > possibly other codes: \xba, \xc9, \xcd. What errors? normalize method is not supposed to give any errors. You mean it doesn't work as expected? Well, I have to admit that using normalize is a far from perfect way to implement search. The most advanced algorithm is published by Unicode guys: If you read it you'll understand it's not so easy. > > I tried to use "NFKD" instead, and the number of errors was only about > half a dozen, for a universe of 600000+ names, on code \xbf. > It looks like I have to do a search and substitute using regular > expressions for these cases. Or is there a better way to do it? Perhaps you can use unicode translate method to map the characters that still give you problems to whatever you want. From me+python at modelnine.org Sun May 14 17:15:49 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 14 May 2006 23:15:49 +0200 Subject: Question regarding checksuming of a file In-Reply-To: <7xiro8qri0.fsf@ruckus.brouhaha.com> References: <126d1u4ke4itg7f@corp.supernews.com> <126ev127h04e2bb@corp.supernews.com> <7xiro8qri0.fsf@ruckus.brouhaha.com> Message-ID: <200605142315.49698.me+python@modelnine.org> Am Sonntag 14 Mai 2006 22:29 schrieb Paul Rubin: > Andrew Robert writes: > > When I run the script, I get an error that the file object does not have > > the attribute getblocks. > > Woops, yes, you have to call getblocks(f). Also, Heiko says you can't > use "return" to break out of the generator; I thought you could but > maybe I got confused. Yeah, you can. You can't return in a generator (of course, this raises a SyntaxError), but you can use return to generate a raise StopIteration. So, it wasn't you who was confused... ;-) --- Heiko. From 63q2o4i02 at sneakemail.com Wed May 17 12:50:51 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 17 May 2006 09:50:51 -0700 Subject: Using python for a CAD program References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Message-ID: <1147884651.321088.230740@g10g2000cwb.googlegroups.com> Thanks for this. I'm enjoying this discussion and I'm learning a lot about people's views and how they differ from mine. However, I'm still wondering about my original post. Can the experts please comment on python's usage for the following: 1. Databases. Assuming I roll my own, does python have any performance issues for this sort of thing? 2. GUI. Can Python command the various gui libraries fast enough to qualify as game-quality, with transparency, anti-aliasing, animations, etc? 3. Computational stuff like simulations and rules-checking. I'm just going to assume this needs to be in C++ or pyrex or SciPy or something. 4. Programmability. How do I embed an interpreter which has some custom CLI commands and knowledge of the graphical conext and which has exposure to the API used in the main application, such that to the user all the necessary things are exposed by default, and so that it doesn't feel like it's just a disconnected console window that he/she needs to set up manually each time? 5. Threads and parallelism. Should I even bother? I've read that it's possibly more tricky with python than with normal dev tools. I've never done it, but I'd like to at least think about it up front so if/when this goes MT it's not a complete rewrite from the ground up. thanks ms From kevin at netkev.com Mon May 22 18:26:01 2006 From: kevin at netkev.com (NetKev) Date: 22 May 2006 15:26:01 -0700 Subject: global name not defined Message-ID: <1148336761.776348.260450@j33g2000cwa.googlegroups.com> I added a function 'warn_Admin' and defined it just before another function 'process_log'. 'process_log' calls this warn_Admin' function. However, when it gets called i get the following error every time: --- Traceback (most recent call last): File "/usr/bin/denyhosts.py", line 202, in ? first_time, noemail, daemon) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 86, in __init__ last_offset) File "/usr/lib/python2.3/site-packages/DenyHosts/daemon.py", line 74, in createDaemon apply(func, args) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 137, in runDaemon purge_time, purge_sleep_ratio) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 178, in daemonLoop last_offset = self.process_log(logfile, last_offset) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 380, in process_log [warn_Admin(ip) for ip in new_denied_hosts] NameError: global name 'warn_Admin' is not defined -- If I take the two functions out of their current environment and store them in test file and run it, it doesn't complain. I'm new to python so I'm guessing there is some weird scope rule I am missing. I did try 'self.warn_Admin(ip)' just to be safe but then I got a 'too many arguments' error? I'm lost :) the added function plus the header of the existing function(its too large): ------------ def warn_Admin(warn_ip): SENDMAIL = "/usr/sbin/sendmail" # sendmail location p = os.popen("%s -t" % SENDMAIL, "w") p.write("To: kevin at netkev.com\n") p.write("Subject: test from denyhosts\n") p.write("\n") # blank line separating headers from body p.write("Some text\n") p.write(warn_ip) sts = p.close() if sts != 0: info("Sendmail exit status: %s", sts) return sts def process_log(self, logfile, offset): ------------- the call to warn_Admin from process_log: --- if new_denied_hosts: info("new denied hosts: %s", str(new_denied_hosts)) #[info(ip) for ip in new_denied_hosts] [warn_Admin(ip) for ip in new_denied_hosts] else: debug("no new denied hosts") -kevin From atul.nene at gmail.com Mon May 8 02:55:05 2006 From: atul.nene at gmail.com (Atul) Date: 7 May 2006 23:55:05 -0700 Subject: Tkfont.families does not list all installed fonts Message-ID: <1147071305.425322.271490@j73g2000cwa.googlegroups.com> Hi, I have installed a truetype font (.ttf) on a linux machne (SUSE linux 10, KDE) by copying it to my .fonts folder. I can use the font in all applications like open-office and firefox browser. However, I cannot use the font in a python app that I am writing. The list returned by Tkfont.families does not contain this particular font. Any suggestions ? Regards, From john at castleamber.com Sat May 20 18:51:59 2006 From: john at castleamber.com (John Bokma) Date: 20 May 2006 22:51:59 GMT Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> Message-ID: "George Sakkis" wrote: > Not trying to be as ass, but can you take this offline or at least in > a perl newsgroup ? Arguing on a particular fact or speculation about > the perl community is rather unproductive and offtopic for a python > newsgroup. Use a real Usenet client, and you can make it skip a thread. Like I said, I am not interested in a(n OT) pissing contest, but when people make silly statements like Edward did, I think its a good thing to point out that import is *not* encouraged by the Perl community. It has been used (abused IMO) a lot in the past, and yes, those modules are still around. But in general OO is perferred, except in those cases that import extends the language with for example constructs like try / catch or case etc. -- 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 ullrich at math.okstate.edu Wed May 10 08:53:56 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Wed, 10 May 2006 07:53:56 -0500 Subject: A critic of Guido's blog on Python's lambda References: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> Message-ID: On Tue, 09 May 2006 05:35:47 -0500, David C. Ullrich wrote: >On Mon, 08 May 2006 18:46:57 -0400, Ken Tilton >wrote: >[...] > >If you, um, look at the code you see that "cells.a = 42" triggers >cells.__setattr__, which fires a's callback; the callback then >reaches inside and sets the value of b _without_ going through >__setattr__, hence without triggering b's callback. > >In Cells you can't have A depend on B and also B depend on A? >That seems like an unfortunate restriction - I'd want to be >able to have Celsius and Farenheit, so that setting either >one sets the other. Realized later that I hadn't thought this through. I'd been assuming that of course we should be allowed to have A and B depend on each other. Hence if a change in A propagates to a change in B that change in B has to be a non-propagating change - thought I was just so clever seeing a way to do that. But duh, if that's how things are then we can't have transitive dependencies working out right; surely we want to be able to have B depend on A and then C depend on B... (And also if A and B are allowed to depend on each other then the programmer has to ensure that the two rules are inverses of each other, which seems like a bad constraint in general, something non-trivial that the programmer has to get right.) So fine, no loops. If anything, if we know that there are no loops in the dependencies that simplifies the rest of the programming, no need for the sort of finagling described in the first paragraph above. But this raises a question: Q: How do we ensure there are no loops in the dependencies? Do we actually run the whole graph through some algorithm to verify there are no loops? The simplest solution seems like adding the cells one at a time, and only allowing a cell to depend on previously added cells. It's clear that that would prevent loops, but it's not clear to me whether or not that disallows some non-looping graphs. A math question the answer to which is not immediately clear to me (possibly trivial, the question just ocurred to me this second): Say G is a (finite) directed graph with no loops. Is it always possible to order the vertices in such a way that every edge goes from a vertex to a _previous_ vertex? >Of course if there are no loops it's easier to see how >you managed to do the stuff you were talking about elsewhere, >(at least sometimes) delaying execution until needed. > >>Anyway...) >> >>> >>> >>>>all >>>>the *programmer* has to care about is what values a slot depends on -- >>>>Cells takes care of inverting that for you, which is important because >>>>that's a job that a computer is much better at than a human. >>> >>> >>> Fine. I suppose that is better; if b is going to return a + 1 >>> the fact that this is what b returns should belong to b, not >>> to a. So a has an update list including b, so when a's value >>> is set a tells b it needs to update itself. >>> >>> If we're allowed to pass (at some point, to some constructor >>> or other) something like (b, a + 1, [a]), which sets up a >>> cell b that shall return a + 1, and where the [a] is used >>> in the constructor to tell a to add b to a's update list >>> then this seems like no big deal. >>> >>> And doing that doesn't seem so bad - now when the programmer >>> is writing b he has to decide that it should return a + 1 >>> and also explicitly state that b shall depend on a; this >>> is all nice and localized, it's still _b_ telling _a_ to >>> add b to a's update list, and the programmer only has >>> to figure out what _b_ depends on when he's writing _b_. >>> Doesn't seem so bad. >>> >>> But of course it would be better to be able to pass just >>> something morally equivalent to (b, a + 1) to whatever >>> constructor and have the system figure out automatically >>> that since b returns a + 1 it has to add a to b's update >>> list. There must be some simple trick to accomplish that >>> (using Python, without parsing code). >> >>Right, you do not want to parse code. It really would not work as >>powerfully as Cells, which notice any dynamic access to another cell >>while a rule is running. So my rule can call a function on "self" (the >>instance that wons the slot being calculated, and since self can have >>pointers to other instances, the algorithm can navigate high and low >>calling other functions before finally reading another ruled slot. You >>want to track those. >> >>> Exactly what the trick is I >>> don't see immediately. >> >>To compute a value for a slot that happens to have a rule associated >>with it, have a little cell datastructure that implements all this and >>associate the cell with the slot and store a pointer to the rule in the >>cell. Then have a global variable called *dependent* and locally: >> >> currentdependent = *dependent* >> oldvalue = cell.value >> newvalue = call cell.rule, passing it the self instance >> *dependent* = currentvalue >> >> if newvalue not = oldvalue >> call on-change on the slot name, self, newvalue and oldvalue >> (the on-chnage needs to dispatch on as many arguments as >> the language allows. Lisp does it on them all) >> >>In the reader on a slot (in your getattr) you need code that notices if >>the value being read is mediated by a ruled cell, and if the global >>*dependent* is non empty. If so, both cells get a record of the other >>(for varying demands of the implementation). >> >>> >>> In Cells do we just pass a rule using other cells to >>> determine this cell's value, or do we also include >>> an explicit list of cells that this cell depends on? >> >>Again, the former. Just write the rule, the above scheme dynamically >>figures out the dependencies. Note then that dependencies vary over time >>because of different branches a rule might take. >> >>I want to reassure the community that this (nor the spreadsheet analogy >>) is not just my crazy idea. In 1992: >> >> http://www.cs.utk.edu/~bvz/active-value-spreadsheet.html >> >>"It is becoming increasingly evident that imperative languages are >>unsuitable for supporting the complicated flow-of-control that arises in >>interactive applications. This paper describes a declarative paradigm >>for specifying interactive applications that is based on the spreadsheet >>model of programing. This model includes multi-way constraints and >>action procedures that can be triggered when constraints change the >>values of variables." >> >>Cells do not do multi-way constraints, btw. > >My _guess_ is that a "multi-way constraint" is something like >what's above, where A depends on B and B depends on A? > >>Nor partial constraints. To >>hard to program, because the system gets non-deterministic. That kinda >>killed (well, left to a small niche) the whole research programme. I >>have citations on that as well. :) >> >>kenny > > >************************ > >David C. Ullrich ************************ David C. Ullrich From martin at v.loewis.de Fri May 12 16:48:57 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Fri, 12 May 2006 22:48:57 +0200 Subject: Time to bundle PythonWin In-Reply-To: References: Message-ID: <4464F4B9.8080603@v.loewis.de> Dave Benjamin wrote: > Why is PythonWin (win32all) still a separate download from a third > party? Is it legal, technical, or what? I think it's about time it be > part of the standard distribution. Both legal and technical. The PythonWin author and maintainer (Mark Hammond) hasn't contributed this package for inclusion into Python. Without him explicitly saying that he wants that to happen, and prefers that over maintaining it outside Python himself, there is no way it could ever get included. This is a basic rule of politeness in open source software: don't fork, not even if you are legally allowed to. [of course, forks happen, typically because people don't consider it important enough to be polite to the original author] Now, if Mark did indeed offer it for inclusion, I would request (and also work on if I find the time) that the structure of these libraries is revised. I know that the current structure tries to be "natural" in some sense, but I find the assignment of API functions to modules quite arbitrary. I also think that some of the API functions should be replaced with their *Ex versions that Microsoft added over time. Coming back to organizational issues: it would surely help if people would actively contribute to PythonWin. I believe this still is primarily a one-man show, and that Mark does an excellent job should not be an excuse for you to not contribute. > There are many useful things that you ought to be able to do without > downloading third-party libraries. Terminating a process, for example. You can use subprocess.TerminateProcess for that (in some limited way). > Communicating with other applications via a standard, common protocol > (COM). We demand these things from our UNIX environments--why do we > tolerate their omission on the Windows platform? We tolerate them because they aren't omitted. They are readily available, and we are all lazy enough to never do more than just post to a newsgroup complaining about it. > It's time to bundle PythonWin. So go and work on that. Regards, Martin From go at away.com Wed May 31 20:34:35 2006 From: go at away.com (3rdshiftcoder) Date: Thu, 01 Jun 2006 00:34:35 GMT Subject: beginner: using parameter in functions References: Message-ID: thanks very much John! so i can have self as function parameter as well as in a method. that allowed me to use properties to retrieve the value set in the constructor. i just changed the function return statement and it worked. i was working along these lines but couldnt get it up and running as fast as you posted. templating sure is a great way to create dynamic query strings. very cool so far but still lots to learn. thanks again, jim "John McMonagle" wrote in message news:mailman.6388.1149119924.27775.python-list at python.org... > On Wed, 2006-05-31 at 23:24 +0000, 3rdshiftcoder wrote: >> hi- >> >> i am having trouble using parameter values in my function and to be >> honest a >> little trouble with >> member variables. i am trying to pass in the argument 'd' representing >> delete. >> what the code will do is if it is 'd' it will make a delete query >> template >> string. >> if it is an 'i' then insert query etc. >> >> this is the results of my attempt to print the contents of the parameter >> values. >> <__main__.getQryStr instance at 0x01151D50> ('d',) me mad >> >> >> (and on a side note if i dont include the *args i get an invalid number >> of >> parameters supplied message.) >> why is it returning the value in this format ('d',) ? >> i cant get x == d >> i guess that value 'd' is stored in a tuple and i'd like to get it out of >> there. >> >> so basically the function returns nope as it stands >> >> python is sure different from other languages i have used. >> >> thanks for any help, >> jim >> > > > Try, the following: > > class getQryStr: > def __init__(self,op): > print op > self.x = 'd' > def returnStr(self, *args): > > print '%s %s me mad' % (self.x,args) > if self.x == 'd': > s = Template("delete from columndef where tblid = $tblid and > colname = $colname") > else: > return 'nope' #this else is just for illustration and > testing > > d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) > > print s.substitute(d) > > return s > > > Regards, > > John > > > > -- > This message has been scanned for viruses and > dangerous content by MailScanner, and is > believed to be clean. > From darkpaladin79 at gmail.com Wed May 3 12:45:07 2006 From: darkpaladin79 at gmail.com (Ivan Shevanski) Date: Wed, 3 May 2006 12:45:07 -0400 Subject: Wake on LAN and Shutdown for Windows and Linux In-Reply-To: References: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> Message-ID: <17d4ae400605030945s19138166re9d24f207125815c@mail.gmail.com> On 5/3/06, Dennis Lee Bieber wrote: > > On 2 May 2006 12:02:50 -0700, diffuser78 at gmail.com declaimed the > following in comp.lang.python: > > > > > Also, How can I shutdown other Linux terminals from my Main (Linux) ? > > > Uhm... Telnet into the other workstations using the root account > (or > some other account with the needed privileges) and execute the machine > specific shutdown command (and disconnect the Telnet session before it > shuts down so you don't accidentally trigger another "wake"?)? > > Windows is the hard one... > > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > You could probably write an easy batch file for windows. . .For Linux? Maybe use the recipe. Sorry its not in Python =D -- -Ivan -------------- next part -------------- An HTML attachment was scrubbed... URL: From john at castleamber.com Fri May 19 19:10:18 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 23:10:18 GMT Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <1148073990.938267.320410@38g2000cwa.googlegroups.com> Message-ID: Edward Elliott wrote: > The question is how to count explicit names like module.class.func; > should that be 1 identifier or 3? Counting as 3 would reward things > like "from X import *" which are generally frowned on in python while > 'use MOD qw(id)' is encouraged in perl. Not by me, and I doubt it is in general. -- 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 lorenzo at excitement.com Tue May 16 01:05:23 2006 From: lorenzo at excitement.com (Lorenzo) Date: Tue, 16 May 2006 00:05:23 -0500 Subject: Aggregate funuctions broken in MySQLdb? References: <1147623011.319336.11820@v46g2000cwv.googlegroups.com> Message-ID: In article , John Salerno wrote: > http://sourceforge.net/docman/?group_id=22307 Yes, I did, but I did not find them thorough enough. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From None at none.none Mon May 22 23:28:39 2006 From: None at none.none (WIdgeteye) Date: Mon, 22 May 2006 22:28:39 -0500 Subject: No math module?? References: Message-ID: On Tue, 23 May 2006 12:40:49 +1000, Ben Finney wrote: Ok this is weird. I checked: /usr/local/lib/python2.3/lib-dynload/math.so Just as you have on your system and it's there. So why in the heck isn't it loading with: import math ???? This is strange. > WIdgeteye writes: >> [quoted text muted] > > It definitely should be part of the default Python install. On my Debian > system: > > ===== > $ python > Python 2.3.5 (#2, Sep 4 2005, 22:01:42) [GCC 3.3.5 (Debian 1:3.3.5-13)] > on linux2 Type "help", "copyright", "credits" or "license" for more > information. >> [quoted text muted] > "" >> [quoted text muted] > $ dpkg -S /usr/lib/python2.3/lib-dynload/math.so python2.3: > /usr/lib/python2.3/lib-dynload/math.so ===== > > Perhaps you should use the official Python package for your operating > system, or double-check you built and installed the source packages the > way you want them. From vbgunz at gmail.com Mon May 8 14:50:52 2006 From: vbgunz at gmail.com (vbgunz) Date: 8 May 2006 11:50:52 -0700 Subject: Using StopIteration In-Reply-To: <1147112608.374083.99030@u72g2000cwu.googlegroups.com> References: <1147112608.374083.99030@u72g2000cwu.googlegroups.com> Message-ID: <1147114252.736315.90800@g10g2000cwb.googlegroups.com> sequence = ['','2'] for index, line in enumerate(sequence): if line.isspace():continue if line[:1].isdigit(): print 'index %s: starts with digit %s' % (index, line[:1]) From Serge.Orlov at gmail.com Tue May 2 06:13:00 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 2 May 2006 03:13:00 -0700 Subject: Can Python kill a child process that keeps on running? References: <1146532884.872505.154370@i40g2000cwc.googlegroups.com> <43F5g.64465$_S7.31584@newssvr14.news.prodigy.com> Message-ID: <1146564779.967937.208040@g10g2000cwb.googlegroups.com> Edward Elliott wrote: > Serge Orlov wrote: > > I. Myself wrote: > >> Suppose it is supposed to run for one minute, but it just keeps going > >> and going. Does Python have any way to kill it? > > > > On linux it's pretty easy to do, just setup alarm signal. On windows > > it's not so trivial to the point you cannot do it using python.org > > distribution, you will need to poke in low level C API using win32 > > Can't you use a Timer thread and then send the runaway process a signal? > Does Windows not have the equivalent of SIGHUP/SIGTERM/SIGKILL? Windows doesn't have signals, so os.kill (that should rather be called os.send_signal) is not implemented on Windows. Perhaps os module should have os.terminate(pid) that can be implemented on Windows. You're right about timer thread, it's better, I didn't think of it because of my lack of experience with threading module. The watchdog process code in my second post is almost useless: it's complicated and os.kill is not available on windows anyway :-( Time to rest. From nobody at 127.0.0.1 Thu May 4 14:23:18 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 04 May 2006 18:23:18 GMT Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> <1146644904.906523.255970@j73g2000cwa.googlegroups.com> <1146651877.687428.294320@v46g2000cwv.googlegroups.com> <1146733769.619181.268050@j33g2000cwa.googlegroups.com> Message-ID: Michele Simionato wrote: >> >>> A = [] # let's declare a "constant" here >> >>> b = A # and let's assign the constant here >> >>> b.append('1') # OOPS! > > But it makes no sense to use a mutable object for a constant! > The user should use a tuple, Sure. Now show me the builtin immutable equivalent of a dict. > or a custom list-like type where > all methods with side effects are removed, so it effectively acts > as a tuple. Ugh, not worth the trouble imo. From maric at aristote.info Thu May 25 08:02:15 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 25 May 2006 14:02:15 +0200 Subject: Why can't timedeltas be divided? In-Reply-To: <1148508445.853563.170030@i39g2000cwa.googlegroups.com> References: <1148508445.853563.170030@i39g2000cwa.googlegroups.com> Message-ID: <200605251402.15646.maric@aristote.info> oups ididn't post it to the good thread :) Le Jeudi 25 Mai 2006 01:10, vous avez ?crit : > The ratio of two durations has no meaning??? Oh, sorry, sure it has, I wanted to say "it has no meaning in timedelta provided arithmetic". It's a ratio (no dimension) not a duration. In that sense the expected result should be a float, and the proposed operator will break the timedelta's arithmetic consistence. t, u, v <- timedeltas t+u # valid t / u # valid t / u + v # invalid while all terms are valids It's a big design flaw and I think it's the full answer to the original question. Le Jeudi 25 Mai 2006 02:26, Robert Kern a ?crit : > > what you want is : > > > > num_weeks = time_diff.days / 7 > > or > > num_weeks = (time_diff / 7).days > > Uh, no. Besides the integer division problem in your first line, keep in > mind that the .days attribute does not give you the time interval measured > in days. It gives you the number of *whole* days in the interval. The first > method will be incorrect if time_diff is not an even multiple of 1 day. > The latter will be incorrect if time_diff is not an even multiple of 7 days. In fact i was computing the exact number of whole weeks in the delta. In respect of that both expression are perfectly correct, but the second one isn't clear IMO (why this "days" attribute should give me the number of weeks ?). This said it's not hard to figure out the correct expression of the decimal value of weeks in deltas (discarding the microseconds which are not relevant) : num_weeks = (time_diff.days * 24* 3600 + time_diff.seconds) / (7.*24*3600) If I need to do much of these in a piece of code I would probably define some helper functions like this : def tomicroseconds(td) : ????????return td.days * 24* 3600 * 10**6 + ???????????????? ? td.seconds * 10 ** 6 + td.microseconds def toseconds(td) : return float(tomicroseonds(td)) / 10 ** 6 tominute, tohours, todays, toweeks, etc... and use float and int / and % operators. This is an easy and clean implementation IMHO. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From kentilton at gmail.com Fri May 12 14:58:38 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 12 May 2006 14:58:38 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147330449.102694.317200@i40g2000cwc.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Michele Simionato wrote: > jayessay wrote: > >>I was saying that you are mistaken in that pep-0343 could be used to >>implement dynamically scoped variables. That stands. > > > Proof by counter example: > > from __future__ import with_statement > import threading > > special = threading.local() > > def getvar(name): > return getattr(special, name) > > def setvar(name, value): > return setattr(special, name, value) > > class dynamically_scoped(object): > def __init__(self, name, value): > self.name = name > self.value = value > def __context__(self): > return self > def __enter__(self): > self.orig_value = getvar(self.name) > setvar(self.name, self.value) > def __exit__(self, Exc, msg, tb): > setvar(self.name, self.orig_value) > > if __name__ == '__main__': # test > setvar("*x*", 1) > print getvar("*x*") # => 1 > with dynamically_scoped("*x*", 2): > print getvar("*x*") # => 2 > print getvar("*x*") # => 1 > > If you are not happy with this implementation, please clarify. Can you make it look a little more as if it were part of the language, or at least conceal the wiring better? I am especially bothered by the double-quotes and having to use setvar and getvar. In Common Lisp we would have: (defvar *x*) ;; makes it special (setf *x* 1) (print *x*) ;;-> 1 (let ((*x* 2)) (print *x*)) ;; -> 2 (print *x*) ;; -> 1 kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From nephish at xit.net Mon May 22 09:47:53 2006 From: nephish at xit.net (nephish at xit.net) Date: 22 May 2006 06:47:53 -0700 Subject: problem with writing a simple module Message-ID: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> ello there. i am having a problem getting a module to work right. i wrote a class that is going to be used in a few different scripts in the same directory. it looks like this: #!/usr/bin/python import MySQLdb class DbConnector(object): """ Database Connection object. class receives the db argument to specify the database. """ def __init__(self, db='test_db', host="10.10.10.16",user="me", passwd="mypass"): self.host = host self.user = user self.passwd = passwd self.db = db # Unpack Other Database Arguments Here self.CreateConnection() def createConnection(self): self.connection = MySQLdb.connect(self.host, self.user, self.passwd, self.db) def killConnection(self): self.connection.close() def getMany(self, sql_statement): cursor = self.connection.cursor() try: cursor.execute(sql_statement) result = cursor.fetchall() self.connection.close() return result except: self.connection.close() the file is saved as DbConnector.py and made executable. then i get this in idle >> import DbConnector >> x = DbConnector() then it tells me that the module object is not callable. this works though >> import DbConnector >> x = DbConnector >> x.db = 'other_db' >> results = x.getOne("SELECT * FROM `stuff`") it tells me that the module has no attribute getOne. i am really not trying for an attribute, but a method. anyone know what i am doing wrong? thanks From jack at performancedrivers.com Thu May 4 18:39:06 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Thu, 4 May 2006 18:39:06 -0400 Subject: Why does built-in set not take keyword arguments? In-Reply-To: References: Message-ID: <20060504223906.GA20952@performancedrivers.com> On Thu, May 04, 2006 at 02:08:30PM -0400, Steven Watanabe wrote: > I'm trying to do something like this in Python 2.4.3: > > class NamedSet(set): > def __init__(self, items=(), name=''): > set.__init__(self, items) > self.name = name > > class NamedList(list): > def __init__(self, items=(), name=''): > list.__init__(self, items) > self.name = name > > I can do: > > >>> mylist = NamedList(name='foo') > > but I can't do: > > >>> myset = NamedSet(name='bar') > TypeError: set() does not take keyword arguments > > How come? How would I achieve what I'm trying to do? setobject.c checks for keyword arguments in it's __new__ instead of its __init__. I can't think of a good reason other to enforce inheriters to be maximally set-like. We're all adults here so I'd call it a bug. bufferobect, rangeobject, and sliceobject all do this too, but classmethod and staticmethod both check in tp_init. Go figure. As a work around use a function to make the set-alike. class NamedSet(set): pass def make_namedset(vals, name): ob = NamedSet(vals) ob.name = name return ob Then make_namedset as a constructor in place of NamedSet(vals, name) -Jack From scott.daniels at acm.org Mon May 22 19:57:56 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 22 May 2006 16:57:56 -0700 Subject: Running script in __main__ shows no output in IDLE In-Reply-To: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> References: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> Message-ID: <44724be3$1@nntp0.pdx.net> heidi.hunter at fantasy-interactive.com wrote: > I just downloaded the most recent (2.4.3) Python and IDLE (1.1.3) to > Windows XP Professional. I'm new to the IDLE environment, so hopefully > someone can tell me what I'm missing here! Below is the code, which I'm > editing within IDLE, and attempting to test with the Run commands. > > I was expecting to see at least see the prints to stdout from the if > __name__ ... statement and main() function, but when I use F5 Run > module I don't see any output or errors. Any suggestions? Does IDLE > still need the executable file statement at the top even if I run it > explicity? > > --------------------------------------------------------------------------------------- > import sys > from xml.sax import ContentHandler, make_parser > from xml.sax.handler import feature_namespaces > > class AuthorHandler(ContentHandler): > # """Converts an author file""" > > def __init__(self,outfilename): > # """Constructor. Takes output file name.""" > self.outfile = "" > self.insertCmd = "INSERT Authors SET " ... Don't comment out those strings, you'll find them more useful in Idle if they are there. > def main(args): > ... > # Parse the file; your handler's methods will get called > parser.parse(args[0]) > > print ah.insertCmd > > if __name__ == "__main__": > print "to main" > main("\\Iceman\propod\flash\xml\webService\XmlData\Authors\Heidi") As someone else said, use both a better string constant and a list, since main looks at "args[0]". If nothing else: main([r"\\Iceman\propod\flash\xml\webService\XmlData\Authors\Heidi"]) To investigate the idle environment, simply add: if __name__ == "__main__": print "to main" main([r"\\Iceman\propod\flash\xml\webService\XmlData\Authors\Heidi"]) else: print 'Sorry, __name was %r, not "__main__".' % __name__ --Scott David Daniels scott.daniels at acm.org From caseyhHAMMER_TIME at istar.ca Tue May 16 20:59:46 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Wed, 17 May 2006 00:59:46 GMT Subject: Is the only way to connect Python and Lua through a C interface? Message-ID: <3btk62hlopp7ou0g5upnarl5eail29lqms@4ax.com> Is the only way to connect Python and Lua through a C interface? -- Regards, Casey From claudio.grondi at freenet.de Sat May 20 06:28:31 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sat, 20 May 2006 12:28:31 +0200 Subject: open file with whitespaces In-Reply-To: <1148049978.121892.198840@y43g2000cwc.googlegroups.com> References: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> <446dd899$0$8108$626a54ce@news.free.fr> <1148049978.121892.198840@y43g2000cwc.googlegroups.com> Message-ID: mardif wrote: > OK OK GUYS!!!! > I've found the solution: ( effectly, a friend of mine has found the > solution ) > > import os > > os.spawnl(os.P_WAIT, "c:\programmi\internet > explorer\iexplore.exe",'"C:\Documents and > Settings\michele\Desktop\ciccio.html"','"C:\Documents and > Settings\michele\Desktop\ciccio.html"') > > The secret are the ' simbols around arguments: > > ' "C:\Documents and Settings\michele\Desktop\ciccio.html" ' > > Without these, don't work! > > Very STRONG!!!!! > > bye and thx > Wasn't that what I have suggested? By the way: it is much better to use double backslashes here, as in case of other file/directory names (e.g. folder\name.txt folder\remote.htm i.e. for all the cases a backslash is followed by a letter making out of this twin one special character) this above won't work. But best is to use in full path file names forward slashes as Python handles them properly not only on *nix and Linux, but also on Windows: '"C:/Documents and Settings/michele/Desktop/ciccio.html"' The "secret" symbols around arguments are single quotation marks making the double quotation marks part of the string passed to the .spawnl() function. Check out in IDLE, that: >>> "x" 'x' >>> '"x"' '"x"' Command shell command arguments need to be enclosed in quotation marks in case spaces can occur in them (as it can happen in file names) as otherwise the spaces will be interpreted as separator characters between the arguments and as consequence of this the command shell command fails due to bad or wrong number of parameter. You see, no "secrets" here ... only some simple rules and a bit more understanding of what is going on behind the scenes. Claudio From sybrenUSE at YOURthirdtower.com.imagination Sun May 28 06:20:29 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 28 May 2006 12:20:29 +0200 Subject: generating random passwords ... for a csv file with user details References: <1148802192.793574.209720@i40g2000cwc.googlegroups.com> Message-ID: k.i.n.g. enlightened us with: > Now I have to write a script to generate random password in the > password field for each user. A simple algorithm is sufficient for > passwords Check out the source of pwsafe, it has a great password generator. It can generate with different lengths, based on amount of entropy, and can also generate different types (alpha/digit, hex, easy to read alpha/digit, etc.) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From keir.robinson at gmail.com Thu May 25 06:21:28 2006 From: keir.robinson at gmail.com (keirr) Date: 25 May 2006 03:21:28 -0700 Subject: Modify one character in a string References: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> Message-ID: <1148552488.130194.272030@y43g2000cwc.googlegroups.com> mp wrote: > X-No-Archive > How do I go about modifying one character in a string elegantly? > In other words, I want a function that will change 'aaaa' to 'aaza', > given the index 2 of the character in the string. > > Also, how do I do this when dealing with a file ; which file mode > should I use and what function should I use to modify a single > character once in that file mode? > > Thanks > MP Technically you can't - strings are immutable. If you use the StringIO module then you can use a common approach between 'strings' in memory, and files, using seek and write. All the best, Keir. From johnjsal at NOSPAMgmail.com Wed May 17 16:51:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 20:51:07 GMT Subject: I'm just not cut out for web programming, I guess :) Message-ID: <%0Mag.2117$No6.46299@news.tufts.edu> Ok, I've tinkered with this thing for a while, and I keep fixing little problems, but I always get a 500 Internal Server error when I go to this site: I don't necessarily even want help just yet, I'd like to figure it out myself, but can someone at least tell me why I'm not getting helpful feedback from the cgitb module? Am I using it wrong? The webpage just displays the internal server error. Thanks. import cryptogen import cgitb; cgitb.enable() quote_file = open('quotes.txt') quote = quote_file.readline().strip() quote_file.close() print '''content-type: text/html
''' quote = cryptogen.convert_quote(quote) for word in quote[0].split(' '): word_len = len(word) print '' % (word, word_len) print '
' From nx13441a at net.vodafone.pt Thu May 4 07:05:49 2006 From: nx13441a at net.vodafone.pt (jonas) Date: 4 May 2006 04:05:49 -0700 Subject: pleac Message-ID: <1146740749.200368.173590@g10g2000cwb.googlegroups.com> Hi, I'm new to python. After a search on http://pleac.sourceforge.net/pleac_python/index.html why python have a low %? Thanks in advance From skip at pobox.com Tue May 16 20:48:14 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 May 2006 19:48:14 -0500 Subject: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? In-Reply-To: <1147818523.764211.234710@u72g2000cwu.googlegroups.com> References: <1147657728.064817.214850@j73g2000cwa.googlegroups.com> <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> <1147804326.793291.53410@j55g2000cwa.googlegroups.com> <1147818523.764211.234710@u72g2000cwu.googlegroups.com> Message-ID: <17514.29390.949028.841659@montanaro.dyndns.org> bob> If you have the same number of entries as buckets, and you have a bob> good hash function, then if you have n buckets your longest chain bob> should have length around ln(n). The average length of a nonempty bob> bucket would be somewhere around 1 1/2. Yes, and it achieves that nice short chain length by consuming gobs of memory. A dictionary with 10**7 keys is going to chew up lots of memory. There's nothing particularly magical about dictionaries in this respect. They are good examples of a classic time-space tradeoff. Skip From rrrn at yahoo.com Thu May 11 23:13:53 2006 From: rrrn at yahoo.com (Butternut squash) Date: Fri, 12 May 2006 03:13:53 GMT Subject: python soap web services Message-ID: Is there any reason why there isn't any python library that makes using soap as easy as how microsoft .net makes it. I mean I write rudimentary asmx files call them from a webbrowser. The WSDL is generated and then there is documentation and a form to invoke a function. When do you think someone will make this available for python web service?? From ttdevelop at gmail.com Thu May 11 01:08:39 2006 From: ttdevelop at gmail.com (Tim) Date: 10 May 2006 22:08:39 -0700 Subject: 345 free programming books In-Reply-To: <1146617514.168901.31540@i40g2000cwc.googlegroups.com> References: <1146020222.383927.319890@i40g2000cwc.googlegroups.com> <1146617514.168901.31540@i40g2000cwc.googlegroups.com> Message-ID: <1147324119.605459.59470@j73g2000cwa.googlegroups.com> Anyone has any free books to submit? From deets at nospam.web.de Mon May 1 11:48:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 May 2006 17:48:11 +0200 Subject: list*list References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> Message-ID: <4bmotsF126gicU1@uni-berlin.de> > There must be a better way to multiply the elements of one list by > another: > > a = [1,2,3] > b = [1,2,3] > c = [] > for i in range(len(a)): > c.append(a[i]*b[i]) > a = c > print a > [1, 4, 9] > > Perhaps a list comprehension or is this better addressed by NumPy? First of all: it's considered bad style to use range if all you want is a enumeration of indices, as it will actually create a list of the size you specified. Use xrange in such cases. You can use a listcomp like this: c = [a[i] * b[i] for i in xrange(len(a))] But maybe nicer is zip: c = [av * bv for av, bv in zip(a, b)] And if lists get large and perhaps multidemnsional, numpy certainly is the way to go. Diez From bnblazer at gmail.com Sun May 21 23:19:46 2006 From: bnblazer at gmail.com (Brian) Date: 21 May 2006 20:19:46 -0700 Subject: performance difference between OSx and Windows In-Reply-To: <1148263521.205652.286240@j55g2000cwa.googlegroups.com> References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> <1148254182.824583.195370@i40g2000cwc.googlegroups.com> <1148255177.190455.217840@u72g2000cwu.googlegroups.com> <1148263521.205652.286240@j55g2000cwa.googlegroups.com> Message-ID: <1148267986.876892.123110@i40g2000cwc.googlegroups.com> Thank you for your answer. I had a feeling that it would be a threading issue, but I wasn't sure. Brian From deets at nospam.web.de Mon May 15 14:53:29 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 20:53:29 +0200 Subject: OOP and Tkinter In-Reply-To: <7gih62p25k5krj9c5l9ot6tpt01c45e723@4ax.com> References: <7gih62p25k5krj9c5l9ot6tpt01c45e723@4ax.com> Message-ID: <4cs113F17n5m7U1@uni-berlin.de> Ronny Mandal schrieb: > Hello. > > I am stuck; provided is the code and error-msg: > > file front_ui.py: > > class Front(object): > _images = [] # Holds image refs to prevent GC > def __init__(self, root): > > > # Widget Initialization > self._listbox_1 = Tkinter.Listbox(root, > height = 0, > width = 0, > ... > ) > > > > > > > other file: > > from Front_ui import Front > > class CustomFront(Front): > > > Front._listbox_1.insert( 0, 'foo' ) > > ... > ... > File "H:\My Documents\Komodo\Front.py", line 63, in CustomFront > Front._listbox_1.insert( 0, foo' ) > AttributeError: type object 'Front' has no attribute '_listbox_1' > > > i.e., it cannot find the listbox! Strange, both files is in the same > folder. What is wrong here? That you refer to the type/class Front with expressions like Front.<...> instead to an _instance_ of Front. You need to do things like this: class CustomFront(Front): def __init__(self, root): super(CustomFront, self).__init__(root) #now the super-classes instance variables are there! self._listbox_1.insert( 0, 'foo' ) Diez From gshepherd281281 at yahoo.com Tue May 23 19:59:58 2006 From: gshepherd281281 at yahoo.com (ProvoWallis) Date: 23 May 2006 16:59:58 -0700 Subject: Looking for help with Regular Expression Message-ID: <1148428798.529016.319100@y43g2000cwc.googlegroups.com> Hi, I'm looking for a little advice about regular expressions. I want to capture a string of text that falls between an opening squre bracket and a closing square bracket (e.g., "[" and "]") but I've run into a small problem. I've been using this: '''\[(.*?)\]''' as my pattern. I was expecting this to be greedy but the funny thing is that it's not greedy enough in some situations. Here's my problem: The end of my string sometimes contains a cross reference to a section in a book and the subsections are cited using square brackets exactly like the one I'm using as the ending point in my original regular expression. E.g., the text string in my data looks like this: see discussion in § 512.16[3][b]] But my regular expression is stopping after the first "]" so after I add the new markup the output looks like this: see discussion in § 512.16[3][b]] So the last subsection is outside of the note tag. I want something like this: see discussion in § 512.16[3][b]] I'm not sure how to make my capture more greedy so I've resorted to cleaning up the data after I make the first round of replacements: data = re.sub(r'''\[(\d*?)\]\[(\w)\]\]''', '''[\1][\2]]''', data) There's got to be a better way but I'm not sure what it is. Thanks, Greg From sjmachin at lexicon.net Thu May 4 01:01:06 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 04 May 2006 15:01:06 +1000 Subject: stripping unwanted chars from string In-Reply-To: References: Message-ID: <44598a93$1@news.eftel.com> On 4/05/2006 1:36 PM, Edward Elliott wrote: > I'm looking for the "best" way to strip a large set of chars from a filename > string (my definition of best usually means succinct and readable). I > only want to allow alphanumeric chars, dashes, and periods. This is what I > would write in **** (bless me father, for I have sinned...): [expletives deleted] and it was wrong anyway (according to your requirements); using \w would keep '_' which is *NOT* alphanumeric. > I could just use re.sub like the second example, but that's a bit overkill. > I'm trying to figure out if there's a good way to do the same thing with > string methods. string.translate seems to do what I want, the problem is > specifying the set of chars to remove. Obviously hardcoding them all is a > non-starter. > > Working with chars seems to be a bit of a pain. There's no equivalent of > the range function, one has to do something like this: > >>>> [chr(x) for x in range(ord('a'), ord('z')+1)] > ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', > 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] >>> alphabet = 'qwertyuiopasdfghjklzxcvbnm' # Look, Ma, no thought required!! Monkey see, monkey type. >>> keepchars = set(alphabet + alphabet.upper() + '1234567890-.') >>> fixer = lambda x: ''.join(c for c in x if c in keepchars) >>> fixer('qwe!@#456.--Howzat?') 'qwe456.--Howzat' >>> > > Do that twice for letters, once for numbers, add in a few others, and I get > the chars I want to keep. Then I'd invert the set and call translate. > It's a mess and not worth the trouble. Unless there's some way to expand a > compact representation of a char list and obtain its complement, it looks > like I'll have to use a regex. > > Ideally, there would be a mythical charset module that works like this: > >>>> keep = charset.expand (r'\w.-') # or r'a-zA-Z0-9_.-' Where'd that '_' come from? >>>> toss = charset.invert (keep) > > Sadly I can find no such beast. Anyone have any insight? As of now, > regexes look like the best solution. I'll leave it to somebody else to dredge up the standard riposte to your last sentence :-) One point on your requirements: replacing unwanted characters instead of deleting them may be better -- theoretically possible problems with deleting are: (1) duplicates (foo and foo_ become the same) (2) '_' becomes '' which is not a valid filename. And a legibility problem: if you hate '_' and ' ' so much, why not change them to '-'? Oh and just in case the fix was accidentally applied to a path: keepchars.update(os.sep) if os.altsep: keepchars.update(os.altsep) HTH, John From gmc at serveisw3.net Sun May 21 05:38:27 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Sun, 21 May 2006 11:38:27 +0200 Subject: Python update trouble (2.3 to 2.4): x< References: <1148197232.312628.255650@i39g2000cwa.googlegroups.com> Message-ID: <44703513.4080806@serveisw3.net> Thank you very much John, I missed the point to add the *and* to workaround the long result issue! I think I understand it now. I am timing the code once translated, so here are the results for the crc calculation function. I did expected a big gap, as this does a lot of lookups to the crc table (a typical call gets 20-250 characters long) so the C extension version with a simple array and pointers perform really a lot better. The C code was glued with pyrex. Fortunately I don't need a great performance for this code in the PocketPC! C CalcCRC16 1 loops -> 4.75e-006 secs 210562 loops -> 0.133 secs 1580403 loops -> 0.973 secs 1580403 loops -> 0.973 secs 0.971 secs 1.12 secs 1580403 loops, best of 3 trials: 0.614 usec per loop Python CalcCRC16 1 loops -> 0.000102 secs 9834 loops -> 0.832 secs 11824 loops -> 1.01 secs 11824 loops -> 1.01 secs 1.02 secs 1.01 secs 11824 loops, best of 3 trials: 85.1 usec per loop Tested with: CalcCRC16('klldjs at ajsdla#kjfdsfj32389293rhcnacak12932842fjos') C Version: long CalcCRC16(char *str) { long crc; for(crc = 0xFFFF; *str != 0; str++) { crc = CRC16Table [(( crc >> 8 ) & 255 )] ^ ( crc << 8 ) ^ *str; } return crc; } John Machin escribi?: >For a start, > > >>>>22002496167782427386022437441624938050682666541682 & 0xffffffffL >>>> >>>> >67560050L > > >so you could just do that at the end. >But you don't really want to be carrying all that rubbish around, >getting longer and longer each time around the loop. And let's further >the translation into Python by getting rid of the xrange gizmoid and a >few other undesirables: > ># tested on your 1 test value >def CalcCRC16v2(astr): # don't shadow str() > # global gCRC16Table # don't need this > crc = 0xFFFFL # start as a long > for c in astr: > crc = gCRC16Table[((crc >> 8) & 255)] ^ ((crc & 0xFFFFFF) << 8) >^ ord(c) > return crc > >That should get you going. Although the whole calculation will be done >with longs instead of ints, the longs will never exceed 32 bits so it >shouldn't be too slow. > >HTH, >John > > > From skip at pobox.com Fri May 19 13:39:08 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 19 May 2006 12:39:08 -0500 Subject: how to read a list from python in C? In-Reply-To: <446DFE05.6070605@126.com> References: <446DFE05.6070605@126.com> Message-ID: <17518.700.220388.213818@montanaro.dyndns.org> lialie> The list has a random length. lialie> Do you mean to do it in this way? lialie> use PyTuple_Size(args), in a loop lialie> use PyTuple_GetItem(args, i) lialie> or lialie> use PyArg_VaParse? Sketch (that means off-the-top-of-my-head, untested, 99.9% guaranteed incorrect in some fashion): static PyObject * my_list_method(PyObject *self, PyObject *args) { PyListObject *list = NULL; PyTupleObject *point = NULL; int list_len; double *points = NULL; double x, y; if (PyArg_ParseTuple(args, "O!", &PyList_Type, &list) == NULL) return NULL; list_len = PyList_GetSize(list); points = PyMem_Alloc(list_len * 2 * sizeof(double)); if (points == NULL) goto fail; for (i = 0; i < list_len; i++) { point = PyList_GetItem(list, i) if (point == NULL || !PyTuple_Check(point)) goto fail; if (Py_ArgParseTuple(point, "(dd)", &x, &y) == NULL) goto fail; Py_DECREF(point); points[i*2] = x; points[i*2+1] = y; /* do your thing with your list of floats here */ ... PyMem_Free(points); Py_DECREF(list); Py_INCREF(None); /* or whatever makes sense */ return None; fail: Py_XDECREF(list); Py_XDECREF(point); if (points != NULL) PyMem_Free(points); return NULL; } From nospam at invalid.com Tue May 9 15:31:32 2006 From: nospam at invalid.com (Jack) Date: Tue, 9 May 2006 12:31:32 -0700 Subject: Can Python installation be as clean as PHP? Message-ID: I like Python but I don't really like Python's installation. With PHP, I only need one file (on Linux) and maybe two files on Windows then I can run my PHP script. This means no installation is required in most cases. I just copy the file and I get PHP. Extending PHP is fairly easy, too, just by copying a few DLLs and modifying the php.ini a bit. With Python, things are really messy. I have to run the installer to install dozens of directories and hundreds of files, and I don't really know if all of them are necessary. Plus, lots of libraries are in .py, which is of course not as efficient/clean as having all of the core functions built-in in the C/C++ core, like in PHP. Then again, I do like the Python language. It would be great if Python (or a variation of Python) can be made the PHP way, one executable file, and you get everything. From kkylheku at gmail.com Tue May 9 13:14:12 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 9 May 2006 10:14:12 -0700 Subject: Multi-line lambda proposal. In-Reply-To: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> Message-ID: <1147194852.528046.91560@y43g2000cwc.googlegroups.com> Kaz Kylheku wrote: > But suppose that the expression and the multi-line lambda body are > reordered? That is to say, the expression is written normally, and the > mlambda expressions in it serve as /markers/ indicating that body > material follows. This results in the most Python-like solution. Unfortunately, while this idea has intuitive appeal, it leaves some problems to solve; namely, lambdas that occur in expressions embedded within statement syntax which has body material of its own. For instance # lambda defined and immediately called here if lambda(x)(4) < 0: print "a" elif y = 4: print "b" else: print "foo" Where to stick the lambda body? It's not hard to come up with straightforward answers, except that they are not particularly appealing. One rule might be that the lambda bodies have to be placed immediately after the statement body material, set off by the lambda: thing. In the case of if/elif/else, they have to be placed behind the closest suite that follows the expression in the syntax of the statement: if lambda(x)(4) < 0: print "a" lambda: return x + 1 elif y = 4: print "b" else: print "foo" The overall rule is simple and uniform: each suite can have lambda: clauses. These have to match lambda() occurences in the expression (or expression list) immediately to the left in the same grammar production. On the other hand, some people might find this compromise more attractive: simply do not allow multi-line lambdas in compound statements. From bignose+hates-spam at benfinney.id.au Wed May 17 23:24:10 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 13:24:10 +1000 Subject: I'm just not cut out for web programming, I guess :) References: <%0Mag.2117$No6.46299@news.tufts.edu> <446be498$0$9391$c3e8da3@news.astraweb.com> Message-ID: <87bqtwm2w5.fsf@benfinney.id.au> John Salerno writes: > So the bottom line is I'm kind of screwed until I can get 1and1 to > update their Python! :) But at least I figured out some stuff. You should also look around for other hosting options. A web hosting provider that doesn't give access to server logs isn't providing good service. -- \ "I'm beginning to think that life is just one long Yoko Ono | `\ album; no rhyme or reason, just a lot of incoherent shrieks and | _o__) then it's over." -- Ian Wolff | Ben Finney From phddas at yahoo.com Thu May 11 02:08:42 2006 From: phddas at yahoo.com (Gary Wessle) Date: 11 May 2006 16:08:42 +1000 Subject: 2 books for me Message-ID: <87lkt9ytxx.fsf@localhost.localdomain> Hi I am about to order 2 books, and thought I should talk to you first. I am getting Python Cookbook by Alex Martelli, David Ascher, Anna Martelli Ravenscroft, Anna Martelli Ravenscroft, since Bruce Eckel's Thinking in Python is not finished and didn't have any new revisions since some time in 2001, having owned his Thinking in C++ v1 and v2 I am used to learning from him. any way, the second book is gui one, I notices there are 3 flavors according to http://wiki.python.org/moin/GuiBooks, wxPython, Qt, and Tkinter.I am not sure what package is best for and would like to know before I order one of those three. thanks From gdamjan at gmail.com Thu May 25 12:20:57 2006 From: gdamjan at gmail.com (Damjan) Date: Thu, 25 May 2006 18:20:57 +0200 Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> Message-ID: <4475d96b$0$15788$14726298@news.sunsite.dk> >> And, if a list have 801 values, I want to get its values index from 300 >> to 400, could use list1[300:400],are right me? > > 300 will be included in your slice whereas the 400th index will be > excluded. you will ultimately have 99 items in your slice. No, he'll have 100 items in the slice... 300, 301,... 399 that's 100 items. -- damjan From apgwoz at gmail.com Fri May 5 09:38:26 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Fri, 5 May 2006 09:38:26 -0400 Subject: Method acting on arguements passed In-Reply-To: <1146832062.017259.265700@y43g2000cwc.googlegroups.com> References: <1146832062.017259.265700@y43g2000cwc.googlegroups.com> Message-ID: > I want a class method to take action depending on the type of the > arguement passed to it. > > ie: > getBook(id) # get the book by ID > getBook(name) # get the book by name Keyword arguments are going to be the best solution, but you'll still have to do checks like in this example which uses a generic keyword and determines it's type.. def getBook(arg): id = None name = None try: id = int(arg) # use the id here except ValueError: name = arg # use name here Now, if you were to use named arguments: def getBook(id=None, name=None): if id: # do whatever for id elif name: # do whatever for name here They are nearly identical. --- Andrew Gwozdziewycz apgwoz at gmail.com http://www.23excuses.com http://ihadagreatview.org http://and.rovir.us From diesch at spamfence.net Sat May 13 00:35:39 2006 From: diesch at spamfence.net (Florian Diesch) Date: Sat, 13 May 2006 06:35:39 +0200 Subject: python rounding problem. References: <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> <125v9g8q00o1d52@corp.supernews.com> Message-ID: <20060513043543.125E.4.NOFFLE@dieschf.news.arcor.de> "Thomas Bartkus" wrote: > "Grant Edwards" wrote in message > news:125v9g8q00o1d52 at corp.supernews.com... >> On 2006-05-08, Thomas Bartkus wrote: >> >> >> does python support true rations, which means that 1/3 is a >> >> true one-third and not 0.333333333 rounded off at some >> >> arbitrary precision? >> > >> > At risk of being boring ;-) >> > >> > - Python supports both rational and irrational numbers as >> > floating point numbers the way any language on any digital >> > computer does - imprecisely. >> > >> > A "true" (1/3) can only be expressed as a fraction. >> >> At the risk of being both boring and overly pedantic, that's >> not true. In base 3, the value in question is precisely >> representable in floating point: 0.1 >> >> > As soon as you express it as a floating point - you are in a >> > bit of trouble because that's impossible. >> >> It's not possible in base 2 or base 10. It's perfectly >> possible in base 9 (used by the Nenets of Northern Russia) base >> 12 (popular on planets where everybody has twelve toes) or base >> 60 (used by th Sumerians). [I don't know if any of those >> peoples used floating point in those bases -- I'm just pointing >> out that your prejudice towards base 10 notation is showing.] >> >> > You can not express (1/3) as a floating point in Python any >> > more than you can do it with pencil and paper. >> >> That's true assuming base 2 in Python and base 10 on paper. The >> base used by Python is pretty much etched in stone (silicon, to >> be precise). There used to be articles about people working on >> base-3 logic gates, but base-3 logic never made it out of the >> lab. However, you can pick any base you want when using paper >> and pencil. >> >> > You can be precise and write "1/3" or you can surrender to >> > arithmetic convenience and settle for the imprecise by writing >> > "0.333333333", chopping it off at some arbitrary precision. >> >> Or you can write 0.1 >> 3 >> >> :) > > Ahhh! > But if I need to store the value 1/10 (decimal!), what kind of a precision > pickle will I then find myself while working in base 3 ? How much better > for precision if we just learn our fractions and stick to storing integer > numerators alongside integer denominators in big 128 bit double registers ? > > Even the Nenets might become more computationally precise by such means ;-) > And how does a human culture come to decide on base 9 arithmetic anyway? Just guessing: * Use one thumb to point at one of the other 9 fingers * Every finger (except for the thumb) has 3 segments (and links), each of which can easily divided in three part (upper, middle, lower or left middle, right for the links) making 9 points for each finger. > Even base 60 makes more sense if you like it when a lot of divisions come > out nice and even. You can count to 60 using two hands: Use the right thumb to point on one of the 12 segments of the remaining 4 fingers and on the left hand one finger for each dozen. Of course this is wasting resources as you can count to 1023 with your fingers. I never heard of a culture doing so, though. Florian -- From conanelbarbaro at gmail.com Mon May 29 10:32:29 2006 From: conanelbarbaro at gmail.com (conan) Date: 29 May 2006 07:32:29 -0700 Subject: unexpected behaviour for python regexp: caret symbol almost useless? In-Reply-To: References: <1148815719.082410.313870@38g2000cwa.googlegroups.com> Message-ID: <1148913149.187171.293080@i40g2000cwc.googlegroups.com> Thank you Paul. Since the only thing i'm doing is extracting this fields, and have no plans to include other stuff, a regexp is fine. However i will take into account 'pyparsing' when i need to do more complex parsing. As you can see in the example i send, i was trying to get info from a glade file, in particular i was tired of doing this everytime i need to access a widget: some_var = xml.get_widget('some_id') (doing this is tiresome when you have more than 10 widgets) So i do a little module to have all widgets instanciated as attributes of the object, for anyone interested it is on: http://www.lugmen.org.ar/~p10n/sources/conan/utilidades/GetWidgets.py However is still pretty unmature, since it lacks some checks. From maxerickson at gmail.com Fri May 19 20:28:30 2006 From: maxerickson at gmail.com (Max Erickson) Date: Sat, 20 May 2006 00:28:30 +0000 (UTC) Subject: altering an object as you iterate over it? References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <446e558d$0$4856$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote > > It has been, at a time, recommended to use file() instead of > open(). Don't worry, open() is ok - and I guess almost anyone > uses it. http://mail.python.org/pipermail/python-dev/2005-December/059073.html From python.list at tim.thechases.com Mon May 29 09:13:19 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 29 May 2006 08:13:19 -0500 Subject: summarize text In-Reply-To: <1148903386.095226.249270@38g2000cwa.googlegroups.com> References: <1148903386.095226.249270@38g2000cwa.googlegroups.com> Message-ID: <447AF36F.5060206@tim.thechases.com> > does anyone know of a library which permits to summarise text? > i've been looking at nltk but haven't found anything yet. any > help would be very welcome. Well, summarizing text is one of those things that generally takes a brain-cell or two to do. Automating the process would require doing it either smartly (some sort of neural-net/NLP/Markov-chain technology, which is a non-trivial task--something one might consider braving in the 3rd or 4th-year of a university computer-science program), or doing it fairly dumbly. As an example of a "dumb" solution, you can use regexps to trim off the first few words and the last few words and call that a "summary": >>> import re >>> r = re.compile(r'^(.{8}.*?\b)\s.*\s(\b.{8}.*?)', re.DOTALL) >>> s = """This is the first line ... and it has a second line ... and a third line ... and the last line is the fourth line.""" >>> result = r.sub(r"\1...\2",s.strip()) >>> result 'This is the...fourth line.' You can adjust the "{8}" portions for more or less leader/trailing context characters. The regexp might need a bit of tweaking for somewhat short strings, but if they're fairly short, one might not need to summarize them ;) -tkc From jstroud at ucla.edu Tue May 9 00:51:39 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 08 May 2006 21:51:39 -0700 Subject: Enumerating Regular Expressions In-Reply-To: <1147148644.762057.238640@v46g2000cwv.googlegroups.com> References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> <1147148644.762057.238640@v46g2000cwv.googlegroups.com> Message-ID: blair.bethwaite at gmail.com wrote: > James Stroud wrote: > >>You mean like re.compile(r'.*') ? > > > No. I mean like: > >>>>regex = re.compile(r'a|b') >>>>regex.enumerate() > > a > b > > You see the difficulty don't you? How will the computer know in advance that the regex matches only a finite set of possible strings? 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 Wed May 24 05:41:36 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 May 2006 11:41:36 +0200 Subject: referrers References: <1148463646.603330.275000@i40g2000cwc.googlegroups.com> Message-ID: <4dio43F1aju6aU1@uni-berlin.de> raghu wrote: > Hi All, > > The sys.getrefcount() is very useful to get the number of references on > a particular object. > > Is there any companion function to get "who" the referrers are ? > > for e.g. > > global x > global y > global z > > > x0=24012 > y=x0 > z=x0 > > print "ref count ",sys.getrefcount(x0) > > > This prints a ref count of 5. > > Basically, I need to know which are the 5 entities who are referring to > x0 ? > > Is there any way of doing it ? Look into the gc-module. Diez From tim.peters at gmail.com Mon May 8 17:29:15 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 8 May 2006 17:29:15 -0400 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1f7befae0605081429g2155dc4eobf3134e57a5b545e@mail.gmail.com> [OlafMeding at gmail.com] > Below are 2 files. The first is a Python program that isolates the > problem within less than 1 hour (often just a few minutes). It does not on my box. I ran that program, from a DOS shell, using the released Windows Python 2.4.3. After an hour, it was still printing. I left it running, and started a second instance of the test program from another DOS box. That was 4 hours ago, and both instances are still printing. > ... > Note, the Python programs hangs (stops responding) with hyper-threading > turned on (a BIOS setting), but works as expected with hyper-threading > turned off. Hyper-threading was turned on here. > ... > Note, the Windows task manager shows 2 CPUs on the Performance tab with > hyper-threading is turned on. Same here, although do note that whether the Performance tab shows one or two CPUs when HT is enabled depends on how the user sets Task Manager's View -> CPU History option. > Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this > problem. I used the python.org 2.4.3. > The operating system is MS Windows XP Professional. Same here. > winmsd.exe shows: > 2CPUs: x86 Family 15 Model 4 Stepping 1 GenuineIntel ~3000 MHz > Version: 5.1.2600 Service Pack 2 Build 2600 Different processor here: 2CPUs: x86 Family 15 Model 3 Stepping 4 GenuineIntel ~3400 Mhz Version 5.1.2600 Service Pack 2 Build 2600 > Could someone with a hyper-threading (or dual core or multi processor) > CPU please confirm this bug? Not me, and I'm tired of trying :-) From onurb at xiludom.gro Wed May 3 12:54:51 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 18:54:51 +0200 Subject: __getattr__ on non-instantiated class In-Reply-To: <1146673922.994217.241620@j33g2000cwa.googlegroups.com> References: <1146671588.529743.249570@v46g2000cwv.googlegroups.com> <4458D4F9.8010900@websafe.com> <1146673922.994217.241620@j33g2000cwa.googlegroups.com> Message-ID: <4458e0b7$0$20293$626a54ce@news.free.fr> Fredp wrote: (snip) > I have something like a simple ORM which objects haven't a fixed number > of fields, and I need to have properties (or methods) for each of them, dumbiest possible example, but this should het you started class Field(object): # dummy def __init__(self, **kw): self.__dict__.update(kw) class SomeORMObject(object): # this is a class property fields = {'toto' : Field(type='int', primary=True), 'tata' : Field(type='varchar', maxlen=255, default=''), } # this is a class method, # the first param is the class object @classmethod def get_field(cls, fldname): return cls.fields.get(fldname, None) SomeORMObject.get_field('toto') Properties won't probably cut it, but you can write custom descriptors (google or search python.org for a description of what descriptors are - for the record, properties are a kind of descriptor). I did use this kind of stuff for an 'object/ldap mapper', using descriptors for ldap attributes and some classmethod for building queries etc... > but currently it is more comfortable for me to use uninstantiaded > classes (as someway SQLObject does). > I guess I'd better taking another approach to him, maybe using > something from ASPN cookbook :-\ Your approach is quite sensible IMHO - minus one detail : you should avoid reinventing the Square Wheel(tm). There already are some Python orms. I'm not found of SQLObject, but I've played a bit with SQLAlchemy and it seems quite promising. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From joh12005 at yahoo.fr Wed May 10 17:40:17 2006 From: joh12005 at yahoo.fr (joh12005 at yahoo.fr) Date: 10 May 2006 14:40:17 -0700 Subject: design a Condition class Message-ID: <1147297217.372888.167960@v46g2000cwv.googlegroups.com> Hello, i posted for suggestions a little idea even if it still needs further thoughts but as i'm sure you could help :) if would like to implement some kind of Condition class which i coud use to build bricks of more complex condition, conditions are based on fields by using regexp class Condition: def __init__(self, field0, field1, field2): self.field0 = field0 self.field1 = field1 self.field2 = field2 def match(self, against): w, t, l = against f0 = False if self.field0 is None: f0 = True else: f0 = self.field0.search(w) if self.field1 is None: f1 = True else: f1 = self.field1.search(t) if self.field2 is None: f2 = True else: f2 = self.field2.search(l) return f0 and f1 and f2 c0 = Condition(re.compile("something"), None, re.compile("somethingelse")) c1 = Condition(re.compile("another"), None, None) i can use if c0.search(myitem) but i would like to be able to have composition such as : c2 = c0 | c1 which should be understood as defining a new c2 which is able to match (c0 or c1) from c0 and c1 already defined. actually i can imagine a def OR(c0, c1): # here => missing None support 'a or None' is 'a' return Condition(re.compile("|".join((c0.field0.pattern, c1.field0.pattern)), re.compile("|".join((c0.field1.pattern, c1.field1.pattern)), re.compile("|".join((c0.field2.pattern, c1.field2.pattern)) the idea is to build c2 = Condition(re.compile("something|another"), None, re.compile("somethingelse")) c2 = OR(c0, c1) but maybe have you clever suggestions ? best regards. From nobody at 127.0.0.1 Tue May 2 20:49:39 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 00:49:39 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: Ben Finney wrote: > So now you're proposing that this be a special case when a function is > declared by that particular syntax, and it should be different to when > a function is created outside the class definition and added as a > method to the object at run-time. > > Thus breaking not only "explicit is better than implicit", but also > "special cases aren't special enough to break the rules". Exactly. Hey, 'for' and 'while' are only special cases of if/goto. Why not ditch them and get back to basics? Rules are made to be broken, the key is when. Method calls are special cases no matter how you slice it. Overall I think implicit self beats explicit self for the typical case: def method (a): self.a = a # self magically appears obj.method (x) vs def method (self, a): # self explicit self.a = a obj.method (x) # arg count mismatch (except in message passing model) Not so much for the argument mismatch problem (see start of thread), which is easily rectified. The former is simply more elegant in my view. Less clutter, less confusion. Sure, if we get into calling "class.method (obj, a)" the argument mismatch problem resurfaces with implicit self. But 1) this is a rarer case, and 2) that's not my primary objection anyway. As long as we're trotting out aphorisms, how about DRY: Don't Repeat Yourself. The rule couldn't be clearer: don't repeat your SELF. ;) Yet that's exactly what explicitly declaring self does, forces me to needlessly repeat what everyone already knows: methods take the object instance as their first parameter. Whether this is a good idea is subject to debate, and I'd like to hear discussion on the merits. What I don't want is a silly battle of maxims. From mariano.difelice at gmail.com Thu May 11 13:00:43 2006 From: mariano.difelice at gmail.com (mardif) Date: 11 May 2006 10:00:43 -0700 Subject: Python memory deallocate In-Reply-To: <44636843$0$278$626a54ce@news.free.fr> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <-yy*V4mgr@news.chiark.greenend.org.uk> <1147355266.189030.131420@y43g2000cwc.googlegroups.com> <4463462a$0$297$626a54ce@news.free.fr> <1147358549.473182.89950@i40g2000cwc.googlegroups.com> <44636843$0$278$626a54ce@news.free.fr> Message-ID: <1147366843.222919.199700@q12g2000cwa.googlegroups.com> OK! i will test my app with python 2.5a2 thx From diffuser78 at gmail.com Tue May 2 15:02:50 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 2 May 2006 12:02:50 -0700 Subject: Wake on LAN and Shutdown for Windows and Linux Message-ID: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> I am using 8 computers on a small network. I have one Main computer which should be able to remotely start other computers. I used Wake on LAN to start them all. My Main computer is Linux. Other 4 are Windows and 3 are Linux. How can I shutdown Windows box from my Main (Linux) ? Also, How can I shutdown other Linux terminals from my Main (Linux) ? Help is appreciated. From DustanGroups at gmail.com Fri May 19 06:54:47 2006 From: DustanGroups at gmail.com (Dustan) Date: 19 May 2006 03:54:47 -0700 Subject: Which is More Efficient? In-Reply-To: References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> <1147990753.406649.80150@y43g2000cwc.googlegroups.com> <1147991742.990761.144730@j73g2000cwa.googlegroups.com> Message-ID: <1148036087.843911.307990@u72g2000cwu.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > > Obviously it takes a geek to know you have to time it, as opposed to > > any other task you could be talking about. > > wasn't the original question "my program uses a lot of CPU, and I want > to make it more efficient" ? what does "a lot of CPU" and "more > efficient" mean to you, and how do you know that your program uses "a > lot of CPU" ? The task manager says "CPU Usage: 100%" when the program is running, and only when the program is running. Efficiency is a measure of 2 things: CPU usage and time. If you measure just time, you're not necessarily getting the efficiency. > > From sybrenUSE at YOURthirdtower.com.imagination Thu May 11 09:01:45 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 11 May 2006 15:01:45 +0200 Subject: redirecting print to a a file References: <7JudnYwllewrrv7ZRVn-vA@comcast.com> <1147352171.658508.187490@y43g2000cwc.googlegroups.com> Message-ID: AndyL enlightened us with: > And what if I want to still send the output to stdout and just a log > it in the file as well? $ python some_program.py | tee output.log Or write a class that has a write() function and outputs to a file and to the original value of sys.stdout (IIRC that's in sys.__stdout__) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From chris at foote.com.au Tue May 16 09:29:01 2006 From: chris at foote.com.au (Chris Foote) Date: Tue, 16 May 2006 22:59:01 +0930 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> Message-ID: <1147788226.309918@teuthos> Claudio Grondi wrote: > Chris Foote wrote: > >> However, please note that the Python bsddb module doesn't support >> in-memory based databases - note the library documentation's[1] wording: >> >> "Files never intended to be preserved on disk may be created >> by passing None as the filename." >> >> which closely mirrors the Sleepycat documentation[2]: >> >> "In-memory databases never intended to be preserved on disk >> may be created by setting the file parameter to NULL." >> >> It does actually use a temporary file (in /var/tmp), for which >> performance for my purposes is unsatisfactory: >> >> # keys dictionary metakit bsddb (all using psyco) >> ------ ---------- ------- ----- >> 1M 8.8s 22.2s 20m25s[3] >> 2M 24.0s 43.7s N/A >> 5M 115.3s 105.4s N/A >> >> Cheers, >> Chris >> >> [1] bsddb docs: >> http://www.python.org/doc/current/lib/module-bsddb.html >> >> [2] Sleepycat BerkeleyDB C API: >> http://www.sleepycat.com/docs/api_c/db_open.html >> >> [3] Wall clock time. Storing the (long_integer, integer) key in >> string form "long_integer:integer" since bsddb doesn't support keys >> that aren't integers or strings. > > I have to admit, that I haven't wrote any own code to actually test > this, but if 20m25s for storing of a single MByte of strings in a > database table index column is really what you are getting, I can't get > rid of the feeling, that there is something elementary wrong with your > way doing it. Hi Claudio. 1M is one million, referring to the number of insertions of keys; not a Megabyte. I'm sorry that you took it that way :-( Berkeley DB is great for accessing data by key for things already stored on disk (i.e. read access), but write performance for each key-value pair is slow due to it being careful about flushing writes to disk by default. > Posting the code for your test cases appears to me to be the only option > to see what is the reason for the mystery you are getting here (this > will clarify also the other mysterious things considered by the posters > to this thread up to now). I agree that posting some test code would have proved useful, but the code is big and has too many interdependencies on external things (e.g. databases, threads & pyro RPC calls) to allow me to separate out examples easily. But if you go back to my original posting, I think my question was quite clear. Best regards, Chris From vinayakchitre at gmail.com Fri May 19 07:03:47 2006 From: vinayakchitre at gmail.com (Vinayakc) Date: 19 May 2006 04:03:47 -0700 Subject: Encode exception for chinese text Message-ID: <1148036627.832162.321340@38g2000cwa.googlegroups.com> Hi all, I am new to python. I have written one small application which reads data from xml file and tries to encode data using apprpriate charset. I am facing problem while encoding one chinese paragraph with charset "gb2312". code is: encoded_str = str_data.encode("gb2312") The type of str_data is The exception is: "UnicodeEncodeError: 'gb2312' codec can't encode character u'\xa0' in position 0: illegal multibyte sequence" Can anyone please give me direction to solve this isssue. Regards, Vinayakc From bdesth.quelquechose at free.quelquepart.fr Tue May 9 20:52:43 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 May 2006 02:52:43 +0200 Subject: problemi con POST In-Reply-To: <1147208587.275024.317410@i40g2000cwc.googlegroups.com> References: <1147208587.275024.317410@i40g2000cwc.googlegroups.com> Message-ID: <44610a77$0$2082$626a54ce@news.free.fr> Heavy a ?crit : > Ciao a tutti, > sto creando una applicazione in python, che deve fungere anche da > server web... > non ho assolutamente problemi a prendere i parametri di una 'GET', mi > limito a fare il parsing della URL, ma come faccio a prendere i > parametri di una 'POST'? io cerco di leggere dal socket di lettura > 'rfile' ma poi resto bloccato all'infinito perch? evidemente resta in > attesa di qualcosaltro... c'? gi? qualche metodo che mi pu? > aiutare?? oppure sapete darmi qualche dritta? grazie... > D?sol?, mais je n'ai rien compris (enfin, si : que tu avais des probl?mes pour parser une requ?te HTTP POST et que tu te retrouvais avec une lecture bloquante sur un socket, mais ce n'est pas avec ?a qu'on va pouvoir t'aider). Tu pourrais nous reposter ?a en english ?-) From deets at nospam.web.de Sat May 27 14:58:53 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 27 May 2006 20:58:53 +0200 Subject: Array? Please help. In-Reply-To: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> Message-ID: <4drlreF1ba60oU1@uni-berlin.de> Dr. Pastor schrieb: > I need a row of 127 bytes that I will use as a > circular buffer. Into the bytes (at unspecified times) > a mark (0 After some time the "buffer" will contain the last 127 marks. > (A pointer will point to the next byte to write to.) > What would be the Pythonic way to do the above? > Thanks for any guidance. Use a list, use append and slicing on it: max_size = 10 buffer = [] for i in xrange(100): buffer.append(i) buffer[:] = buffer[-max_size:] print buffer Diez From python at rcn.com Sat May 27 00:50:53 2006 From: python at rcn.com (Raymond Hettinger) Date: 26 May 2006 21:50:53 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> Message-ID: <1148705453.123243.167820@y43g2000cwc.googlegroups.com> akameswaran at gmail.com wrote: > Ok, this is really irritating me. I'm sure there are different ways of > doing this - I'm interested in the algo, not the practical solution, > I'm more trying to play with iterators and recursion. I want to create > a program that generates every possible combination of a set of a n > dice, with s sides. . . . > Any ideas? or better terms to google? cuz I've tried. There are several interesting tidbits in the ASPN Cookbook: http://aspn.activestate.com/ASPN/search?query=combinations§ion=PYTHONCKBK&type=Subsection http://tinyurl.com/frxqz Raymond From stijndesaeger at gmail.com Fri May 5 11:54:10 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 08:54:10 -0700 Subject: Tuple assignment and generators? In-Reply-To: <4c174hF13bbpoU1@uni-berlin.de> References: <1146826136.746268.4060@i40g2000cwc.googlegroups.com> <445b3960$1_3@news.bluewin.ch> <1146831804.396839.316070@v46g2000cwv.googlegroups.com> <1146839183.981537.216320@y43g2000cwc.googlegroups.com> <4c174hF13bbpoU1@uni-berlin.de> Message-ID: <1146844449.954124.12120@u72g2000cwu.googlegroups.com> > You've been told that quite a few times before that "is" is not intended for > what you used it. I got that. I was cleaning up some code that used "is" incorrectly immediately after. > Some people actually listen to what others tell. Others seem to be driven by > the deep desire to make even the tiniest bit of getting-a-grasp a public > affair. Not really. I always found python to be true to that -- admittedly elusive -- principle of least surprise up to now ("special cases aren't special enough to break the rules", maybe? I don't know. but then you figured that, right?), and was thrown off quite a bit by the behaviour described in one of the earlier posts, that is all. I wanted to ask people's explanations about it and learnt a few things on the way (thanks Dave). What did you get from all of this? From jeffshannon at gmail.com Sun May 7 22:26:51 2006 From: jeffshannon at gmail.com (jeffshannon at gmail.com) Date: 7 May 2006 19:26:51 -0700 Subject: utility functions within a class? In-Reply-To: <1147049176.712585.205560@j73g2000cwa.googlegroups.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> Message-ID: <1147055211.899384.323190@v46g2000cwv.googlegroups.com> You do *NOT* want to put double-underscores before and after a method name. That does not indicate a private method, it indicates a "magic method" -- something that has special meaning to Python. Thus, you have special methods like __init__(), __len__(), __getattr__(), __setattr__(), etc; all of these methods may be called *by Python* in certain specific circumstances, and allow you to customize how your objects respond to those circumstances. Naming methods that are *not* special "magic methods" using this naming convention is a very bad idea. On the other hand, methods with only a single or double *leading* underscore, and no trailing underscore(s), can be considered to express some degree of privacy. A single underscore, by convention, indicates an internal method or attribute, and that name will typically not be exported. A double underscore will trigger minimal name mangling; not only will the name not be exported, but it will be converted to ___, making it a bit more difficult to access from outside the class. (Access inside the class is via the unmangled name.) In this circumstance, I'd probably have methods _generate_head(self) and _generate_body(self). Don't mess with making them class/static methods unless it's important to be able to access them when you don't have any instance of the class available (and if you're calling them from inside a regular method, then you *do* have an instance available). Even if you don't end up referring to self or any instance attributes within the method, it's simpler to keep it as a normal method. --Jeff Shannon From chris.cavalaria at free.fr Thu May 4 04:55:39 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 04 May 2006 10:55:39 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com><4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> <445880e8$0$27057$626a54ce@news.free.fr> Message-ID: <4459c1e5$0$2617$636a55ce@news.free.fr> Fredrik Lundh a ?crit : > Christophe wrote: > > >>That's easy, since A is a symbolic constant know at compile time, and >>since it's a known mutable objet, the code once compiled will be >>equivalent to: >> >> >>> b = [[]] >> >> >>> # much later >> >>> b|0].append('1') > > > the OP talked about constants as names for immutable objects, not pre- > processor macros. but alright, using the "symbolic constant" approach, > what would this print ? > > >>> def foo(var): > ... var.append('1') > ... print var > ... > >>> b = [] > >>> foo(b) > >>> foo(b) I think you've made a mistake in your example. This is valid today's Python you know :) And it'll print more or less : ['1'] ['1', '1'] > and this ? > > >>> constant A = [] > >>> print A is A Obviously, False. From andychambers2002 at yahoo.co.uk Sun May 28 04:21:25 2006 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 28 May 2006 01:21:25 -0700 Subject: generating random passwords ... for a csv file with user details In-Reply-To: <1148802192.793574.209720@i40g2000cwc.googlegroups.com> References: <1148802192.793574.209720@i40g2000cwc.googlegroups.com> Message-ID: <1148804484.835931.123740@j33g2000cwa.googlegroups.com> import random def rand_str(len): chars = ''.join(['abcdefghijklmnopqrstuvwxyz', 'ABCDEFGHIJKLMNOPQRSTUVWXYZ', '1234567890', '_+']) # plus whatever additional characters you want return ''.join([random.choice(chars) for i in range(len)]) print rand_str(10) From johnjsal at NOSPAMgmail.com Mon May 15 15:24:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 19:24:16 GMT Subject: common practice for creating utility functions? In-Reply-To: References: Message-ID: John Salerno wrote: > John Salerno wrote: >> Just a quickie for today > > Another quick one I'll combine in this thread: How can I create two > separate conditions in a for loop? > > Such as this, which doesn't seem to work beyond string.punctuation: > > for char in string.punctuation or string.whitespace: I tried this: punc_space = string.punctuation + string.whitespace for char in punc_space: From claird at lairds.us Fri May 26 13:16:21 2006 From: claird at lairds.us (Cameron Laird) Date: Fri, 26 May 2006 17:16:21 +0000 Subject: Python for my mum References: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> <1148644991.633948.32260@j55g2000cwa.googlegroups.com> Message-ID: <5opjk3-dam.ln1@lairds.us> In article <1148644991.633948.32260 at j55g2000cwa.googlegroups.com>, vbgunz wrote: >maybe you can tell your moms what to do and what binaries to download >or maybe you can download them for her and either send it to her >through email or put it on a disc for her... I understand the Windows >XP installation binary is easy enough for anyone to get going. Just >follow the prompts. > >Once Python is installed, double clicking .py files would be almost >like clicking on executables. If a gui should pop up and the Python >installation went in OK, she should be able to see a Gui and not know >any different in regards to what exactly is happening in the >background... > >Start with the binary, get it installed and double click the .py files. >It should just work. Good luck! > I'm a leeeeettle surprised no one's mentioning the ActivePython distribution, which to me seems perfectly fitted for such situations. From lance at augustmail.com Tue May 16 11:11:37 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Tue, 16 May 2006 10:11:37 -0500 Subject: regex help Message-ID: <4469eba9$0$61166$ae4e5890@news.nationwide.net> I have the following table and I am trying to match percentage the 2nd column on the 2nd Tiger line (9.0). I have tried both of the following. I expected both to match but neither did? Is there a modifier I am missing? What changes do I need to make these match? I need to keep the structure of the regex the same. TIGER.append(re.search("TIGER\s{10}.*?(?:(\d{1,3}\.\d)\s+){2}", target_table).group(1)) TIGER.append(re.search("^TIGER.*?(?:(\d{1,3}\.\d)\s+){2}", target_table).group(1)) BASE - TOTAL TIGER 268 268 173 95 101 - 101 57 - 57 78 2 76 268 192 76 230 21 DOG 79 79 44 35 31 - 31 17 - 17 25 1 24 79 55 24 75 1 29.5 29.5 25.4 36.8 30.7 - 30.7 29.8 - 29.8 32.1 50.0 31.6 29.5 28.6 31.6 32.6 4.8 CAT 46 46 28 18 20 - 20 7 - 7 14 - 14 46 32 14 39 4 17.2 17.2 16.2 18.9 19.8 - 19.8 12.3 - 12.3 17.9 - 18.4 17.2 16.7 18.4 17.0 19.0 LAMB 32 32 23 9 10 - 10 8 - 8 12 - 12 32 20 12 28 1 11.9 11.9 13.3 9.5 9.9 - 9.9 14.0 - 14.0 15.4 - 15.8 11.9 10.4 15.8 12.2 4.8 TRIPOD 32 32 23 9 9 - 9 9 - 9 11 1 10 32 22 10 28 3 11.9 11.9 13.3 9.5 8.9 - 8.9 15.8 - 15.8 14.1 50.0 13.2 11.9 11.5 13.2 12.2 14.3 TIGER 24 24 16 8 5 - 5 10 - 10 7 - 7 24 17 7 18 2 9.0 9.0 9.2 8.4 5.0 - 5.0 17.5 - 17.5 9.0 - 9.2 9.0 8.9 9.2 7.8 9.5 From sjmachin at lexicon.net Tue May 16 02:18:55 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2006 23:18:55 -0700 Subject: using target words from arrays in regex, pythons version of perls 'map' In-Reply-To: <41mi62hih1d3i53nnhdkfi9tpil77bfdp7@4ax.com> References: <44691fc2$0$61162$ae4e5890@news.nationwide.net> <41mi62hih1d3i53nnhdkfi9tpil77bfdp7@4ax.com> Message-ID: <1147760335.159838.146390@v46g2000cwv.googlegroups.com> Think about how well the above solutions scale as len(targets) increases. 1. Make "targets" a set, not a list. 2. Have *ONE* regex which includes a bracketed match for a generic target e.g. ([A-Z\s]+) 3. Do *ONE* regex search, not 1 per target 4. If successful, check if the bracketed gizmoid is in the set of targets. It's not 100% apparent whether it is possible that there can be more than one target in the inappropriately named file2 (it is a string, isn't it?). If so, then write your own findall-like loop wrapped around steps 2 & 3 above. Compile the regex in advance. HTH, John From miki.tebeka at gmail.com Sun May 14 09:05:42 2006 From: miki.tebeka at gmail.com (Miki) Date: 14 May 2006 06:05:42 -0700 Subject: send an email with picture/rich text format in the body In-Reply-To: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> Message-ID: <1147611942.057703.211760@j73g2000cwa.googlegroups.com> Hello Anya, See http://docs.python.org/lib/node597.html IMO if you'll place the picture as 1'st MutliMime part the *some* email readers will show it like you want. HTH, Miki From sjmachin at lexicon.net Fri May 26 21:17:21 2006 From: sjmachin at lexicon.net (John Machin) Date: 26 May 2006 18:17:21 -0700 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com><44778e7f$1@nntp0.pdx.net> <127f61eluend535@corp.supernews.com> <127f7rrn8i2qea3@corp.supernews.com> Message-ID: <1148692641.456369.52330@j33g2000cwa.googlegroups.com> Grant> OTOH, it looks like I'm screwed either way. My python interpolator is so hopelessly slow it's useless in practice. It can only process 4 points per second and I need to process arrays of 10,000 to 50,000 elements. :( Pardon my utter ignorance of scipy, but are neither psyco nor pyrex any use? Cheers, John From bblais at bryant.edu Wed May 17 12:40:31 2006 From: bblais at bryant.edu (Brian Blais) Date: Wed, 17 May 2006 12:40:31 -0400 Subject: \t not working In-Reply-To: <1147883344.070704.127080@g10g2000cwb.googlegroups.com> References: <1147883344.070704.127080@g10g2000cwb.googlegroups.com> Message-ID: <446B51FF.3030103@bryant.edu> Alex Pavluck wrote: > I am just learning Python and I am using the book, "Thinking like a > Computer Scientist". There is an exercise that I am not able to get > working and it is really easy so I thought I would ask for help here. > > > Q: As an exercise, write a single string that: > Procuces > this > output. > > > A? > print "produces",'\n',"\t","this","\n","\t","output." > You could use: print "produces \n\t this \n\t\t output" bb -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From johnjsal at NOSPAMgmail.com Wed May 10 11:56:28 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 15:56:28 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: References: Message-ID: Bo Yang wrote: >> This matches all the 'ab' followed by an 'a', but it doesn't include >> the 'a'. What I'd like to do is find all the 'aba' matches. A regular >> findall() gives four results, but really there are seven. >> >> > I try the code , but I give seven results ! Sorry, I meant that findall() only returns 4 results when searching for 'aba', when there are actually seven instances of 'aba'. This doesn't involve the look-ahead RE. From sjmachin at lexicon.net Fri May 26 21:11:40 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 27 May 2006 11:11:40 +1000 Subject: stupid perl question In-Reply-To: References: <44778C05.9020701@grads.ece.mcmaster.ca> Message-ID: <4477A74C.6080605@lexicon.net> On 27/05/2006 9:51 AM, BJ?rn Lindqvist wrote: >> how can i split a string that contains white spaces and '_' >> >> any clue? > > If the white spaces and the '_' should be applied equivalently on the > input and you can enumerate all white space characters, you could do > like this: Yes, you could write out the whitespace characters for the 8-bit encoding of your choice, or you could find them using Python (and get some possibly surprising answers): >>> mkws = lambda enc, sz=256: "".join([chr(i) for i in range(sz) if chr(i).decode(enc, 'ignore').isspace()]) >>> mkws('cp1252') '\t\n\x0b\x0c\r\x1c\x1d\x1e\x1f \xa0' >>> mkws('latin1') '\t\n\x0b\x0c\r\x1c\x1d\x1e\x1f \x85\xa0' >>> mkws('cp1251') '\t\n\x0b\x0c\r\x1c\x1d\x1e\x1f \xa0' >>> mkws('ascii', 128) '\t\n\x0b\x0c\r\x1c\x1d\x1e\x1f ' and compare the last one with the result for the C locale: >>> "".join([chr(i) for i in range(256) if chr(i).isspace()]) '\t\n\x0b\x0c\r ' > > def split_helper(list, delims): > if not delims: > return list > ch = delims[0] > lst = [] > for item in list: > lst += split_helper(item.split(ch), delims[1:]) > return lst > > def split(str, delims): > return split_helper([str], delims) > >>>> split("foo_bar eh", "_ ") > ['foo', 'bar', 'eh'] > > Though I bet someone will post a one-line solution in the next 30 > minutes. :) Two one-liners, depending on what the OP really wants: >>> re.split(r"[\s_]", "foo_bar zot plugh _ xyzzy") ['foo', 'bar', '', '', '', '', '', 'zot', 'plugh', '', '', 'xyzzy'] which is what your ever-so-slightly-baroque effort does :-) or >>> re.split(r"[\s_]+", "foo_bar zot plugh _ xyzzy") ['foo', 'bar', 'zot', 'plugh', 'xyzzy'] Cheers, John From nobody at 127.0.0.1 Fri May 12 04:50:36 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 08:50:36 GMT Subject: syntax for -c cmd References: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> Message-ID: Fredrik Lundh wrote: > hint: > > $ python -c 'import sys; print sys.argv' 'else: print "no"' > > Yeah the man page knows all. About the only time I use python on the command line is with the timeit module, which evals all arguments given. Hence the confusion. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From bignose+hates-spam at benfinney.id.au Wed May 17 01:11:51 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 15:11:51 +1000 Subject: assignment in a for loop References: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> <1147841186.146299.114250@i40g2000cwc.googlegroups.com> Message-ID: <871wutp754.fsf@benfinney.id.au> "MackS" writes: [MackS, please don't top-post.] > Suppose I want to do modify all arguments which are passed to a > function. Do I need to use a list comprehension such as > > def f(arg1,arg2,arg3): > > arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)] > ... > > This would be awful when, eg, one adds an argument to the function > definition. It would require edition of the code at two different > locations. If you anticipate increasing the number of values passed to the function, and you're doing the same operation on all of them, why not pass in a list:: >>> def add_one_to_each(nums): ... """ Makes a new list with each value incremented by one. """ ... ... incremented_nums = [x+1 for x in nums] ... return incremented_nums ... >>> foo = [3, 5, 8] >>> bar = add_one_to_each(foo) >>> bar [4, 6, 9] -- \ "Some mornings, it's just not worth chewing through the leather | `\ straps." -- Emo Philips | _o__) | Ben Finney From spamspam at spam.eggs Tue May 9 11:37:19 2006 From: spamspam at spam.eggs (Ben C) Date: 9 May 2006 15:37:19 GMT Subject: clear memory? how? References: <4cb49uF15811rU1@uni-berlin.de> Message-ID: On 2006-05-09, Diez B. Roggisch wrote: > N/A wrote: > >> Hi all, >> I am learning Python. Just wondering how to clear saved memory in >> Python? Like in Matlab I can simply use "clear all" to clear all saved >> memory. > > You don't - python does it for you. It is called garbage collection. All you > have to to is get into granny-mode(tm): forget about things. That means: > once an object is not referenced by your code anymore, it will be cleaned > up. I think Matlab's "clear all" is more like what you might call "del all" in python. You could perhaps define it like this: def clearall(): all = [var for var in globals() if var[0] != "_"] for var in all: del globals()[var] This deletes any global not starting with an _, since it's probably inadvisable to delete this lot: {'__builtins__': , '__file__': '/etc/pythonstart', '__name__': '__main__', '__doc__': None} More correct I suppose might be something like this: def clearall(): all = [var for var in globals() if "__" not in (var[:2], var[-2:])] for var in all: del globals()[var] since I think magic things always start and end with __. Looking briefly at GNU octave which is similar to MatLab, clear all may also del all the locals; so you can do something similar with the builtin function locals(). From grante at visi.com Mon May 29 22:54:21 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 30 May 2006 02:54:21 -0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> Message-ID: <127ncut3mpadoc5@corp.supernews.com> On 2006-05-30, xkenneth wrote: > I'm writing a couple python applications that use the serial port > (RS-232) quite extensively. Is there any way I can monitor all activity > on the serial port and have it printed as the transactions occur? I'm > trying to reverse engineer a microcontroller serial routine and I'd > like to see any response the chip sends back. What OS? Under windows you can use portmon from sysinternals. I don't think there's anything for Linux. I've noclue about OS X. -- Grant Edwards grante at visi.com From jimlewis at miclog.com Sun May 21 22:43:01 2006 From: jimlewis at miclog.com (Jim Lewis) Date: 21 May 2006 19:43:01 -0700 Subject: Pyrex installation on windows XP: step-by-step guide References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> <1148251275.211468.221460@g10g2000cwb.googlegroups.com> Message-ID: <1148265781.367465.323470@j73g2000cwa.googlegroups.com> Thanks. I had done that but it seems I had to remove "install". Now it works. From bignose+hates-spam at benfinney.id.au Mon May 1 09:51:31 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 01 May 2006 23:51:31 +1000 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> Message-ID: <874q09etuk.fsf@benfinney.id.au> "Holger" writes: > ---------------------------------------------------- > TypeError: addFile() takes exactly 1 argument (2 given) > ---------------------------------------------------- > > ---------------------------------------------------- > import sys > > class KeyBase: > def addFile(file): > print "initialize the base with lines from this file" You've misunderstood -- or never followed -- the tutorial, especially how Python does object methods. Please follow the whole tutorial through, understanding each example as you work through it. You'll then have a solid basis of knowledge to go on with. -- \ "We are not gonna be great; we are not gonna be amazing; we are | `\ gonna be *amazingly* amazing!" -- Zaphod Beeblebrox, _The | _o__) Hitch-Hiker's Guide To The Galaxy_, Douglas Adams | Ben Finney From michele.petrazzo at gmail.com Thu May 11 12:07:19 2006 From: michele.petrazzo at gmail.com (Michele Petrazzo) Date: 11 May 2006 09:07:19 -0700 Subject: Python memory deallocate References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <1147347601.597292.15220@j73g2000cwa.googlegroups.com> <1147353348.028544.143470@u72g2000cwu.googlegroups.com> Message-ID: <1147363639.855800.87930@j33g2000cwa.googlegroups.com> Heiko Wundram wrote: > As was said before: as long as you keep a reference to an object, the object's > storage _will not be_ reused by Python for any other objects (which is > sensible, or would you like your object to be overwritten by other objects > before you're done with them?). Besides, even if Python did free the memory > that was used, the operating system wouldn't pick it up (in the general case) > anyway (because of fragmentation issues), so Python keeping the memory in an > internal free-list for new objects is a sensible choice the Python developers > took here. This isn't true. Just tried with python 2.5a2 and: d:\python25\python.exe >>> a = range(1000 * 100 *100) # 173 MB >>> del a # 122MB So now, like you saied, if I try to allocate another memory chunk, python'll re-use it... But this isn't true: >>> b = range(100 * 100 * 100) # 126 MB >>> del b # 122MB >>> exit() # :) d:\python25\python.exe >>> b = range(100 * 100 * 100) # 19 MB Do why python don't reuse the freed memory and re-allocate 4 MB (126 - 122)? For me it's a problem... > --- Heiko. Bye, Michele From tbrkic at yahoo.com Tue May 9 07:57:01 2006 From: tbrkic at yahoo.com (glomde) Date: 9 May 2006 04:57:01 -0700 Subject: What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY? Message-ID: <1147175821.309279.271730@j33g2000cwa.googlegroups.com> Hi I would like to extend python so that you could create hiercical tree structures (XML, HTML etc) easier and that resulting code would be more readable. The syntax i would like is something like the below: # Example creating html tree '*!*' is an operator that creates an new node '*=*' is an operator that sets an attribute. bodyNode = body() *!* bodyNode: *=* color = blue *=* bg = white for i in headings: *!* H1(heading[i]): This would translate to something like this in python: bodyNode = body() if True: bodyNode.attr['color'] = blue bodyNode.attr['bg'] = white for i in headings: if True: bodyNode.append(H1(heading[i])) I think that with the added syntax you get better overview on how your tree looks like. But the thing is how to implement my added syntax. I dont want to mess with Python source code to add the syntax. So I searched a bit on the net and think there might be three alternatves. 1. MetaClasses. I tried to understand them but my head almost exploded :-). But my conclusion was that it is not possible with metaclasses. Since this is a real syntax change. 2. Tokenize.py. I modify tokenize.py to recognize my new operators '#!#' and '#=#' and then I write a parser that exports the code. This option I understand somewhat how to implement. But I would reduce my own code for the parser, so is there any parser that can handle tokenize.py input? So that I could somehow write rules for my code. 3. Use PLY or any other python parser. Write rules for my language. But would I need to write rules that can handle the whole python languager? Then this seems to be overkill. I would just like to recognize my added syntax and convert that. So I would really like to have a rule file that handles python and then add rules for my syntax. Are there any Python rule file for the python language and a python parser for it? Then I could just add my syntax to the rule file and be able to create the output. I would be very thankfull for any hints or thougts on how to do it. Best regards, G From bblais at bryant.edu Thu May 11 08:38:31 2006 From: bblais at bryant.edu (Brian Blais) Date: Thu, 11 May 2006 08:38:31 -0400 Subject: which windows python to use? Message-ID: <44633047.8010007@bryant.edu> Hello, Are there any recommendations for which Windows python version to use? I'd like to see a pros-and-cons description of each, given that different uses might dictate different versions. The versions I know (and there are surely more) are: 1) download from www.python.org 2) enthought 3) activepython Are there advantages/disadvantages? I have used enthought before, but it seems as if they are not at 2.4, and may lag behind in versions (which may not be a bad thing). Any other recommendations? thanks, Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From DierkErdmann at mail.com Tue May 16 08:56:29 2006 From: DierkErdmann at mail.com (DierkErdmann at mail.com) Date: 16 May 2006 05:56:29 -0700 Subject: Google-API Bad-Gateway-Error In-Reply-To: References: <1147783046.944898.43470@i39g2000cwa.googlegroups.com> Message-ID: <1147784189.292674.145010@i39g2000cwa.googlegroups.com> It's quite strange, after calling the script several times it started to work; but sometimes the error occurs again. Maybe google has technical probs. Dierk From chris.cavalaria at free.fr Thu May 4 04:48:33 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 04 May 2006 10:48:33 +0200 Subject: Because of multithreading semantics, this is not reliable. In-Reply-To: <1146691613.911363.242620@e56g2000cwe.googlegroups.com> References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <1146691613.911363.242620@e56g2000cwe.googlegroups.com> Message-ID: <4459c03b$0$2633$636a55ce@news.free.fr> OlafMeding at gmail.com a ?crit : > Tim and Grant > > > if q.empty(): > return > > > Of course you explanation is understood and ideally should be included > as a note in the Python documentation. And the "not reliable" should > be removed from the documentation! > > Anyway, many thanks for your explanations (I feel "safer" now). > > Olaf > You could go as far as to say that since the function return itself isn't wrapped in a mutex, the value can be obsolete before even the function returns. ie that code can sometimes return the wrong value : def empty(self): self.acquire_mutex() result = self.count == 0 self.release_mutex() return result before that line, some other thread added a value ! From onurb at xiludom.gro Tue May 9 08:16:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 14:16:47 +0200 Subject: List of lists of lists of lists... In-Reply-To: References: Message-ID: <44608890$0$18266$636a55ce@news.free.fr> ?ngel Guti?rrez Rodr?guez wrote: > I would like to have a list of lists N times deep, and my solution is (in > pseudocode): > > def deep(x): > a=[x] > return a Hint : what's exactly the difference between deep(x) and [x] ? > mylist=[] > for N: mylist=deep(mylist) > > Is there a more elegant way to do it? for N: mylist = [mylist] > The maine idea is: from a list having the numbre of steps along N > dimensions, generate a list with an item at each possible point. > > Example 1: N=2 list=[2,3] result=[[1,2],[1,2],[1,2]] > Example 2: N=3 list=[3,1,2] result=[[[1,2,3]],[[1,2,3]]] I'm afraid I don't understand. Could you forgive my stupidity and re-explain this a bit more clearly ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From johnjsal at NOSPAMgmail.com Tue May 2 14:52:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 18:52:48 GMT Subject: simultaneous assignment In-Reply-To: References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> Message-ID: <4UN5g.2038$No6.43609@news.tufts.edu> Steve R. Hastings wrote: > Anyway, the major point I want you to take away from all this: it doesn't > matter whether the "is" test succeeds or fails, if all you care about is > the *value* of a variable. Python reuses object references to save > memory, because this doesn't affect expressions that only care about the > *value*. Your logic tests only care about True vs. False; they don't care > about the underlying implementation of how True and False are expressed. Great explanation. Thanks! > This is a simple problem. I suggest you loop over the list and simply > count how many values are false, and how many are true. I just wrote and > tested this function in about a minute. Yeah, after trying some crazy things, I just wrote it this way: def truth_test(seq): truth = 0 for item in seq: if item: truth += 1 if truth == 1: return True else: return False Not sure I like having to keep a counter though, but the other stuff I did was really convoluted, like checking to see if the first item was True, and if it was, popping it from the list and iterating over the rest of the items (needless to say, the in-place change wasn't helpful). From mcPas.De.Spam at mclaveauPas.De.Spam.com Mon May 1 10:32:45 2006 From: mcPas.De.Spam at mclaveauPas.De.Spam.com (Michel Claveau) Date: Mon, 01 May 2006 16:32:45 +0200 Subject: python and xulrunner References: <1146439953.280364.309130@e56g2000cwe.googlegroups.com> <1146485029.892845.45380@i40g2000cwc.googlegroups.com> Message-ID: Hi! My answer is (perhaps a little) hard, but... I read pages and pages, and traversed sites and sites. Conclusion : - XPcom functions, perhaps, on some special configurations. - xulrunner is an idea (vapor?) But, in production, nothing of all that is usable (for the moment?) -- @-salutations Michel Claveau From jstroud at ucla.edu Sat May 20 16:10:31 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 20 May 2006 13:10:31 -0700 Subject: Question about Python on Mac In-Reply-To: <1148073591.308980.289300@u72g2000cwu.googlegroups.com> References: <1148073591.308980.289300@u72g2000cwu.googlegroups.com> Message-ID: elventear wrote: > Hello, > > I am working with Python 2.4.3 built from source courtesy of Fink. So > far so good, until now. I want to use a module called GMPY > (http://gmpy.sf.net/). I am able to build correctly the module, but > once I try to import it I get the following error: > > ImportError: Failure linking new module: gmpy.so: Symbol not found: > ___gmpn_sub_nc > Referenced from: /sw/lib/libgmp.3.dylib > Expected in: dynamic lookup > > The weird thing is that just for kicks I tried building with Python > that comes with MacOSX (py2.3) and it works. It builds and it loads > fine. Anybody have an idea why this would happen? Any ideas how to > solve this? In the worse case scenario, can I use the binary (gmpy.so) > built with against Python 2.3 with Python 2.4.3 (It seems to load > correctly but I don't know if I should expect any meltdowns later on) > > I would appreciate any suggestions. > > Thanks. > I think fink is not detecting the gmp (GNU multiple precision arithmetic library) dependency. Try: % fink install gmp Then try building gmpy with /sw/bin/python. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From birchb at ozemail.com.au Wed May 10 00:15:31 2006 From: birchb at ozemail.com.au (birchb at ozemail.com.au) Date: 9 May 2006 21:15:31 -0700 Subject: Deferred Evaluation in Recursive Expressions? In-Reply-To: References: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> <1147189028.751527.157640@j73g2000cwa.googlegroups.com> Message-ID: <1147234531.245540.307990@g10g2000cwb.googlegroups.com> That's a good fix. But I have misgivngs about needing a global name registry. I need to support anonymous types and types with local (lexical) scope. For example: def makeAnonymousRecursiveType(T): # anonymous type expression with local scope LinkedList = (T, lambda: LinkedList) return LinkedList local = makeAnonymousRecursiveType(int) From bruno at modulix.org Fri May 26 07:16:14 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 26 May 2006 04:16:14 -0700 Subject: __getattr__ and functions that don't exist In-Reply-To: <44762cf8$1@nntp.zianet.com> References: <44762cf8$1@nntp.zianet.com> Message-ID: <1148642174.788458.136020@j55g2000cwa.googlegroups.com> class Parrot(object): class _dummy(object): def __init__(self, obj, name): self.name = name self.obj = obj def __call__(self, *args, **kw): print "dummy %s for %s" % (self.name, self.obj) print "called with %s - %s" % (str(args), str(kw)) def __getattr__(self, name): return self._dummy(self, name) hth From stijndesaeger at gmail.com Fri May 5 06:48:56 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 03:48:56 -0700 Subject: Tuple assignment and generators? In-Reply-To: <4c0o60F13ut8cU1@uni-berlin.de> References: <1146821724.732068.268960@g10g2000cwb.googlegroups.com> <1146824577.242547.315600@y43g2000cwc.googlegroups.com> <4c0o60F13ut8cU1@uni-berlin.de> Message-ID: <1146826136.746268.4060@i40g2000cwc.googlegroups.com> > """ > E.g., after "a = 1; > b = 1", > a and b may or may not refer to the same object with the value one, > depending on the implementation, > """ But when in a specific implementation this property _does_ hold for ints having value 1, I expect the same behaviour for ints with other values than 1. I guess I'm kind of weird that way. From deets at nospam.web.de Tue May 2 13:50:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 May 2006 19:50:25 +0200 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <4bpj08F12b91rU1@uni-berlin.de> Message-ID: <4bpkfbF12kmh3U1@uni-berlin.de> > Hmm, classes still scare me a little, but I should consider this. The > only thing is, it is not known in advance if the propositions are true > or false, you have to figure that out yourself based on the combination > of the statements given. I don't know if this changes the idea behind > your Proposition class...I'll have to give it some more thought. No, that was just an example to illustrate the comparison semantics. I don't know enough about your problem to model it more appropriately. Besides, you can of course change that self._v of a proposition. Diez From g.horvath at gmx.at Thu May 11 13:08:45 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 11 May 2006 19:08:45 +0200 Subject: Install libraries only without the program itself In-Reply-To: <1147354784.387775.51270@i40g2000cwc.googlegroups.com> References: <1147354784.387775.51270@i40g2000cwc.googlegroups.com> Message-ID: Serge Orlov schrieb: > I believe it's better to keep *everything* on the file server. Suppose Certainly! > your OS is windows and suppose you want to keep everything in s:/tools. > The actions are: > 3. Create little dispatcher s:/tools/win32/client.py: > #!s:/tools/python24-win32/python.exe > import sys > sys.path[0] = "s:/tools/client-1.0.0" > import client I also had to set the paths for the imports and current directory manually (why?). This worked for me: #!y:/python24-win32/python24.dll import sys import os sys.path = ["","y:\\","y:\\python24-win32\\lib\\site-packages","y:\\python24-win32\\DLLs","y:\\python24-win32\\lib","y:\\python24-win32\\lib\\plat-win","y:\\python24-win32\\lib\\lib-tk","y:\\python24-win32", "y:\\python24-win32\\lib\\site-packages\\win32", "y:\\python24-win32\\lib\\site-packages\\win32\\lib", "y:\\python24-win32\\lib\\site-packages\\Pythonwin", "Y:\\python24-win32\\python24.zip","y:\\python24-win32"] os.chdir("y:\\") import hobel300 5. I also had to copy all required dlls from the c:\winnt directory (for example pywintypes24.dll) into the current directory. Thanks for this solution, works great, did not know that you can run python programs even without a python installation on the local machine! Nice! -- Servus, Gregor http://www.gregor-horvath.com From claudio.grondi at freenet.de Sat May 13 05:46:14 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Sat, 13 May 2006 11:46:14 +0200 Subject: How to install pyTrix? In-Reply-To: <44652d37$0$15982$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <44652d37$0$15982$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: DeepBlue wrote: > Hi all, > > can any1 please tell me how to install pyTrix? > > thx! The first step should be to get it, but how can it be got? Claudio From martin at v.loewis.de Fri May 12 01:22:54 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Fri, 12 May 2006 07:22:54 +0200 Subject: A Unicode problem -HELP In-Reply-To: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> Message-ID: <44641baf$0$8865$9b622d9e@news.freenet.de> manstey wrote: > 1. I have # -*- coding: UTF-8 -*- as my first line. > 2. In Wing IDE I have set Default Encoding to UTF-8 > 3. I have imported codecs and opened and written my file, which doesn't > have a BOM, as encoding=UTF-8 > 4. I have written a dictionary for translation, with entries such as > {'F':u'\u0254'} and a function to do the translation > > Everything works fine, except that my output file, when loaded in > unicode aware emeditor has > (u'F', u'\u0254') I couldn't quite follow this description: what is "your output file" (in what step is it created?), and how does (u'F', u'\u0254') get into this file? What is the precise Python statement that produces that line of output? > So my questions are: > 1. How do I do this? Most likely, you use (directly or indirectly) the repr() function to convert a tuple into that string. You shouldn't do that; instead, you should format the elements of the tuple yourself, e.g. through print >>f, u"('%s', '%s')" % value Regards, Martin From bearophileHUGS at lycos.com Fri May 19 17:07:02 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 May 2006 14:07:02 -0700 Subject: bitstream In-Reply-To: <1148065311.920568.6870@i40g2000cwc.googlegroups.com> References: <1148065311.920568.6870@i40g2000cwc.googlegroups.com> Message-ID: <1148072822.023173.79420@j33g2000cwa.googlegroups.com> Maybe this is what you are looking for: http://cheeseshop.python.org/pypi/BitBuffer/0.1 Bye, bearophile From diffuser78 at gmail.com Fri May 5 09:48:19 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 5 May 2006 06:48:19 -0700 Subject: cross platform libraries In-Reply-To: References: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> Message-ID: <1146836899.678804.168000@g10g2000cwb.googlegroups.com> I went to this webpage http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 Isn't it supposed to run on the network and close the connected machine. Every help is appreciate, Dennis Lee Bieber wrote: > On 4 May 2006 09:57:15 -0700, diffuser78 at gmail.com declaimed the > following in comp.lang.python: > > > I am using python on a linux terminal. > > > > I want to shutdown a remote windows box. I found a script which does > > something like this. My question is can we use windows libraries in > > linux as follows .... > > > > import win32api > > import win32con > > import win32netcon > > import win32security > > import win32wnet > > > That set... HIGHLY UNLIKELY... They all rely upon having the M$ > kernel DLLs available... > > Now, if the remote box is running a telnet server, you might be able > to telnet over (logging in as the boxes admin account) and initiate a > shutdown from it... (I seem to have a "shutdown.exe" on my system). > -- > 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 kentilton at gmail.com Sun May 7 23:57:37 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sun, 07 May 2006 23:57:37 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147030835.498512.314110@u72g2000cwu.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hew3d4.1x2eems1pb7o5N%aleaxit@yahoo.com> <1147030835.498512.314110@u72g2000cwu.googlegroups.com> Message-ID: olsongt at verizon.net wrote: > Alex Martelli wrote: > >>Steve R. Hastings wrote: >> ... >> >>>>But the key in the whole thread is simply that indentation will not >>>>scale. Nor will Python. >>> >>>This is a curious statement, given that Python is famous for scaling well. >> >>I think "ridiculous" is a better characterization than "curious", even >>if you're seriously into understatement. >> > > > When you consider that there was just a big flamewar on comp.lang.lisp > about the lack of standard mechanisms for both threading and sockets in > Common Lisp (with the lispers arguing that it wasn't needed) I find it > "curious" that someone can say Common Lisp scales well. > We're talking about whether the language can grow to have new capabilities, while you are talking about libraries, and specifically whether different implementations have the same API. They all have sockets, just not the same API, probably because, to be honest that is not something that belongs in a /language/ API. But those of us who bounce from implementation to implementation see a standard APi as saving us some conditional compilation and (effectively) rolling our own common API out of dii implementation's socket APIs, so a few socket gurus are working on a standard now. And yes, they will be able to do this with Common Lisp as it stands. Try to think a little more rigorously in these discussions, Ok? Thx, kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From larry.bates at websafe.com Fri May 19 10:52:12 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 19 May 2006 09:52:12 -0500 Subject: Script to make Windows XP-readable ZIP file In-Reply-To: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> Message-ID: pac wrote: > I'm preparing to distribute a Windows XP Python program and some > ancillary files, > and I wanted to put everything in a .ZIP archive. It proved to be > inordinately > difficult and I thought I would post my solution here. Is there a > better one? > > Suppose you have a set of files in a directory c:\a\b and some > additional > files in c:\a\b\subdir. Using a Python script, you would > like to make a Windows-readable archive (.zip) that preserves this > directory structure, and where the root directory of the archive is > c:\a\b. In other words, all the files from c:\a\b appear in the > archive > without a path prefix, and all the files in c:\a\b\subdir have a path > prefix of \subdir. > > This looks like it should be easy with module zipfile and the handy > function os.walk. Create a zip file, call os.walk, and add the files > to > the archive like so: > > import os > import zipfile > > z = > zipfile.ZipFile(r"c:\a\b\myzip.zip",mode="w",compression=zipfile.ZIP_DEFLATED) > > for dirpath,dirs,files in os.walk(r"c:\a\b"): > for a_file in files: > a_path = os.path.join(dirpath,a_file) > z.write(a_path) # Change, see below > z.close() > > This creates an archive that can be read by WinZip or by another Python > script > that uses zipfile. But when you try to view it with the Windows > compressed folder > viewer it will appear empty. If you try to extract the files anyway > (because > you know they are really there), you get a Windows Security Warning and > XP > refuses to decompress the folder - XP is apparently afraid it might be > bird flu > or something. > > If you change the line marked #Change to "z.write(a_path,file)", > explicitly naming > each file, now the compressed folder viewer will show all the files in > the archive. > XP will not treat it like a virus and it will extract the files. > However, the > archive does not contain a subdirectory; all the files are in a single > directory. > > Some experimentation suggests that Windows does not like any filename > in the > archive that begins with either a drive designator like c:, or has a > path containing > a leading slash like "\a\b\afile.txt". Relative paths like > "subdir\afile.txt" are > okay, and cause the desired behavior when the archive is extracted, > e.g., a new directory subdir is created and afile.txt is placed in it. > > Since the method ZipFile.write needs a valid pathname for each file, > the correct > solution to the original problem entails messing around with the OS's > current > working directory. Position the CWD in the desired base directory of > the archive, > add the files to the archive using their relative pathnames, and put > the CWD back > where it was when you started: > > import os > import zipfile > > z = > zipfile.ZipFile(r"c:\a\b\myzip.zip",mode="w",compression=zipfile.ZIP_DEFLATED) > > cwd = os.getcwd() > os.chdir(base_dir) > try: > for dirpath,dirs,files in os.walk(''): # This starts the walk at > the CWD > for a_file in files: > a_path = os.path.join(dirpath,a_file) > z.write(a_path,a_path) # Can the second argument be > omitted? > z.close() > finally: > os.chdir(cwd) > > This produces an archive that can be extracted by Windows XP using its > built-in > capability, by WinZip, or by another Python script. Now that I have > the solution it > seems to make sense, but it wasn't at all obvious when I started. > > Paul Cornelius > Others have addressed your specific question, I wanted to make a more general suggestion. You should really take a look at Inno Installer and py2exe combination for creating .zip library and Windows distribution. I PROMISE it will be worth your time on future projects. Rolling your own installer will take much more time/effort over the long haul. -Larry Bates From steven.klass at gmail.com Tue May 9 18:17:09 2006 From: steven.klass at gmail.com (rh0dium) Date: 9 May 2006 15:17:09 -0700 Subject: Dictionaries -- ahh the fun.. (newbie help) Message-ID: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> Hi all, Can someone help me out. I am trying to determing for each run whether or not the test should pass or fail but I can't seem to access the results .. Alternatively can someone suggest a better structure ( and a lesson as to the reasoning ) that would be great too!! cells={} cells["NOR3X1"]= { 'run' : [ 'lvs', 'drc' ], 'results' : [{ 'lvs' : 'pass' }, { 'drc' : 'fail' }] } cells["OR3X1"] = { 'run' : [ 'lvs' ], 'results' : [{ 'lvs' : 'pass' }] } cells["AND3X1"] = { 'run' : [ 'drc' ], 'results' : [{ 'drc' : 'fail' }] } def main(): for cell in cells: print cell for run in cells[cell]['run']: print cell, run, "should", cells[cell]['results'].index(run) I would expect the following OR3X1 OR3X1 lvs should pass NOR3X1 NOR3X1 lvs should pass NOR3X1 drc should fail AND3X1 AND3X1 drc should fail From kkylheku at gmail.com Tue May 16 13:51:35 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 16 May 2006 10:51:35 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147801895.830394.17130@v46g2000cwv.googlegroups.com> Xah Lee wrote: > Tabs vs Spaces can be thought of as parameters vs hard-coded values, or > HTML vs ascii format, or XML/CSS vs HTML 4, or structural vs visual, or > semantic vs format. In these, it is always easy to convert from the > former to the latter, but near impossible from the latter to the > former. Bahaha, looks like someone hasn't thought things through very well. Spaces, under a mono font, offer greater precision and expressivity in achieving specific alignment. That expressivity cannot be captured by tabs. The difficulty in converting spaces to tabs rests not in any bridgeable semantic gap, but in the lack of having any way whatsoever to express using tabs what the spaces are expressing. It's not /near/ impossible, it's /precisely/ impossible. For instance, tabs cannot express these alignments: /* * C block * comment * in a common style. */ (lisp (nested list with symbols and things)) (call to a function with many parameters) ;; how do you align "to" and "with" using tabs? ;; only if "to" lands on a tab stop; but dependence on specific tab stops ;; destroys the whole idea of tabs being parameters. To do these alignments structurally, you need something more expressive than spaces or tabs. But spaces do the job under a mono font, /and/ they do it in a completely unobtrusive way. If you want to do nice typesetting of code, you have to add markup which has to be stripped away if you actually want to run the code. Spaces give you decent formatting without markup. Tabs do not. Tabs are only suitable for aligning the first non-whitespace character of a line to a stop. Only if that is the full extent of the formatting that you need to express in your code can you acheive the ideal of being able to change your tab parameter to change the indentation amount. If you need to align characters which aren't the first non-whitespace in a line, tabs are of no use whatsoever, and proportional fonts must be banished. From phddas at yahoo.com Sun May 7 22:45:16 2006 From: phddas at yahoo.com (Gary Wessle) Date: 08 May 2006 12:45:16 +1000 Subject: evaluation of > Message-ID: <87bqu99qv7.fsf@localhost.localdomain> Hi what does the i > a in this code mean. because the code below is giving False for all the iteration. isn't suppose to evaluate each value of i to the whole list? thanks a = range(8) i = 0 while i < 11: print i > a i = i + 1 False False False False False False False False False False False thanks From mivabe at nospam.invalid Wed May 17 16:46:36 2006 From: mivabe at nospam.invalid (Mivabe) Date: Wed, 17 May 2006 22:46:36 +0200 Subject: Python script windows servcie References: <1147866489.128112.100710@y43g2000cwc.googlegroups.com> Message-ID: Serge Orlov submitted this idea : > Mivabe wrote: >> >> No-one who can help me or did i visit the wrong group for this >> 'problem'? > > Indeed. Next time you'd better ask in a windows specific list: Ke, thnx :-) -- No line here today .... Posted by news://news.nb.nu From pmartin at snakecard.com Fri May 5 12:09:16 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 11:09:16 -0500 Subject: Is this a legal / acceptable statement ? References: <2AI6g.10201$9c6.5375@dukeread11> <-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> <445b67bb$0$16736$626a54ce@news.free.fr> <35K6g.8733$B42.4422@dukeread05> <445b7730$0$23440$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > Philippe Martin wrote: >> bruno at modulix wrote: >> >> >>>Philippe Martin wrote: >>>(snip) >>> >>>>l_init really is a boolean parameter and l_value a value that _might_ >>>>exist in a shelve. >>>> >>>>So I just want to have a parameter to a method so if the first value >>>>tested is false (l_init) then the second (l_value) does not get tested >>>>... because it is the second in the statement and only seems to get >>>>evaluated if the first one is true. >>> >>>s/seems to get/is/ >>> >>>But this is a really unpythonic way to do things IMHO. Either use a >>>try/except block (probably the most straightforward solution), or, as in >>>Larry's post, test for the existence of 'l_value' in locals(). >>> >>>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('@')])" >> >> >> Well, that was the question - I wanted to avoid that because I'm already >> in a try/except and do not like to imbricate them too much. > > Then reads Fredrik's answer and this: > ''' > Help on module shelve: > > (...) > > DESCRIPTION > A "shelf" is a persistent, dictionary-like object. > (...) > """ > > What about : > > if shelf.has_key('l_value'): > ... > > ?-) > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" Yes that would make sense. Philippe From fredrik at pythonware.com Fri May 19 10:07:34 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 16:07:34 +0200 Subject: noob import question References: <4d5vqaF18i4l1U1@uni-berlin.de> <16532b502ad5283d1e53f8782898aaf8@gmail.com> Message-ID: "PA" wrote: > Restrictive or not, what's so fundamentally devious in putting a class > declaration in a separate file whose name is that of the declared class > (class Queue -> Queue.py)? nothing. > Sounds like a handy way of organizing your code, no? sure, if you prefer to do things that way. the Python style guide (PEP 8) used to recommend naming a module that con- tains only one class (plus support factories and other functions) after the class, but now recommends using other names for the module, to avoid confusion. for some reason, some people seem to treat the latest edition of each PEP as a divine truth, and all earlier editions as works of the devil. I guess they reset their brain before each svn update. From jmcmonagle at velseis.com.au Wed May 31 19:57:13 2006 From: jmcmonagle at velseis.com.au (John McMonagle) Date: Thu, 01 Jun 2006 09:57:13 +1000 Subject: beginner: using parameter in functions In-Reply-To: References: Message-ID: <1149119833.26711.12.camel@kuepper.vels-int.com.au> On Wed, 2006-05-31 at 23:24 +0000, 3rdshiftcoder wrote: > hi- > > i am having trouble using parameter values in my function and to be honest a > little trouble with > member variables. i am trying to pass in the argument 'd' representing > delete. > what the code will do is if it is 'd' it will make a delete query template > string. > if it is an 'i' then insert query etc. > > this is the results of my attempt to print the contents of the parameter > values. > <__main__.getQryStr instance at 0x01151D50> ('d',) me mad > > > (and on a side note if i dont include the *args i get an invalid number of > parameters supplied message.) > why is it returning the value in this format ('d',) ? > i cant get x == d > i guess that value 'd' is stored in a tuple and i'd like to get it out of > there. > > so basically the function returns nope as it stands > > python is sure different from other languages i have used. > > thanks for any help, > jim > Try, the following: class getQryStr: def __init__(self,op): print op self.x = 'd' def returnStr(self, *args): print '%s %s me mad' % (self.x,args) if self.x == 'd': s = Template("delete from columndef where tblid = $tblid and colname = $colname") else: return 'nope' #this else is just for illustration and testing d = dict(tblid=t.tblid.getText(), colname=t.colName.getText()) print s.substitute(d) return s Regards, John -- This message has been scanned for viruses and dangerous content by MailScanner, and is believed to be clean. From nobody Thu May 25 18:17:43 2006 From: nobody (Erik Johnson) Date: Thu, 25 May 2006 16:17:43 -0600 Subject: __getattr__ and functions that don't exist Message-ID: <44762cf8$1@nntp.zianet.com> Maybe I just don't know the right special function, but what I am wanting to do is write something akin to a __getattr__ function so that when you try to call an object method that doesn't exist, it get's intercepted *along with it's argument*, in the same manner as __getattr__ intercepts attributes references for attributes that don't exist. This doesn't quite work: >>> class Foo: ... def __getattr__(self, att_name, *args): ... print "%s%s" % (att_name, str(tuple(*args))) ... >>> f = Foo() >>> f.bar bar() >>> f.bar(1,2,3) bar() Traceback (most recent call last): File "", line 1, in ? TypeError: 'NoneType' object is not callable >>> f.bar() bar() Traceback (most recent call last): File "", line 1, in ? TypeError: 'NoneType' object is not callable Is there some other special function like __getattr__ that does what I want? Thanks, -ej From me+python at modelnine.org Thu May 18 02:43:54 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 18 May 2006 08:43:54 +0200 Subject: Reference Counts In-Reply-To: <1147933695.752344.195350@u72g2000cwu.googlegroups.com> References: <1147933695.752344.195350@u72g2000cwu.googlegroups.com> Message-ID: <200605180843.54265.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 08:28 schrieb raghu: > #!/usr/bin/python > > import sys > global a > > print "Total Reference count at the start =",sys.gettotalrefcount() > a=1 > print "a ref count =",sys.getrefcount(a) > b=a > print "a ref count =",sys.getrefcount(a) > > del a > del b > > print "Total Reference count at the end =",sys.gettotalrefcount() > ... > Total Reference count at the start = 16538 > a ref count = 49 > a ref count = 50 > Total Reference count at the end = 16540 > [6416 refs] > > There are a few questions that I am having on this. > > (1) Why should 'a' reference count be 49 before I even made an > assignment ? Because "1" is a special integer. Small integers (-1..100, but this depends on the Python version) are interned, similar to strings, so there are already references to the integer object before you assign it to "a" (at least one; 1 is such a "magic" constant that you can guess that there are already other references to it in other places of the stdlib, which has loaded when your script runs, so it's not hard to imagine that 1 already has 48 references outside of your program). > (2) The Total Reference count at the end has increased by 2 . Why ? Am > I leaking memory ? No. I'd guess that the names "a" and "b" were interned as strings (as they are used as dict lookup keys in the globals() dict), and you have one reference to each interned object. > (3) I have read somewhere that an increase in sys.gettotalrefcount() is > indicative of a memory leak ? Aint that correct ? Yes. It is correct if consecutive runs of your algorithm always yield a higher sys.gettotalrefcount() for each run. In this case (where you run your "algorithm" only once), it isn't. It just shows you some of the innards of the Python runtime machinery. Execute the following script to see the result of a memory leak: >>> import sys x = {} i = 0 def test(): global x, i x[i] = "test" i += 1 # Forget to clean up x... LEAK a reference to "test"! for j in xrange(10000): print "Before", j, ":", sys.gettotalrefcount() test() print "After", j, ":", sys.gettotalrefcount() >>> And, the following (slightly altered) program doesn't exhibit this memory leak: >>> import sys x = {} i = 0 def test(): global x, i x[i] = "test" i += 1 del x[i-1] # Properly clean up x. for j in xrange(10000): print "Before", j, ":", sys.gettotalrefcount() test() print "After", j, ":", sys.gettotalrefcount() >>> I don't have a debug build of Python at hand, so I can't run them now. But, if you're interested in the results, you'll certainly do that yourself. ;-) --- Heiko. From lahirister at gmail.com Wed May 24 15:44:41 2006 From: lahirister at gmail.com (lahirister at gmail.com) Date: 24 May 2006 12:44:41 -0700 Subject: simple print is not working.. In-Reply-To: <1148499666.824598.313720@i40g2000cwc.googlegroups.com> References: <1148499666.824598.313720@i40g2000cwc.googlegroups.com> Message-ID: <1148499881.048367.210390@j73g2000cwa.googlegroups.com> lahiris... at gmail.com wrote: Sorry typo: Script is like this: #!/usr/bin/python fsfile = open('/tmp/fs_info.al', 'r') for line in fsfile.readlines(): print line fsfile.close() *not* fsfiles as I typed in original post. > What is wrong with this script? > > #!/usr/bin/python > fsfile = open('/tmp/fs_info.al', 'r') > for line in fsfiles.readlines(): > print line > fsfile.close() > > > #./get_fs_info.py > File "./get_fs_info.py", line 4 > print line > ^ > SyntaxError: invalid syntax > > > Any ideas? > > Thanks > AL From NOatkinwSPAM at rpi.edu Sun May 7 14:30:26 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 14:30:26 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> Message-ID: <87mzdt4ri5.fsf@rpi.edu> Alexander Schmolck writes: > [trimmed groups] > > Ken Tilton writes: > >> yes, but do not feel bad, everyone gets confused by the /analogy/ to >> spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief >> period I swore off the analogy because it was so invariably misunderstood. >> Even Graham misunderstood it. > > Count me in. > >> >> But it is such a great analogy! >> >> > but what's the big deal about PyCells? >> > Here is 22-lines barebones implementation of spreadsheet in Python, >> > later I create 2 cells "a" and "b", "b" depends on a and evaluate all >> > the cells. The output is >> > a = negate(sin(pi/2)+one) = -2.0 >> >> > b = negate(a)*10 = 20.0 >> >> Very roughly speaking, that is supposed to be the code, not the output. So you >> would start with (just guessing at the Python, it has been years since I did >> half a port to Python): >> >> >> v1 = one >> a = determined_by(negate(sin(pi/2)+v1) >> b = determined_by(negate(a)*10) >> print(a) -> -2.0 ;; this and the next are easy >> print(b) -> 20 >> v1 = two ;; fun part starts here >> print(b) -> 40 ;; of course a got updated, too >> > > do you mean 30? > > I've translated my interpretation of the above to this actual python code: > > from math import sin, pi > v1 = cell(lambda: 1) > a = cell(lambda:-(sin(pi/2)+v1.val), dependsOn=[v1]) > b = cell(lambda: -a.val*10, dependsOn=[a], > onChange=lambda *args: printChangeBlurp(name='b',*args)) > print 'v1 is', v1 > print 'a is', a # -2.0 ;; this and the next are easy > print 'b is', b # 20 > v1.val = 2 # ;; fun part starts here > print 'v1 now is', v1 > print 'b now is', b # 30 ;; of course a got updated, too > > > I get the following printout: > > v1 is 1 > a is -2.0 > b is [cell 'b' changed from <__main__.unbound object at 0xb4e2472c> to 20.0, > it was not bound]20.0 > [cell 'b' changed from 20.0 to 30.0, it was bound ] v1 now is 2 > b now is 30.0 > > Does that seem vaguely right? > >> The other thing we want is (really inventing syntax here): >> >> on_change(a,new,old,old-bound?) print(list(new, old, old-bound?) > > Is the above what you want (you can also dynamically assign onChange later > on, as required or have a list of procedures instead)? > >> >> Then the print statements Just Happen. ie, It is not as if we are just hiding >> computed variables behind syntax and computations get kicked off when a value >> is read. Instead, an underlying engine propagates any assignment throughout >> the dependency graph before the assignment returns. > > Updating on write rather than recalculating on read does in itself not seem > particularly complicated. > >> My Cells hack does the above, not with global variables, but with slots (data >> members?) of instances in the CL object system. I have thought about doing it >> with global variables such as a and b above, but never really seen much of >> need, maybe because I like OO and can always think of a class to create of >> which the value should be just one attribute. > > OK, so in what way does the quick 35 line hack below also completely miss your > point? > > > # (NB. for lispers: 'is' == EQ; '==' is sort of like EQUAL) > > def printChangeBlurp(someCell, oldVal, newVal, bound, name=''): > print '[cell %r changed from %r to %r, it was %s]' % ( > name, oldVal, newVal, ['not bound', 'bound '][bound]), > > _unbound = type('unbound', (), {})() # just an unique dummy value > def updateDependents(dependents): > seen = {} > for dependent in dependents: > if dependent not in seen: > seen[dependent] = True > dependent.recalculate() > updateDependents(dependent._dependents) > class cell(object): > def __init__(self, formula, dependsOn=(), onChange=None): > self.formula = formula > self.dependencies = dependsOn > self.onChange = onChange > self._val = _unbound > for dependency in self.dependencies: > if self not in dependency._dependents: > dependency._dependents.append(self) > self._dependents = [] > def __str__(self): > return str(self.val) > def recalculate(self): > newVal = self.formula() > if self.onChange is not None: > oldVal = self._val > self.onChange(self, oldVal, newVal, oldVal is not _unbound) > self._val = newVal > def getVal(self): > if self._val is _unbound: > self.recalculate() > return self._val > def setVal(self, value): > self._val = value > updateDependents(self._dependents) > val = property(getVal, setVal) > > > > 'as Here's how one of the cells examples might look in corrupted Python (this is definitely not executable): class FallingRock: def __init__(self, pos): define_slot( 'velocity', lambda: self.accel * self.elapsed ) define_slot( 'pos', lambda: self.accel * (self.elapsed ** 2) / 2, initial_position = cell_initial_value( 100 ) ) self.accel = -9.8 rock = FallingRock(100) print rock.accel, rock.velocity, rock.pos # -9.8, 0, 100 rock.elapsed = 1 print rock.accel, rock.velocity, rock.pos # -9.8, -9.8, -9.8 rock.elapsed = 8 print rock.accel, rock.velocity, rock.pos # -9.8, -78.4, -627.2 Make sense? The idea is to declare what a slot's value represents (with code) and then to stop worrying about keeping different things synchronized. Here's another of the examples, also translated into my horrific rendition of Python (forgive me): class Menu: def __init__(self): define_slot( 'enabled', lambda: focused_object( self ).__class__ == TextEntry and focused_object( self ).selection ) Now whenever the enabled slot is accessed, it will be calculated based on what object has the focus. Again, it frees the programmer from having to keep these different dependencies updated. -- This is a song that took me ten years to live and two years to write. - Bob Dylan From anton.vredegoor at gmail.com Mon May 8 04:14:44 2006 From: anton.vredegoor at gmail.com (Anton Vredegoor) Date: Mon, 08 May 2006 10:14:44 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147030835.498512.314110@u72g2000cwu.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hew3d4.1x2eems1pb7o5N%aleaxit@yahoo.com> <1147030835.498512.314110@u72g2000cwu.googlegroups.com> Message-ID: <445efe7d$1@usenet.zapto.org> olsongt at verizon.net wrote: > When you consider that there was just a big flamewar on comp.lang.lisp > about the lack of standard mechanisms for both threading and sockets in > Common Lisp (with the lispers arguing that it wasn't needed) I find it > "curious" that someone can say Common Lisp scales well. In comp.lang.python there are often discussions about which is the best web framework or what is the best gui. There seems to be some common meme in these kinds of discussions and the lambda controversy. I'm even ready to expand the concept even more and include documentation problems and polymorphic typing. So what is the big advantage of using parens then that is making people give up documenting their code by naming functions? (See, I'm getting into the right kind of lingo for discussing these kind of questions) Well, there seems to be some advantage to conceptually decoupling a function from what it is doing *now* (which can be easily named) and what it is doing in some other situation. Naming things is only a ballast and makes the mental model not "fit the brain" (introducing pythonic terminology here for the lispers). This is a lot like polymorphic functions. For example an adding function sometimes adds integers and sometimes floats or complex variables and it can be defined just once without specifying which type of parameters it is going to get. I assume this to be a piece of cake for most lispers and pythoneers, but possibly this could still confuse some static typers. An anonymous function is like a polymorphic function in that it is possible to make the "mental model" about it polymorphic, instead of just its parameters. This enables the lispers to just "take what it does and paste it where that needs to be done" (inventing crypto speak here). This is a very effective way of handling operations and it would surprise me if not 99 percent of the Python coders do things mentally this way too and only add names and documentation at the last possible moment (mental compile time documentation procedure). So here we're integrating mental models concerning polymorphism into the way we talk and think about code, and naming things explicitly always seems to be a burden. But now we let the other side of our brain speak for a moment, it was always the side that translated everything we wanted to say to each other here into mental Unicode so that we can hear what the others are saying (further diving into the linguistic pit I am digging here). Yes, communication is what suffers from *not* naming things, and right after it documentation and standardization. How else are we going to communicate our findings verbally to the non coders and the trans coders? Also naming functions and variables can help us create appropriate mental models that 'fix' certain things in place and keep them in the same state, because now they are 'documented'. This promotes people being able to work together and also it enables measuring progress, very important aspects for old world companies who won't understand the way things are evolving (even if they seem to have roaring success at the moment). Not to say that I invented something new, it was always a theme, but now it's a meme,(he, he), the conflict between the scripture and the mysticism. It's such a pity that everyone understands some way or another that mysticism is the way things work but that none wants to acknowledge it. What am I doing here coding Python one might ask, well, the knowledge has to be transfered to my brain first *somehow*, and until someone finds a better way to do that or until there is so much procedural information in my head that I can start autocoding (oh no) that seems to be the better option. Anton From nobody at 127.0.0.1 Fri May 19 23:29:49 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 20 May 2006 03:29:49 GMT Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <1148073990.938267.320410@38g2000cwa.googlegroups.com> Message-ID: John Bokma wrote: > Edward Elliott wrote: > >>>> like "from X import *" which are generally frowned on in python while >>>> 'use MOD qw(id)' is encouraged in perl. >>> >>> Not by me, and I doubt it is in general. >> >> Well it's all over the Perl Cookbook. > > Yeah, sure, all over. 125 occurences in 78 recipes. Sure looks like all over to me. > Maybe check the book again. It is used in some > examples, sure. And it even explains how it works. Yep, 125 times. In 78 recipes. Out of 105 total recipes with 'use'. I'd say a 3:1 ratio is pretty strong encouragement. > Don't forget that most > of the book was written around 1998. Yes, 8 years ago. Doesn't matter. It's still the standard example reference. People use it heavily. They don't magically know what parts are now deprecated. > You can even find examples on my site that use imported functions (which I > will fix, because I frown upon it :-) ). But I doubt you can find a > majority in the perl community that *encourages* the use of imported > functionality. I can readily believe that the "community" frequenting the newsgroups, mailing lists, and blogs don't encourage it anymore. But that's a tiny fraction of all perl programmers, and most of them have no exposure to this little clique. For many people, whatever the cookbook says goes. If it's wrong, update it. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From alisonken1 at gmail.com Tue May 2 17:46:04 2006 From: alisonken1 at gmail.com (alisonken1) Date: 2 May 2006 14:46:04 -0700 Subject: ConfigParser and multiple option names In-Reply-To: References: Message-ID: <1146606364.446770.250880@j33g2000cwa.googlegroups.com> Florian Lindner wrote: > Hello, > since ConfigParser does not seem to support multiple times the same option > name, like: > > dir="/home/florian" > dir="/home/john" > dir="/home/whoever" Another option would be to switch to the XMLParser library and use an XML file for the configuration. That way, you can build using the same name: #==== config_file.xml ==== "/home/florian" "/home/john" "/home/whoever" {other options} #==== config_file.xml ==== There are also several tutorials Uche Ogbuji's Akara site has some excellent XML tutorials which include python XML processing. From andrew.arobert at gmail.com Thu May 25 12:42:30 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 12:42:30 -0400 Subject: regex/lambda black magic In-Reply-To: References: <127be5or10v59e9@corp.supernews.com> Message-ID: <127bnkqc8pdoef5@corp.supernews.com> Max Erickson wrote: > Try getting rid of the lamba, it might make things clearer and it > simplifies debugging. Something like(this is just a sketch): > > > max > Yeah.. trying to keep everything on one line is becoming something of a problem. To make this easier, I followed something from another poster and came up with this. import re,base64 # Evaluate captured character as hex def ret_hex(value): return base64.b16encode(value) def ret_ascii(value): return base64.b16decode(value) # Evaluate the value of whatever was matched def eval_match(match): return ret_ascii(match.group(0)) # Evaluate the value of whatever was matched # def eval_match(match): # return ret_hex(match.group(0)) out=open(r'e:\pycode\sigh.new2','wb') # Read each line, pass any matches on line to function for # line in file.readlines(): for line in open(r'e:\pycode\sigh.new','rb'): print (re.sub('[^\w\s]',eval_match, line)) The char to hex pass works but omits the leading % at the start of each hex value. ie. 22 instead of %22 The hex to char pass does not appear to work at all. No error is generated. It just appears to be ignored. From python.list at tim.thechases.com Thu May 4 08:45:13 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 May 2006 07:45:13 -0500 Subject: Python function returns: In-Reply-To: References: Message-ID: <4459F759.2050806@tim.thechases.com> > In Python, there does not seem to be an easy way to have > functions return multiple values except it can return a > list such as: strHostname, nPortNumber, status = > get_network_info (strIpAddress, strHostname, nPortNumber) > Am I missing something obvious? Is there a better, or > more standard way to return values from functions? This *is* the "better" and "standard" way to do it. There are *worse* ways to emulate C/C++ if you want, but it takes being *more* obtruse. Because certain objects are mutable, nothing[*] prevents you from doing something like x = [] def foo(q): x.append(42) foo(x) print repr(x) which will return that you've added "42" to your list. However, it's ugly and relies on side effects. They Python way (that you deride) is much clearer. Your input goes in the parameters, and your output gets assigned the way functions are intended to work. Unambiguous. I don't expect to call a sine function, and get the result in the parameter; rather I expect to get it as the result of the function. Okay...unless I'm working in Assembly language (but that's one of many reasons *why* I choose Python ;) Just a few thoughts, -tkc [*] nothing other than being given dirty looks by folks reading your code... From apardon at forel.vub.ac.be Tue May 9 07:52:04 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 May 2006 11:52:04 GMT Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> Message-ID: Op 2006-05-09, Scott David Daniels schreef : > Kaz Kylheku wrote: >> I've been reading the recent cross-posted flamewar, and read Guido's >> article where he posits that embedding multi-line lambdas in >> expressions is an unsolvable puzzle. >> >> So for the last 15 minutes I applied myself to this problem and come up >> with this off-the-wall proposal for you people. Perhaps this idea has >> been proposed before, I don't know. > > Well, ask yourself, what is the complexity, and what is the > benefit. You are solving a problem that causes very little > pain, and introducing a mechanism that is likely to inspire > thousands of lines of unmaintainable code. Essentially, a > rule that says, "if it is not a simple expression, pick a > name for it" is just not a bad idea. Well I guess that seems a good rule of thumb. The problem is that even a simple "expression" sometimes requires a name in python or turns it into a more complex function. Take the following example: def incr_cnt_by_one(obj): obj.cnt += 1 IMO that is simple enough not to require a name. But it is almost impossible to put this behaviour in a lambda. If you do you end up with something like: lambda obj: setattr(obj, 'cnt', obj.cnt + 1) So maybe a general lambda is indeed impossible in python. A pity IMO, but not that big a deal. But the limit that certain statements are not expressions makes that you sometimes require a name even with some simple stuff like: def Raise_ValueError(): raise ValueError RegisterErrorFunction(Raise_ValueError) What would be so horrible if we could do the following: RegisterErrorFunction(lambda: raise ValueError) or treat_all(aList, lambda obj: obj.cnt += 1) -- Antoon Pardon From eurleif at ecritters.biz Mon May 8 21:10:39 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 08 May 2006 21:10:39 -0400 Subject: Multi-line lambda proposal. In-Reply-To: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> Message-ID: <445feb5c$0$3700$4d3efbfe@news.sover.net> Kaz Kylheku wrote: > But suppose that the expression and the multi-line lambda body are > reordered? That is to say, the expression is written normally, and the > mlambda expressions in it serve as /markers/ indicating that body > material follows. This results in the most Python-like solution. I think your proposal is good, but it might be more easily understood if we gave names to the lambdas, so that they could be easily picked out in the source code. It could look something like this: func(lambda foo): foo: print "Foo!" Come to think of it, maybe we could put the lambdas before the statement they're used in instead of in front of it. That could look something like this: lambda foo: print "Foo!" func(lambda foo) Then again, it would probably be simpler to reuse an existing block-starting keyword for the purpose. Maybe something like this? def foo(): print "Foo!" func(foo) From OlafMeding at gmail.com Mon May 8 09:33:14 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 8 May 2006 06:33:14 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> Message-ID: <1147095194.029310.68260@e56g2000cwe.googlegroups.com> Tim > I did this under a debug build of Python Perhaps this is the reason why you were not able to reproduce the problem. Could you try again with a standard build of Python? I am a bit surprised that nobody else has tried running the short Python program above on a hyper-threading or dual core / dual processor system. Olaf From 4zumanga at gmail.com Tue May 23 13:27:19 2006 From: 4zumanga at gmail.com (4zumanga) Date: 23 May 2006 10:27:19 -0700 Subject: Guide to using python for bash-style scripting Message-ID: <1148405239.840908.120910@j33g2000cwa.googlegroups.com> I have a bunch of really horrible hacked-up bash scripts which I would really like to convert to python, so I can extend and neaten them. However, I'm having some trouble mapping some constructs easily, and was wondering if anyone know of a guide to mapping simple uses of command line programs to python. For an example, the kind of thing I am thinking of are things like (yes, this is horrible code). # These are a run of a program I have written ./proggy -test1 > out1 ./proggy -test2 > out2 #Do some simple manipulation of the output. grep Node out1 > new_out1 grep Node out2 > new_out2 diff out1 out2 From steve at hastings.org Tue May 2 23:42:29 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 02 May 2006 20:42:29 -0700 Subject: what is the 'host' for SMTP? References: <44581205$0$25583$c3e8da3@news.astraweb.com> Message-ID: On Tue, 02 May 2006 22:12:31 -0400, John Salerno wrote: > If I want to write a cgi script that reads the contents of an HTML form > and emails it to me, what would I use as the host parameter for my SMTP > instance? Take a look at your email client. Find where it specifies the server for outgoing mail. Use whatever it says there. For example, I am a customer of blarg.net; I am therefore permitted to use mail.blarg.net, which has a mail server running on it. If your ISP is example.com, you probably will be using one of these: mail.example.com smtp.example.com But it really could be anything: norwegianblue.example.com lovelyplumage.example.com > The example in the docs is 'localhost', but I don't know what > that means or refers to. "localhost" is a standard UNIX/Linux alias for "my computer's address". It will be bound to 127.0.0.1, which is a special, magic address that can stand in for your computer's actual address. (Thus the old joke about "hey, try to hack my firewall! Here's the address: 127.0.0.1 If someone runs an attack script against that address, they are attacking their own computer.) If you have an SMTP server running on your computer, then you could use "localhost" and it will work. Otherwise, not. > I imagine I would have to use something that > was tied to me specifically, but tied to what? My computer? My email > address? SMTP is a protocol. You can talk SMTP to any computer that has an SMTP server running. The standard port number for SMTP is port 25. These days, most SMTP servers won't just let anyone use them to send email just anywhere; an SMTP server configured to allow that is called an "open relay" and spammers love to find them. If you are using email, then as I said above, your email client should have an SMTP server filled in already, and you are already using it every time you send email. So I suggest you use that. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From Bulkan at gmail.com Mon May 15 04:20:44 2006 From: Bulkan at gmail.com (placid) Date: 15 May 2006 01:20:44 -0700 Subject: Windows Copy Gui In-Reply-To: References: Message-ID: <1147681244.730350.327070@j33g2000cwa.googlegroups.com> Tim Golden wrote: > [placid] > > | Just wondering if anyone knows how to pop up the dialog that windows > | pops up when copying/moving/deleting files from one directory to > | another, in python ? > > http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html#shell thanks, thats what i was after > > 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 ptmcg at austin.rr._bogus_.com Mon May 22 21:05:40 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 23 May 2006 01:05:40 GMT Subject: Too big of a list? and other problems References: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> Message-ID: "Brian" wrote in message news:1148343552.037687.214420 at j55g2000cwa.googlegroups.com... > First off, I am sorry for cluttering this group with my inept > questions, but I am stuck again despite a few hours of hair pulling. > Don't apologize for getting stuck, especially after you have made an honest effort at solving your own problems. > I have a function (below) that takes a list of html pages that have > images on them (not porn but boats). This function then (supposedly) > goes through and extracts the links to those images and puts them into > a list, appending with each iteration of the for loop. The list of > html pages is 82 items long and each page has multiple image links. > When the function gets to item 77 or so, the list gets all funky. > Sometimes it goes empty, and others it is a much more abbreviated list > than I expect - it should have roughly 750 image links. > > When I looked at it while running, it appears as if my regex is > actually appending a tuple (I think) of the results it finds to the > list. My best guess is that the list is getting too big and croaks. 750 elements is really pretty modest in the universe of Python lists. This should not be an issue. > Since one of the objects of the function is also to be able to count > the items in the list, I am getting some strange errors there as well. > > Here is the code: > > def countPics(linkList): > foundPics = [] > count = 0 > for link in linkList: > picPage = > urllib.urlopen("http://continuouswave.com/whaler/cetacea/" + > link) > count = count +1 > print 'got page', count > html = picPage.read() > picPage.close() > pics = re.compile(r"images/.*\.jpeg") > foundPics.append(pics.findall(html)) > #print len(foundPics) > print "found", len(foundPics), "pictures" > print foundPics > > Again, I sincerely appreciate the answers, time and patience this group > is giving me. > > Thank you for any help you can provide in showing me where I am going > wrong. > Brian > I'm not overly familiar with the workings of re.findall so I ran these statements on the Python command line: >>> r = re.compile("A.B") >>> print r.findall("SLDKJFOIWUEAJBLJEQUSAUBSLJF:SDFA_B") ['AJB', 'AUB', 'A_B'] >>> print list(r.findall("SLDKJFOIWUEAJBLJEQUSAUBSLJF:SDFA_B")) ['AJB', 'AUB', 'A_B'] >>> print r.findall("SLDKJFOIWUEAJBLJEQUSAUBSLJF:SDF") ['AJB', 'AUB'] >>> print r.findall("SLDKJFOIWUEAJBLJEQUSSLJF:SDF") ['AJB'] >>> print type(r.findall("SLDKJFOIWUEAJBLJEQUSSLJF:SDF")) Everything looks just like one would expect. A minor nit is that you *don't* have to compile your pics regexp in the body of the loop. Move the pics = re.compile(r"images/.*\.jpeg") statement to before the start of the for loop - you can safely reuse it on each successive web page without having to recompile (this is the purpose of compiling re's in the first place - otherwise, you could just call re.findall(r"images/.*\.jpeg",html). Compiling the regexp saves some processing in the body of the loop.) But this should not account for your described odd behavior. How is countPics being called? Are you accidentally calling it multiple times? This would explain why the list of found pics goes back to zero (since you reset it at the start of the function). -- Paul From onurb at xiludom.gro Tue May 23 06:45:59 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 23 May 2006 12:45:59 +0200 Subject: Name conflict in class hierarchy In-Reply-To: <44724152$1@nntp0.pdx.net> References: <44717552$0$10541$636a55ce@news.free.fr> <44724152$1@nntp0.pdx.net> Message-ID: <4472e853$0$7645$626a54ce@news.free.fr> Scott David Daniels wrote: > bruno at modulix wrote: > >> Ralf Muschall wrote: >> >>> Jeffrey Barish wrote: >>> >>> [overriding of base class member functions by subclass] .... >>> In Python, a function not intended to be overriden should be either >>> have a name starting with an underscore >> >> >> actually with *two* underscores. The single-leading-underscore naming >> scheme is the convention for 'protected' (read: 'implementation, not >> API') attributes. > > > The double-underscore is there to generate names that are unlikely to > accidentally conflict. Yes, I do know this, and uses it when appropriate (that is : almost never) I was just correcting Ralf's wrong statement about the single leading underscore convention meant to denote "functions not intended to be overriden". -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From scott.daniels at acm.org Sun May 28 13:52:25 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 28 May 2006 10:52:25 -0700 Subject: Array? Please help. In-Reply-To: References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> <4478bd43$1@nntp0.pdx.net> Message-ID: <4479df10$1@nntp0.pdx.net> Dr. Pastor wrote: > Scott David Daniels wrote: >> Dr. Pastor wrote: >>> I need a row of 127 bytes that I will use as a >>> circular buffer. Into the bytes (at unspecified times) >>> a mark (0>> After some time the "buffer" will contain the last 127 marks. >> Sounds a lot like homework. > No it is not home work. OK, taking you at your word, here's one way: class Circular(object): def __init__(self): self.data = array.array('b', [0] * 127) self.point = len(self.data) - 1 def mark(self, value): self.point += 1 if self.point >= len(self.data): self.point = 0 self.data[self.point] = value def recent(self): result = self.data[self.point :] + self.data[: self.point] for n, v in enumerate(result): if v: return result[n :] return result[: 0] # an empty array -- --Scott David Daniels scott.daniels at acm.org From tim.peters at gmail.com Sat May 20 00:33:20 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 20 May 2006 00:33:20 -0400 Subject: DO NOT USE file() (was Re: altering an object as you iterate over it?) In-Reply-To: <446e8a54$0$5326$c3e8da3@news.astraweb.com> References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <446e8a54$0$5326$c3e8da3@news.astraweb.com> Message-ID: <1f7befae0605192133m1760cb91wfb8dee9e4936c2ad@mail.gmail.com> [John Salerno, on the difference between `open` and `file`] > Interesting. What is the difference between them now? In 2.5 `file` is unchanged but `open` becomes a function: >>> file >>> open From dave at waveform.plus.com Tue May 2 14:05:20 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 02 May 2006 18:05:20 GMT Subject: using ftplib References: <4456743d$0$2563$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: <44579f60$0$2576$ed2619ec@ptn-nntp-reader02.plus.net> Steve Holden wrote: > John Salerno wrote: > [...] > > > > So if I already have files on the server and I want to change file > > permissions, do I need to mess with TYPE A/TYPE I commands, or are > > those strictly for when you transfer files? Because I just did a > > quick test of changing file permissions through my FTP program, > > and it still sent a TYPE A command in the process. I know that the > > retr and stor methods might do this automatically, but if I don't > > need to use those, and just need to use transfercmd (assuming this > > is the right method to use when changing file permissions), do I > > need to manually send a TYPE A/I command as well? > > The answer is "probably not", but a better answer is "try it in the > interactive interpreter and see". As far as I recall your speculation is indeed correct: a TYPE command is only necessary before a transfer (it's only used to transform data passing over the secondary data connection). I'm reasonably certain you don't need *anything* before a SITE command (like SITE CHMOD), not even PORT or PASV (unless the specific SITE command being invoked requires a data transfer, which CHMOD shouldn't). But as Steve suggests, the best way to know for sure is to give it a whirl and see what happens :-) Incidentally, you might like to experiment with the command line ftp client. On both Linux and Windows, the "quote" command can be used to send commands "raw" to the FTP server. For example: ftp> quote SITE CHMOD 755 afile.py Dave. -- From cktsoi at school.hk Mon May 15 01:32:24 2006 From: cktsoi at school.hk (Jacky) Date: Mon, 15 May 2006 13:32:24 +0800 Subject: Web framework to recommend Message-ID: Hi all, I just started learning Python and would like to starting writing some web-based applications with Python. I did have pretty much experience with doing so with PHP and Java, but Python seems a bit different for me. Do you guys have some good web framework to recommend? (I don't want to use CGI mode) Thanks a lot. -- Jacky From grante at visi.com Sat May 27 01:19:04 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 05:19:04 -0000 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com> <44778e7f$1@nntp0.pdx.net> <127f61eluend535@corp.supernews.com> <127f7rrn8i2qea3@corp.supernews.com> <127fagudgh3fa7e@corp.supernews.com> Message-ID: <127foa8lceavnc2@corp.supernews.com> On 2006-05-27, Robert Kern wrote: > Grant Edwards wrote: > >> I found another module that claims to do what I want >> >> http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/griddata.html >> >> But, no matter what data I pass, I get either all zeros or all >> NaNs back. :/ >> >> I'm 0 for 3 now. > > I pointed you to > > http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data > > earlier. Does that not do what you want? Yes, after installer newer versions of things and straightening out some other issues. -- Grant Edwards grante Yow! Are we on STRIKE yet? at visi.com From micklee74 at hotmail.com Tue May 2 03:38:13 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 2 May 2006 00:38:13 -0700 Subject: strip newlines and blanks In-Reply-To: References: <1146551463.451811.266960@j73g2000cwa.googlegroups.com> Message-ID: <1146555493.669199.217990@j73g2000cwa.googlegroups.com> thanks..and sorry, i am using the web version of google groups and didn't find an option i can edit my post, so i just removed it.. thanks again for the reply.. From sxn02 at yahoo.com Tue May 16 12:53:33 2006 From: sxn02 at yahoo.com (Sori Schwimmer) Date: Tue, 16 May 2006 09:53:33 -0700 (PDT) Subject: Wrong args and issuing a SIGUSR1 signal Message-ID: <20060516165333.84026.qmail@web32902.mail.mud.yahoo.com> Hi All, I finally put my hands on a GUI-less Linux box and tried the little signal sending experiment. It gives the same! I'm left wondering what is the frame object... Regards, Sorin Schwimmer __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From cvanarsdall at mvista.com Tue May 16 13:14:00 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 16 May 2006 10:14:00 -0700 Subject: [silly] Does the python mascot have a name ? In-Reply-To: References: Message-ID: <446A0858.7050904@mvista.com> Steve wrote: > > Well, so Monty it is ! ...btw, did you know, the Camel > (http://dev.perl.org/perl6/rfc/343.html) doesn't have a name either ? ...looks > like Duke (http://www.java.com/en/dukeszone/) is the only dude with a name > ...but then duke is not an animal (wtf is it ?), so it had to be called something ! > > Well, we could call the perl camel Joe but I don't know if the perlcores (read: hardcore PERL users) would be down for that ;) .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From tundra at tundraware.com Wed May 10 15:03:51 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: 10 May 2006 15:03:51 EDT Subject: [ANN] tdir 1.69 Released And Available Message-ID: <1bq9j3-q86.ln1@eskimo.tundraware.com> 'tdir' Version 1.69 is released and available at: http://www.tundraware.com/Software/tdir/ A FreeBSD port update has also been submitted. What's New ---------- This version introduces the -D option which supresses "dotfile/dir" display. What Is 'tdir'? --------------- 'tdir' is a reimplementation and enhancement of the old 'xdir' CP/M utility from Ancient Times. 'tdir' is an advanced directory display utility written in Pure Python, and runs on both *nix and Win32 systems.\ With 'tdir' you can display directories sorted by file "extension", display directory trees, and separate directories from files in the output listing. From aleaxit at yahoo.com Mon May 8 01:09:35 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 22:09:35 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <1vspxcmldcqa5.t1b4abyraqom.dlg@40tude.net> <1heytyi.lope5l1p029gfN%aleaxit@yahoo.com> <19qhkvgj0bdmg.1ex2haasqrgrj.dlg@40tude.net> <1heyw5k.1997033mne3xrN%aleaxit@yahoo.com> Message-ID: <1hezmfi.5fnajr1t7vuvfN%aleaxit@yahoo.com> Frank Buss wrote: > Alex Martelli wrote: > > > Not sure what the &key means here, but omitting that > > > > def black_white(function, limit): > > def result(x,y): > > if function(x, y) > limit: return 1.0 > > else: return 0.0 > > return result > > &key is something like keyword arguments in Python. And looks like you are Ah, thanks. > right again (I've tested it in Pyhton) and my assumption was wrong, so the > important thing is to support closures, which Python does, even with local > function definitions. We do appear to entirely agree. In Python <= 2.4, where if is just a statement (not an expression), you'd need some trick to get this effect with a lambda, e.g.: def black_white(function, limit, key=None): return lambda x,y: 1.0 * (function(x,y) > limit) assuming it's important to get a float result -- the > operator per se returns an int, so you can call float() on it, or multiply it by 1.0, etc -- if you had two arbitrary colors, e.g. def two_tone(function, limit, key=None, low=0.0, high=1.0): return lambda x,y: (low, high)[function(x,y) > limit] which is a pretty obscure alternative. In Python >= 2.5, an if expression has been added, but I'll leave you to judge if it's actually an improvement (sigh)...: def two_tone(function, limit, key=None, low=0.0, high=1.0): return lambda x,y: high if function(x,y) > limit else low Personally, I'd rather use the named-function version. Anyway, they're all semantically equivalent (sigh), and the key point is that the semantics (building and returning functions on the fly) IS there, whether the functions are named or unnamed, as we agree. Alex From paddy3118 at netscape.net Tue May 23 13:26:16 2006 From: paddy3118 at netscape.net (Paddy) Date: 23 May 2006 10:26:16 -0700 Subject: What's with the @ sign In-Reply-To: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> References: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> Message-ID: <1148405175.941215.207770@j55g2000cwa.googlegroups.com> Oh please, please, can I answer! They are decorators. Check-out http://zephyrfalcon.org/weblog2/arch_e10_00610.html#e610 (decorate this), or http://paddy3118.blogspot.com/ " Python function attributes" and then " Function Attributes assigned by decorator". Of course there is also: http://wiki.python.org/moin/PythonDecoratorLibrary - Pad. From http Mon May 22 15:34:21 2006 From: http (Paul Rubin) Date: 22 May 2006 12:34:21 -0700 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> <2lmcg.90657$dW3.29599@newssvr21.news.prodigy.com> <1148324738.039440.57700@j73g2000cwa.googlegroups.com> Message-ID: <7xwtcdc0qq.fsf@ruckus.brouhaha.com> "SamFeltus" writes: > I am uncomfortable with the seperating of the code from the visual/time > element, as well as the lack of emphasis on the visual/time element. Maybe you should buy a camcorder and make movies, instead of doing web sites. > I am not a big Perl/PHP fan, I find Python with SimpleJSON, SQLObject > and the included Python batteries pretty well does all I want to do > server side. Is it correct to think that is gonna be a solid, simple > solution for a Flash coder to use server side? Or, is there something > better and easier? (In advance, I find XML irritating compared to > JSON) Well, you won't find many Perl/PHP fans here, though PHP is (for now) probably simpler than Python to get started and do basic dynamic Web sites with. Python beats PHP once the backend logic gets complex enough that PHP's language deficiencies outweigh its ease of installation. I don't know if that applies to what you're doing. From nholtz at docuweb.ca Sat May 13 09:02:27 2006 From: nholtz at docuweb.ca (nholtz) Date: 13 May 2006 06:02:27 -0700 Subject: Tkinter: ability to delete widgets from Text and then re-add them In-Reply-To: <1147457698.020383.213280@j33g2000cwa.googlegroups.com> References: <1147457698.020383.213280@j33g2000cwa.googlegroups.com> Message-ID: <1147525347.007707.35670@y43g2000cwc.googlegroups.com> I now see that I can accomplish what I want using the Canvas widget, instead of the Text widget (I.e., I can create a window on it, delete the window, then re add it without recreating the underlying widget object). As I don't want the raw contents user-editable, I guess its better to use a Canvas, rather than a Text (slightly harder to use, though, I guess) neal From phillipsd at cromwell.co.uk Wed May 3 05:30:02 2006 From: phillipsd at cromwell.co.uk (Fuzzydave) Date: 3 May 2006 02:30:02 -0700 Subject: Calling a Postgres Function using CGI written in Python Message-ID: <1146648602.110172.191810@g10g2000cwb.googlegroups.com> I need to call a function stored in Postgres which does a lot of the db and calculation work all the SQL queries are hardcoded in a file called cmi.py. What i need to do is too to call my function from postgres passing in my product_code variable into it and returning the value from the query into a variable i can print to screen as part of a HTML page. I am sure its very easy but have never done anything in python as have none of the guys i work with making this a bit of a problem. Cheers Guys David From anatoli.barski at googlemail.com Tue May 30 18:14:12 2006 From: anatoli.barski at googlemail.com (anatoli.barski at googlemail.com) Date: 30 May 2006 15:14:12 -0700 Subject: how to print newline in xml? Message-ID: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> I currently use xml.dom.minidom and ext to create a dom-tree which I would write to an xml-file. My intention is to create something like this: but I didn't find any possibility either to put comment directly behind a tag nor did I found how to put a new line like in example between the two joints. The reason why I'm trying to achieve this: the file should be easy to read for a human... now I can just print the upper document like this: which is already not very readable - but it becomes even worse along with increasing number of comments From khoa.coffee at gmail.com Wed May 17 13:57:53 2006 From: khoa.coffee at gmail.com (Khoa Nguyen) Date: Wed, 17 May 2006 13:57:53 -0400 Subject: Pyparsing: Grammar Suggestion Message-ID: <3d00e6dc0605171057l6220b138gb9f8211886938c02@mail.gmail.com> > record = f1,f2,...,fn END_RECORD > All the f(i) has to be in that order. > Any f(i) can be absent (e.g. f1,,f3,f4,,f6 END_RECORD) > Number of f(i)'s can vary. For example, the followings are allowed: > f1,f2 END_RECORD > f1,f2,,f4,,f6 END_RECORD > > Any suggestions? > > > -------- > pyparsing includes a built-in expression, commaSeparatedList, for just such > a case. Here is a simple pyparsing program to crack your input text: > > > data = """f1,f2,f3,f4,f5,f6 END_RECORD > f1,f2 END_RECORD > f1,f2,,f4,,f6 END_RECORD""" > > from pyparsing import commaSeparatedList > > for tokens,start,end in commaSeparatedList.scanString(data): > print tokens > > > This returns: > ['f1', 'f2', 'f3', 'f4', 'f5', 'f6 END_RECORD'] > ['f1', 'f2 END_RECORD'] > ['f1', 'f2', '', 'f4', '', 'f6 END_RECORD'] > > Note that consecutive commas in the input return empty strings at the > corresponding places in the results. > > Unfortunately, commaSeparatedList embeds its own definition of what is > allowed between commas, so the last field looks like it always has > END_RECORD added to the end. We could copy the definition of > commaSeparatedList and exclude this, but it is simpler just to add a parse > action to commaSeparatedList, to remove END_RECORD from the -1'th list > element: > > def stripEND_RECORD(s,l,t): > last = t[-1] > if last.endswith("END_RECORD"): > # return a copy of t with last element trimmed of "END_RECORD" > return t[:-1] + [last[:-(len("END_RECORD"))].rstrip()] > > commaSeparatedList.setParseAction(stripEND_RECORD) > > > for tokens,start,end in commaSeparatedList.scanString(data): > print tokens > > > This returns: > > ['f1', 'f2', 'f3', 'f4', 'f5', 'f6'] > ['f1', 'f2'] > ['f1', 'f2', '', 'f4', '', 'f6'] > Thanks for your reply. This looks promising, but I have a few more questions: 1. If f(i) is non-terminal (e.g f(i) is another grammar expression), how would I adapt your idea to a more generic way? 2. The field delimiter is not always ',' in my case. So I guess I'll have to use delimtedList instead? Thanks again, Khoa From fredrik at pythonware.com Fri May 5 05:27:02 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 May 2006 11:27:02 +0200 Subject: Tuple assignment and generators? References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com><1vSdnRC7JP5K08fZRVn-rw@comcast.com><1146803131.996632.207770@v46g2000cwv.googlegroups.com><1146813639.825116.21780@g10g2000cwb.googlegroups.com><1146814457.388702.263120@i39g2000cwa.googlegroups.com> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> Message-ID: "vdrab" wrote: > Given this though, what other such beauties are lurking in the > interpreter, under the name of 'implementation accidents'? One of the > things that drew me to python is the claimed consistency and > orthogonality of both language and implementation, not sacrificing > clarity for performance, minimizing ad-hoc design hacks and weird > gotcha's, etc... so anything you don't understand, and cannot be bothered to look up in the documentation, just has to be an inconsistent ad-hoc weird-gotcha design ? I think we can all safely *plonk* you know. From gherron at islandtraining.com Tue May 9 16:45:06 2006 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 09 May 2006 13:45:06 -0700 Subject: Shadow Detection? In-Reply-To: References: Message-ID: <4460FF52.3090503@islandtraining.com> Michael Yanowitz wrote: >Hello: > > Many times, people are warning things like >"Don't use 'str' as a variable name as it will shadow the >built in str function." > Is there some way to determine if a string is already >defined in some higher scope? >Maybe something like > > >if isdefined ('str'): > print 'str is already defined, please choose another name' > > > > If not, would it be easy to write this? > >Thanks in advance: > > > Just try to access the name and see what happens, catching the resulting error if you wish try: xyzzy except NameError: print 'xyzzy is not currently bound' From tim.leeuwvander at nl.unisys.com Mon May 8 04:04:31 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 8 May 2006 01:04:31 -0700 Subject: printing out elements in list In-Reply-To: <1147074279.391832.158350@y43g2000cwc.googlegroups.com> References: <1147074279.391832.158350@y43g2000cwc.googlegroups.com> Message-ID: <1147075471.291128.262900@j73g2000cwa.googlegroups.com> Using slices and built-in zip: >>> alist = ['>QWER' , 'askfhs', '>REWR' ,'sfsdf' , '>FGDG', 'sdfsdgffdgfdg' ] >>> dict(zip(alist[::2], alist[1::2])) {'>QWER': 'askfhs', '>FGDG': 'sdfsdgffdgfdg', '>REWR': 'sfsdf'} Slightly more efficient might be to use izip from itertools: >>> from itertools import izip >>> dict(izip(alist[::2], alist[1::2])) {'>QWER': 'askfhs', '>FGDG': 'sdfsdgffdgfdg', '>REWR': 'sfsdf'} And perhaps using islice from iterools might improve efficiency even more: >>> from itertools import islice, izip >>> dict(izip(islice(alist, 0, None, 2), islice(alist, 1, None, 2))) {'>QWER': 'askfhs', '>FGDG': 'sdfsdgffdgfdg', '>REWR': 'sfsdf'} (I didn't try to time any of these solutions so I have no real idea which is more efficient, but using iterators from the itertools-module should in theory mean you create less temporary objects; especially with large lists this can be a win) Cheers, --Tim From http Tue May 16 02:54:34 2006 From: http (Paul Rubin) Date: 15 May 2006 23:54:34 -0700 Subject: Decrypt DES by password References: <7xlkt3dtps.fsf@ruckus.brouhaha.com> Message-ID: <7xr72u5uj9.fsf@ruckus.brouhaha.com> Thomas Dybdahl Ahle writes: > > I'm not aware of a standard that says how CryptDeriveKey is supposed > > to work.... > I tried to find out how the monofolks did it, but also they didn't know > the algorithms. Actually this is almost certainly an entry into the Windows Crypto API. If you're persistent you might be able to figure it out from the CAPI does at http://msdn.microsoft.com. Start by typing CryptDeriveKey into the search box and follow links and do more searches from there. From paddy3118 at netscape.net Sun May 28 13:43:16 2006 From: paddy3118 at netscape.net (Paddy) Date: 28 May 2006 10:43:16 -0700 Subject: (mostly-)POSIX regular expressions In-Reply-To: <1148764193.962418.192750@j73g2000cwa.googlegroups.com> References: <1148764193.962418.192750@j73g2000cwa.googlegroups.com> Message-ID: <1148838196.463101.210180@i39g2000cwa.googlegroups.com> maybe this: http://www.pcre.org/pcre.txt and ctypes might work for you? (I was suprised to find out that PCRE supported POSIX but don't know what version it supports or how well). - Pad From steve at holdenweb.com Mon May 1 22:14:57 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 May 2006 03:14:57 +0100 Subject: using ftplib In-Reply-To: References: <4456743d$0$2563$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: John Salerno wrote: [...] > > So if I already have files on the server and I want to change file > permissions, do I need to mess with TYPE A/TYPE I commands, or are those > strictly for when you *transfer* files? Because I just did a quick test > of changing file permissions through my FTP program, and it still sent a > TYPE A command in the process. I know that the retr and stor methods > might do this automatically, but if I don't need to use those, and just > need to use transfercmd (assuming this *is* the right method to use when > changing file permissions), do I need to manually send a TYPE A/I > command as well? The answer is "probably not", but a better answer is "try it in the interactive interpreter and see". regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From dan at catfolks.net Wed May 31 17:24:48 2006 From: dan at catfolks.net (Dan M) Date: Wed, 31 May 2006 14:24:48 -0700 Subject: TSV to HTML References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> Message-ID: > 1) in the code define a css > 2) use a regex to extract the info between tabs In place of this, you might want to look at http://effbot.org/librarybook/csv.htm Around the middle of that page you'll see how to use a delimiter other than a comma > 3) wrap the values in the appropriate tags and insert into table. 4) > write the .html file > > Thanks again for your patience, > Brian From david at david-steuber.com Sat May 6 22:57:23 2006 From: david at david-steuber.com (David Steuber) Date: 06 May 2006 22:57:23 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Message-ID: <878xpebkz0.fsf@david-steuber.com> "Xah Lee" writes: > In this post, i'd like to deconstruct one of Guido's recent blog about > lambda in Python. Why couldn't you keep this to comp.lang.python where it would almost be relevant? Before I pulled down the headers, I thought maybe something interesting was posted to comp.lang.lisp. Followups set. -- http://www.david-steuber.com/ 1998 Subaru Impreza Outback Sport 2006 Honda 599 Hornet (CB600F) x 2 Crash & Slider It's OK. You only broke your leg in three places. Walk it off. From ankyhe at gmail.com Mon May 8 02:39:18 2006 From: ankyhe at gmail.com (ankyhe at gmail.com) Date: 7 May 2006 23:39:18 -0700 Subject: Why list.sort() don't return the list reference instead of None? Message-ID: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> L = [4,3,2,1] L=L.sort() L will refer to None, why L.sort() don't return the L? I want to ask why the designer of Python do so? From dreedmac at columbus.rr.com Sat May 6 17:08:37 2006 From: dreedmac at columbus.rr.com (David Reed) Date: Sat, 6 May 2006 17:08:37 -0400 Subject: GladeGen and initializing widgets at startup In-Reply-To: <1146947945.953256.164400@j33g2000cwa.googlegroups.com> References: <1146947945.953256.164400@j33g2000cwa.googlegroups.com> Message-ID: On May 6, 2006, at 4:39 PM, Aengys wrote: > Hi all, > > Being struck by article 7421 of the linux journal > (http://www.linuxjournal.com/article/7421), I'll tried to give it a > go. > Mainly because I have done some experiments with Glade and found that > it is really easy to create good looking GUIs. On the other end, there > is the GladeGen tool which helps you in building a skeleton in Python > such that you only have to code the events. But being a newbie with > Python as well as Glade I'm heavily dependent on documentation (mainly > online a big part being usenet). There I found that almost nobody > seems to use it, or they don't have any problems with it. In this > group > there is only thread that has a reference to it! > > So my questions: > > Does anybody use GladeGen? If not, why? > > For those that do use it, where do I write the code which has to be > executed when a window loads? The thing is pretty basic here. I > have a > window with a treeview, and I simply want that treeview filled up when > opening the window. > > Hoping for some echos... > > Aengys > I'm the author of it - I got a number (20-30 I think) of responses from people using it and a few quick questions. I emailed the gnome- python maintainer to see if they were interested in including it or taking it over, but never heard back. If anyone wants to take it over and extend it, you're welcome to. I believe Linux Journal maintained copyright ownership for a few months after the publication but then it reverts back to the author so I'll happily release it under the GPL for anyone to extend. To answer your question, you can put your code in the init method after the call to: GladeWindow.__init__ or you can override the GladeWindow's show method in your class if you want it to be called every time the window is shown. I often wrote a method named "populate" to file in data in widgets and then called it from the show method. Dave From alexander.kozlovsky at gmail.com Sun May 21 08:19:29 2006 From: alexander.kozlovsky at gmail.com (Alexander Kozlovsky) Date: Sun, 21 May 2006 16:19:29 +0400 Subject: dict!ident as equivalent of dict["ident"] Message-ID: <1315219425.20060521161929@gmail.com> Hello all! I have small silly syntax suggestion (SSSS) In many cases, keys in dictionary-like objects are strings, and moreover - valid Python identifiers. Something like: foo["bar"]["baz"].x = y How about small syntactic sugar: foo!bar!baz.x = y With this suggestion, mapping!identifier becomes fully equivalent to mapping["identifier"] -- Best regards, Alexander mailto:alexander.kozlovsky at gmail.com From richie at entrian.com Mon May 15 04:57:20 2006 From: richie at entrian.com (Richie Hindle) Date: Mon, 15 May 2006 09:57:20 +0100 Subject: Making all string literals Unicode Message-ID: Hi, Am I imagining it, or is there a switch or an environment variable to make Python treat all string literals as unicode? I seem to recall seeing it mentioned somewhere, but now I can't find it anywhere. Thanks, -- Richie Hindle richie at entrian.com From edeveaud at pasteur.fr Tue May 9 04:29:19 2006 From: edeveaud at pasteur.fr (Eric Deveaud) Date: Tue, 9 May 2006 08:29:19 +0000 (UTC) Subject: combined files together References: <87psirslhy.fsf@localhost.localdomain> <87slnmog19.fsf@localhost.localdomain> Message-ID: Gary Wessle wrote: > > I need to traverse those files in the order they were created > chronologically. listdir() does not do it, is there a way besides > build a list then list.sort(), then for element in list_of_files open > element? are the name of the files describing the cration date, or have to rely on the creation date ? if the name allows to discriminate the chronology, check glob module. Eric From grante at visi.com Wed May 3 13:22:02 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 03 May 2006 17:22:02 -0000 Subject: NaN handling References: Message-ID: <125hplqmppfeq29@corp.supernews.com> On 2006-05-03, Andy McDonagh wrote: > Dear python experts, > > I am new to python and this site, so I apologize if this is off topic (i.e. is it a SciPy question?). I will try to demonstrate my problem below: > -------------------------------------------------------- > #!/usr/local/bin/python > > from scipy import * > from scipy.stats import * > a=norm(loc=0,scale=1) > a_data = a.rvs(10) > > problem = zeros(10) > print problem > > h_x1_x2 = -sum(problem * log2(a_data)) > > print h_x1_x2 > #NaN > ---------------------------------------------------------- > > I need a way of handling NaNs NaNs are handled. Apparently they aren't handled the way you want them to be? > for example R has the 'na.omit' option. Does anybody know if > this exists? It would help if you explain how you want NaNs handled, but I don't recall that tehre are any "options" for handling NaNs other than the default way in scipy. -- Grant Edwards grante Yow! It's NO USE... I've at gone to "CLUB MED"!! visi.com From bugs at almad.net Wed May 10 10:53:49 2006 From: bugs at almad.net (Almad) Date: 10 May 2006 07:53:49 -0700 Subject: PIL thumbnails unreasonably large Message-ID: <1147272829.719796.150680@y43g2000cwc.googlegroups.com> Hello, I wonder how do I create reasonable thumbnails from JPEG with PIL. My code: logging.debug('Downloading image %s' % id) uri = ''.join([config['photo']['masterpath'], '?p=', str(id)]) uf = urlopen(uri).read() f = tmpfile() f.write(uf) f.seek(0) logging.debug('Resizing image %s' % id) img = Image.open(f) prev = img.copy() img.thumbnail((180,180)) if prev.size[0] > 640 or prev.size[1] > 640: prev.thumbnail((640,640)) # save resized to temporary files f.seek(0) img.save(f, "JPEG", quality=50) fp = tmpfile() prev.save(fp, "JPEG", quality=200) Well, works fine, but img size is about 0,5 MB (!), but strangely, prev one is around 200 kb. How do I change this? I tried to play with various quality settings, but with no effect. img thumbnail is supposed to be < 10 kb... Thank You, Almad From steven.klass at gmail.com Thu May 18 18:47:59 2006 From: steven.klass at gmail.com (rh0dium) Date: 18 May 2006 15:47:59 -0700 Subject: Subprocess or Process or OMG!! Message-ID: <1147992479.110490.41960@i40g2000cwc.googlegroups.com> Hi all, Here I was happily coming to working thinking - OK I need to create a wrapper for a tool (UNIX) which does nothing but lauch the end tool and send a sql instert letting the db know the tool was launched (Can we say Big Brother..). Some of the tools are very long running with lots of data others are small and very fast.. So I started down my traditional approach - Check google groups for the answer. I quickly became aware of how challenging this actually is. See my approach was simple Tool name = FOOBAR Symbolically link FOOBAR to my Wrapper.py 1. Get the args and some other key data (user, cwd, etc) 2. Fork this process and get FOOBAR running (time is of essense of course) 3. On the side submit a mySQL call saying what happened... Sounds simple and I thought I was ready to go.. Until google groups... http://groups.google.com/group/comp.lang.python/browse_frm/thread/4a2766a16e67cec8/79e4b404b4f0e1ff?lnk=st&q=Python+Fork+Wrapper&rnum=3#79e4b404b4f0e1ff OK so now I need to think about I/O redirection hmmm OK More data.. People have dealt with this - but most of it's dated.. Wait import subprocess.. Looks promising hey some has really used this.. http://www.dalkescientific.com/writings/diary/archive/2005/04/12/wrapping_command_line_programs.html http://www.third-bit.com/swc2/lec/integrate.html http://www.easysw.com/~mike/cups/strfiles/1648/smtp Needless to say this is much more complex than what I was "hoping" for. Has anyone solved this in a generic approach.. #!/usr/bin/env python import os,sys,string import subprocess argc = len(sys.argv) # Yes I move all exe's to the .bin direcotory sys.argv[0]=os.path.join(os.getcwd() + "/.bin/" + os.path.basename(sys.argv[0])) cmd = string.join(sys.argv," ") subprocess.Popen( cmd ) This has several problems - least of which args aren't working.... Has anyone really tried this approach? From mauricio.tellez at gmail.com Wed May 10 23:33:41 2006 From: mauricio.tellez at gmail.com (Mauricio Tellez) Date: Wed, 10 May 2006 22:33:41 -0500 Subject: Formmating excel cells with PyExcelerator or COM Message-ID: Hi, I just want that a number like 1234.123 appear in excel as 1,234.12 In excel I just select some cells, then right click on them and select "Cell Formatting" then select Number, and check "Use thounsands separator" and 2 decimal places. I can't find how to do this with PyExcelerator neither with COM. Any clue? -- Mauricio Tellez -------------- next part -------------- An HTML attachment was scrubbed... URL: From siona at chiark.greenend.org.uk Fri May 5 10:47:57 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 05 May 2006 15:47:57 +0100 (BST) Subject: how to remove 50000 elements from a 100000 list? References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> Message-ID: <58z*NLTfr@news.chiark.greenend.org.uk> Tim Chase wrote: >Another attempt might be to try > > >>> a = [x for x in a if x not in b] > >However, this is still doing A*B checks, and will likely >degrade with as their sizes increase. Combine this with the use of sets others have suggested if the order of a matters, ie: >>> bset = set(b) >>> a = [ x for x in a if x not in bset ] which gets you down to O(A) since set membership is O(1). -- \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 petr at tpc.cz Thu May 4 17:44:04 2006 From: petr at tpc.cz (Petr Jakes) Date: 4 May 2006 14:44:04 -0700 Subject: Can I use python for this .. ?? In-Reply-To: <1146774288.904851.278130@i39g2000cwa.googlegroups.com> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146774288.904851.278130@i39g2000cwa.googlegroups.com> Message-ID: <1146779044.307500.50810@u72g2000cwu.googlegroups.com> Why using Python? What about? 1. Open Power Options in Control Panel. (Click Start, click Control Panel, and then double-click Power Options.) 2.Click the Hibernate tab, select the Enable hibernate support check box, and then click Apply. (If the Hibernate tab is unavailable, your computer does not support this feature.) then: 1: Click Start and Shut Down, 2: Point the standby button and maintain the shift key pushed, 3: A new hibernation button appears: click it while still holding the shift key: voila your PC will hibernate (it mens computer will save your current setting and will switch off). Petr Jakes From pecoraREMOVE at THISanvil.nrl.navy.mil Wed May 24 15:35:10 2006 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Wed, 24 May 2006 15:35:10 -0400 Subject: Bind an instance of a base to a subclass - can this be done? Message-ID: I've been scanning Python in a Nutshell, but this seems to be either undoable or so subtle that I don't know how to do it. I want to subclass a base class that is returned from a Standard Library function (particularly, subclass file which is returned from open). I would add some extra functionality and keep the base functions, too. But I am stuck. E.g. class myfile(file): def myreadline(): #code here to return something read from file Then do something like (I know this isn't right, I'm just trying to convey the idea of what I would like) mf=myfile() mf=open("Afile","r") s=mf.myreadline() # Use my added function mf.close() # Use the original file function Possible in some way? Thanks in advance for any clues. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From elventear at gmail.com Fri May 19 17:19:51 2006 From: elventear at gmail.com (elventear) Date: 19 May 2006 14:19:51 -0700 Subject: Question about Python on Mac Message-ID: <1148073591.308980.289300@u72g2000cwu.googlegroups.com> Hello, I am working with Python 2.4.3 built from source courtesy of Fink. So far so good, until now. I want to use a module called GMPY (http://gmpy.sf.net/). I am able to build correctly the module, but once I try to import it I get the following error: ImportError: Failure linking new module: gmpy.so: Symbol not found: ___gmpn_sub_nc Referenced from: /sw/lib/libgmp.3.dylib Expected in: dynamic lookup The weird thing is that just for kicks I tried building with Python that comes with MacOSX (py2.3) and it works. It builds and it loads fine. Anybody have an idea why this would happen? Any ideas how to solve this? In the worse case scenario, can I use the binary (gmpy.so) built with against Python 2.3 with Python 2.4.3 (It seems to load correctly but I don't know if I should expect any meltdowns later on) I would appreciate any suggestions. Thanks. From 13812327 at sun.ac.za Wed May 3 05:06:48 2006 From: 13812327 at sun.ac.za (Wynand Singels) Date: Wed, 03 May 2006 09:06:48 -0000 Subject: Images and mouse events In-Reply-To: Message-ID: <009801c1930d$5097ad20$8ba9e892@Bhukka.co.za> Hi there everyone I'm trying to figure out the best (and fastest way) to display a JPEG image and then input several (x,y) coordinate pairs from mouse clicks on the image. I figured out how to do this in pylab using matplotlib as follows: img = 256 - S.misc.pilutil.imread('pic1.jpg') P.imshow(img) P.connect('button_press_event',click) P.show() The function click() gets the coordinates form the event.xdata and event.ydata, but this is very slow and cumbersome. The other option I was looking at was using wxPython - a staticbitmap with EVT_LEFT_DOWN or something like that. But I'm struggling to get this to work. Please take into account that my end product will have to have a full GUI. Is there some other package I can use? Or am I missing some part of wxPython that can do this? Wynand From tim.peters at gmail.com Thu May 11 12:57:47 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 11 May 2006 12:57:47 -0400 Subject: Python memory deallocate In-Reply-To: <1147356093.328235.22450@j33g2000cwa.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <1147347601.597292.15220@j73g2000cwa.googlegroups.com> <1147353348.028544.143470@u72g2000cwu.googlegroups.com> <1147356093.328235.22450@j33g2000cwa.googlegroups.com> Message-ID: <1f7befae0605110957y4194c7fdhb721db2f3a56881a@mail.gmail.com> [Serge Orlov] > BTW python 2.5 now returns free memory to OS, but if a program keeps > allocating more memory with each new iteration in python 2.4, it will > not help. No version of CPython ever returns memory to "the OS". All memory is obtained via the platform C's alloc() or realloc(), and any memory "returned" is given back to the platform C's free(). Whether and when the platform C's free() in turn gives memory back to the OS is entirely up to the OS and C's implementation of free(), varies across OSes and platform free() implementations, typically has no easy answer, and is something Python has no control over regardless. It's true that Python 2.5 will, in some cases, return more memory to free() than did previous versions of CPython. When it does, that may or may not affect what the OS reports as the process's memory use. From steven.vereecken at gmail.com Tue May 2 15:57:50 2006 From: steven.vereecken at gmail.com (steven.vereecken at gmail.com) Date: 2 May 2006 12:57:50 -0700 Subject: RFC 822 continuations References: <4457907E.5010502@websafe.com> Message-ID: <1146599870.007807.245700@i40g2000cwc.googlegroups.com> Larry Bates wrote: > Florian Lindner wrote: > > Hello, > > http://docs.python.org/lib/module-ConfigParser.html writes: > > > > "with continuations in the style of RFC 822; " > > > > what is meant with these continuations? > > > > Thanks, > > > > Florian > > From ConfigParser source code: > > Continuations are represented by an embedded newline then > leading whitespace. > > -Larry Bates In case this is not clear enough (wasn't clear to me either, the first time I saw it, what with talk of "continuations" in other contexts), it basically means that the values for a config option can span multiple lines. A line starting with whitespace is considered to be a "continuation" of the previous line. Polaar From kylotan at gmail.com Thu May 11 11:32:03 2006 From: kylotan at gmail.com (Ben Sizer) Date: 11 May 2006 08:32:03 -0700 Subject: String concatenation performance In-Reply-To: <1147355908.655992.5720@g10g2000cwb.googlegroups.com> References: <1147355908.655992.5720@g10g2000cwb.googlegroups.com> Message-ID: <1147361523.499630.315110@i39g2000cwa.googlegroups.com> Cristian.Codorean wrote: > I was just reading a "Python Speed/Performance Tips" article on the > Python wiki > http://wiki.python.org/moin/PythonSpeed/PerformanceTips > and I got to the part that talks about string concatenation and that it > is faster when using join instead of += because of strings being > immutable. The idea is that you call join() once rather than calling += many times. You achieve this by placing all the strings you want concatenating into a single list, not by calling join() with multiple lists. -- Ben Sizer From tjreedy at udel.edu Sat May 6 13:32:24 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 May 2006 13:32:24 -0400 Subject: NaN handling References: <125hplqmppfeq29@corp.supernews.com><01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> <1146929327.30335.5.camel@kenshin.CASA> <445CD5E3.1070600@cs.uoregon.edu> Message-ID: "Ryan Forsythe" wrote in message news:445CD5E3.1070600 at cs.uoregon.edu... > Terry Reedy wrote: >> "Felipe Almeida Lessa" wrote in message >> news:1146929327.30335.5.camel at kenshin.CASA... >>> This works everywhere: >>> >>> nan = float('nan') >> >> Not. >> >>>>> nan = float('nan') >> >> Traceback (most recent call last): >> File "", line 1, in -toplevel- >> nan = float('nan') >> ValueError: invalid literal for float(): nan >> >> Above is Windows, which requires something else. > > I think he meant: > > >>> float("NaN") > nan > > That's Python 2.4.1 on Mac OS X. >>> float("NaN") Traceback (most recent call last): File "", line 1, in -toplevel- float("NaN") ValueError: invalid literal for float(): NaN As Tim Peters has said often enough, this sort of thing is specific to the underlying C library and will remain so until someone cares enough to write or fund a cross-platform solution. Terry Jan Reedy From hove at ntnu.no Sat May 13 12:14:51 2006 From: hove at ntnu.no (Joakim Hove) Date: Sat, 13 May 2006 18:14:51 +0200 Subject: Unicode & ZSI interaction ?? Message-ID: Dear newsgroup, I have written a cgi script in Python, and it has worked fine for some time. Now the installed Python version has been upgraded to 2.4.1 and I am having problems with non ascii characters. The core of the problem I have is as follows: 1. The webpage contains a text field where the user enters her/his name. 2. My cgi script uses the 'cgi' class to extract the name the user has entered. 3. The cgi script writes the name the user has given to a file. Now, the webpage in question is in Norway; and many Norwegian names are not 8bit clean, i.e. they contain characters which can not be represented with a 7bit ascii encoding. As a consequence I get *either* a UnicodeDecodeError *or* just blanks when writing it to file. Simplest case: -------------- name = "?se" fileH = open("/tmp/namelist.txt","w") fileH.write(name) In this case the first character in the name variable is not in the plain 7bit ascii encoding. The code written above runs without errors or warnings, but the problematic character is simple replaced by a space in the file '/tmp/namelist.txt'. More complicated case: ---------------------- The application uses the SOAP protocol via the ZSI module to communicate with some other site. The SOAP call returns a variable, and when this variable is combined with the name variable above I get the UnicodeDecodeError: name = "?SE" ref = SOAP_return_value() fileH = open("/tmp/namelist.txt","a") fileH.write("name:%s ref:%s \n" % (name,ref)) fileH.close() This bombs with: UnicodeEncodeError: 'ascii' codec can't encode character u'\xc5' in position 45: ordinal not in range(128) The variable 'ref' returned from the SOAP interaction is (seemingly ...) pure 7bit ascii. Any suggestions greatly appreciated. Joakim Hove -- Joakim Hove hove AT ntnu.no / Tlf: +47 (73 5)9 34 27 / Stabburveien 18 Fax: ................. / N-5231 Paradis http://www.ift.uib.no/~hove/ / 55 91 28 18 / 92 68 57 04 From chris at foote.com.au Tue May 16 05:08:45 2006 From: chris at foote.com.au (Chris Foote) Date: Tue, 16 May 2006 18:38:45 +0930 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> Message-ID: <1147772609.836089@teuthos> Paul McGuire wrote: > "Claudio Grondi" wrote in message > news:e49va0$m72$1 at newsreader3.netcologne.de... >> Chris Foote wrote: >>> Hi all. >>> >>> I have the need to store a large (10M) number of keys in a hash table, >>> based on a tuple of (long_integer, integer). The standard python >>> dictionary works well for small numbers of keys, but starts to >>> perform badly for me inserting roughly 5M keys: >>> >>> # keys dictionary metakit (both using psyco) >>> ------ ---------- ------- >>> 1M 8.8s 22.2s >>> 2M 24.0s 43.7s >>> 5M 115.3s 105.4s >>> >>> Has anyone written a fast hash module which is more optimal for >>> large datasets ? >>> >>> p.s. Disk-based DBs are out of the question because most >>> key lookups will result in a miss, and lookup time is >>> critical for this application. >>> >> Python Bindings (\Python24\Lib\bsddb vers. 4.3.0) and the DLL for >> BerkeleyDB (\Python24\DLLs\_bsddb.pyd vers. 4.2.52) are included in the >> standard Python 2.4 distribution. >> >> "Berkeley DB was 20 times faster than other databases. It has the >> operational speed of a main memory database, the startup and shut down >> speed of a disk-resident database, and does not have the overhead of >> a client-server inter-process communication." >> Ray Van Tassle, Senior Staff Engineer, Motorola >> >> Please let me/us know if it is what you are looking for. > > sqlite also supports an in-memory database - use pysqlite > (http://initd.org/tracker/pysqlite/wiki) to access this from Python. Hi Paul. I tried that, but the overhead of parsing SQL queries is too high: dictionary metakit sqlite[1] ---------- ------- --------- 1M numbers 8.8s 22.2s 89.6s 2M numbers 24.0s 43.7s 190.0s 5M numbers 115.3s 105.4s N/A Thanks for the suggestion, but no go. Cheers, Chris [1] pysqlite V1 & sqlite V3. From onurb at xiludom.gro Fri May 19 14:10:34 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 20:10:34 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1148052675.065004.173390@38g2000cwa.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1148052675.065004.173390@38g2000cwa.googlegroups.com> Message-ID: <446e0a83$0$26884$626a54ce@news.free.fr> Ian Bicking wrote: > glomde wrote: > >>i I would like to extend python so that you could create hiercical >>tree structures (XML, HTML etc) easier and that resulting code would be >>more readable than how you write today with packages like elementtree >>and xist. >>I dont want to replace the packages but the packages could be used with >>the >>new operators and the resulting IMHO is much more readable. > > > You might want to look at PEP 359 for ideas: > http://www.python.org/dev/peps/pep-0359/ > And more specifically here - this answers my doubts about the possibility to use the with statement: http://mail.python.org/pipermail/python-list/2006-April/336774.html -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From oliphant.travis at ieee.org Sat May 27 23:29:05 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Sat, 27 May 2006 21:29:05 -0600 Subject: Looking for triangulator/interpolator In-Reply-To: <127gjvrhk7udbcc@corp.supernews.com> References: <127f313dbhl7gf4@corp.supernews.com> <127fp09e6v176a5@corp.supernews.com> <127gjvrhk7udbcc@corp.supernews.com> Message-ID: <44791901.6000603@ieee.org> Grant Edwards wrote: > On 2006-05-27, Travis E. Oliphant wrote: > >> Not that you made a bad choice. I do wonder, how much of your >> difficulty was with the interface to the underlying fitpack >> routines. > > I've no idea. I had never done anything with splines before, > so it's quite possible I just wasn't doing things right. I > never got it to work at all for non-gridded data (which is what > I needed). Since it wasn't stable even for gridded data, I > more or less gave up. > >> The interface is pretty involved as there are lots of >> parameter choices to the underlying routine. It's very >> possible the interface is broken in some strange way. > > I took a look at underlying Fortran code, but that made my > dizzy. Just to finish this thread, I should mention I spent some time yesterday looking into the details of the underlying surfit fucntion used by bisplrep. It appears to have difficulties when s=0 is used. It seems to be geared toward smoothing applications where you are trying to fit "noisy" scattered data to a smooth function. There are many warnings about choosing s to be too low. Thus, trying to use bisplrep for interpolation (instead of data smoothing) is probably going to be difficult with bisplrep. We still need a good N-d re-gridding algorithm in SciPy. -Travis From nobody at 127.0.0.1 Tue May 16 21:38:58 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 01:38:58 GMT Subject: python vs perl lines of code References: Message-ID: John Bokma wrote: > Edward Elliott wrote: > >> This is just anecdotal, but I still find it interesting. Take it for >> what it's worth. I'm interested in hearing others' perspectives, just >> please don't turn this into a pissing contest. > > Without seeing the actual code this is quite meaningless. Evaluating my experiences yes, relating your own no. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From scott.daniels at acm.org Mon May 15 15:00:33 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 15 May 2006 12:00:33 -0700 Subject: common practice for creating utility functions? In-Reply-To: References: Message-ID: <4468cbe6$1@nntp0.pdx.net> John Salerno wrote: > ...Is it common ...[and preferred] to create a function that has the sole job of > calling another function? > > Example: ... cryptogram. Right now I have four functions: > > convert_quote -- the main function that starts it all > make_code -- makes and returns the cryptogram > make_set -- called from make_code, converts the quote into a set so each > letter gets only one coded letter > test_sets -- makes sure a letter isn't assigned to itself > > So my first question is this: should I make a Cryptogram class for this, > or are functions fine? Functions are just fine. I'd use a class if they wanted to share state. > ... can I do something like this: > def convert_quote(quote): > return make_code(quote) > Or does it not make sense to have a function just call another function? Obviously you _can_ do that. I wouldn't, however. If (to you) the four functions above "mean" something different, I'd implement convert_quote with: convert_quote = make_code -- -Scott David Daniels scott.daniels at acm.org From kent at kentsjohnson.com Thu May 25 12:13:20 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 25 May 2006 12:13:20 -0400 Subject: Best way to handle exceptions with try/finally In-Reply-To: <1148543006.392324.74040@j33g2000cwa.googlegroups.com> References: <1148481073.976420.316970@j55g2000cwa.googlegroups.com> <1148511177.319796.228280@g10g2000cwb.googlegroups.com> <1148513110.914528.121280@i40g2000cwc.googlegroups.com> <1148543006.392324.74040@j33g2000cwa.googlegroups.com> Message-ID: <4475d6cb$1_3@newspeer2.tds.net> Zameer wrote: > I wonder where the "else" goes in try..except..finally... > try / except / else / finally See the PEP: http://www.python.org/dev/peps/pep-0341/ Kent From pydecker at gmail.com Mon May 15 17:44:39 2006 From: pydecker at gmail.com (Peter Decker) Date: Mon, 15 May 2006 17:44:39 -0400 Subject: Tabs versus Spaces in Source Code In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: On 5/15/06, Edward Elliott wrote: > If such tools are lacking, use substitutes in the meantime. Don't allow any > code to be checked in where a line departs more than one tab indentation > level from its neighbors. It's not perfect, but it eliminates the worst > offenses. Good enough often is. I've recently adopted the Dabo convention of using two indent levels to indicate continued lines, which helps distinguish such lines from the indented blocks below them. But other than that case, one tab it is! -- # p.d. From wescpy at gmail.com Wed May 3 10:46:02 2006 From: wescpy at gmail.com (w chun) Date: Wed, 3 May 2006 07:46:02 -0700 Subject: ANN: Advanced Python training, May 17-19, San Francisco Message-ID: <78b3a9580605030746t4b10144he7c6ca55584d1778@mail.gmail.com> FINAL REMINDER... we still have some seats left! What: Advanced Python Programming When: May 17-19, 2006 Where: San Francisco (SFO/San Bruno), CA, USA http://cyberwebconsulting.com (click on "Python Training") This course, meant to follow our in-depth introduction class, adds new tools to the Python programmer's toolkit. We explore advanced topics such as: sockets, Internet clients, GUIs with Tkinter, Web/CGI, databases/SQL, XML, Extending Python with C, threads, etc. We provide lectures, code samples, and some exer- cises to get attendees comfortable developing applications with Python in these disciplines. We are proud to be the only ones offering Python training in such advanced topics. Come join us in beautiful Northern California for another rigorous Python training event taught by software engineer, "Core Python Programming" author, and technical instructor, Wesley Chun. This is an introduction to Python in various areas of advanced topics geared towards those who have some programming experience in Python (any implemention, plat- form, or architecture). This course will take place in San Bruno right near the San Francisco International Airport at the: Staybridge Suites San Francisco Airport 1350 Huntington Ave San Bruno, CA 94066 USA +1-650-588-0770 LOCALS: it'll be at a hotel with easy 101/280/380, BART and CalTrain access (San Bruno stations) VISITORS: free shuttle directly from the San Francisco airport, lots of free food and wireless The cost is $1295 per attendee. Discounts are available for multiple registrations as well as teachers/students and those with financial hardship. For more information and registration, go to the website above. From john at castleamber.com Fri May 19 02:50:41 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 06:50:41 GMT Subject: Script to make Windows XP-readable ZIP file References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> <1148011001.613000.294750@g10g2000cwb.googlegroups.com> <1148014650.844340.212540@38g2000cwa.googlegroups.com> Message-ID: "softwindow" wrote: > Carl Banks is right Did he write to check out: http://groups.google.com/support/bin/answer.py?answer=14213 ? Why didn't you do so? -- 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 bray at sent.com Wed May 10 10:37:09 2006 From: bray at sent.com (Brian Ray) Date: Wed, 10 May 2006 09:37:09 -0500 Subject: Chicago Python Users Group Thurs May 11 at 7pm Message-ID: <7B589DAC-E7C7-4E69-8A56-1372DFE635CC@sent.com> This will be our best meeting yet! ChiPy's Monthly meeting this Thurs. May 11, 2006. 7pm. (except for folks who want to help setup at 6:30 and get first dibs on pizza) Location -------- ThoughtWorks' Chicago office 651 West Washington Blvd., 6th floor Chicago, IL 60661 Location description: "6 story, brick building on the Southwest corner of Washington Blvd. and Desplaines St." "Right next to the 90/94 freeway" "Across the street from the Social Security building" * Map * "Official" info Call jason at 3 1 2 - 3 7 3 . 8 5 5 6 if you get locked out or lost. (The external doors should be open, but be sure to enter on the "east" side (Desplaines) Street (meter) parking is available in the area. Shoot for "free" (no meters) parking on the South side of the building if you're lucky. And be sure to feed those meters; Brother Leader Daley collects tons of cash from meter fines in this area. Garage parking is also available across the street (technically across the interstate) at the very tall SkyBridge condo building. 1) The closest "L" stop is Clinton on the "Green Line". (About an 8 minute walk from TW.) 2) The closest Metra station is the Ogilvie Transportation Center (in the Citibank Building) 2 blocks east of TW. (a 4 minute walk) 3) The closest water taxi stop is at Madison Street Bridge at 2 North Riverside Plaza. () ;-) 4) I can't find good info on the nearest helipad. Sorry, Mr. Trump. 5) Besides garage parking at SkyBridge across the freeway and meter parking around the building, there is additional garage parking at the Presidential Towers at Jefferson & Madison. There are 2 non-garage parking lots adjacent to our building. (I don't know the lots' "after 5pm" parking rules, though). Theme: If you're addicted to oil, there are lots of parking options within a short walk. Topics ------ * Selenium-testing-Django -- (Jason Huggins) * Some lightning talks, crypt ... * PyCon in Chicago in 2008, bid. 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: ---- Forward this on. From apardon at forel.vub.ac.be Tue May 16 04:04:49 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 16 May 2006 08:04:49 GMT Subject: do/while structure needed References: <4466bddd$0$18984$c3e8da3@news.astraweb.com> <1147585422.693953.292480@u72g2000cwu.googlegroups.com> <4467786c$0$1956$c3e8da3@news.astraweb.com> Message-ID: Op 2006-05-15, Terry Reedy schreef : > > "John Salerno" wrote in message > news:4467786c$0$1956$c3e8da3 at news.astraweb.com... >> Thanks, that looks pretty good. Although I have to say, a do/while >> structure is the much more obvious way. I wonder why it hasn't been >> added to the language. > > Been suggested many times, been considered, and rejected. Easily similated > with while True: ... if exit_condition: break which also solves 'loop and a > half' problem, which is more common. Requires new keyword for little gain. > Etc. It isn't rejected. PEP 315 is only deferred. Which as far as I understand means it is postponed because other things seemed more important. -- Antoon Pardon From sjmachin at lexicon.net Sat May 13 08:30:53 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 May 2006 22:30:53 +1000 Subject: Named regexp variables, an extension proposal. In-Reply-To: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> References: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> Message-ID: <4465D17D.8020605@lexicon.net> On 13/05/2006 7:39 PM, Paddy wrote: [snip] > Extension; named RE variables, with arguments > =================================== > In this, all group definitions in the body of the variable definition > reference the literal contents of groups appearing after the variable > name, (but within the variable reference), when the variable is > referenced > > So an RE variable definition like: > defs = r'(?smx) (?P/GO/ go \s for \s \1 )' > > Used like: > rgexp = defs + r""" > (?P=GO (it) ) > \s+ > (?P=\GO (broke) ) > """ > Would match the string: > "go for it go for broke" > > As would: > defs2 = r'(?smx) (?P/GO/ go \s for \s (?P=subject) )' > rgexp = defs2 + r""" > (?P=GO (?P it) ) > \s+ > (?P=\GO (?P broke) ) > """ > > The above would allow me to factor out sections of REs and define > named, re-ussable RE snippets. > > > Please comment :-) 1. Regex syntax is over-rich already. 2. You may be better off with a parser for this application instead of using regexes. 3. "\\" is overloaded to the point of collapse already. Using it as an argument marker could make the universe implode. 4. You could always use Python to roll your own macro expansion gadget, like this: C:\junk>type paddy_rx.py import re flags = r'(?smx)' GO = r'go \s for \s &1 &2' WS = r'\s+' ARGMARK = "&" # Can the comments about the style of # this code; I've just translated it from # a now-dead language with max 6 chars in variable names :-) def macsub(tmplt, *infils): wstr = tmplt ostr = "" while wstr: lpos = wstr.find(ARGMARK) if lpos < 0: return ostr + wstr ostr = ostr + wstr[:lpos] nch = wstr[lpos+1:lpos+2] if "1" <= nch <= "9": x = ord(nch)-ord("1") if x < len(infils): ostr = ostr + infils[x] elif nch == ARGMARK: # double & (or whatever) ostr = ostr + ARGMARK else: ostr = ostr + ARGMARK + nch wstr = wstr[lpos+2:] return ostr regexp = " ".join([ flags, macsub(GO, 'it,\s', 'Paddy'), WS, macsub(GO, 'broke'), ]) print regexp text = "go for it, Paddy go for broke" m = re.match(regexp, text) print len(text), m.end() C:\junk>paddy_rx.py (?smx) go \s for \s it,\s Paddy \s+ go \s for \s broke 30 30 Cheers, John From kadeko at gmail.com Mon May 22 06:47:39 2006 From: kadeko at gmail.com (looping) Date: 22 May 2006 03:47:39 -0700 Subject: Includeing Python in text files In-Reply-To: References: Message-ID: <1148294859.382427.215920@j73g2000cwa.googlegroups.com> Paolo Pantaleo wrote: > I am working on this: > > I have a text file, containig certain section in the form > python code here > py?> > > I parse the text file and substitute the python code with its result > [redirecting sys.stdin to a StringIO]. It something like php or > embedded perl. > > So my little toy works not bad, but I was wondering if such a feature > already existed, if yes, can you point me out some links? > > Thnx > PAolo > > -- > if you have a minute to spend please visit my photogrphy site: > http://mypic.co.nr Like Diez had said, use a template system or you could look at COG: http://www.nedbatchelder.com/code/cog/ From hymort at hotmail.com Mon May 1 18:09:17 2006 From: hymort at hotmail.com (hymort at hotmail.com) Date: 1 May 2006 15:09:17 -0700 Subject: set partitioning Message-ID: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> Can someone tell me of a good algorithm to partition a set of n elements into m non-empty, disjoint subsets, where each subset has size k? From kay.schluehr at gmx.net Wed May 24 14:33:17 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 24 May 2006 11:33:17 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1148465076.973889.77040@i40g2000cwc.googlegroups.com> References: <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <44681F95.9040400@gmail.com> <1148411496.691868.53440@j73g2000cwa.googlegroups.com> <1148465076.973889.77040@i40g2000cwc.googlegroups.com> Message-ID: <1148495597.586562.181350@j73g2000cwa.googlegroups.com> Michele Simionato wrote: > Kay Schluehr wrote: > > http://www.fiber-space.de/EasyExtend/doc/EE.html > > Well, I have not read that page yet, but the name "fiber space" reminds > me of old > memories, when I was doing less prosaic things than now. Old times .. > ;) > > Michele Simionato But I guess that time this stuff was taught to you as "fiber bundles", right? Oh, yes. Old times ;) Well, besides the cute rhyme on "cyberspace" I had this analogy in mind and that's why I called the extension languages "fibers". The association is "fibers over a base space" or a base language as in this case. The terms are not used strictly of course. I could not even say what triviality could be in this context. But I still seek for an acceptable glue mechanism which is beyond the scope of the current first release :) Kay From dyoo at hkn.eecs.berkeley.edu Thu May 25 09:55:40 2006 From: dyoo at hkn.eecs.berkeley.edu (Danny Yoo) Date: Thu, 25 May 2006 06:55:40 -0700 (PDT) Subject: [Python-Help] os listdir access denied when run as a service In-Reply-To: <03cf01c67faf$97f94d20$346ea8c0@tintz.co.nz> References: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz><1146620207.56.7672@mint-julep.mondoinfo.com><002901c66e57$05a69090$346ea8c0@tintz.co.nz><1146624295.41.7841@mint-julep.mondoinfo.com><003501c66e64$316deb30$346ea8c0@tintz.co.nz><1146677203.2.7870@mint-julep.mondoinfo.com><00f701c673e5$a3af0860$346ea8c0@tintz.co.nz><1147292340.91.3040@mint-julep.mondoinfo.com><012d01c67473$09fc0450$346ea8c0@tintz.co.nz><1147305886.06.3304@mint-julep.mondoinfo.com><016201c67497$22a91d70$346ea8c0@tintz.co.nz> <1147311218.22.3304@mint-julep.mondoinfo.com> <03cf01c67faf$97f94d20$346ea8c0@tintz.co.nz> Message-ID: On Thu, 25 May 2006, Thomas Thomas wrote: > I am trying to access a mapped network drive folder. everything works > fine normally. But when i run the application as service I am getting > the error The error is on the line: for filename in os.listdir(folder):#line 25 and I have to assume that the bad call here is to os.listdir(). What's the particular input that's being sent to os.listdir() at the point of failure? As far as I can tell, the error message: > Traceback (most recent call last): > File "docBoxApp.py", line 129, in ? > File "core\PollFiles.pyc", line 332, in doPoll > File "core\PollFiles.pyc", line 47, in createFileList > File "core\PollFiles.pyc", line 25, in addFolderFiles > WindowsError: [Errno 5] Access is denied:'G:\\DT Hot Folder test/*.*' suggests that 'G:\\DT Hot Folder test/*.*' might be the folder being passed. If so, that could be the problem, since os.listdir takes the name of a directory: it does not take a file glob. Can you check to see what 'folder' is being passed into your program in the context of a file service? The problem may simply be bad input. We can check early on this by programming a bit defensively, mandating that on entry to addFolderFiles that 'folder' must be an existing directory: ######################################## def addFolderFiles(folder, filelist=[]): assert os.path.isdir(folder) ... ######################################## in which case, if we get past the assertion, we'll be able to at least know that we're getting in semi-good input. One other note: it is not recommended that we use a list as a default parameter value. That value will be shared among all calls to addFolderFiles, so we will see side effects. See the "Important Warning" in: http://docs.python.org/tut/node6.html#SECTION006710000000000000000 From grante at visi.com Tue May 23 13:25:28 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 23 May 2006 17:25:28 -0000 Subject: graphs and charts References: Message-ID: <1276hc8c8uf9870@corp.supernews.com> On 2006-05-23, Yaron Butterfield wrote: > What's the best way to on-the-fly graphs and charts using Python? Or is > Python not really the best way to do this? I like Gnuplot-py, but I've been a Gnuplot for 15+ years, so I'm biased. http://gnuplot-py.sourceforge.net/ -- Grant Edwards grante Yow! I have accepted at Provolone into my life! visi.com From bnblazer at gmail.com Wed May 31 21:48:30 2006 From: bnblazer at gmail.com (Brian) Date: 31 May 2006 18:48:30 -0700 Subject: TSV to HTML In-Reply-To: <447e268a$0$3699$4d3efbfe@news.sover.net> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> <447e268a$0$3699$4d3efbfe@news.sover.net> Message-ID: <1149126509.984331.306530@h76g2000cwa.googlegroups.com> First let me say that I appreciate the responses that everyone has given. A friend of mine is a ruby programmer but knows nothing about python. He gave me the script below and it does exactly what I want, only it is in Ruby. Not knowing ruby this is greek to me, and I would like to re-write it in python. I ask then, is this essentially what others here have shown me to do, or is it in a different vein all together? Code: class TsvToHTML @@styleBlock = <<-ENDMARK ENDMARK def TsvToHTML::wrapTag(data,tag,modifier = "") return "<#{tag} #{modifier}>" + data + "\n" end # wrapTag def TsvToHTML::makePage(source) page = "" rowNum = 0 source.readlines.each { |record| row = "" record.chomp.split("\t").each { |field| # replace blank fields with   field.sub!(/^$/," ") # wrap in TD tag, specify style row += wrapTag(field,"td","class=\"" + ((rowNum == 0)?"cellTitle":"cell#{rowNum % 2}") + "\"") } rowNum += 1 # wrap in TR tag, add row to page page += wrapTag(row,"tr") + "\n" } # finish page formatting [ [ "table","cellpadding=0 cellspacing=0 border=0" ], "body","html" ].each { |tag| page = wrapTag(@@styleBlock,"head") + page if tag == "html" page = wrapTag(page,*tag) } return page end # makePage end # class # stdin -> convert -> stdout print TsvToHTML.makePage(STDIN) From silveraltima at gmail.com Tue May 2 09:50:41 2006 From: silveraltima at gmail.com (saltima) Date: 2 May 2006 06:50:41 -0700 Subject: Pamie and Python - new browser focus Message-ID: <1146577841.461719.181010@e56g2000cwe.googlegroups.com> Hi all, I'm trying to automate my web browser testing by using Pamie and Python. Everything is going great except for when a new window opens up. (on the previous page, I click next, and a new window is opened up) The focus it seems is never transferred. I suspect this because the control is not being recognized. Here's the line for the control on the new page. ie.listBoxSelect('ddlOrType','1') Here's the error msgs: ** elementFind() did not find select-name;id-ddlOrType ** listBoxSelect() did not find ddlOrType-1 I can't seem to figure this out. Any ideas?? I would appreciate any help. From rpdooling at gmail.com Mon May 15 15:39:30 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 May 2006 12:39:30 -0700 Subject: common practice for creating utility functions? References: <7xd5efdstn.fsf@ruckus.brouhaha.com> Message-ID: <1147721970.417910.170780@i40g2000cwc.googlegroups.com> QOTW "Programming is not just creating strings of instructions for a computer to execute. It's also 'literary' in that you are trying to communicate a program structure to other humans reading the code." Paul Rubin rpd From andymac at bullseye.apana.org.au Thu May 11 09:16:44 2006 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Fri, 12 May 2006 00:16:44 +1100 Subject: Slow network reading? In-Reply-To: References: Message-ID: <4463393C.4000702@bullseye.apana.org.au> Ivan Voras wrote: > def query(self, sql): > self.sf.write("SQL %s\r\n" % sql) > self.sf.flush() > resp = self.sf.readline().rstrip() > m = SQLCacheD.re_rec.match(resp) > if m != None: # only if some rows are returned (SELECT) > n_rows = int(m.group(1)) > n_cols = int(m.group(2)) > cols = [] > for c in xrange(n_cols): > cols.append(self.sf.readline().rstrip()) > rs = [] > for r in xrange(n_rows): > row = {} > for c in cols: > row[c] = self.sf.readline().rstrip() > rs.append(row) > return rs > m = SQLCacheD.re_ok.match(resp) > if m != None: # no rows returned (e.g. INSERT/UPDATE/DELETE) > return True > raise SQLCacheD_Exception(resp) Comparative CPU & memory utilisation statistics, not to mention platform and version of Python, would be useful hints... Note that the file-like object returned by makefile() has significant portions of heavy lifting code in Python rather than C which can be a drag on ultimate performance... If on a Unix platform, it may be worth experimenting with os.fdopen() on the socket's fileno() to see whether the core Python file object (implemented in C) can be used in place of the lookalike returned from the makefile method. Even without that, you are specifying a buffer size smaller than the default (8k - see Lib/socket.py). 16k might be even better. Although they're only micro-optimisations, I'd be interested in the relative performance of the query method re-written as: def query(self, sql): self.sf.write("SQL %s\r\n" % sql) self.sf.flush() sf_readline = self.sf.readline resp = sf_readline().rstrip() m = self.re_rec.match(resp) if m is not None: # some rows are returned (SELECT) rows = range(int(m.group(1))) cols = range(int(m.group(2))) for c in cols: cols[c] = sf_readline().rstrip() for r in rows: row = {} for c in cols: row[c] = sf_readline().rstrip() rows[r] = row return rows elif self.re_ok.match(resp) is not None: # no rows returned (e.g. INSERT/UPDATE/DELETE) return True raise SQLCacheD_Exception(resp) This implementation is based on 2 strategies for better performance: - minimise name lookups by hoisting references from outside the method to local references; - pre-allocate lists when the required sizes are known, to avoid the costs associated with growing them. Both strategies can pay fair dividends when the repetition counts are large enough; whether this is the case for your tests I can't say. -- ------------------------------------------------------------------------- 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 ptmcg at austin.rr._bogus_.com Sat May 27 12:52:20 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 27 May 2006 16:52:20 GMT Subject: groupby References: <1148356503.165982.247800@y43g2000cwc.googlegroups.com> Message-ID: <8t%dg.63057$Qq.50603@tornado.texas.rr.com> "Paul McGuire" wrote in message news:bzxcg.53765$Qq.42913 at tornado.texas.rr.com... > So here's how to save the values from the iterators while iterating over the > groupby: > > >>> m = [(x,list(y)) for x,y in groupby([1, 1, 1, 2, 2, 3])] > >>> m > [(1, [1, 1, 1]), (2, [2, 2]), (3, [3])] > > -- Paul > > Playing some more with groupby. Here's a one-liner to tally a list of integers into a histogram: # create data set, random selection of numbers from 1-10 dataValueRange = range(1,11) data = [random.choice(dataValueRange) for i in xrange(10)] print data # tally values into histogram: # (from the inside out: # - sort data into ascending order, so groupby will see all like values together # - call groupby, return iterator of (value,valueItemIterator) tuples # - tally groupby results into a dict of (value, valueFrequency) tuples # - expand dict into histogram list, filling in zeroes for any keys that didn't get a value hist = [ (k1,dict((k,len(list(g))) for k,g in itertools.groupby(sorted(data))).get(k1,0)) for k1 in dataValueRange ] print hist Gives: [9, 6, 8, 3, 2, 3, 10, 7, 6, 2] [(1, 0), (2, 2), (3, 2), (4, 0), (5, 0), (6, 2), (7, 1), (8, 1), (9, 1), (10, 1)] Change the generation of the original data list to 10,000 values, and you get something like: [(1, 995), (2, 986), (3, 941), (4, 998), (5, 978), (6, 1007), (7, 997), (8, 1033), (9, 1038), (10, 1027)] If you know there wont be any zero frequency values (or don't care about them), you can skip the fill-in-the-zeros step, with one of these expressions: histAsList = [ (k,len(list(g))) for k,g in itertools.groupby(sorted(data)) ] histAsDict = dict((k,len(list(g))) for k,g in itertools.groupby(sorted(data))) -- Paul From vbgunz at gmail.com Fri May 26 06:47:52 2006 From: vbgunz at gmail.com (vbgunz) Date: 26 May 2006 03:47:52 -0700 Subject: how to clear up a List in python? In-Reply-To: References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148636521.026385.171410@y43g2000cwc.googlegroups.com> <1148638555.440810.277540@i40g2000cwc.googlegroups.com> Message-ID: <1148640472.914547.11640@j55g2000cwa.googlegroups.com> I read the ten commandments. I enjoyed the link. I see my mistakes. Thank you. From mensanator at aol.com Wed May 3 14:30:13 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 3 May 2006 11:30:13 -0700 Subject: A python problem about int to long promotion just see the idle session In-Reply-To: <1146676227.349286.280250@v46g2000cwv.googlegroups.com> References: <1146676227.349286.280250@v46g2000cwv.googlegroups.com> Message-ID: <1146681013.414888.144770@g10g2000cwb.googlegroups.com> gen_tricomi wrote: > Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] > on win32 > Type "copyright", "credits" or "license()" for more information. > > **************************************************************** > Personal firewall software may warn about the connection IDLE > makes to its subprocess using this computer's internal loopback > interface. This connection is not visible on any external > interface and no data is sent to or received from the Internet. > **************************************************************** > > IDLE 1.1.2 > >>> import sys > >>> save_maxint = sys.maxint > >>> save_maxint > 2147483647 > >>> save_maxint += 1 > >>> save_maxint > 2147483648L > >>> save_maxint - 1 > 2147483647L > >>> save_maxint + 1 > 2147483649L > >>> save_maxint - 1 > 2147483647L > >>> save_maxint + 1 > 2147483649L > >>> save_maxint - 1 > 2147483647L > >>> save_maxint + 1 > 2147483649L > > > from the above you can see what int to long promotion is causing Nope, it's not the promotion causing the problem. > i dont need to say much please see for yourself. is this a bug or > a feature. Neither. Try changing the "+" and "-" to "+=" and "-=". > > please mail me if you can help "I don't think there can be any question about it. It can only be attributable to human error. This sort of thing has cropped up before... ...and it has always been due... ...to human error." - HAL, 2001: A Space Odessy > > ogahejini at yahoo.com From "reverse[nepank.noot]" at fft.be Tue May 16 10:19:57 2006 From: "reverse[nepank.noot]" at fft.be (Toon Knapen) Date: Tue, 16 May 2006 16:19:57 +0200 Subject: build now requires Python exist before the build starts Message-ID: <4469df8d$0$442$6c56d894@reader0.news.be.easynet.net> I'm trying to build the svn-trunk version of python on a Solaris box. However I do not have a python installed yet and apparantly the build of python requires a python to be accessible (as also annotated in the Makefile generated during the ./configure). How can I solve this situation? Thanks, toon From fredrik at pythonware.com Thu May 25 17:54:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 May 2006 23:54:31 +0200 Subject: Problem with itertools.groupby. In-Reply-To: References: <1148591325.875006.246120@j55g2000cwa.googlegroups.com> Message-ID: > itertools only looks for changes to the key value (the one returned by > operator.itemgetter(0) in your case); it doesn't sort the list for you. > > this should work: > > for k, g in itertools.groupby(sorted(vals), operator.itemgetter(0)): > print k, [i for i in g] footnote: to turn the contents in an iterator into a list object, list(g) is a bit more convenient than [i for i in g]. From imcsee at gmail.com Tue May 9 07:57:34 2006 From: imcsee at gmail.com (imcs ee) Date: Tue, 9 May 2006 19:57:34 +0800 Subject: Python editor recommendation. In-Reply-To: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: free and vim or wingide On 5/9/06, DeepBlue <123 at 321.com> wrote: > > Hi all, > > Can any one please recommend me an editor for coding Python. Thank u. > I have Komodo (www.activestate.com) in my mind. Is the editor any good? > > regards. > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From simon.hibbs at gmail.com Fri May 12 11:43:28 2006 From: simon.hibbs at gmail.com (simon.hibbs at gmail.com) Date: 12 May 2006 08:43:28 -0700 Subject: listener program in Python References: <1147445594.747005.61620@y43g2000cwc.googlegroups.com> Message-ID: <1147448608.316757.228500@v46g2000cwv.googlegroups.com> diffuser78 at gmail.com wrote: > I basically want to remotely shut down windows from linux and write > such a program in python. You probably don't need to write a service in windows for this. All you need is to write your Linux python program with an SNMP library and configure the Windows box to accept SNMP calls to shut down. Frankly I'm not 100% sure how to do this. You'd have to enable the SNMP Agent on Windows, and probably the "Force shutdown from a remote system" system policy would have to be changed. The O'Reilly book "Python programming on Win32" explains how to write Windows services and do basic networking. This article explains one way: http://tinyurl.com/ezjx7 Simon Hibbs From johnjsal at NOSPAMgmail.com Tue May 9 15:21:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 19:21:04 GMT Subject: regular expressions, substituting and adding in one step? In-Reply-To: <4460e0d7$1_1@newspeer2.tds.net> References: <4460e0d7$1_1@newspeer2.tds.net> Message-ID: Kent Johnson wrote: > Do it all in one match / substitution using \1 to insert the value of > the paragraph group at the new location: > > In [19]: test = "self.source += '

' + paragraph + '

\n\n'" > > In [20]: re.sub(r"'

' \+ (.*?) \+ '

\n\n'", r"'

%s

\n\n' % > \1", test) > Out[20]: "self.source += '

%s

\n\n' % paragraph" Interesting. Thanks! I was just doing some more reading of the re module, so now I understand sub() better. I'll give this a try too. Call me crazy, but I'm interested in regular expressions right now. :) From chris.uppal at metagnostic.REMOVE-THIS.org Wed May 10 04:58:34 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Wed, 10 May 2006 09:58:34 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <87wtcyy5i0.fsf@rpi.edu> <445dc17a$1$25449$bed64819@news.gradwell.net> <87d5eq6rx1.fsf@rpi.edu> Message-ID: <4461c69f$1$647$bed64819@news.gradwell.net> Bill Atkins wrote: > My favorite macro is ITERATE [...] Thanks for the examples. -- chris From gherron at islandtraining.com Wed May 17 13:05:48 2006 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 17 May 2006 10:05:48 -0700 Subject: Process forking on Windows In-Reply-To: <126mi8q1t31r9e0@corp.supernews.com> References: <126mgi2j7fl4b4b@corp.supernews.com> <446b45b1$0$7132$636a55ce@news.free.fr> <126mi8q1t31r9e0@corp.supernews.com> Message-ID: <446B57EC.7040001@islandtraining.com> Andrew Robert wrote: >bruno at modulix wrote: > > >>Andrew Robert wrote: >> >> >>>Hi everyone, >>> >>> >>>I have a python program that will need to interact with an MQSeries >>>trigger monitor. >>> >>>It does this fine but it hogs the trigger monitor while it executes. >>> >>>I'd like to fork the program off and terminate the parent process so >>>that the trigger monitor frees up. >>> >>> >> >>Is this really the solution ? >> >> >> >> >>>Does anyone how this can be accomplished on a Windows platform? >>> >>> >>AFAIK, there's no fork in Windows - you might want to give a try with >>CreateProcess. >>http://www.byte.com/art/9410/sec14/art3.htm >>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/html/UCMGch01.asp >> >>HTH >> >> > > >Unfortunately there is a real need for this. > >The MQSeries trigger monitor is single threaded. > >Because of this, my program would absorb it until it completes. > >The way to get around this would be to fork off and terminate the parent. > >Unfortunately, Windows appears to be somewhat stubborn about it. > >Creating a subprocess does not alleviate the need to get the originating >process out of the trigger monitor. > > The windows CreateProcess call has many of the same semantics as the Unix fork, i.e., a new process is created sharing all the resources of the original process. The "subprocess" modules uses CreateProcess, but if that does not give you sufficient control over the process creation, you can call CreateProcess directly via the "win32process" module in the win32all package. However, I still don't understand *what* the "MQSeries trigger monitor" is or *how* it would create the need for such a solution. Gary Herron From eric_brunel at despammed.com Mon May 22 04:05:38 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Mon, 22 May 2006 10:05:38 +0200 Subject: Tk.iconname still there? References: <87odxqubbj.fsf@localhost.localdomain> Message-ID: On 22 May 2006 10:56:16 +1000, Gary Wessle wrote: > Hi > > I am going through a tutorial on Tkinter > http://doctormickey.com/python/pythontutorial_201.html, it referees to > Tk.iconname() but I could not locate one after googleing and browsed > and searched the Tkinter On-line reference material in the Tkinter > reference: a GUI for Python, 84 pp. pdf from > here http://infohost.nmt.edu/tcc/help/pubs/lang.html Unfortunately, AFAICT, the only reference you can trust for Tkinter is the manual pages for tcl/tk, available here: http://www.tcl.tk/man/ The iconname method is mapped to the command "wm iconname" in tk, so just look for this one in the man pages for your tk version and you'll get the most up to date documentation you may have for it. BTW, both the tutorial and the "reference" you're using contain a few things I would not do: - Both create menu bars via Menubutton widgets. This is obsolete: menu bars are now standard Menu widgets containing only cascade items and are attached to the containing window via: wdw.configure(menu=menuInstance). - The Application class in the minimal application described in the "reference" inherits from Frame: this is a bad idea. If you want to inherit from something, inherit from Tk. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From onurb at xiludom.gro Fri May 12 09:32:31 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 15:32:31 +0200 Subject: NEWBIE: Tokenize command output In-Reply-To: References: <446478eb$0$287$626a54ce@news.free.fr> Message-ID: <44648ed3$0$12812$636a55ce@news.free.fr> Tim Chase wrote: >>> starLines = [line for line in p.readlines() if line.startswith("*")] >> >> >> files are iterators, so no need to use readlines() (unless it's an old >> Python version of course): >> >> starLines = [line for line in p if line.startswith("*")] > > > Having started with some old Python, it's one of those things I "know", > but my coding fingers haven't yet put into regular practice. :) I reeducated my fingers after having troubles with huge files !-) >>> or you may optionally want to prune of the "\n" characters in the >>> process: >>> >>> starLines = [line[:-1] for line in p.readlines() if >>> line.startswith("*")] >> >> >> *please* use str.rstrip() for this: >> starLines = [line.rstrip() for line in p if line.startswith("*")] > > > They can yield different things, no? > >>>> s = "abc \n" >>>> s[:-1] > 'abc ' >>>> s.rstrip() > 'abc' >>>> s.[:-1] == s.rstrip() > False > > If trailing space matters, you don't want to throw it away with rstrip(). then use rstrip('\n') - thanks for this correction. > Otherwise, just to be informed, what advantage does rstrip() have over > [:-1] (if the two cases are considered uneventfully the same)? 1/ if your line doesn't end with a newline, line[:-1] will still remove the last caracter. 2/ IIRC, if you don't use universal newline and the file uses the DOS/Windows newline convention, line[:-1] will not remove the CR - only the LF (please someone correct me if I'm wrong here). I know this may not be a real issue in the actual case, but using rstrip() is still a safer way to go IMHO - think about using this same code to iterate over a list of strings without newlines... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From andy at neotitans.com Wed May 17 06:18:34 2006 From: andy at neotitans.com (Andy Sy) Date: Wed, 17 May 2006 18:18:34 +0800 Subject: Tabs are evil, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: Harry George wrote: > This has been discussed repeatedly, and the answer is "If you only > work alone, never use anyone else's code and no one ever uses your > codes, then do as you please. Otherwise use tab-is-4-spaces." > > When you do Agile Programming with people using emacs, vim, nedit, > xedit, wordpad, eclipse, and who knows what else, the 4-spaces rule is > necessary for survival. > > The reason is simple: People get confused, and accidentally get the > wrong tab indents when they move among editors or among settings on > the same editor. In most languages this is an irritation, requiring > some cleanup. In Python it is a disaster requiring re-inventing the > coded algorithms. 1. Tabs as 8 spaces just take up way too much horizontal space, so you can't use 8-space tabs... 2. BUT... you can't use any other value (not even 4)... !! WHY?? Because if you do, you will screw up display using /something as basic as cat, less, more (and many other unix utilities where the historical assumption that tabs are 8 spaces is hardcoded)! DOES ANYONE NEED ANY REASON MORE COMPLICATED THAN THE ABOVE TO JUST *NOT* USE TABS?? Yet ANOTHER proof that tabs are evil: 3. If tabs weren't around, we wouldn't have all these time-wasting threads on tabs vs. spaces, or on how many spaces a tab should represent. Tabs were an unnecessary Rube Goldberg invention misguidedly carried over from the typewriter era. They are the appendix of text editors. Just because they're there doesn't necessarily mean they serve any (even remotely) useful purpose. -- It's called DOM+XHR and it's *NOT* a detergent! From robert.kern at gmail.com Fri May 5 18:25:58 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 05 May 2006 17:25:58 -0500 Subject: NaN handling In-Reply-To: <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> References: <125hplqmppfeq29@corp.supernews.com> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> Message-ID: Ivan Vinogradov wrote: >> >>There are those of us that need NaNs in production code, so it >>would have to be something that could be configured. I find >>that in my programs the places where I need to do something >>"exceptional" with a NaN are very limited. The vast majority >>of the time, I need them to propagate quietly. > > Our programming expectations may differ, but an option to catch NaNs as > an exception is a great idea. numpy lets the programmer control how NaNs are handled in numpy code. Producing a NaN can be ignored, create a warning, raise an exception or call a function. It's not well documented at the moment, but the functions are seterr(), seterrcall(), seterrobj(), geterr(), geterrcall(), and geterrobj(). Pure Python has a similar, but somewhat less flexible method, on UNIX platforms. http://docs.python.org/dev/lib/module-fpectl.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From kevin.bell at slcgov.com Mon May 15 12:11:38 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Mon, 15 May 2006 10:11:38 -0600 Subject: py on windows Mobile 5.0? Message-ID: <2387F0EED10A4545A840B231BBAAC722608345@slcimail1.slcgov.com> Does anyone know if/how to go about using python on a windows mobile 5.0 PDA? Kevin From junkytownMAKNI at gmail.com Mon May 29 07:28:05 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Mon, 29 May 2006 13:28:05 +0200 Subject: saving settings In-Reply-To: References: Message-ID: aum wrote: > On Mon, 29 May 2006 09:05:36 +0200, SuperHik wrote: > >> Hi, >> >> I was wondering how to make a single .exe file, say some kind od clock, >> and be able to save some settings (alarm for example) into the same >> file? Basically make code rewrite it self... >> >> thanks! > > Yikes!!! > > I'd strongly suggest you read the doco for ConfigParser, and load/save > your config file to/from os.path.join(os.path.expanduser("~")). > > Another option - save your stuff in the Windows Registry > but if I copy this file on the other computer settings will be lost... From nobody at 127.0.0.1 Wed May 17 13:08:48 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 17:08:48 GMT Subject: Tabs versus Spaces in Source Code References: <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> <1147862865.142339.117610@j55g2000cwa.googlegroups.com> <1147868309.125766.112550@u72g2000cwu.googlegroups.com> <1352828.BsCtm2PuaN@jupiter.g2ctech> <1147874691.650993.54610@j33g2000cwa.googlegroups.com> Message-ID: achates wrote: > Jorge Godoy wrote > >>Emacs guess what's used in the file and allows me to use tabs all the >>time, doing the correct thing... > > That sounds like useful behaviour. vim can do it to. http://www.vim.org/scripts/script.php?script_id=1171 -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From __peter__ at web.de Tue May 2 03:15:36 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 May 2006 09:15:36 +0200 Subject: string.find first before location References: <87hd49m0xc.fsf@localhost.localdomain> Message-ID: Gary Wessle wrote: > I have a string like this > > text = "abc abc and Here and there" > I want to grab the first "abc" before "Here" > > import string > string.find(text, "Here") # > > I am having a problem with the next step. These days str methods are preferred over the string module's functions. >>> text = "abc abc and Here and there" >>> here_pos = text.find("Here") >>> text.rfind("abc", 0, here_pos) 4 Peter From phddas at yahoo.com Thu May 4 05:50:17 2006 From: phddas at yahoo.com (Gary Wessle) Date: 04 May 2006 19:50:17 +1000 Subject: scope of variables References: <874q06bz4c.fsf@localhost.localdomain> <87zmhyagqq.fsf@localhost.localdomain> Message-ID: <87lktinmp2.fsf@localhost.localdomain> Ryan Forsythe writes: > Gary Wessle wrote: > > the example was an in-accuretlly representation of a the problem I am > > having. my apologies. > > > > a = [] > > def prnt(): > > print len(a) > > > >>>> prnt > > > > > > I expect to get 0 "the length of list a" > > You want prnt(), not prnt: > I finally was able to duplicate the error with a through away code as follows, **************************************************************** acc = [1,2,3] def a(): b = [4, 5, 6] acc = acc + b print len(acc) a() **************** error **************** Traceback (most recent call last): File "a.py", line 12, in ? a() File "a.py", line 9, in a acc = acc + b UnboundLocalError: local variable 'acc' referenced before assignment From fred at adventistcare.org Wed May 31 14:45:35 2006 From: fred at adventistcare.org (Sells, Fred) Date: Wed, 31 May 2006 14:45:35 -0400 Subject: ideas for programs? Message-ID: <1A4BF05172023E468CB6E867923BC90402B6E102@accmail2.sunbelt.org> to regurgitate what others have said. trying to solve a real-world problem is significantly more educational that writing toy programs and class assignments. Solving a real-world problem will generate more interest in your potential ability that knowing any language. Pick a problem that you and others you know would like to have solved, then you can get support, feedback and motivation to keep going. good luck! --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From ilitzroth at gmail.com Tue May 30 05:36:28 2006 From: ilitzroth at gmail.com (ilitzroth at gmail.com) Date: 30 May 2006 02:36:28 -0700 Subject: John Bokma harassment In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> Message-ID: <1148981788.547993.91320@g10g2000cwb.googlegroups.com> >Your first question should be: Is it alright that Xah harasses 5 >newsgroups? Or maybe work on your spelling, harass is with one r, but >maybe you didn't read the subject, which wouldn't amaze me, since you >sound like you should be spending time on MySpace OMG!. Dear John, Should I ask myself the question about Xah first, or work on my spelling? I knew har*ass it had 1 or more r's in it but I couldn't figure out the exact number. That makes me suspect my spelling is good enough and I should dive right into the Xah issue. What do you think John? I don't get the MySpace OMG reference, but rest assured John, you are still my favorite newsnet nazi. I know you have been feeling pretty insecure about this Xah fellow, but you know that is just silly, don't you? Yours truly Immanuel P.S Do not hesitate to comment on form, spelling or style of this message. I am always eager to learn. From fredrik at pythonware.com Sat May 20 03:25:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 May 2006 09:25:45 +0200 Subject: Creating a new file object; open() vs file() In-Reply-To: <87wtchiily.fsf_-_@benfinney.id.au> References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <87wtchiily.fsf_-_@benfinney.id.au> Message-ID: Ben Finney wrote: >> I see what you mean, but I think that's why I like using open, >> because I like having my functions be verbs instead of nouns. > > Note though that you're calling a class (in this case, type) > constructor, to return a new object. no, he's calling a factory function to get an object that provides the expected behaviour. in future versions of Python, open() may not always create an instance of the file type. From fredrik at pythonware.com Mon May 1 14:17:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 1 May 2006 20:17:28 +0200 Subject: how to do with the multi-frame GIF References: <1146501122.180961.11580@i39g2000cwa.googlegroups.com> <5f56302b0605011101ia970684p5ccffdba5115ac83@mail.gmail.com> Message-ID: Daniel Nogradi wrote: > The source distribution of the 1.1.4 version comes with a Scripts > directory where you can find player.py, gifmaker.py and explode.py > which all deal with animated gif. I don't know if they work with > version 1.1.5 though. they're still shipped with 1.1.5 (and 1.1.6), and they should work. if all you're missing is a few files from the script directory, you can get them here: http://effbot.python-hosting.com/browser/pil/Scripts/ From thomasbartkus at comcast.net Wed May 10 12:03:39 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 10 May 2006 11:03:39 -0500 Subject: MySQLdb trouble References: Message-ID: "John Salerno" wrote in message news:U_n8g.2079$No6.45875 at news.tufts.edu... > Thomas Bartkus wrote: > > > 1) His code body will be less likely to cause migrane headaches when he > > tries to read and interpret what he did a year from now. If you are trying > > to figure out what is going on with the logic, user names and passwords can > > be so much chaff your brain needs to wade through in order to get to the > > central idea. > > > > 2) The coder won't have to repeat himself if he needs to re-open the > > databases. > > Ah, that makes sense! It seemed like an unnecessary step, but in some > ways it might end up being more efficient. For the machine - it *is* an unnecessary step. For the human being who must write and maintain code, it is quite a useful step. And a very excellent coding habit to get into ;-) Thomas Bartkus From rpdooling at gmail.com Wed May 31 20:31:40 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 31 May 2006 17:31:40 -0700 Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> <1149083447.370584.197070@f6g2000cwb.googlegroups.com> <1149116972.201718.155660@h76g2000cwa.googlegroups.com> Message-ID: <1149121900.895494.24360@y43g2000cwc.googlegroups.com> > I can only assume that there was some type of cache problem. Could it > have been in the .pyc? I thought that was recompiled every time a .py > is run/set to be interpreted. If you are on Windows, check your PATHEXT environment variable and make sure that .py is listed ahead of .pyc and any other .py? See, e.g., a bug in earlier versions of ActiveState distrib http://tinyurl.com/qok9v rd "Electricity is actually made up of extremely tiny particles called electrons, that you cannot see with the naked eye unless you have been drinking."--Dave Barry From garylinux at gmail.com Tue May 2 19:47:06 2006 From: garylinux at gmail.com (garylinux at gmail.com) Date: 2 May 2006 16:47:06 -0700 Subject: detect video length in seconds Message-ID: <1146613626.090047.186390@j33g2000cwa.googlegroups.com> Is there a way to get the length of a video clip (divix/xvid) in seconds? oh this is on linux. I first tryed to see if mplayer would tell me then I could wrap the call in a popen object and be done but it does not appear to output the length. Now I am looking at pymedia .It would be nice if there was some actual docmentation for it. From aylwyn at cantab.net Mon May 15 20:06:19 2006 From: aylwyn at cantab.net (achates) Date: 15 May 2006 17:06:19 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147737979.892505.33010@i40g2000cwc.googlegroups.com> Harry George wrote: > The reason is simple: People get confused, and accidentally get the > wrong tab indents when they move among editors or among settings on > the same editor. People certainly do get confused. I'm always amazed that so many people, even amongst those who manage to make a living out of writing software, are unable to grasp the concept of a tab. But then a lot of code is badly written, so maybe it figures. A tab is not equivalent to a number of spaces. It is a character signifying an indent, just like the newline character signifies the end of a line. If your editor automatically converts tabs to spaces (i.e. you are unable to create source files containing tabs) then either it's broken or you have misconfigured it. Either way you probably shouldn't be using it to write code. From dale at riverhall.nospam.co.uk Mon May 22 11:00:48 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Mon, 22 May 2006 16:00:48 +0100 Subject: XML/HTML Encoding problem Message-ID: A colleague has asked me this and I don't know the answer. Can anyone here help with this? Thanks in advance. Here is his email: I am trying to parse an HTML document using the xml.dom.minidom parser and then outputting a valid HTML document, all using the ISO-8859-1 charset. For example: My input: € Desired output: € Note that it doesn't matter if the '' header gets stripped. ?What does matter is that the input document has the 'ISO-8859-1' charset and is an ANSI encoded file. The problem I get is that when I run, for example: from xml.dom.minidom import parseString output = parseString(strHTML).toxml() The output is: <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type"/> </head> <body> ? </body> </html> So it encodes the entity reference to ? (Euro sign). ?I need it to remain as € so that the resulting HTML can render properly in a browser. ?Is there a way to make the parser not convert the entity references? ?Or is there a convenient post processing function that will do the conversion? -- Dale Strickland-Clark Riverhall Systems www.riverhall.co.uk From softwindow at gmail.com Wed May 24 05:41:41 2006 From: softwindow at gmail.com (softwindow) Date: 24 May 2006 02:41:41 -0700 Subject: hi,every body. a problem with PyQt. In-Reply-To: <1148463003.324183.279350@y43g2000cwc.googlegroups.com> References: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> <1148463003.324183.279350@y43g2000cwc.googlegroups.com> Message-ID: <1148463700.936915.279470@i40g2000cwc.googlegroups.com> thanks everyone! From Symantec_Mail_Security_for_SMTP at hu.edu.jo Mon May 22 09:13:56 2006 From: Symantec_Mail_Security_for_SMTP at hu.edu.jo (Symantec_Mail_Security_for_SMTP at hu.edu.jo) Date: Mon, 22 May 2006 15:13:56 +0200 (CEST) Subject: =?utf-8?B?RGVsaXZlcnkgZmFpbHVyZSBub3RpZmljYXRpb25=?= Message-ID: <20060522131356.10EC01E4007@bag.python.org> Your message with Subject: yrzlpth could not be delivered to the following recipients: brent at fau.edu Please do not resend your original message. Delivery attempts will continue to be made for 5 day(s). From bignose+hates-spam at benfinney.id.au Fri May 19 21:15:33 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 May 2006 11:15:33 +1000 Subject: noob import question References: <mailman.5945.1148045097.27775.python-list@python.org> <4d5vqaF18i4l1U1@uni-berlin.de> <DB3DA882-103B-4AFF-ADFF-458070A8CD3C@brianandkate.com> Message-ID: <874pzljy2y.fsf@benfinney.id.au> [Please don't top-post. Please don't indiscriminately quote the entire message you respond to. <URL:http://en.wikipedia.org/wiki/Top_posting>] Brian Blazer <brian at brianandkate.com> writes: > Thank you for your responses. I had a feeling is had something to > do with a namespace issue but I wasn't sure. Another point to note is that 'from foo import *' is bad practice. It causes a problem known as "namespace pollution", where you can't tell where a particular name you're using comes from, or if you have accidentally clobbered an existing name. Either import the module to a single name, so you can qualify the names inside that module: import foo import awkward_long_module_name as bar foo.eggs() bar.beans() Or, if you only need a few objects from the module, import those specifically and use their names directly: from foo import spam, eggs eggs() spam() > You are right, I do come from a Java background. If it is poor form > to name your class file the same as your class, can I ask what the > standard is? Since we don't need to have one file per class, the convention is to group your modules by coherent functionality. Place any names, functions, classes, whatever that all relate to a discrete, coherent set of functionality in a single module. The Python coding guidelines[0] also recommend that the module be named all in lower-case, but that's more about consistency within your own code base. [0]: <URL:http://www.python.org/dev/peps/pep-0008> -- \ "I have a map of the United States; it's actual size. It says | `\ '1 mile equals 1 mile'... Last summer, I folded it." -- Steven | _o__) Wright | Ben Finney From paddy3118 at netscape.net Tue May 23 14:09:50 2006 From: paddy3118 at netscape.net (Paddy) Date: 23 May 2006 11:09:50 -0700 Subject: how to work with tab-delimited files? In-Reply-To: <j1Icg.2154$No6.46850@news.tufts.edu> References: <j1Icg.2154$No6.46850@news.tufts.edu> Message-ID: <1148407790.158164.29430@i39g2000cwa.googlegroups.com> Hmm, check your editor to see if it has an option to display non-printable characters, or see if you can search for tabs in its find utility. If you find that your editor has the ability to insert spaces instead of tabs then turn it off. Thats all that comes to mind... - Pad. From manstey at csu.edu.au Wed May 17 00:20:16 2006 From: manstey at csu.edu.au (manstey) Date: 16 May 2006 21:20:16 -0700 Subject: A Unicode problem -HELP References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <mailman.5778.1147833528.27775.python-list@python.org> Message-ID: <1147839615.973950.54770@y43g2000cwc.googlegroups.com> I'm a newbie at python, so I don't really understand how your answer solves my unicode problem. I have done more reading on unicode and then tried my code in IDLE rather than WING IDE, and discovered that it works fine in IDLE, so I think WING has a problem with unicode. For example, in WING this code returns an error: a={'a':u'\u0254'} print a['a'] UnicodeEncodeError: 'ascii' codec can't encode character u'\u0254' in position 0: ordinal not in range(128) but in IDLE it correctly prints open o So, assuming I now work in IDLE, all I want help with is how to read in an ascii string and convert its letters to various unicode values and save the resulting 'string' to a utf-8 text file. Is this clear? so in pseudo code 1. F is converted to \u0254, $ is converted to \u0283, C is converted to \u02A6\02C1, etc. (i want to do this using a dictionary TRANSLATE={'F':u'\u0254', etc) 2. I read in a file with lines like: F$ FCF$ $$C$ etc 3. I convert this to \u0254\u0283 \u0254\u02A6\02C1\u0254 etc 4. i save the results in a new file when i read the new file in a unicode editor (EmEditor), i don't see \u0254\u02A6\02C1\u0254, but I see the actual characters (open o, esh, ts digraph, modified letter reversed glottal stop, etc. I'm sure this is straightforward but I can't get it to work. All help appreciated! From conor.robinson at gmail.com Wed May 10 19:38:21 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 10 May 2006 16:38:21 -0700 Subject: Best form when using matrices and arrays in scipy... Message-ID: <1147304301.787642.309380@v46g2000cwv.googlegroups.com> Using large arrays of data I found it is MUCH faster to cast arrays to matricies and then multiply the two matricies togther (scipy.matrix(ARRAY1)*scipy.matrix(ARRAY2)) in order to do a matrix multipy of two arrays vs. scipy.matrixmultipy(ARRAY1, ARRAY2). Are there any logical/efficiency errors with this train of thought and is there a valid reason for the speed increase? Thanks, Conor From xi at gamma.dn.ua Mon May 8 07:25:01 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 8 May 2006 14:25:01 +0300 Subject: [ANN] PyYAML-3.01: YAML parser and emitter for Python Message-ID: <20060508112500.GA13310@58sirius016.dc.ukrtel.net> PyYAML: YAML parser and emitter for Python ========================================== I am pleased to announce the initial release of PyYAML. YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. You may download PyYAML from http://pyyaml.org/wiki/PyYAML. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... version: 3.01 ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'version': 3.01, 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) homepage: http://pyyaml.org/wiki/PyYAML version: 3.01 name: PyYAML keywords: [YAML, serialization, configuration, persistance, pickle] description: YAML parser and emitter for Python Links ===== PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.01.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.01.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.01.win32.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core Changes ======= * Initial release. The version number reflects the codename of the project (PyYAML 3000) and differenciates it from the abandoned PyYaml module. Copyright ========= The PyYAML module is written by Kirill Simonov <xi at resolvent.net>. PyYAML is released under the MIT license. -- xi From bray at sent.com Wed May 10 09:13:00 2006 From: bray at sent.com (bray at sent.com) Date: Wed, 10 May 2006 08:13:00 -0500 Subject: Chicago Python Users Group Thurs May 11 at 7pm In-Reply-To: <1144783523.18842.258867354@webmail.messagingengine.com> References: <1144783523.18842.258867354@webmail.messagingengine.com> Message-ID: <1147266780.20863.261082962@webmail.messagingengine.com> This will be our best meeting yet! ChiPy's Monthly meeting this Thurs. May 11, 2006. 7pm. (except for folks who want to help setup at 6:30 and get first dibs on pizza) Location -------- ThoughtWorks' Chicago office 651 West Washington Blvd., 6th floor Chicago, IL 60661 Location description: "6 story, brick building on the Southwest corner of Washington Blvd. and Desplaines St." "Right next to the 90/94 freeway" "Across the street from the Social Security building" * Map <http://tinyurl.com/mgcxo> * "Official" info <http://www.thoughtworks.com/chicagoInfo.html> Call jason at 3 1 2 - 3 7 3 . 8 5 5 6 if you get locked out or lost. (The external doors should be open, but be sure to enter on the "east" side (Desplaines) Street (meter) parking is available in the area. Shoot for "free" (no meters) parking on the South side of the building if you're lucky. And be sure to feed those meters; Brother Leader Daley collects tons of cash from meter fines in this area. Garage parking is also available across the street (technically across the interstate) at the very tall SkyBridge condo building. 1) The closest "L" stop is Clinton on the "Green Line". (About an 8 minute walk from TW.) 2) The closest Metra station is the Ogilvie Transportation Center (in the Citibank Building) 2 blocks east of TW. (a 4 minute walk) 3) The closest water taxi stop is at Madison Street Bridge at 2 North Riverside Plaza. (<http://www.wendellariverbus.com/rbdock.htm>) ;-) 4) I can't find good info on the nearest helipad. Sorry, Mr. Trump. 5) Besides garage parking at SkyBridge across the freeway and meter parking around the building, there is additional garage parking at the Presidential Towers at Jefferson & Madison. There are 2 non-garage parking lots adjacent to our building. (I don't know the lots' "after 5pm" parking rules, though). Theme: If you're addicted to oil, there are lots of parking options within a short walk. Topics ------ * Selenium-testing-Django -- (Jason Huggins) * Some lightning talks, crypt ... * PyCon in Chicago in 2008, bid. 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: <http://chipy.org> ChiPy Mailing List: <http://mail.python.org/mailman/listinfo/chicago> Python website: <http://python.org> ---- Forward this on. From panos.laganakos at gmail.com Fri May 5 08:27:42 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 5 May 2006 05:27:42 -0700 Subject: Method acting on arguements passed Message-ID: <1146832062.017259.265700@y43g2000cwc.googlegroups.com> I want a class method to take action depending on the type of the arguement passed to it. ie: getBook(id) # get the book by ID getBook(name) # get the book by name ... Other languages use the term function/method overloading to cope with this. And when I googled about it seems that GvR is testing it for 3.0 inclusion or so. I was thinking of right after the function declaration check for the parameter passed by isinstance() or type() and use if..elif..else to act. Is this the pythonic way/best practice to apply here? From robin.diederen at gmail.com Mon May 15 07:37:06 2006 From: robin.diederen at gmail.com (robin.diederen at gmail.com) Date: 15 May 2006 04:37:06 -0700 Subject: Two ZSI questions Message-ID: <1147693026.251106.236710@v46g2000cwv.googlegroups.com> Hi, I'm currently developing a SOAP client for the Zimbra collaboration suite (www.zimbra.com). I'm writing a WSDL and using ZSI's "wsdl2py.py" to export it to Python code. There are two things I can't get to work and I cannot find any documentation on. 1. The Zimbra framework requires messages to be formed like this: <account by="name"> robin </account> How do I get the 'by="name"' part in the method tag? The "name" is variable; other values, like "id" etc... I'd like to define this in the WSDL; but I can't find how. Also, I can't find wether ZSI supports such constructs... 2. I need to attach headers to my SOAP requests. How do I put the headers in the SOAP message, using the WSDL? If I get the headers in, will I (from the client) code need to invoke them manually? Examples are welcome of course :) Thanks, Robin From akameswaran at gmail.com Tue May 30 15:02:48 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 30 May 2006 12:02:48 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <4e3e6hF1cp3p8U1@uni-berlin.de> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <mailman.6282.1148767807.27775.python-list@python.org> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> <4e3e6hF1cp3p8U1@uni-berlin.de> Message-ID: <1149015768.375210.100080@38g2000cwa.googlegroups.com> This would only work for combinations of identical sets, and also does not seem to work with generated sets, or iterators. Forgetting dice for a moment. Say I have 3 very long files, and i want to generate the combinations of lines in the files. This provides a well known iterator for the example. file1 = open('foo.txt') file2 = open('bar.txt') file3 = open('baz'.xt') All examples I have seen and all attempts I have written generally do something similar - which is they only iterates through the possible combinations for the last element and do nothing for all other elements. I saw an interesting example that generates a nested function for the given number of sets. While the example still didn't work with generators as input, I think a little tweaking would make it work. This should fulfill my requirements with a rather harsh limit of python's max nesting depth (20?) From Serge.Orlov at gmail.com Mon May 29 08:55:38 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 29 May 2006 05:55:38 -0700 Subject: saving settings References: <e5e6g2$nbv$1@ss408.t-com.hr> <pan.2006.05.29.07.30.20.70376@spam.me.please> <e5els6$5sa$1@ss408.t-com.hr> Message-ID: <1148907338.459790.41880@g10g2000cwb.googlegroups.com> SuperHik wrote: > aum wrote: > > On Mon, 29 May 2006 09:05:36 +0200, SuperHik wrote: > > > >> Hi, > >> > >> I was wondering how to make a single .exe file, say some kind od clock, > >> and be able to save some settings (alarm for example) into the same > >> file? Basically make code rewrite it self... > >> > >> thanks! > > > > Yikes!!! > > > > I'd strongly suggest you read the doco for ConfigParser, and load/save > > your config file to/from os.path.join(os.path.expanduser("~")). > > > > Another option - save your stuff in the Windows Registry > > > > but if I copy this file on the other computer settings will be lost... Put your program in a writable folder and save configuration right into that folder. Then your can transfer the whole folder. Tip: sys.path[0] always contains the path to the directory where "__main__" module is located. From Serge.Orlov at gmail.com Wed May 24 16:49:01 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 24 May 2006 13:49:01 -0700 Subject: Python Version Testing Tool? References: <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <mailman.6162.1148501945.27775.python-list@python.org> Message-ID: <1148503741.019001.134570@j33g2000cwa.googlegroups.com> Michael Yanowitz wrote: > Hello: > > Is there a version testing tool available for Python > such that I can check to see if my code will still run in > versions 2.2, 2.3, 2.4.3, and 1.1 (for example) (or whatever) > without having to install all these different versions on my > computer? Such tool will never be reliable, unless it duplicates all the work that went into all python versions. From p at ulmcnett.com Wed May 17 17:17:39 2006 From: p at ulmcnett.com (Paul McNett) Date: Wed, 17 May 2006 14:17:39 -0700 Subject: I'm just not cut out for web programming, I guess :) In-Reply-To: <%0Mag.2117$No6.46299@news.tufts.edu> References: <%0Mag.2117$No6.46299@news.tufts.edu> Message-ID: <446B92F3.2060004@ulmcnett.com> John Salerno wrote: > Ok, I've tinkered with this thing for a while, and I keep fixing little > problems, but I always get a 500 Internal Server error when I go to this > site: > > I don't necessarily even want help just yet, I'd like to figure it out > myself, but can someone at least tell me why I'm not getting helpful > feedback from the cgitb module? Am I using it wrong? The webpage just > displays the internal server error. > > Thanks. > > > > import cryptogen > import cgitb; cgitb.enable() > > quote_file = open('quotes.txt') > quote = quote_file.readline().strip() > quote_file.close() > > print '''content-type: text/html > > <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN" > "http://www.w3.org/TR/html4/strict.dtd"> > > <html lang="en-us"> > <head> > <meta http-equiv="content-type" content="text/html; charset=utf-8"> > <title> > > >
''' > > quote = cryptogen.convert_quote(quote) > for word in quote[0].split(' '): > word_len = len(word) > print '' % (word, word_len) > > print '
' Are you sure the python that the web server runs has the cryptogen module available? Have you set the execute bit on your script? What's the output in your web server error log? -- Paul McNett http://paulmcnett.com http://dabodev.com From bencvt at gmail.com Wed May 24 19:03:02 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 24 May 2006 16:03:02 -0700 Subject: Bind an instance of a base to a subclass - can this be done? In-Reply-To: References: Message-ID: <1148511782.422564.210750@j73g2000cwa.googlegroups.com> Lou Pecora wrote: > I want to subclass a base class that is returned from a Standard Library > function (particularly, subclass file which is returned from open). I > would add some extra functionality and keep the base functions, too. > But I am stuck. > > E.g. > > class myfile(file): > def myreadline(): > #code here to return something read from file > > Then do something like (I know this isn't right, I'm just trying to > convey the idea of what I would like) > > mf=myfile() > > mf=open("Afile","r") > > s=mf.myreadline() # Use my added function > > mf.close() # Use the original file function > > > Possible in some way? Thanks in advance for any clues. This: >>> mf=myfile() >>> mf=open("Afile","r") Is actually creating an instance of myfile, then throwing it away, replacing it with an instance of file. There are no variable type declarations in Python. To accomplish what you want, simply instantiate the subclass: >>> mf=myfile("Afile","r") You don't need to do anything tricky, like binding the instance of the base class to a subclass. Python does actually support that, e.g.: >>> class Base(object): def f(self): return 'base' >>> class Subclass(Base): def f(self): return 'subclass' >>> b = Base() >>> b.__class__ >>> b.f() 'base' >>> b.__class__ = Subclass >>> b.__class__ >>> b.f() 'subclass' But the above won't work for the built-in file type: >>> f = file('foo') >>> f.__class__ >>> f.__class__ = Subclass TypeError: __class__ assignment: only for heap types Again though, just instantiate the subclass. Much cleaner. Or if that's not an option due to the way your module will be used, just define your custom file methods as global functions that take a file instance as a parameter. Python doesn't force you to use OOP for everything. --Ben From deets at nospam.web.de Thu May 4 12:06:24 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 May 2006 18:06:24 +0200 Subject: Calling superclass References: Message-ID: <4bun4rF13b7ttU1@uni-berlin.de> Florian Lindner wrote: > Hello, > I try to call the superclass of the ConfigParser object: > > class CustomizedConfParser(ConfigParser.SafeConfigParser): > def get(self, section, attribute): > try: > return super(CustomizedConfParser, self).get(section, > attribute) > # [...] > > > but that gives only > > return super(CustomizedConfParser, self).get(section, attribute) > TypeError: super() argument 1 must be type, not classobj > > I don't really understand the error message. super works only for newstyle-classes. So additionally extend CustomizedConfParser from object. diez From vinogri at mcmaster.ca Fri May 5 19:39:21 2006 From: vinogri at mcmaster.ca (Ivan Vinogradov) Date: Fri, 5 May 2006 19:39:21 -0400 Subject: NaN handling In-Reply-To: <125nlbgm8l1fi17@corp.supernews.com> References: <125hplqmppfeq29@corp.supernews.com> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> <125nlbgm8l1fi17@corp.supernews.com> Message-ID: On 5-May-06, at 6:45 PM, Grant Edwards wrote: > On 2006-05-05, Robert Kern wrote: > >>> Our programming expectations may differ, but an option to catch >>> NaNs as >>> an exception is a great idea. >> > [...] > >> Pure Python has a similar, but somewhat less flexible method, on >> UNIX platforms. >> >> http://docs.python.org/dev/lib/module-fpectl.html > > For which "Unix" platforms? It's not there under Linux: It doesn't seem to be here under OSX either (universal Python install). Since numpy seems to be working on a variety of platforms/hardware, how hard would it be to extract this functionality from it to add to Python proper? Cheers, Ivan. From johnjsal at NOSPAMgmail.com Tue May 2 14:32:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 18:32:17 GMT Subject: simultaneous assignment In-Reply-To: <44579c58$0$23113$626a54ce@news.free.fr> References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > Now if I may ask: what is your actual problem ? Ok, since you're so curious. :) Here's a scan of the page from the puzzle book: http://johnjsalerno.com/spies.png Basically I'm reading this book to give me little things to try out in Python. There's no guarantee that this puzzle is even conducive to (or worthy of) a programming solution. From jordan.taylor2 at gmail.com Fri May 19 10:12:37 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 19 May 2006 07:12:37 -0700 Subject: memory error with zipfile module In-Reply-To: <446dbe4d$0$8013$626a54ce@news.free.fr> References: <446dbe4d$0$8013$626a54ce@news.free.fr> Message-ID: <1148047956.998124.47790@u72g2000cwu.googlegroups.com> Take a look at the pywin32 extension, which I believe has some lower level memory allocation and file capabilities that might help you in this situation. If I'm completely wrong, someone please tell me XD. Of course, you could just make the read() a step process, reading, O lets say 8192 bytes at a time (could be bigger if u want), writes them to the new file, and then reads the next portion. This will be slower (not sure how much) than if you had some AMD X2 64 with 3 gigs of ram and could just read the file all at once, but it should work. From darkbard at gmail.com Tue May 16 09:05:39 2006 From: darkbard at gmail.com (Gabriele *darkbard* Farina) Date: 16 May 2006 06:05:39 -0700 Subject: Unicode digit to unicode string Message-ID: <1147784739.786522.234280@v46g2000cwv.googlegroups.com> Hi, I have a unicode digit stored into a variable ('0020' for example) and I'd like to retrieve the corrisponding unicode character based on the current encoding. How can i do that ? From johnjsal at NOSPAMgmail.com Thu May 18 10:08:35 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 18 May 2006 14:08:35 GMT Subject: creating a new database with mysqldb In-Reply-To: <1147927982.322181.20880@i39g2000cwa.googlegroups.com> References: <126nj7utnok7u6e@corp.supernews.com> <446be190$0$5024$c3e8da3@news.astraweb.com> <1147927982.322181.20880@i39g2000cwa.googlegroups.com> Message-ID: BartlebyScrivener wrote: > I was hoping you'd find this earlier when I suggested that you type: > > creating a new database with MySQL > > into google. > > It's the number one hit: > > http://coronet.iicm.edu/mysql/create.html > > If you send the commands listed there via the commandline or through > MySQLdb you should be in business. > I saw this one, but it seems to use a lot of the command line, and I didn't know how all that translates into a Python script. My goal was to do it all using just mysqldb, but maybe it's just easier (or more normal) to create a database in another way, and *then* use mysqldb to manipulate it. From pydecker at gmail.com Fri May 19 12:18:56 2006 From: pydecker at gmail.com (Peter Decker) Date: Fri, 19 May 2006 12:18:56 -0400 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: On 19 May 2006 07:18:03 GMT, Duncan Booth > Can you point at any significant body of publically visible Python code > which uses tabs exclusively? All of the Python projects I've ever been > involved with use spaces only as a convention (although as I pointed out in > my previous post, some with more success than others). Dabo. http://dabodev.com -- # p.d. From sybrenUSE at YOURthirdtower.com.imagination Thu May 18 03:15:26 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 18 May 2006 09:15:26 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> Message-ID: SamFeltus enlightened us with: > I am trying to figure out why so little web development in Python > uses Flash as a display technology. There are a couple of reasons: - Flash is bad for websites that are 100% done inside the Flash movie. In such a case the back-button doesn't work anymore, which is a major usability issue. - In the above case, bookmarking a page doesn't work either. - You need an extra plugin. Even though it's available for the major OSses and hardware systems, it's not available for every platform that can run a browser. - The plugin is closed-source. - The format that is the "source" for the SWF files is a closed, proprietary format. - Many user-interface widgets are generally badly implemented in Flash. For instance, on many scrolling thingies, the scrollwheel doesn't work. Or, the regular scrollwheel works, but for scrolling horizontally the tilt wheel isn't supported. Another example: sometimes it's only clear what a link points to when you hover over it (revealing a text behind an image, for instance), which is impossible on some devices (think handhelds with a touch-screen). - Search engines don't understand Flash movies. They are also unable to link directly to relevant pages. - Many more reasons... > It seems most Python applications choose HTML/CSS/JS as the display > technology, yet Flash is a far more powerful and elegant display > technology. Flash is indeed more powerful, but not elegant at all. > On the other hand, HTML/JS seems clunky and antiquated. It's getting a lot better. Try using XHTML 1.1 and only up to date, platform/browser-independent JavaScript, it'll be much better. > I am a gardener, and not a coder by trade, but Flash seems to > integrate just fine with Python. It's absolute crap when it comes to coding. ActionScript stands almost perpendicular to Python when it comes to the Python way of thinking. In ActionScript there are many ways of doing the same thing, none of which are obvious. Another thing is that when you call a function that doesn't exist, that call is silently ignored. The same holds for getting the value of a non-existing variable. This makes debugging very difficult. > http://SamFeltus.com Your site looks quite "unstyled" without flash... And I don't have Flash player 8... Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From rpdooling at gmail.com Sat May 13 08:26:17 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 May 2006 05:26:17 -0700 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <1147520965.186376.185570@j33g2000cwa.googlegroups.com> References: <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> <1147490582.719840.51200@i39g2000cwa.googlegroups.com> <44655f44$0$9414$c3e8da3@news.astraweb.com> <1147520965.186376.185570@j33g2000cwa.googlegroups.com> Message-ID: <1147523177.330098.74190@v46g2000cwv.googlegroups.com> >> driv="bbdatabank" Oops, sorry, I meant, driv='DSN=bbdatabank' rick From eflorac at imaginet.fr Tue May 23 15:55:22 2006 From: eflorac at imaginet.fr (Emmanuel Florac) Date: Tue, 23 May 2006 21:55:22 +0200 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> Message-ID: Le Tue, 23 May 2006 08:58:12 -0500, John D Salt a ?crit?: > > What exciting new ideas exist in software that are both important and > cannot be traced back to 1986 or earlier? Actually it looks like the latest breakthru was invention of LISP circa 1957. Well, Perhaps OO paradigm and Smalltalk, circa 1973, too. -- Le commissaire : Comment vous appelez-vous? Garance : Moi je ne m'appelle jamais, je suis toujours l?. J'ai pas besoin de m'appeler. Mais les autres m'appellent Garance, si ?a peut vous int?resser. Pr?vert,"les enfants du Paradis". From tjreedy at udel.edu Fri May 5 02:53:33 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 May 2006 02:53:33 -0400 Subject: Can I use python for this .. ?? References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com><1146774288.904851.278130@i39g2000cwa.googlegroups.com><1146779044.307500.50810@u72g2000cwu.googlegroups.com> <1146807680.232551.97460@y43g2000cwc.googlegroups.com> Message-ID: "placid" wrote in message news:1146807680.232551.97460 at y43g2000cwc.googlegroups.com... .) > > When you hibernate/boot up/hibernate for a long time without a clean > reboot, Windows becomes unstable... This seems to depend on the system. I have gone at least a week, maybe two, with nightly hibernations and no problems. Maybe you meant much longer than that. But installs and updates often require reboots anyway. tjr From akameswaran at gmail.com Sat May 27 02:50:44 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 26 May 2006 23:50:44 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <1148705453.123243.167820@y43g2000cwc.googlegroups.com> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148705453.123243.167820@y43g2000cwc.googlegroups.com> Message-ID: <1148712644.720452.32330@y43g2000cwc.googlegroups.com> hmmm, just needed better search words, thanks :) From me+python at modelnine.org Wed May 24 02:52:22 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 24 May 2006 08:52:22 +0200 Subject: NEWB: how to convert a string to dict (dictionary) In-Reply-To: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> References: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> Message-ID: <200605240852.22386.me+python@modelnine.org> Am Mittwoch 24 Mai 2006 07:52 schrieb manstey: > Hi, > > How do I convert a string like: > a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}" > > into a dictionary: > b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'} b = eval(a) (if a contains a dict-repr) --- Heiko. From onurb at xiludom.gro Tue May 2 14:38:39 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 02 May 2006 20:38:39 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> Message-ID: <4457a78b$0$5171$626a54ce@news.free.fr> Edward Elliott wrote: > bruno at modulix wrote: > >>>that 1) b is an object not a module*, and 2) objects pass references to >>>themselves as the first argument to their methods. >> >>Nope. It's the MethodType object (a descriptor) that wraps the function >>that do the job. The object itself is totally unaware of this. > > > It's shorthand, not to be taken literally. > It is to be taken literally. Either you talk about how Python effectively works or the whole discussion is useless. > >>>Making people pass 'self' >> >>s/self/the instance/ >> >> >>>explicitly is stupid >> >>No. It's actually a feature. > > potato, potahto. > tss... > >>>the first argument, leading to these kinds of mistakes. The compiler >>>should handle it for you > >> >>I don't think this would be possible if we want to keep the full >>dynamism of Python. How then could the compiler handle the following code >>? >> >>class MyObj(object): >> def __init__(self, name): >> self.name = name > > > class MyObj(object): > def __init__(name): > self.name = name You skipped the interesting part, so I repost it and ask again: how could the following code work without the instance being an explicit parameter of the function to be used as a method ? def someFunc(obj): try: print obj.name except AttributeError: print "obj %s has no name" % obj import types m = MyObj('parrot') m.someMeth = types.MethodType(someFunc, obj, obj.__class__) m.someMeth() You see, wrapping a function into a method is not done at compile-time, but at runtime. And it can be done manually outside a class statement. In the above example, someFunc() can be used as a plain function. In fact, almost any existing function taking at least one argument can be turned into a method (in theory at least - practically, you of course need to make sure the first argument is of a compatible type). This wouldn't work with some automagical injection of the instance in the function's local namespace, because you would then have to write "method"'s code diffently from function's code. > And the rest should work fine. When the interpreter sees a method > declaration, The interpreter never sees a 'method declaration', since there is no such thing as a 'method declaration' in Python. The def statement creates a *function* object: >>> class Parrot(object): ... def test(self): ... pass ... print "type(test) is : ", type(test) ... type(test) is : >>>but in practice you don't declare >>>self as a parameter to module functions >> >>def someOtherFunc(): >> print "hello there" >> >>m.someFunc = someOtherFunc >>m.someFunc() > > Complete non-sequitor, what does this have to do with self? It has to do that the obj.name() syntax doesn't imply a *method* call - it can as well be a plain function call. Also, and FWIW: >>> def moduleFunc(): ... print self.name ... >>> moduleFunc() Traceback (most recent call last): File "", line 1, in ? File "", line 2, in moduleFunc NameError: global name 'self' is not defined >>> HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aylwyn at cantab.net Thu May 18 04:34:58 2006 From: aylwyn at cantab.net (achates) Date: 18 May 2006 01:34:58 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: References: <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <446B6AD1.4080104@mvista.com> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <1147907634.532463.63730@u72g2000cwu.googlegroups.com> Message-ID: <1147941298.356018.251890@j55g2000cwa.googlegroups.com> Edward Elliott wrote: > What really should happen is that every time an editor reads in source code, > the code is reformatted for display according to the user's settings. The > editor becomes a parser, breaking the code down into tokens and emitting it > in a personally preferred format. I completely agree, and I guess that is what I was groping towards in my remarks about using modern editing tools. At the same time I would be resist any move towards making source files less huiman-readable. There will still be times when those tools aren't available (e.g. for people working on embedded s/w or legacy systems), and that's when having ASCII source with tabbed indentation would be so useful. But it looks, sadly, like we're fighting a rearguard action on that one. From rpdooling at gmail.com Fri May 12 23:23:02 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 12 May 2006 20:23:02 -0700 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <446530ec$0$11696$c3e8da3@news.astraweb.com> References: <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> Message-ID: <1147490582.719840.51200@i39g2000cwa.googlegroups.com> Add the mysql db to your datasources using Administrative Tools/Datasources(ODBC). Once that's done it's simple to access it, using mxODBC. I'm assuing you are on Windows XP? Here's mxODBC http://www.egenix.com/files/python/mxODBC.html and you'll need the MySql connector http://dev.mysql.com/downloads/connector/odbc/3.51.html rick From pod at internode.on.net Fri May 19 12:10:40 2006 From: pod at internode.on.net (PoD) Date: Sat, 20 May 2006 01:10:40 +0900 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <446c319d$0$5298$626a54ce@news.free.fr> <446d7c23$0$7133$626a54ce@news.free.fr> Message-ID: On Fri, 19 May 2006 10:04:15 +0200, Christophe wrote: > PoD a ?crit : >> Maybe what Python should do (but never will given the obsession with using >> spaces) is only allow one level of indentation increase per block so that >> >> def foo(): >> return 'bar' >> >> would return a syntax error > > Which would make mandatory for indentation. What about some > freedom of choice ? Hey, if people are allowed to say that tabs should be banned, then I'm allowed to say they should be mandatory ;) From andy at neotitans.com Wed May 17 14:29:56 2006 From: andy at neotitans.com (Andy Sy) Date: Thu, 18 May 2006 02:29:56 +0800 Subject: Tabs versus Spaces in Source Code (semantic vs. arbitrary indentation) In-Reply-To: <34bb7f5b0605160154i403f9b73q28c0579b1d82f8d9@mail.gmail.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <4468B996.5000407@sweetapp.com> <34bb7f5b0605160154i403f9b73q28c0579b1d82f8d9@mail.gmail.com> Message-ID: Ed Singleton wrote: > On 5/15/06, Brian Quinlan wrote: >> The problem with tabs is that people use tabs for alignment e.g. >> >> def foo(): >> ->query = """SELECT * >> -> -> -> FROM sometable >> -> -> -> WHERE condition""" >> >> Now I change my editor to use 8-space tabs and the code is all messed >> up. Of course, a very disciplined group of people could be trained to >> never use tabs except to align with the current block level but, in >> practice, that doesn't work. Therefore tabs are bad. > > def foo(): > ->query = """SELECT * > -> .......FROM sometable > -> .......WHERE condition""" > > That would solve it. Tabs for indentation, spaces for spacing. > > Ed Ok, this is a somewhat workable solution. Cons: 1) You have to be more conscientious regarding how many tabs you use at the beginning of a line. If your text editor does not display tabs explicitly (SciTE can), it can be a *REAL* hassle. 2) Because you have to use all pure spaces after the proper # of tabs, you will often end up having to type a lot of them compared to if your tab key generated pure spaces. Pro: 1) Happily, you do get your 'semantic indentation' so people can dynamically change the indentation-size they want to view your code with. You do need everyone to understand 1 thing: NEVER use tab characters (and consequently the tab key) for anything EXCEPT semantic indentation. Big question though: is the above guaranteed to work nicely in all situations in python? Also, in free-format languages like C, Java, C#, the temptation to mix semantic and arbitrary indentation might be just too great for sloppy programmers. If anyone wants to use tabs, I think the above is the ONLY right way to use them and it also happily eliminates any arguments over how many spaces you should use for your tab setting. If ALL tab users followed this convention, I will happily consider myself agnostic... ;-) Now, on to the next holy war... date formats.... ANY OTHER FORMAT BESIDES ISO YYYYMMDD (but it's ok to put dashes in between or use word MMM instead of numerical MM) IS *EVIL* AND *MISGUIDED*! -- It's called DOM+XHR and it's *NOT* a detergent! From arv.nntp at gmail.com Mon May 1 11:45:44 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Mon, 01 May 2006 17:45:44 +0200 Subject: critique this little script, if you like In-Reply-To: <%3p5g.2019$No6.43931@news.tufts.edu> References: <44554a32$0$11750$c3e8da3@news.astraweb.com> <%3p5g.2019$No6.43931@news.tufts.edu> Message-ID: John Salerno escribi?: > Alexis Roda wrote: >> >> > The >> > try block seems nicer because it doesn't have such an ugly-looking >> check >> > to make. >> > > Why do you think that this try block is preferred over what I have (if I > were to stick with the try block)? My example has nothing to do with your script, apart from trying to illustrate why I think you should use "if" instead of "try" with a kind of "reductio ad absurdum" reasoning. To me i == 0 seems as ugly as len(sys.argv) == 1 (*), so, according to your statement about ugly checks, you should avoid code like: if i == 0 : do_something_if_zero() and write something like: try: x = 1 / i except ZeroDivisionError : do_something_if_zero() but probably you wouldn't, the "if" block seems more "natural" than the convoluted "try" block, so ... Regards (*) len(sys.argv) == 1 is exactly the same as len(sys.argv) - 1 == 0 From steve at holdenweb.com Sun May 21 07:15:14 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 May 2006 12:15:14 +0100 Subject: Feature request: sorting a list slice In-Reply-To: <1148198065.724613.253490@j55g2000cwa.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> <1148198065.724613.253490@j55g2000cwa.googlegroups.com> Message-ID: Feature? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From NOatkinwSPAM at rpi.edu Sun May 7 06:38:34 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 06:38:34 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <87wtcyy5i0.fsf@rpi.edu> <445dc17a$1$25449$bed64819@news.gradwell.net> Message-ID: <87d5eq6rx1.fsf@rpi.edu> "Chris Uppal" writes: > Bill Atkins wrote: > >> But why should I have to worry about any of this? Why can't I do: >> >> (with-indentation (pdf (+ (indentation pdf) 4)) >> (out-header) >> (out-facts)) >> >> and then within, say out-facts: >> >> (with-indentation (pdf (+ (indentation pdf) 4)) >> (write pdf "some text")) >> >> More readable, and no bookkeeping to worry about. This is great! And >> here's the macro: > . [...] > > Can you explain to a non-Lisper why macros are needed for this ? I'm a > Smalltalker, and Smalltalk has no macros, nor anything like 'em, but the > equivalent of the above in Smalltalk is perfectly feasible, and does not > require a separate layer of semantics (which is how I think of true macros). > > aPdf > withAdditionalIndent: 4 > do: [ aPdf writeHeader; writeFacts ]. > > and > > aPdf > withAdditionalIndent: 4 > do: [ aPdf write: '... some text...' ]. > > Readers unfamiliar with Smalltalk may not find this any easier to read that > your Lisp code, but I can assure them that to any Smalltalker that code would > be both completely idiomatic and completely transparent. (Although I think a > fair number of Smalltalkers would choose to use a slightly different way of > expressing this -- which I've avoided here only in order to keep things > simple). To be honest, all I know about Smalltalk are the parts of it that were grafted onto Ruby. But if your example is doing the same as my code, then I can't say that there's much of an advantage to using a macro over this. > >> Macros rock. > > I have yet to be persuaded of this ;-) My favorite macro is ITERATE, which was written at MIT to add a looping mini-language to CL. There is a macro called LOOP that is part of Common Lisp, but ITERATE improves upon it in lots of ways. The cool thing about ITERATE is that it lets you express looping concepts in a language designed explicitly for such a purpose, e.g. (iter (for x in '(1 3 3)) (summing x)) => 7 (iter (for x in '(1 -3 2)) (finding x maximizing (abs x))) => -3 (iter (for x in '(a b c 1 d 3 e)) (when (symbolp x) (collect x))) => (a b c d e) This is a tiny, tiny chunk of what ITERATE offers and of the various ways these clauses can be combined. But it should be obvious that being able to express loops this way is going to make your code much more concise and more readable. But it gets even better: since ITERATE is a macro, the code passed to it is error-checked and analyzed at compile-time, and then converted to primitive Lisp forms - also at compile-time. What this means is you get all this extra expressive power at absolutely no runtime cost. At the risk of causing brains to explode, here is what the third ITER form expands into: (LET* ((#:LIST17 NIL) (X NIL) (#:RESULT16 NIL) (#:END-POINTER18 NIL) (#:TEMP19 NIL)) (BLOCK NIL (TAGBODY (SETQ #:LIST17 '(A B C 1 D 3 E)) LOOP-TOP-NIL (IF (ATOM #:LIST17) (GO LOOP-END-NIL)) (SETQ X (CAR #:LIST17)) (SETQ #:LIST17 (CDR #:LIST17)) (IF (SYMBOLP X) (PROGN NIL (PROGN (SETQ #:TEMP19 (LIST X)) (SETQ #:END-POINTER18 (IF #:RESULT16 (SETF (CDR #:END-POINTER18) #:TEMP19) (SETQ #:RESULT16 #:TEMP19))) #:RESULT16)) NIL) (GO LOOP-TOP-NIL) LOOP-END-NIL) #:RESULT16)) This is obviously not something any sane programmer would sit down and write just to get an efficient loop. But this code is highly tuned; for instance, it tracks the end of the list it's building up to save time. I, as a programmer, get all this expressiveness and efficiency for free. I think that's awesome. There are lots more examples of macros. My second favorite macro to use as an example are Peter Seibel's macros for processing binary files: http://gigamonkeys.com/book/practical-parsing-binary-files.html He builds a set of macros so that in the next chapter he can define an ID3 tag reader and writer with: (define-tagged-binary-class id3v2.3-frame () ((id (frame-id :length 4)) (size u4) (flags u2) (decompressed-size (optional :type 'u4 :if (frame-compressed-p flags))) (encryption-scheme (optional :type 'u1 :if (frame-encrypted-p flags))) (grouping-identity (optional :type 'u1 :if (frame-grouped-p flags)))) (:dispatch (find-frame-class id))) The macro generates code for methods that let you read and write ID3 files in a structured way - and it can of course be used for any other kind of binary file. The :dispatch parameter at the end will jump to a different class to parse the rest based on the result of executing the expression attached to it. There are lots more, too. Lispers and their environments are often much more proficient at writing and modifying s-expressions than HTML, so there are neat HTML generation macros like: (<:html (<:head (<:title "foo")) (<:body (<:b :style "font-color: orange" "hello!"))) This example uses Marco Baringer's YACLML package. Again, we get this expressiveness (no need to use closing tags, the ability to let our editor indent or transpose tags and so on) for free. At compile-time, these macros all get parsed down to much, much simpler code: (PROGN (WRITE-STRING " foo " *YACLML-STREAM*) SOME-VARIABLE (WRITE-STRING " " *YACLML-STREAM*)) All of the tags have been streamlined down to a single stream constant. Again we get more expressiveness but still keep killer efficiency. There are still more! _On Lisp_ has a lot of interesting ones, like an embedded Prolog interpreter and compiler: (<-- (father billsr billjr)) (?- (father billsr ?)) ? = billjr We have Marco Baringer's ARNESI package, which adds continuations to Common Lisp through macros, even though Common Lisp does not include them. The Common Lisp Object System (CLOS), although now part of Common Lisp, could be (and originally was) built entirely from macros [1]. That should give a rough idea of their power. There are macros like DESTRUCTURING-BIND, which is part of Common Lisp, but could just as easily have been written by you or me. It handles destructuring of lists. A very simple case: (destructuring-bind (a b c) '(1 2 3) (+ a b c)) => 6 I hope this gives you a general idea of the coolness of macros. [1] Strictly speaking, there are a couple of things that the Lisp implementation has to take care of, but they are not absolutely essential features. -- This is a song that took me ten years to live and two years to write. - Bob Dylan From ryan.qian at gmail.com Tue May 30 05:21:29 2006 From: ryan.qian at gmail.com (Moneyhere) Date: 30 May 2006 02:21:29 -0700 Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional In-Reply-To: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> Message-ID: <1148980889.507643.52440@u72g2000cwu.googlegroups.com> Good :) Can someone provide this ebook? . I'm looking forwards it. From max at alcyone.com Fri May 5 03:37:42 2006 From: max at alcyone.com (Erik Max Francis) Date: Fri, 05 May 2006 00:37:42 -0700 Subject: Tuple assignment and generators? In-Reply-To: <1146814457.388702.263120@i39g2000cwa.googlegroups.com> References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> Message-ID: vdrab wrote: > what the...? > does anybody else get mighty uncomfortable about this? No. Why should you ever care about whether two integers representing values are the same object? Your tests should be with `==`, not `is`. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis More fodder for the new lost generation -- Nik Kershaw From mike.klaas at gmail.com Mon May 1 15:32:31 2006 From: mike.klaas at gmail.com (Klaas) Date: 1 May 2006 12:32:31 -0700 Subject: list*list In-Reply-To: <4bmotsF126gicU1@uni-berlin.de> References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> <4bmotsF126gicU1@uni-berlin.de> Message-ID: <1146511951.257209.100260@e56g2000cwe.googlegroups.com> Diez wrote: > First of all: it's considered bad style to use range if all you want is a > enumeration of indices, as it will actually create a list of the size you > specified. Use xrange in such cases. > But maybe nicer is zip: > c = [av * bv for av, bv in zip(a, b)] By your logic, shouldn't it also be "bad style" to create an unnecessary list with zip instead of using izip? -Mike From ny_r_marquez at yahoo.com Mon May 8 12:54:08 2006 From: ny_r_marquez at yahoo.com (RM) Date: 8 May 2006 09:54:08 -0700 Subject: 4 little Python programs In-Reply-To: References: <1146833949.544241.88330@y43g2000cwc.googlegroups.com> Message-ID: <1147107248.213925.160560@g10g2000cwb.googlegroups.com> Terry, Thanks for the feedback. I've done what you said, except for deleting the EXEs. While people on this forum can figure out how to get them to work with just the source, most people will be better off with the installers. I also added screen shots to each of the programs. I am especially interested in improving CocoRename. I think that it would be nice to add wild cards, regular expressions, incremental digits for the filenames, etc, I just haven't had the time. I ran it on Linux a while back using KDE's equivalent of "Send to", "Service Menus", and was blown away by how much better it worked than on Windows. So, I think it has potential. I don't think that there is a GUI for 7Zip on Linux yet, so 7Squeeze could be used until a more complete version appears. However, since it is only a wrapper for the command line version of 7Zip I think I would have to include some way to capture all the relevant information that the program normally sends to the terminal. Currently, starting 7Squeeze from a terminal is actually better on Linux because you get to see the feedback. So, I think it needs a little work. However, I do think that 7Squeeze's Squeeze and UnSqueeze features are standout features. I hope some will give it a try. Any way, I am interested in any improvements any one can make to this programs. And of course, I would love to know if any one finds them useful. -Ruben Terry Reedy wrote: > "RM" wrote in message > news:1146833949.544241.88330 at y43g2000cwc.googlegroups.com... > > I had been thinking of releasing some of my little personal apps for a > > while. So, this finally motivated me to clean them up enough for > > release. The website is not yet finished, but I couldn't wait to share > > with you these little Python programs. I have packaged them nicely for > > Windows using py2exe and InnoSetup. Unfortunately, I haven't had the > > time to do the same for Linux. I plan to that soon. You can get them > > here. > > > > http://rmcorrespond.googlepages.com/customsoftware > > > > I have been using them for several years, but never got around to > > releasing them. Any way, I hope you like them. Oh, they are all > > licensed with the GPL, but for now, since I don't yet have a way to > > track downloads, I am only making the source available upon request. If > > you have any questions or suggestions let me know. > > Since you asked: delete the .exes and release the source and give a link to > python.org for anyone who does not have it already installed. Since I > already have at least two versions of Python installed, I don't need four > more copies. Since I have no reason to trust that you are not distributing > malware, I would not touch your .exes anyway. Python is really meant for > source distribution. > > Terry Jan Reedy From creolophus at gmail.com Fri May 19 05:39:13 2006 From: creolophus at gmail.com (creo) Date: 19 May 2006 02:39:13 -0700 Subject: calling python functions using variables Message-ID: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> Hi all! this is a (relatively) newbie question I am writing a shell in Python and I am facing a problem The problem is, after taking the input from user, i have to execute the command which is a python function i invoke an 'ls' command like this commands.ls() where commands.py is a file in the same directory what i want to do is commands.VARIABLE() where VARIABLE holds the name of the function which i want to execute and depends on what the user has typed what should i do to achieve that? any help is appreciated thank you -creo P.S. if you want me to clarify the question, please tell me so From steve at holdenweb.com Sun May 21 13:13:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 May 2006 18:13:38 +0100 Subject: newbie: windows xp scripting In-Reply-To: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> References: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> Message-ID: oscartheduck wrote: > I've been having trouble with the following style of script. It's > simple stuff, I know, but it's stumping me: > > import os > > dirfrom = 'C:\\test' > dirto = 'C:\\test1\\' > > copy_command = 'copy "%s" "%s"' % (dirfrom, dirto) > > if os.system(copy_command) == 0: > print "yay" > else: > print "boo" > > > What's going wrong is with the %s substitution part. I've tried more > complex scipts and kept running against an error where my script just > wouldn't work. So I stripped back and back and back to this point, > where I'm just trying to run a simple copy command. But for some > reason, it fails. > > If I don't use the %s substitution but use the full pathnames > explicitly in the copy command, it works fine. So that's where my issue > seems to be. Help! > Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. Started with C:/Steve/.pythonrc >>> import os >>> dirfrom = 'C:\\Steve\\t1' >>> dirto = 'C:\\Steve\\t2\\' >>> copy_command = 'copy "%s" "%s"' % (dirfrom, dirto) >>> if os.system(copy_command) == 0: ... print 'yay!' ... else: ... print 'boo!' ... C:\Steve\t1\hello.txt 1 file(s) copied. yay! >>> I don't suppose it's possible your from directory is empty? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From nobody at 127.0.0.1 Thu May 18 18:09:52 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 22:09:52 GMT Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: John Bokma wrote: > "akameswaran at gmail.com" wrote: >> It seems to me the discussion could actually be beneficial. If several >> different coders gave similar responses, ie code line/character count >> comparisons, we might be able to see if there is a trend of any sort - >> the more "anecdotes" given and we start to have trends - or maybe we >> don't. > > What's the point? So you can say: Perl code has on average 1.727 more > lines compared to Python? That's more than we know right now. You never know what data will reveal until you collect and analyze it. BTW I'm not limiting this discussion to lines of code. That was simply the most convenient metric available. If people have other metrics to consider, by all means post them. > What's the point, both are tools. People who use both Perl and Python pick > one to solve a problem because they want to pick what they believe is the > right tool. I doubt that the number of lines is often on their mind. What's the point in learning trigonometry? People who survey land just want to mark off boundaries, not solve a bunch of equations. The Pythagoreans built a religious cult on the study of geometric figures. They didn't know or care that their discoveries would be useful in engineering and science. More knowledge = more choice = better tools. When all you have is a hammer, everything looks like a nail. It's as simple as that. If you're happy playing with your hammers, fine. Go away and post in some other thread. > People who just know either Perl or Python don't care much about such > figures, or so I hope. I don't know Ruby, but if you could show me it produced significantly shorter code with comparable readability to Python, I'd certainly look into it. >> Lastly, Ed - can you post the code? That may be putting your head in >> the lion's mouth so to speak and make the whole thread even worse - and >> your coding style will get shredded by perl advocates... ok nevermind >> don't post it.' > > And not by Python advocates? I don't care who rips my code to what. I haven't posted code because people will dissect it to death and lose sight of the big picture. Code can always be improved, it's a question of resources. The point is not what could be done better in my code, but what was done with my skill and my time committment, and what others have done with their skill and their time committment. At some point I may post small snippets of each so others can gauge my style and experience, but I'm afraid it will devolve into a code crtitiquing fest. >> Ok I'm going to end with a flamebait - but I would posit, ALL OTHER >> THINGS BEING EQUAL - that a smaller number of characters and lines in >> code is more maintainable than larger number of characters and lines in >> the code. > > And I think that's why a lot of people posted very negative, in the hope > that people would not be tempted to make the above very dumb statement. That's not a dumb statement, it's a sensible and testable hypothesis. The more people post their own experiences, the more patterns emerge and testable hypotheses form, which can then be confirmed or debunked with further study. The journey of 1000 miles starts with a single step, etc, etc. Didn't your mother ever tell you how science works? It's not all bunsen burners and test tubes. To everyone who thinks this thread is pointless or a bad idea: please just go away. Your objections have been noted, at this point you're not contributing anything to the discussion. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From kkylheku at gmail.com Thu May 11 12:52:11 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 11 May 2006 09:52:11 -0700 Subject: Multi-line lambda proposal. In-Reply-To: References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> <1147333696.789718.189050@v46g2000cwv.googlegroups.com> Message-ID: <1147366331.637492.129980@i39g2000cwa.googlegroups.com> Duncan Booth wrote: > One big problem with this is that with the decorator the function has a > name but with a lambda you have anonymous functions so your tracebacks are > really going to suck. Is this an issue with this particular design that is addressed by other designs? Are the existing one-line lambdas free from this problem? Is there really a problem? The Python tracebacks identify every frame by file and line number, as well as name, if one is available. Let me make the observation that name of an inner function is, alone, insufficient to identify that function in a debugging scenario. If you have some inner function called I, defined within function F, you need to know that it's the I inside F, and not some other I. Look at what happens with: >>> def err(): ... def inner(): ... return nonexistent ... return inner ... >>> err() >>> err()() Traceback (most recent call last): File "", line 1, in ? File "", line 3, in inner NameError: global name 'nonexistent' is not defined In the traceback, the programmer is told that the error occured in a function called inner. However, there could be many functions called inner, including a global one. The programmer is not told that it's the function inner which is defined inside the function err, which could be done with some qualified name syntax like err.inner or whatever. So this piece of information is about as useful as being told that it was inside a lambda. The real key which lets the programmer correlate the error back to the source code is the file name and line number. When he locates that line of code, then it's obvious---aha---it is in the middle of an inner function called "inner", which also happens to be inside a global function called "err". From john at castleamber.com Mon May 22 19:23:50 2006 From: john at castleamber.com (John Bokma) Date: 22 May 2006 23:23:50 GMT Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <44723437$0$11063$9b4e6d93@newsread4.arcor-online.net> Message-ID: fupto: poster Dra?en Gemi? wrote: > Timo Stamm wrote: >> Dra?en Gemi? schrieb: >> >>> Xah Lee wrote: >>> >>>> Software Needs Philosophers >>>> >>> >>> Welcome to my junk filters !!!! >> >> >> >> Thanks for informing each and every reader of the newsgroups >> comp.lang.perl.misc, comp.lang.python, comp.lang.java.programmer, >> comp.lang.lisp, comp.lang.function about your junk filters. > > Anytime...... Instead of adding Xah to your junk filter, you might want to complain with his ISP: abuse at sbcglobal dot net Hosting provider has already taken steps Google Groups might not care, but its worth a try. The more people complain, the faster Xah has to hop ISPs and providers, and maybe one day he understand that shitting in your garden costs money. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From ullrich at math.okstate.edu Mon May 8 09:05:38 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Mon, 08 May 2006 08:05:38 -0500 Subject: A critic of Guido's blog on Python's lambda References: <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> Message-ID: <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> On Sun, 07 May 2006 10:36:00 -0400, Ken Tilton wrote: >[...] > >Your spreadsheet does not have slots ruled by functions, it has one slot >for a dictionary where you store names and values/formulas. > >Go back to your example and arrange it so a and b are actual slots (data >members? fields?) of the spreadsheet class. You can just stuff numbers in a: > > sheet1.a = 42 > >but b should be somehow associated with a rule when sheet1 is created. >As I said in the other post, also associate an on-change callback with >slots a and b. I must be missing something - seems this should be easy using __setattr__ and __getattr__. Then _literally_ there's just a dict containing names and functions, but when you _use_ the class it looks just like the above: >[...] > >When that is done we can look at a working example and see how well >Python fared without macros and full-blown lambda. No lambda in the non-programmer-half-hour implementation below. You need to define a named function for each cell to use as a callback. Except for that what are Cells supposed to do that the implementation below doesn't do? """PyCells.py""" class Cell: def __init__(self, name, owner, callback): self.name = name self.callback = callback self.owner = owner def onchange(self, value): self.value = value self.callback(self, value) class Cells: def __init__(self): #self.slots = {} #Oops, don't work so well with __setattr__: self.__dict__['slots'] = {} def __setattr__(self, name, value): self.slots[name].onchange(value) def __getattr__(self, name): return self.slots[name].value def AddCell(self, name, callback): self.slots[name] = Cell(name, self, callback) *********** Sample use: cells = Cells() def acall(cell, value): cell.owner.slots['b'].value = value + 1 cells.AddCell('a',acall) def bcall(cell, value): cell.owner.slots['a'].value = value - 1 cells.AddCell('b',bcall) cells.a = 42 print cells.a, cells.b cells.b = 24 print cells.a, cells.b ************************ David C. Ullrich From ptmcg at austin.rr._bogus_.com Sun May 14 14:32:15 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 14 May 2006 18:32:15 GMT Subject: continue out of a loop in pdb References: <87mzdkwke3.fsf@localhost.localdomain> Message-ID: "Gary Wessle" wrote in message news:87mzdkwke3.fsf at localhost.localdomain... > Hi > > using the debugger, I happen to be on a line inside a loop, after > looping few times with "n" and wanting to get out of the loop to the > next line, I set a break point on a line after the loop structure and > hit c, that does not continue out of the loop and stop at the break > line, how is it down, I read the ref docs on pdb but could not figure > it out. > > thanks This is exactly how I do this operation using pdb, and it works for me, so you are on the right track. Is it possible that something inside the loop is raising an exception, thereby jumping past your breakpoint? Try putting the loop inside a try-except. -- Paul From antroy at gmail.com Wed May 17 07:12:26 2006 From: antroy at gmail.com (Ant) Date: 17 May 2006 04:12:26 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147858647.488974.92230@j73g2000cwa.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> Message-ID: <1147864346.266669.234000@j55g2000cwa.googlegroups.com> > Ant wrote: > > spaces. Pragmatically though, you can't tell in an editor where spaces > > are used and where tabs are used. > Um, I don't follow this. If you can't tell the editor where > tabs/spaces are used, who does? Re-read my post. Note the key word 'in'. > > Perhaps if editors colored the background of tab characters differently > > from spaces this wouldn't be a problem, > Some editors do. Some isn't nearly good enough to solve the problem. > python -tt Not the default behaviour, and so not good enough for tabs to be a good indent character. > > In reality, neither of these are likely > > to be implemented any time soon! > > um OK. Widely implemented and default behaviour. Your points are fine if you are working by yourself (hell you could use Perl and it wouldn't matter ;-) ), but in for example an open source project where work is distributed over developers working in vastly different environments, tabs currently aren't a workable option. From tkpmep at hotmail.com Tue May 9 17:57:57 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 9 May 2006 14:57:57 -0700 Subject: PyExcelerator: How does one close a file? Message-ID: <1147211877.683702.272710@i40g2000cwc.googlegroups.com> I use PyExcelerator to write data into Excel files, and repeatedly call the function writeData with different filenames fn from my main routine. Unfortunately, only one file - the last one - is created. The problem seems to lie with the fact that I do not close the existing file before calling the function again, and the existing file is therefore just saved with a new name. Is there a way to close a PyExcelerator Excel file so that each call to the function results in a new file? There is no close() method as far as I can tell. def writeData(fn, Data): """Write the data into an Excel file named fn using PyExcelerator Data is a list of real numbers""" w=PyExcelerator.Workbook() ws = w.add_sheet("Sheet1") for i in range(len(Data)): ws.write(i, 0, Data[i]) w.save(fn) Thanks in advance Thomas Philips From fredrik at pythonware.com Mon May 29 02:35:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 May 2006 08:35:29 +0200 Subject: HTMLParser chokes on bad end tag in comment In-Reply-To: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> References: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> Message-ID: Rene Pijlman wrote: > The code below results in an exception (Python 2.4.2): > > HTMLParser.HTMLParseError: bad end tag: "", at line 4, > column 6 > > Should it? The end tag it chokes on is in comment, isn't it? no. STYLE and SCRIPT elements contain character data, not parsed character data, so comments are treated as characters, and the first " From panos.laganakos at gmail.com Mon May 1 11:17:04 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 1 May 2006 08:17:04 -0700 Subject: Setting a module package to use new-style classes Message-ID: <1146496624.798907.327060@e56g2000cwe.googlegroups.com> Is there a way to have a whole module package use the new-style classes, without having to specify it per module-file or even worse, per class definition? Maybe by declaring the __metaclass__ in the module's __init__.py? From ryanf at cs.uoregon.edu Sat May 6 16:31:37 2006 From: ryanf at cs.uoregon.edu (Ryan Forsythe) Date: Sat, 06 May 2006 13:31:37 -0700 Subject: sort a list of files In-Reply-To: <877j4ysy29.fsf@localhost.localdomain> References: <877j4ysy29.fsf@localhost.localdomain> Message-ID: <445D07A9.5050300@cs.uoregon.edu> Gary Wessle wrote: > Hi > > I am trying to print out the contents of a directory, sorted. ... > if I remove ".sort()" at the end of line 6 I get an unsorted list of > files, if I leave it I get None. who do I fix this? `blah.sort()` sorts in-place and returns None. You probably want sorted(blah): >>> a = [3, 1, 4, 1, 5, 9] >>> sorted(a) [1, 1, 3, 4, 5, 9] >>> a [3, 1, 4, 1, 5, 9] >>> a.sort() >>> a [1, 1, 3, 4, 5, 9] -- Ryan Forsythe From vbgunz at gmail.com Mon May 8 22:34:06 2006 From: vbgunz at gmail.com (vbgunz) Date: 8 May 2006 19:34:06 -0700 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> Message-ID: <1147142046.458555.261870@j33g2000cwa.googlegroups.com> to throw fire on the fuel (:P), you can get the value back to an in-place mutable change with a single expression... mylist = [2,3,4,1] print mylist.sort() or mylist might not be too pythonic or maybe it is. I guess depends on what side of the glass you might wish to view the solution :) From DaleWKing [at]gmail [dot] com Tue May 16 12:14:17 2006 From: DaleWKing [at]gmail [dot] com (Dale King) Date: Tue, 16 May 2006 12:14:17 -0400 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147772344.649771.301610@i40g2000cwc.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147772344.649771.301610@i40g2000cwc.googlegroups.com> Message-ID: Iain King wrote: > Oh God, I agree with Xah Lee. Someone take me out behind the chemical > sheds... > > Xah Lee wrote: Please don't feed the troll! And for the record, spaces are 100% portable, tabs are not. That ends the argument for me. Worse than either tabs or spaces however is Sun's mixture of the two. -- Dale King From nobody at 127.0.0.1 Sun May 14 16:47:33 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 14 May 2006 20:47:33 GMT Subject: help using smptd Message-ID: I'm having trouble using the smptd module. The docs are woefully inadequate and inspecting the source didn't help either. So far I've figured out how to subclass smtpd.SMTPServer and override the process_message method to handle smtp messages. I create an instance of my server and it listens on the given interface. I can connect to the port it's on and send SMTP commands but it doesn't respond. I've verified that it's actually bound and I'm connecting to the right port. The server object doesn't appear to have any methods like poll() or loop() to continually handle connections, which is all I want it to do. There is a listen method but it does something else. Does SMTPServer have an equivalent to the serve_forever method of BaseHTTPServer.BaseHTTPRequestHandler? If not how do I handle smtp sessions? SMTPServer derives from asyncore/asynchat, but I didn't find what I wanted there either. import smtpd class SMTPProxy (smtpd.SMTPServer): def process_message (self, peer, mailfrom, rcpttos, data): # my code here proxy = SMTPProxy (listen_addr, relay_addr) # now what? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From phddas at yahoo.com Sat May 13 18:53:33 2006 From: phddas at yahoo.com (Gary Wessle) Date: 14 May 2006 08:53:33 +1000 Subject: retain values between fun calls Message-ID: <87d5ehh6z6.fsf@localhost.localdomain> Hi the second argument in the functions below suppose to retain its value between function calls, the first does, the second does not and I would like to know why it doesn't? and how to make it so it does? thanks # it does def f(a, L=[]): L.append(a) return L print f('a') print f('b') # it does not def f(a, b=1): b = a + b return b print f(1) print f(2) From rpdooling at gmail.com Sun May 14 01:05:47 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 May 2006 22:05:47 -0700 Subject: count items in generator Message-ID: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> Still new. I am trying to make a simple word count script. I found this in the great Python Cookbook, which allows me to process every word in a file. But how do I use it to count the items generated? def words_of_file(thefilepath, line_to_words=str.split): the_file = open(thefilepath) for line in the_file: for word in line_to_words(line): yield word the_file.close() for word in words_of_file(thefilepath): dosomethingwith(word) The best I could come up with: def words_of_file(thefilepath, line_to_words=str.split): the_file = open(thefilepath) for line in the_file: for word in line_to_words(line): yield word the_file.close() len(list(words_of_file(thefilepath))) But that seems clunky. From donald.welch at hp.com Mon May 8 12:14:48 2006 From: donald.welch at hp.com (dwelch) Date: Mon, 08 May 2006 09:14:48 -0700 Subject: get Windows file type In-Reply-To: <1147089470.336984.173510@u72g2000cwu.googlegroups.com> References: <1147089470.336984.173510@u72g2000cwu.googlegroups.com> Message-ID: <445f6e83$1@usenet01.boi.hp.com> BartlebyScrivener wrote: > Using Python on Windows XP, I am able to get almost all file and path > info using os.path or stat, but I don't see a way to retrieve the file > type? E.g. Microsoft Word file, HTML file, etc, the equivalent of what > is listed in the "Type" column in the Windows Explorer box. > > Thanks, > > rick > This worked well for me on Linux, should work on Windows: http://www.demonseed.net/~jp/code/magic.py -Don From aleax at mac.com Mon May 8 01:57:18 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 7 May 2006 22:57:18 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <1heytan.zl0xgh9v134kN%aleaxit@yahoo.com> Message-ID: <1hezn87.h8wwmp3kpz96N%aleax@mac.com> Tomasz Zielonka wrote: ... > Also, having anonymous functions doesn't take your common sense away, so > you still "have a chance". I've seen many people (presumably coming from Lisp or Scheme) code Python such as: myname = lambda ... rather than the obvious Python way to do it: def myname(... ((they generally do that right before they start whining that their absurd choice doesn't let them put statements inside the "unnamed function that they need to assign to a name")). _THAT_ is what having many semantically overlapping (or identically equivalent) ways to perform the same task does to people: it takes the common sense away from enough of them that I'm statistically certain to have to wrestle with some of them (be it as suppliers, people I'm trying to help out on mailing lists etc, students I'm mentoring -- at least being at Google means I don't have to fear finding such people as my colleagues, but the memories and the scars of when I was a freelance consultant are still fresh, and my heart goes out to the 99% of sensible Pythonistas who don't share my good luck). As long as Guido planned to remove lambda altogether in Python 3.0, I could console myself with the thought that this frequent, specific idiocy wasn't one I would have to wrestle with forever; now I know I will have no such luck -- it's back to the dark ages. ((If I ever _DO_ find a language that *DOES* mercilessly refactor in pursuit of the ideal "only one obvious way", I may well jump ship, since my faith in Python's adherence to this principle which I cherish so intensely has been so badly broken by GvR's recent decisions to keep lambdas, keep [] as an identical synonym for list(), add {1,2,3} as an identical synonym for set((1,2,3))...); though, being a greedy fellow, I'll probably wait until all my Google options have vested;-)). Alex From nobody at 127.0.0.1 Wed May 3 23:36:57 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 04 May 2006 03:36:57 GMT Subject: stripping unwanted chars from string Message-ID: I'm looking for the "best" way to strip a large set of chars from a filename string (my definition of best usually means succinct and readable). I only want to allow alphanumeric chars, dashes, and periods. This is what I would write in Perl (bless me father, for I have sinned...): $filename =~ tr/\w.-//cd, or equivalently $filename =~ s/[^\w.-]// I could just use re.sub like the second example, but that's a bit overkill. I'm trying to figure out if there's a good way to do the same thing with string methods. string.translate seems to do what I want, the problem is specifying the set of chars to remove. Obviously hardcoding them all is a non-starter. Working with chars seems to be a bit of a pain. There's no equivalent of the range function, one has to do something like this: >>> [chr(x) for x in range(ord('a'), ord('z')+1)] ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z'] Do that twice for letters, once for numbers, add in a few others, and I get the chars I want to keep. Then I'd invert the set and call translate. It's a mess and not worth the trouble. Unless there's some way to expand a compact representation of a char list and obtain its complement, it looks like I'll have to use a regex. Ideally, there would be a mythical charset module that works like this: >>> keep = charset.expand (r'\w.-') # or r'a-zA-Z0-9_.-' >>> toss = charset.invert (keep) Sadly I can find no such beast. Anyone have any insight? As of now, regexes look like the best solution. From bignose+hates-spam at benfinney.id.au Fri May 19 05:57:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 May 2006 19:57:15 +1000 Subject: calling python functions using variables References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> Message-ID: <871wuql4lg.fsf@benfinney.id.au> Peter Otten <__peter__ at web.de> writes: > creo wrote: > > what i want to do is > > commands.VARIABLE() > > where VARIABLE holds the name of the function which i want to execute > > and depends on what the user has typed > > You want > > getattr(commands, VARIABLE)() You'll also need to anticipate the situation where the value bound to VARIABLE is not the name of an attribute in 'commands'. Either deal with the resulting NameError exception (EAFP[0]) or test first whether the attribute exists (LBYL[1]). [0] Easier to Ask Forgiveness than Permission [1] Look Before You Leap -- \ "Our products just aren't engineered for security." -- Brian | `\ Valentine, senior vice-president of Microsoft Windows | _o__) development | Ben Finney From luismgz at gmail.com Thu May 25 13:38:51 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 25 May 2006 10:38:51 -0700 Subject: IronPython 1.0 Beta 7 Released References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> <1148518396.856710.173810@g10g2000cwb.googlegroups.com> <1148532003.624344.88030@38g2000cwa.googlegroups.com> <1148536183.520726.289960@i39g2000cwa.googlegroups.com> Message-ID: <1148578731.255929.310250@g10g2000cwb.googlegroups.com> Ravi Teja wrote: > Also, IronPython cannot access CPython libraries. So it cannot be used > as a drop-in replacement for CPython in most non-trivial apps. Python > for .NET however allows you to both use both CPython and .NET > libraries. It will be able to access the standard libraries, as long as they are writen in pure python, otherwise they should be rewriten in a .NET language. People are doing it already, it's just a matter of time... From s99999999s2003 at yahoo.com Mon May 22 07:28:16 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 22 May 2006 04:28:16 -0700 Subject: grabbing portions of a file to output files Message-ID: <1148297296.330413.68540@j73g2000cwa.googlegroups.com> hi. I have a file with this kind of structure: Hxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ......... ..... ..... xxxxx Hxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ... .... ... xxxxx Hxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx ..... .... and so on....lines starting with 'H' are headers. I wish to get the parts of the file where line start with 'H' all the way till before the next 'H' and save to files of different names...how is the best way to do it ? thanks From sjmachin at lexicon.net Mon May 15 07:15:44 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2006 04:15:44 -0700 Subject: Unicode to DOS filenames (to call FSUM.exe) References: Message-ID: <1147691744.880789.296320@y43g2000cwc.googlegroups.com> According to my reading of the source, the function you have called expects an 8-bit string. ==== static PyObject * PyGetShortPathName(PyObject * self, PyObject * args) { char *path; if (!PyArg_ParseTuple(args, "s:GetShortPathName", &path)) ==== If it is given Unicode, PyArg_ParseTuple will attempt to encode it using the default encoding (ascii). Splat. Looks like you need a GetShortPathNameW() but it's not implemented. Raise it as an issue on the pywin32 sourceforge bug register. Tell Mark I sent you :-) It may be possible to fake up your default encoding to say cp1252 BUT take the advice of anyone who screams "Don't do that!" and in any case this wouldn't help you with a Russian, Chinese, etc etc filename. Another thought: try using ctypes. Hope some of this helps, John From runlevelten at gmail.com Thu May 11 14:03:24 2006 From: runlevelten at gmail.com (Ten) Date: Thu, 11 May 2006 19:03:24 +0100 Subject: which windows python to use? In-Reply-To: <44633047.8010007@bryant.edu> References: <44633047.8010007@bryant.edu> Message-ID: <200605111903.25043.runlevelten@gmail.com> On Thursday 11 May 2006 13:38, Brian Blais wrote: > Hello, > > Are there any recommendations for which Windows python version to use? I'd > like to see a pros-and-cons description of each, given that different uses > might dictate different versions. The versions I know (and there are > surely more) are: > > 1) download from www.python.org > 2) enthought > 3) activepython > > Are there advantages/disadvantages? I have used enthought before, but it > seems as if they are not at 2.4, and may lag behind in versions (which may > not be a bad thing). > > Any other recommendations? > As mentioned elsewhere, it depends what your criteria are. Will it be deployed to end users? Your servers? Is python itself being bundled with the program? Is the target a cross-platform or single-platform app? Etc.? If you want "general" advice, here it is: I'd stick with python python and install what extras you need yourself. I've always used the python from python.org and added stuff I need, and I have to be honest, I haven't come across a single comparative disadvantage of doing so yet. Besides, I think installing modules yourself and knowing what's *extra* for an average python-enabled machine is a Good Thing. -- There are 10 types of people in this world, those who understand binary, and those who don't. From mhearne808 at yahoo.com Mon May 29 01:00:47 2006 From: mhearne808 at yahoo.com (mhearne808) Date: Mon, 29 May 2006 05:00:47 -0000 Subject: dynamically loaded libraries Message-ID: I have a question about how dynamically loaded C++ modules work, which I will phrase as a hypothetical scenario involving the Numeric module. Please understand that I don't really care about Numeric per se, it's just a useful example of a module that defines a generally useful data type. Let's say I want to create a C++ Python extension module that has methods accepting the Numeric array type as input, and also create these arrays as output. In order to make this work, do I have to statically link against the Numeric source, or do I only have to include the headers, under the assumption (??) that the Numeric functionality will be available because the Python executable has dynamically loaded it? Thanks! Mike From larry.bates at websafe.com Wed May 31 16:39:08 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 31 May 2006 15:39:08 -0500 Subject: Help requested -- importing stuff from a .COM DLL into python In-Reply-To: References: Message-ID: <447DFEEC.2070708@websafe.com> John D Salt wrote: > I wonder if some kind soul can help me in my struggle with DLLs? > > I am trying -- not because I want to, but because I have been told to -- > to import things from an API that exists as a bunch of .COM DLLs. > > I had originally hoped to get them into a Python 2.4 program by a simple > import statement. This does not appear to work, so I secured a copy of > win32com, and have proven that it works to the extent of opening a M$ > Word application. > > The same approach with the DLLS I actually need to use consistently fails > with the message "Invalid class string" (full traceback included below, I > doubt that it helps). After a couple of afternoons of vigorous easter- > egging, I have not hit upon a valid class string, and my childish > assumption that it would be one of the names listed in the API > ocumentation is obviously wrong. Staring at the DLL contents with > PEBrowse tells me nothing useful. > > Does anyone with experience of getting .COM stuff from DLLs know where I > am going wrong? > > (Alternatively, can anyone who has got Python to use the MooD API tell me > how?) > > I have no experience of .COM up to this point, and am hoping to keep it > that way once this nonsense is done with. > > Thanks for any assistance, and all the best, > > John. > > - - - - - - - - cut here - - - - - - - - > > Traceback (most recent call last): > File "D:\Program Files\MooD\2006\MooDAPI\APIstrangler0_1.py", line 470, > in ? > thing = win32com.client.Dispatch("MooDAPI.Object.Info") # Fails, > "Invalid class string > File "D:\Python24\Lib\site-packages\win32com\client\__init__.py", line > 95, in Dispatch > dispatch, userName = dynamic._GetGoodDispatchAndUserName > (dispatch,userName,clsctx) > File "D:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 98, in _GetGoodDispatchAndUserName > return (_GetGoodDispatch(IDispatch, clsctx), userName) > File "D:\Python24\Lib\site-packages\win32com\client\dynamic.py", line > 78, in _GetGoodDispatch > IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, > pythoncom.IID_IDispatch) > com_error: (-2147221005, 'Invalid class string', None, None) Not exactly sure I understand what you need. I call functions that are stored in Windows .DLLs by using either dynawin.calldll (older method) or ctypes (newer method). I never thought of them as COM, but rather compiled C functions stored in .DLL libraries. Maybe you can call via COM, but I just haven't ever done that. You should be able to use ctypes to interface to them. The "tricky" part is passing data back and forth. Building the proper data structures in Python can take some work. You should take a look at ctypes from: http://sourceforge.net/project/showfiles.php?group_id=71702 COM sample is here: http://starship.python.net/crew/theller/ctypes/sum_sample.html HTH, Larry Bates From johnzenger at gmail.com Tue May 16 12:20:58 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 16 May 2006 09:20:58 -0700 Subject: Help System For Python Applications In-Reply-To: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> References: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> Message-ID: <1147796457.988353.257930@y43g2000cwc.googlegroups.com> redefined.horizons at gmail.com wrote: > On a related note, is there a way to fire up Adobe's Acorbat Reader or > and Web Browser from Python and have the external application open a > specified PDF or HTML file? (For example, I want to open the file > "myhelp.pdf" in reader from Python code.) The webbrowser module lets you open any page. HTML will open in the user's default web browser; PDF opens in Acrobat (at least on my Windows machine). >>> import webbrowser >>> webbrowser.open(r"C:\\helpfile.pdf") From bj_666 at gmx.net Thu May 4 17:14:29 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Thu, 04 May 2006 23:14:29 +0200 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> <125ir8gpofq3i1c@corp.supernews.com> Message-ID: In <125ir8gpofq3i1c at corp.supernews.com>, Grant Edwards wrote: > On 2006-05-04, OlafMeding at gmail.com wrote: >> The sleep statement does not return! > > Never, or does it just take a long time? > >> And this should not happen. > > Dude, it's MS Windows. > > It does all _sorts_ of stuff that it shouldn't. > > Having sleep() take orders of magnitude longer than it should > is not an uncommon complaint for MS Windows users. There was a > fairly extensive thread in this group about that problem just a > few weeks ago. IIRC, disabling some other program or service > fixed it for one MS victem. IIRC it was something like an NTP daemon that caused the clock to "jump" a little and (Window's) sleep was confused. Ciao, Marc 'BlackJack' Rintsch From steven.bethard at gmail.com Wed May 10 00:33:37 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 09 May 2006 22:33:37 -0600 Subject: optparse and counting arguments (not options) Message-ID: I feel like I must be reinventing the wheel here, so I figured I'd post to see what other people have been doing for this. In general, I love the optparse interface, but it doesn't do any checks on the arguments. I've coded something along the following lines a number of times: class OptionArgParser(optparse.OptionParser): def __init__(self, *args, **kwargs): self.min_args = kwargs.pop('min_args', None) self.max_args = kwargs.pop('max_args', None) self.arg_values = kwargs.pop('arg_values', None) optparse.OptionParser.__init__(self, *args, **kwargs) def parse_args(self, args=None): options, args = optparse.OptionParser.parse_args(self, args) if self.min_args is not None and len(args) < self.min_args: self.error('too few arguments') if self.max_args is not None and len(args) > self.max_args: self.error('too many arguments') if self.arg_values is not None: for arg, values in zip(args, self.arg_values): if values is not None and arg not in values: message = 'argument %r is not one of: %s' self.error(message % (arg, ', '.join(values))) return options, args This basically lets me skip some simple checks by creating instances of OptionArgParser instead of optparse.OptionParser, and supplying my new options: parser = OptionArgParser( min_args=1, arg_values=[commands], usage='%%prog [options] (%s) ...' % '|'.join(commands), description='invoke one of the commands') Is this problem already solved in some module that I've missed? STeVe From maric at aristote.info Wed May 24 18:06:16 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 25 May 2006 00:06:16 +0200 Subject: Bind an instance of a base to a subclass - can this be done? In-Reply-To: <4djshnF1asdovU1@uni-berlin.de> References: <4djshnF1asdovU1@uni-berlin.de> Message-ID: <200605250006.16944.maric@aristote.info> Le Mercredi 24 Mai 2006 22:04, Diez B. Roggisch a ?crit?: > Nope, not in that way. But you might consider writing a proxy/wrapper > for an object. That looks like this (rouch sketch from head): > > class FileWrapper(object): > ? ? def __init__(self, f): > ? ? ? ?self._f = f > > ? ? def __getattr__(self, name): > ? ? ? ?return getattr(self._f, name) > > ? ? def myreadline(self): > ? ? ? ?.... Why use a proxy when you can just inherit from the builtin file object ? class myFile(file) : def myreadline(self) : print 'yo' In [20]: myFile('frwiki-20060511-abstract.xml') Out[20]: In [21]: myFile('frwiki-20060511-abstract.xml').myreadline() yo In [22]: -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From telesphore4 at gmail.com Wed May 17 00:17:12 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 16 May 2006 21:17:12 -0700 Subject: A better way of making subsclassing of built-in types stick for attributes? Message-ID: <1147839432.816504.318290@38g2000cwa.googlegroups.com> Is there a better way to make the subclassing of built-in types stick? The goal is to have the the fields of a class behave like strings with extra methods attached. That is, I want the fact that the fields are not strings to be invisible to the client programmers. But I always want the extras to be there for the clients too. What I'm doing is subclassing str. Of course, whenever you then set mystr = 'a string' you loose the extra goodies that I have attached in the subclass. So, to get around this I set up __get__ers and __set__ers for the fields. The question is there a more succinct way to have the extended string behavior stick than using descriptors? Just to make things concrete here's some abbreviated sample code: class Person(Table.Table): def __init__(self, tcs, gender=None, first=None, last=None, status=None): self.gender = gender self.first = first self.last = last self.status = status # Using mix-ins to get the desired behavior class Gender(Field.InitAlways, Field.SqlVarchar): table = ('F', 'M') fillNext = -1 @classmethod def fill(cls, rec): cls.fillNext += 1 return cls.table[cls.fillNext % 2] #classes First, Last, & Status are analogous but more complicated # The descriptors are set up at the bottom of the module like so: Person.first = Field.Descriptor(First) Person.gender = Field.Descriptor(Gender) Person.status = Field.Descriptor(Status) # Moving along to other stripped supporting code class Descriptor(object): def __init__(self, cls, name=None): self.cls = cls if name == None: self.name = cls.__name__.lower() else: self.name = name.lower() def __set__(self, inst, value): if inst.__dict__.has_key(self.name): inst.__dict__[self.name] = self.cls(inst, value, True) else: inst.__dict__[self.name] = self.cls(inst, value, False) class InitAlways(str): def __new__(cls, rec, value, reset): if reset: return str.__new__(cls, value) if value == Empty: return str.__new__(cls, '') if value == Fill or value == None: #if value in (None, Fill, ''): return str.__new__(cls, cls.fill(rec) or '') return str.__new__(cls, value or '') From WSobczuk at gmail.com Thu May 18 10:36:54 2006 From: WSobczuk at gmail.com (WSobczuk at gmail.com) Date: 18 May 2006 07:36:54 -0700 Subject: Strange error In-Reply-To: References: <1147962206.900840.19130@38g2000cwa.googlegroups.com> Message-ID: <1147963014.880378.44270@i39g2000cwa.googlegroups.com> Evaluation of default values seems to have nothing to do with the case I described. The default values are both tags = {}, and still inside mysearch() I sometimes get some value from previous call inside tags, when the tags keyword argument is not specified. From kent at kentsjohnson.com Thu May 25 09:53:37 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 25 May 2006 09:53:37 -0400 Subject: Finding Upper-case characters in regexps, unicode friendly. In-Reply-To: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> References: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> Message-ID: <4475b60c$1_3@newspeer2.tds.net> possibilitybox at gmail.com wrote: > I'm trying to make a unicode friendly regexp to grab sentences > reasonably reliably for as many unicode languages as possible, focusing > on european languages first, hence it'd be useful to be able to refer > to any uppercase unicode character instead of just the typical [A-Z], > which doesn't include, for example ?. Is there a way to do this, or > do I have to stick with using the isupper method of the string class? > See http://tinyurl.com/7jqgt Kent From kentilton at gmail.com Fri May 12 20:06:32 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 12 May 2006 20:06:32 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Alexander Schmolck wrote: > Duane Rettig writes: > > >>Alexander Schmolck writes: >> >> >>>Ken Tilton writes: >>> >>> >>>>In Common Lisp we would have: >>>> >>>> (defvar *x*) ;; makes it special >>>> (setf *x* 1) >>>> (print *x*) ;;-> 1 >>>> (let ((*x* 2)) >>>> (print *x*)) ;; -> 2 >>>> (print *x*) ;; -> 1 >>> >>>You seem to think that conflating special variable binding and lexical >>>variable binding is a feature and not a bug. What's your rationale? I will expand on my earlier "transparency" rationale with a further rationale for transparency: I do not need no stinkin' rationale. A special variable is still a variable. They should be set, read, and bound (say, by "let") the same way as any other variable. You need a rationale. It sounds as if you want some noisey syntax to advertise the specialness. I do not think the Python community will appreciate you messing up their pretty code. You are right about one thing: specialness needs advertising. You know what we do in Lisp? We obediently name special variables with bracketing *s, like *this*. Too simple? >> >>A bug is a non-conformance to spec. > > > There is a world beyond specs, you know. If copies of allegro CL accidently > sent out death-threats to the US president on a weekly basis, because someone > at franz accidently or purposefully left in some pranky debugging code the > fact that this behaviour would likely neither violate the ansi spec nor any > other specs that ACL officially purports to adhere to wouldn't make it any > less of a bug (or help to pacify your customers). > > >>Kenny's statement was specifically about Common Lisp > > > No Kenny's statement was about contrasting the way something is done in python > and the way something is done in common lisp (with the implication that the > latter is preferable). Close, but no. The question I was weighing in was "has Michele replicated special variables?". My implication was, "Not yet -- can you match the transparency?", and it was an honest question, I do not know. Again, transparency is a qualitative difference. I liked your solution better, btw, because it does minimize the noise. For fun, you should call the class ** instead of special, so we end up with: **.b = 42 We'll understand. :) > Of course the way something is done in common lisp is > almost tautologically in closer agreement with the ansi common lisp spec than > the way it is done in python, so agreement with the clhs is not a useful > criterion when talking about design features and misfeatures when contrasting > languages. Again, no, it is not the spec, it is the highly-valued Python quality of clean code. Also, the consistency of treating variables as variables, regardless of some special/dynamic quality. Some background. Lisp is a big language, and I am self taught and do not like to read, grew up in Lisp in isolation. Not many Lispers in the exercise yard. Discovered special variables only when we hired an old hand who gently corrected a howler: (let* ((old-x *x*)) (setf *x* 42) .... (setf *x* old-x)) I still laugh at that. Anyway, as soon as I learned that, I was able to make Cells syntax infinitely more transparent. And guess what? It also made dependency identification automatic instead of cooperative, and when I rebuilt a huge Cells-based app I discovered two or three cases where I had neglected to publish a dependency. It's a mystery, but somehow simpler syntax... oh, wait, this is c.l.python, I am preaching to the choir. > > I just don't think the way special variable binding (or variable binding in > general[1]) is handled in common lisp is particularly well designed or > elegant. See above. There is nothing like a concrete experience of implementing a hairy library like Cells /without/ leveraging specials and then converting to specials. Talk about an Aha! experience. I mean, bugs ran screaming from their nests simply because of the implementation change-- we call that A Message From God that the design has taken a correct turn. > > Special variables and lexical variables have different semantics and using > convention and abusing[2] the declaration mechanism to differentiate between > special and lexical variables doesn't strike me as a great idea. I know what you mean, but I like reading tea leaves, and I find it fascinating that *this* somehow eliminates all ambiguity. Background: don't know where I might find it, but I once saw a thread demonstrating the astonishing confusion one could create with a special variable such as a plain X (no *s). Absolutely mind-bogglingly confusing. Go back and rename the special version *x*, and use *x* where you want to rebind it. Result? Utterly lucid code. Scary, right? > > I can certainly think of problems that can occur because of it (E.g. ignoring > or messing up a special declaration somewhere; setf on a non-declared variable > anyone? Sh*t, you don't respond to compiler warnings? Don't blame CL for your problems. :) > There are also inconsistent conventions for naming (local) special > variables within the community (I've seen %x%, *x* and x)). OK, you are in flamewar mode, now you are just making things up. > > Thus I don't see having to use syntactically different binding and assignment > forms for special and lexical variables as inherently inferior. DUDE! They are both variables! Why the hell /should/ the syntax be different? "Oh, these are /cross-training/ sneakers. I'll wear them on my hands." Hunh? :) kenny From grante at visi.com Fri May 19 10:02:04 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 19 May 2006 14:02:04 -0000 Subject: calling python functions using variables References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <446da180$0$10184$636a55ce@news.free.fr> Message-ID: <126rjus43k450df@corp.supernews.com> On 2006-05-19, bruno at modulix wrote: >> Either deal with the resulting NameError exception (EAFP[0]) > > try: > getattr(commands, VARIABLE)() > except NameError: > print >> sys.stderr, "Unknown command", VARIABLE > >> or test >> first whether the attribute exists (LBYL[1]). > > command = getattr(commands, VARIABLE, None) > if command is None: > print >> sys.stderr, "Unknown command", VARIABLE > else: > command() > > I'd go for the first solution. Me too. Assuming the user isn't clueless, the normal case is where the command exists. Write code for the normal case and use the exception that occurs for exceptional cases. -- Grant Edwards grante Yow! This PIZZA symbolizes at my COMPLETE EMOTIONAL visi.com RECOVERY!! From sam at nuevageorgia.com Mon May 22 16:39:42 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 22 May 2006 13:39:42 -0700 Subject: Python - Web Display Technology In-Reply-To: References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> Message-ID: <1148330381.986680.121760@i40g2000cwc.googlegroups.com> Don't worry, you won't have to look if it makes you feel dirty... :) From bignose+hates-spam at benfinney.id.au Mon May 22 22:40:49 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 23 May 2006 12:40:49 +1000 Subject: No math module?? References: Message-ID: <87fyj131la.fsf@benfinney.id.au> WIdgeteye writes: > ImportError: No module named math > [...] > I have been using python on my computer since it first came out and > this is the first time I have runinto this. I have Python 2.3.2 > installed on Slackware Linux. I installed it from source download > from the Python.org web site. It definitely should be part of the default Python install. On my Debian system: ===== $ python Python 2.3.5 (#2, Sep 4 2005, 22:01:42) [GCC 3.3.5 (Debian 1:3.3.5-13)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import math >>> repr(math) "" >>> $ dpkg -S /usr/lib/python2.3/lib-dynload/math.so python2.3: /usr/lib/python2.3/lib-dynload/math.so ===== Perhaps you should use the official Python package for your operating system, or double-check you built and installed the source packages the way you want them. -- \ "My doctor told me to stop having intimate dinners for four. | `\ Unless there are three other people." -- Orson Welles | _o__) | Ben Finney From mumia.w.18.spam+fbi.gov at earthlink.net Tue May 23 09:19:56 2006 From: mumia.w.18.spam+fbi.gov at earthlink.net (Mumia W.) Date: Tue, 23 May 2006 13:19:56 GMT Subject: Tabs versus Spaces in Source Code In-Reply-To: <1148382162.678105.303890@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1148382162.678105.303890@g10g2000cwb.googlegroups.com> Message-ID: <0_Dcg.1017$Sf2.574@newsread1.news.pas.earthlink.net> Xah Lee wrote: > the following are 2 FAQ following this thread. Thanks. > > Addendum: 2006-05-15 > > Q: What you mean by embeding tab position info into the source code? > How's that gonna be done? > > A: Tech geekers may not realize, but such embedding of meta info do > exist in many technologies by various means because of a need. For > example, Mac OS Classic's resource fork and Mac OS X's bundling system, > unix shell script's shebang (#!), emacs and Python's encoding > declaration ?#-*- coding: utf-8 -*-?, Unicode's BOM, CVS's > change-log insertion, Mathematica's source code system the Notebook, > Microsoft Word's transparent meta data, as well as HTML and XML's > various declarations embedded in the file. Some of these systems are > good designs and some are hacks. > Vim's mode-lines do this too. > Somehow tech geekers have the sense that ?source code? must be a > plain text file containing nothing else but the programing code. This > may be a defendable position, but as we can see in the above examples, > this idea is primitive and does not address the various needs. If the > tech geekers have thought out about these issues, computing languages > and its source code may have developed into more powerful and flexible > integrated systems as the above standardized examples. The tech geekers have thought about it. Donald Knuth invented TeX, and went on to invent the WEB literate programming system. You don't get any geekier than that :) > For instance, > many commercial development systems actually already have such > meta-data embodied with the source code. (e.g. Borland Delphi, > Metrowerks's CodeWarrior, Microsoft Visual Studio, Wolfram Research's > Mathematica.) Some of which, not only embody development-related info > such as debug points or linking files, but also allow programers to > high-light code for visual purposes like a word processor, or even > display them visually as type-set mathematics. > > Q: Converting spaces to tabs is actually easy. I don't see how spacess > lose info. > > A: Here is a illustration on how it is not possible to convert spaces > to tabs. Suppose you are writing in a language where the indentation is > part of the semantics, not just for appearance. Now, suppose you have > these two lines: I'd say that such a language removes the choice of whether to use tabs or spaces, and the discussion is over when you don't have a choice. > > 1234567890 > A > B > > The first line has 2 space prefix and second line has 4 space prefix. > How, if you convert this to tabs, how do you know that's 1 and 2 tabs, > or 2 and 4 tabs? In essence, there is no way to tell how many tabs n > represents, where n is the smallest space prefix in the code, unless n > == 1. vim: tabstop=4 The argument for spaces over tabs says that you have to include some metadata in order for the document to look right on other people's computers if you use tabs. This example, plus my example mode-line for vim, reinforces that idea IMO. > > The above demonstrates the information loss in using spaces for > indentation in a theoretical way. There are also practical problems. In > practice, many languages allow string literals like this myName="i love > you", and strings easily can have a run of spaces. One cannot simply > run a blind find-n-replace operation to replace all spaces to tabs. But > also, many unix languages contains a so-called construct of > ?heredoc? as a mean to embed a literal block of text. For example, > here's a PHP construct of heredoc: > > $novelText = << (__) > (oo) > /-------\/ > / | || > * ||----|| > ~~ ~~ > arbitraryCharsHereAsDelimiter; > } > Yes, there are lots of situations like this where you can't just willy-nilly convert between tabs and spaces. But even in this case shows that, if you use consistent tab widths, the text has a chance of surviving. I converted your little doggie to and from text with tab sizes of eight, and he survived. (I did it with tabs set to four too, and it worked.) > Regardless of its design as a language construct, the purpose of > ?heredoc? is that it allows programers to easily embed a text (a > large string), without worrying about the text containing sequence of > characters that may be meaningful to the language. If a language has > heredoc construct, then it is basically impossible to convert from > spaces to tabs, as that will botch literal string embedded in heredoc. Yes it would. Upon printing, if the terminal tab width was set to eight, but the text conversion was done with tabs at four, bye bye doggie. > However, it is less of a problem to convert tabs to spaces, because the > frequency of spaces appearing in literal strings are far higher than > literal tabs. > > Another practical issue is error recovery. Suppose, one uses 4 spaces > for a indentation. Now, it is not uncommon to see lines with odd number > of space prefixes such as 7 or 10 out of common sloppiness. Such error > would happen more often if spaces are used for indentation, and the > essence is that tabs enforce a semantic association and is impossible > to make a half-indentation. > What I've learned is that, if I'm going to use tabs for indentation, I have to be consistent. > Q: Well, i just like spaces because they are most compatible. > > A: Sure, crass simplicity is always more compatible. Suppose a unixer > will say, he doesn't like HTML because it is fret with problems and > incompatibilities. He'd rather prefer plain text. And, indeed, a lot > unixers seriously think that. > > --------------------------- > PS in the answer to the first question, i gave the following examples > of IDE/Language that actually embed formatting info in the source code: > Borland Delphi, Metrowerks's CodeWarrior, Microsoft Visual Studio, > Wolfram Research's Mathematica > Perl's POD and Java's javadoc do it too. > actually, i know Mathematica does, but i'm not quite sure about the > other examples. So, my question is, does any one knows a language or > IDE that actually allows the coder to manually highlight parts of the > code and this highlight stick with the file upon reopening, as if a > word processor? > > Xah > xah at xahlee.org > ? http://xahlee.org/ > > Xah Lee wrote: >> Tabs versus Spaces in Source Code >> This post is archived at: >> http://xahlee.org/UnixResource_dir/writ/tabs_vs_spaces.html > I'm slowly moving into the "spaces" camp. After reading your earlier post on tabs vs. spaces and other people's responses, I began thinking about why I like tabs so much, and there is only one answer--backspace. If I use tabs, when I backspace I go back to the previous tab position, which is what I want. With spaces, I have to hit the backspace key several times to get back. That's it--one feature is the only reason I like tabs, so I decided to investigate vim's features to see if vim would let me backspace to the previous tab position with one keystroke. 'Softtabstop' (sts) is the feature. I would have never thought to look for this feature without your post. Thanks again Xah. Your posts are on topic, informative, engaging and necessary. Keep them coming Xah. :) From ullrich at math.okstate.edu Thu May 4 08:39:02 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Thu, 04 May 2006 07:39:02 -0500 Subject: Multiple Version Install? Message-ID: Would there be issues (registry settings, environment variables, whatever) if a person tried to install versions 1.x and 2.x simultaneously on one Windows system? Windows 98, if it matters. (I can handle the file associations with no problem.) Thanks. ************************** If anyone feels like pointing out that there's simply no reason to want to keep 1.x after installing the current version: By all means talk me into that! The problem is not that I'm concerned about backwards compatibility of Python code. The problem is that I use Python embedded in various Delphi programs, including a "DIDE" that I use really a lot, via a certain set of Delphi "components". These components don't seem to work with 2.x. Presumably the PyDelphi people have new versions of the components that do work with Python 2.x. These presumably use much newer versions of Delphi than what I have. A new version of Delphi is not free... If I could use Python 2.x when I need to while continuing to use 1.x the way I have been for things that don't need 2.x that would be convenient. ************************ David C. Ullrich From ognjen at mailshack.com Sun May 14 14:33:56 2006 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Sun, 14 May 2006 19:33:56 +0100 Subject: Converting hex to char help In-Reply-To: References: Message-ID: <200605141933.57679.ognjen@mailshack.com> Hi all, I am trying to convert a hexdecimal value to a char using this code: print ' %c ' % int(0x62) this works fine, but if I want to do this: number = "62" print ' %c ' % int("0x" + number) I get an error: Traceback (most recent call last): File "",line 1, in ? ValueError: invalid literal for in(): 0x62 How can I convert a string "0x62" to int/hex without this problem? Thanks! From a.schmolck at gmail.com Fri May 12 17:10:58 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 12 May 2006 22:10:58 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Duane Rettig writes: > Alexander Schmolck writes: > > > Ken Tilton writes: > > > >> In Common Lisp we would have: > >> > >> (defvar *x*) ;; makes it special > >> (setf *x* 1) > >> (print *x*) ;;-> 1 > >> (let ((*x* 2)) > >> (print *x*)) ;; -> 2 > >> (print *x*) ;; -> 1 > > > > You seem to think that conflating special variable binding and lexical > > variable binding is a feature and not a bug. What's your rationale? > > A bug is a non-conformance to spec. There is a world beyond specs, you know. If copies of allegro CL accidently sent out death-threats to the US president on a weekly basis, because someone at franz accidently or purposefully left in some pranky debugging code the fact that this behaviour would likely neither violate the ansi spec nor any other specs that ACL officially purports to adhere to wouldn't make it any less of a bug (or help to pacify your customers). > Kenny's statement was specifically about Common Lisp No Kenny's statement was about contrasting the way something is done in python and the way something is done in common lisp (with the implication that the latter is preferable). Of course the way something is done in common lisp is almost tautologically in closer agreement with the ansi common lisp spec than the way it is done in python, so agreement with the clhs is not a useful criterion when talking about design features and misfeatures when contrasting languages. I thought it would have been pretty obvious that I was talking about language design features and language design misfeatures (Indeed the infamously post hoc, "It's a feature, not a bug" I was obviously alluding too doesn't make much sense in a world were everything is tightly specified, because in it nothing is post-hoc). >, which has a spec. Bah -- so does fortran. But scheme also has operational semantics. > Now, what was your rationale for it _being_ a bug? I just don't think the way special variable binding (or variable binding in general[1]) is handled in common lisp is particularly well designed or elegant. Special variables and lexical variables have different semantics and using convention and abusing[2] the declaration mechanism to differentiate between special and lexical variables doesn't strike me as a great idea. I can certainly think of problems that can occur because of it (E.g. ignoring or messing up a special declaration somewhere; setf on a non-declared variable anyone? There are also inconsistent conventions for naming (local) special variables within the community (I've seen %x%, *x* and x)). Thus I don't see having to use syntactically different binding and assignment forms for special and lexical variables as inherently inferior. But I might be wrong -- which is why was asking for the rationale of Kenny's preference. I'd be even more interested in what you think (seriously; should you consider it a design feature (for reasons other than backwards compatiblity constraints), I'm pretty sure you would also give a justification that would merrit consideration). 'as Footnotes: [1] The space of what I see as orthogonal features (parallel vs. serial binding, single vs. multiple values and destructuring vs non-destructuring etc.) is sliced in what appear to me pretty arbitrary, non-orthogonal and annoying (esp. superfluous typing and indentation) ways in CL. [2] Generally declarations don't change the meaning of an otherwise well-defined program. The special declaration does. It's also a potential source of errors as the declaration forces you to repeat yourself and to pay attention to two places rather than one. From robert.kern at gmail.com Wed May 10 01:22:27 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 10 May 2006 00:22:27 -0500 Subject: SciPy - I need an example of use of linalg.lstsq() In-Reply-To: References: Message-ID: I. Myself wrote: > And it has to run on Windows, so it can't use xplt. Huh? A. xplt runs on Windows, too. B. xplt has nothing to do with linalg.lstsq(). C. xplt has been removed from scipy. > I would prefer that it use the simplest multi-dimensional model, z = k + > a*x1 + b*x2 + c*x3 + d*x4 In [1]: import numpy as np In [2]: np.linalg.lstsq? Type: function Base Class: String Form: Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/numpy-0.9.7.2476-py2.4-macosx-10.4-ppc.egg/numpy/linalg/linalg.py Definition: np.linalg.lstsq(a, b, rcond=1e-10) Docstring: returns x,resids,rank,s where x minimizes 2-norm(|b - Ax|) resids is the sum square residuals rank is the rank of A s is the rank of the singular values of A in descending order If b is a matrix then x is also a matrix with corresponding columns. If the rank of A is less than the number of columns of A or greater than the number of rows, then residuals will be returned as an empty array otherwise resids = sum((b-dot(A,x)**2). Singular values less than s[0]*rcond are treated as zero. In [3]: z = np.rand(10) In [4]: x1 = np.rand(10) In [5]: x2 = np.rand(10) In [6]: x3 = np.rand(10) In [7]: x4 = np.rand(10) In [8]: A = np.column_stack([x1, x2, x3, x4, np.ones(10, float)]) In [9]: A Out[9]: array([[ 0.07257264, 0.36544251, 0.68467294, 0.33813333, 1. ], [ 0.09520828, 0.27102091, 0.04673061, 0.12905473, 1. ], [ 0.839834 , 0.46010114, 0.3949568 , 0.38983012, 1. ], [ 0.49776387, 0.70666191, 0.85005579, 0.47738743, 1. ], [ 0.25457977, 0.93335912, 0.88441593, 0.05255062, 1. ], [ 0.85982216, 0.97920853, 0.27991214, 0.94230651, 1. ], [ 0.03224487, 0.1275237 , 0.66943552, 0.320765 , 1. ], [ 0.86807363, 0.63800103, 0.67153924, 0.69125023, 1. ], [ 0.26571213, 0.68845408, 0.06478114, 0.03657494, 1. ], [ 0.46615143, 0.99464106, 0.9303421 , 0.61363703, 1. ]]) In [10]: np.linalg.lstsq(A, z) Out[10]: (array([-0.32421087, -0.23330787, 0.13369118, -0.28334431, 0.84010014]), array([ 0.22958042]), 5, array([ 4.59505886, 1.1181838 , 0.85704672, 0.70211311, 0.4420187 ])) If you have more scipy questions, you will probably want to ask on the scipy-user list: http://www.scipy.org/Mailing_Lists -- 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 jiba at tuxfamily.org Thu May 25 16:22:21 2006 From: jiba at tuxfamily.org (jiba at tuxfamily.org) Date: 25 May 2006 13:22:21 -0700 Subject: Secure Pickle-like module Message-ID: <1148588541.444993.115600@u72g2000cwu.googlegroups.com> Hi all, I'm currently working on a secure Pickle-like module, Cerealizer, http://home.gna.org/oomadness/en/cerealizer/index.html Cerealizer has a pickle-like interface (load, dump, __getstate__, __setstate__,...), however it requires to register the class you want to "cerealize", by calling cerealizer.register(YourClass). Cerealizer doesn't import other modules (contrary to pickle), and the only methods it may call are YourClass.__new__, YourClass.__getstate__ and YourClass.__setstate__ (Cerealizer keeps it own reference to these three method, so as YourCall.__setstate__ = cracked_method is harmless). Thus, as long as __new__, __getstate__ and __setstate__ are not dangerous, Cerealizer should be secure. The performance are quite good and, with Psyco, it is about as fast as cPickle. However, Cerealizer is written in less than 300 lines of pure-Python code. I would appreciate any comments, especially if there are some security gurus here :-) Jiba From g.brandl-nospam at gmx.net Thu May 4 09:37:30 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Thu, 04 May 2006 15:37:30 +0200 Subject: unable to resize mmap object In-Reply-To: <1146601239.702098.156640@j33g2000cwa.googlegroups.com> References: <1146601239.702098.156640@j33g2000cwa.googlegroups.com> Message-ID: Carl Banks wrote: > Frankly, I'm not so sure matching Windows behavior is a great idea. > mmap module seems to be having an identity crisis. Is it a low-level > system call, or a high-level, OS-independent way to access files as > blocks of memory? The modules is moving towards the latter (what with > Unix mmap accepting ACCESS-style flags, and now this file-resizing > behavior). I actually favor a two-level approach similar to file I/O: > there would low-level system calls in the os module, and high-level > mmap object. (The high-level object would go all the way. It would > accept a filename rather than a file descriptor, anonymous blocks would > be handled OS-independently, rather than mapping /dev/zero, and so on.) I'm sure that we will gladly accept a patch implementing this approach. Cheers, Georg From gh at ghaering.de Fri May 19 12:48:17 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Fri, 19 May 2006 18:48:17 +0200 Subject: Python sqlite and regex. In-Reply-To: <1148054261.004682.310800@38g2000cwa.googlegroups.com> References: <1148054261.004682.310800@38g2000cwa.googlegroups.com> Message-ID: <446DF6D1.4020407@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Matt Good wrote: > SQLite3 already has a REGEXP function, so you don't need to create your > own. [...] Yes, but SQLite does not include a regular expression engine, and thus according to the SQLite docs you need to register a REGEXP function in order to make the REGEXP operator work: """ The REGEXP operator is a special syntax for the regexp() user function. No regexp() user function is defined by default and so use of the REGEXP operator will normally result in an error message. If a user-defined function named "regexp" is defined at run-time, that function will be called in order to implement the REGEXP operator. """ - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEbfbQdIO4ozGCH14RAqqqAJ49/9Kpi8xA6AyGB0tVJ/JcU4MczgCgoIsW gdYgUl9ge63CiHqj4Mzgpns= =1ZDV -----END PGP SIGNATURE----- From sybrenUSE at YOURthirdtower.com.imagination Mon May 8 08:16:42 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 8 May 2006 14:16:42 +0200 Subject: Logging vs printing References: <4c6o1sF14hhjuU1@individual.net> <1147035825.643595.139800@e56g2000cwe.googlegroups.com> <4c8qroF14g6feU1@individual.net> Message-ID: Leo Breebaart enlightened us with: > I think the main reason why I am not using it by default is because, > when all is said and done, it still comes easier to me to resort to > guarded print statements then to set up and use the logging > machinery. The logging "machinery" isn't that huge nor is it difficult to set up: ================================================== import logging logging.basicConfig() log = logging.getLogger('your.module.name') ================================================== and that's all there is to it. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From n.estner at gmx.de Wed May 10 09:05:38 2006 From: n.estner at gmx.de (nikie) Date: 10 May 2006 06:05:38 -0700 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <1147194852.528046.91560@y43g2000cwc.googlegroups.com> Message-ID: <1147266338.952060.210140@y43g2000cwc.googlegroups.com> Kaz Kylheku wrote: > Kaz Kylheku wrote: > > But suppose that the expression and the multi-line lambda body are > > reordered? That is to say, the expression is written normally, and the > > mlambda expressions in it serve as /markers/ indicating that body > > material follows. This results in the most Python-like solution. > > Unfortunately, while this idea has intuitive appeal, It does? Didn't seem so in the responses you got so far, did it... ;-) SCNR > it leaves some > problems to solve; namely, lambdas that occur in expressions embedded > within statement syntax which has body material of its own. For > instance > > # lambda defined and immediately called here > if lambda(x)(4) < 0: > print "a" > elif y = 4: > print "b" > else: > print "foo" > > Where to stick the lambda body? It's not hard to come up with > straightforward answers, except that they are not particularly > appealing. One rule might be that the lambda bodies have to be placed > immediately after the statement body material, set off by the lambda: > thing. In the case of if/elif/else, they have to be placed behind the > closest suite that follows the expression in the syntax of the > statement: > > if lambda(x)(4) < 0: > print "a" > lambda: > return x + 1 > elif y = 4: > print "b" > else: > print "foo" > > The overall rule is simple and uniform: each suite can have lambda: > clauses. These have to match lambda() occurences in the expression (or > expression list) immediately to the left in the same grammar > production. Sorry to tell you this, but I think that kind of thing is exactly what the BDFL had in mind when he talked about "Rube-Goldberg-Devices" in Python... From martin at v.loewis.de Wed May 17 01:03:04 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 17 May 2006 07:03:04 +0200 Subject: Time to bundle PythonWin In-Reply-To: References: <4464F4B9.8080603@v.loewis.de> Message-ID: <446AAE88.3060208@v.loewis.de> Dave Benjamin wrote: > Sure. I wasn't proposing that this be done behind Mark's back. I wasn't > even proposing a fork; rather, just two installers bundled into one. The > user, upon running the .msi file, would simply be asked if they'd like > PythonWin also. PythonWin could be automatically combined into the > installer by downloading the latest version from SourceForge, perhaps. That is technologically challenging. Contributions are welcome. Regards, Martin From OlafMeding at gmail.com Tue May 9 10:35:35 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 9 May 2006 07:35:35 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1147185335.762830.180260@j73g2000cwa.googlegroups.com> Dave send me the below as an email. Olaf Hi Olaf, I'm running your test for you - it's been going for about an hour now and is continuing to generate output[1]. c:\>py Python 2.4.3 (#69, Mar 29 2006, 17:35:34) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> winmsd says: OS Name Microsoft Windows XP Professional Version 5.1.2600 Service Pack 1 Build 2600 Processor x86 Family 15 Model 2 Stepping 9 GenuineIntel ~2992 Mhz Processor x86 Family 15 Model 2 Stepping 9 GenuineIntel ~2992 Mhz (it's a hyperthreaded P4 - not 2 true CPUs - so it should be similar to your setup) -Dave [1] Here's the output (line breaks added by my email program): c:\Temp>testsleep.py thread 1 started, sleep time 0.010 thread 2 started, sleep time 0.003 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 From onurb at xiludom.gro Fri May 12 07:59:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 13:59:04 +0200 Subject: NEWBIE: Tokenize command output In-Reply-To: References: Message-ID: <446478eb$0$287$626a54ce@news.free.fr> Tim Chase wrote: (snip) > starLines = [line for line in p.readlines() if line.startswith("*")] files are iterators, so no need to use readlines() (unless it's an old Python version of course): starLines = [line for line in p if line.startswith("*")] > or you may optionally want to prune of the "\n" characters in the process: > > starLines = [line[:-1] for line in p.readlines() if line.startswith("*")] *please* use str.rstrip() for this: starLines = [line.rstrip() for line in p if line.startswith("*")] -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From richie at entrian.com Tue May 9 09:48:09 2006 From: richie at entrian.com (Richie Hindle) Date: Tue, 09 May 2006 14:48:09 +0100 Subject: ascii to latin1 In-Reply-To: <1147180014.685659.325830@i39g2000cwa.googlegroups.com> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <4460831e$0$15794$14726298@news.sunsite.dk> <1147180014.685659.325830@i39g2000cwa.googlegroups.com> Message-ID: <4t51621qcearu7dsnmprqc1kh7skfkthmc@4ax.com> [Serge] > I have to admit that using > normalize is a far from perfect way to implement search. The most > advanced algorithm is published by Unicode guys: > If you read it you'll understand > it's not so easy. I only have to look at the length of the document to understand it's not so easy. 8-) I'll take your two-line normalization function any day. > IMHO It is perfectly acceptable to declare you don't interpret those > symbols. After all they are called *compatibility* code points. I > tried "a quater" symbol: Google and MSN don't interpret it. Yahoo > doesn't support it at all. [...] > if you have character "digit two" followed by "superscript > digit two"; they look like 2 power 2, but NFKD will convert them into > 22 (twenty two), which is wrong. So if you want to use NFKD for search > your will have to preprocess your data, for example inserting space > between the twos. I'm not sure it's obvious that it's wrong. How might a user enter "2" into a search box? They might enter a genuine "" in which case you're fine, or they might enter "2^2" in which case it depends how you deal with punctuation. They probably won't enter "2 2". It's certainly not wrong in the case of ligatures like LATIN SMALL LIGATURE FI - it's quite likely that the user will search for "fish" rather than finding and (somehow) typing the ligature. Some superscripts are similar - I imagine there's a code point for the "superscript st" in "1st" (though I can't find it offhand) and you'd definitely want to convert that to "st". NFKD normalization doesn't convert VULGAR FRACTION ONE QUARTER into "1/4" - I wonder whether there's some way to do that? > After all they are called *compatibility* code points. Yes, compatible with what the user types. 8-) -- Richie Hindle richie at entrian.com From roy at panix.com Wed May 24 20:05:21 2006 From: roy at panix.com (Roy Smith) Date: Wed, 24 May 2006 20:05:21 -0400 Subject: Python keywords vs. English grammar References: <4474d559$1_4@news.bluewin.ch> Message-ID: In article <4474d559$1_4 at news.bluewin.ch>, Boris Borcic wrote: > Roy Smith wrote: > > and all three keywords are verbs, so when you describe the code, you can > > use the same English words as in the program source, "You try to execute > > some code, but it throws a foo, which is caught by the handler". > > Not convincing at all I wasn't trying to convince anybody of anything. Just making an observation. From onurb at xiludom.gro Thu May 18 10:59:48 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 16:59:48 +0200 Subject: Strange error In-Reply-To: <1147963014.880378.44270@i39g2000cwa.googlegroups.com> References: <1147962206.900840.19130@38g2000cwa.googlegroups.com> <1147963014.880378.44270@i39g2000cwa.googlegroups.com> Message-ID: <446c8c4c$0$14894$626a54ce@news.free.fr> WSobczuk at gmail.com wrote: > Evaluation of default values seems to have nothing to do with the case > I described. It does. Please *read* the faq: http://pyfaq.infogami.com/why-are-default-values-shared-between-objects > The default values are both tags = {}, and still inside mysearch() I > sometimes get some value from previous call inside tags, when the tags > keyword argument is not specified. def wtf(foo, args=[]): args.append(foo) print args wtf('???') wtf('???') wtf('???') You didn't post the actual code for mysearch(), but chances are your code is modifying it !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From johnjsal at NOSPAMgmail.com Fri May 19 16:44:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 20:44:57 GMT Subject: altering an object as you iterate over it? In-Reply-To: References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> Message-ID: Paul McGuire wrote: >>> answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!! >> Doh! I see that now! :) >> > > Sorry about the ALL CAPS... I think I got a little rant-ish in that last > post, didn't mean to shout. :) > > Thanks for being a good sport, Heh heh, actually it was the all caps that kept making me read it over and over until I really knew what you were saying! :) From pecoraREMOVE at THISanvil.nrl.navy.mil Thu May 25 11:00:33 2006 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Thu, 25 May 2006 11:00:33 -0400 Subject: Bind an instance of a base to a subclass - can this be done? References: <4djshnF1asdovU1@uni-berlin.de> <4dkf5aF1amcjrU1@uni-berlin.de> Message-ID: I came up with this solution for subclassing the file object and making some easy I/O functions (much thanks to Maric Michaud for pointing me in the right direction). My goal was to make I/O of variables easy and in a form that I could easily visually examine the file (which I often need to do). The code also keeps it very clear as to what is being read in or out in a single function call. The class (inherited from file) in file ezfile.py: # ==== File subclass from file for EZ I/O ======================= class ezfile(file): # ---- Write items to file ------------------ # converts items list to string first using repr fcn. def printline(_, ls): sls=repr(ls) _.writelines(sls) # ---- Scan line from file & return items -------------------- # converts scanned string to list first using eval fcn. def scanline(_,): sls=_.readline() return eval(sls) An example in a Python session: >>> from ezfile import * # Define some variables >>> x=2.334 >>> i= 7 >>> str='Some stuff here' # Open a file and output the variables to it >>> ff=ezfile('junk','w') >>> ff.printline([x,i,str]) >>> ff.close() # Open the same file and read the values back in to other variables >>> f2=ezfile('junk','r') >>> y,j,thestr=f2.scanline() >>> print y,j,thestr 2.334 7 Some stuff here >>> f2.close() >>> The file content looks like this: [2.3340000000000001, 7, 'Some stuff here'] easy to see what is saved to the file. It works! Thanks, again. Comments welcome. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From __peter__ at web.de Wed May 17 05:38:08 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 17 May 2006 11:38:08 +0200 Subject: simultaneous reading and writing a textfile References: Message-ID: Mark Wilkinson wrote: > Why this: > >> lines = iter(infile.readline, "") >> # copy one line at a time >> for line in lines: > > Rather than this? > >> for line in infile: file.next() uses an internal cache. The data in that cache would be lost when the rest of the file is copied using file.read() with for block in iter(lambda: infile.read(BLOCKSIZE), ""): ????outfile.write(block) Demonstration: >>> open("tmp.txt", "w").write("alpha\nbeta\ngamma\n") >>> infile = open("tmp.txt") >>> infile.next() 'alpha\n' >>> infile.read() '' # where is 'beta\ngamma\n'? I admit I didn't profile whether the suggested approach is an overall win over line-wise copying of the whole file or manually keeping track of the position in the file followed by a seek(). Peter From tdelaney at avaya.com Tue May 30 22:48:48 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 31 May 2006 12:48:48 +1000 Subject: genexp performance problem? Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E735@au3010avexu1.global.avaya.com> Kent Johnson wrote: > Reusing the generator doesn't give a correct answer; after the first > sum() the generator is exhausted: Duh - good point. I forgot it was returning a generator object, not generator function. Tim Delaney From sxn02 at yahoo.com Fri May 12 14:03:58 2006 From: sxn02 at yahoo.com (Sori Schwimmer) Date: Fri, 12 May 2006 11:03:58 -0700 (PDT) Subject: Wrong args when issuing a SIGUSR1 signal Message-ID: <20060512180358.63973.qmail@web32912.mail.mud.yahoo.com> Hi All, Say I launch a shell under KDE and start typing: $ python Python 2.4.2 (#10, Feb 16 2006, 17:44:37) [GCC 3.3.5-20050130 (Gentoo 3.3.5.20050130-r1, ssp-3.3.5.20050130-1, pie-8.7.7. on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def fn(a=0,b=0): ... print 'Arguments:',a,b ... >>> from signal import * >>> signal(SIGUSR1,fn) Now, suppose I'm launching a second shell, and typing: $ ps ax ... (cut for brevity) ... 5780 pts/2 S+ 0:00 python 5781 pts/1 R+ 0:00 ps ax $ python Python 2.4.2 (#10, Feb 16 2006, 17:44:37) [GCC 3.3.5-20050130 (Gentoo 3.3.5.20050130-r1, ssp-3.3.5.20050130-1, pie-8.7.7. on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from signal import * >>> import os >>> os.kill(5780,SIGUSR1) >>> Now, back in the first shell, after pressing once, I get: Arguments: 10 Obviously, I put the two args after experimenting without them, and receiving an error: TypeError: fn() takes no arguments (2 given) What is going on here? How should I handle this? Thanks, Sorin Schwimmer __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From johnjsal at NOSPAMgmail.com Fri May 12 21:00:49 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 12 May 2006 21:00:49 -0400 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <4465079d$0$11703$c3e8da3@news.astraweb.com> References: <4465079d$0$11703$c3e8da3@news.astraweb.com> Message-ID: <446530ec$0$11696$c3e8da3@news.astraweb.com> John Salerno wrote: > Traceback (most recent call last): > File "C:\Python24\myscripts\db_test.py", line 6, in -toplevel- > db='bbdatabank') > File "C:\Python24\lib\site-packages\MySQLdb\__init__.py", line 66, in > Connect > return Connection(*args, **kwargs) > File "C:\Python24\lib\site-packages\MySQLdb\connections.py", line > 134, in __init__ > super(Connection, self).__init__(*args, **kwargs2) > OperationalError: (2003, "Can't connect to MySQL server on 'localhost' > (10061)") Latest development: I turned off my firewall and it worked. :) From jaco at hitweb.co.za Mon May 22 03:22:00 2006 From: jaco at hitweb.co.za (Jaco Smuts) Date: Mon, 22 May 2006 09:22:00 +0200 Subject: multithreading - managing transactions and sequence of processing Message-ID: <44716698.60209@hitweb.co.za> Hello there question: I'm looking for information / patterns / recipe's for implementing a multi threaded program (multiple producers / consumers) that will manage transactions and maintain sequence across the different threads. background: I'm busy writing an adapter taking messages from ibm websphere mq using pymqi and inserting these messages into a database (after some processing, the messages come in as xml). If I comment out the database .execute bit of the code, i process hundreds of messages per second, the database slows the whole process down to around 60 - 100 messages per second. I'm hoping to speed this up some by having 2 threads reading the messages from mq, and another populating the database - at least then the database bit will never have to wait for me to fetch another message. (i'm thinking of later adding a second thread for the databse as well). The challenge is that these messages need to be processed in exact sequence and transactionally. (ie. the thread that fetched a message will have to wait for confirmation that the message has successfully been inserted into the database before committing the transaction, in mq terms the message will only really be deleted then.) I've started implementing a kind of state machine using dictionary's to facilitate this, but I'm now concerned that - there is a better way - i might get bitten with dictionary processing updating / setting of values not necessarily being thread safe. I've looked at this recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/302997 as a possible replacement for dictionary's but I'm not even sure if I'm using it correctly. thank you jaco From mramos at montevideo.com.uy Mon May 15 10:07:32 2006 From: mramos at montevideo.com.uy (Marcelo Ramos) Date: Mon, 15 May 2006 11:07:32 -0300 Subject: Sending mail with attachment... In-Reply-To: <1147508571.532690.292650@v46g2000cwv.googlegroups.com> References: <1147508571.532690.292650@v46g2000cwv.googlegroups.com> Message-ID: <44688B24.5070706@montevideo.com.uy> Merrigan escribi?: > Hi, > > I have now eventually finished my newbie-backup script and I'm very > proud of the way it functions... > > Anyways, I am looking for an easy way to use smtplib to send an email > with the output log of the script to multiple accounts. I need to use > it with a smtp server, and cannot pipe it directly to sendmail. > > I have tried about 50 different ways that I have googled for in the > last 6 hours, but none of them work, I keep on getting errors. > > The script runs on a Linux system. > > Thanks for any help. > > I have a python script in production doing what you want using smtplib and it works perfectly. Send us your code and the errors you are getting. Regards. -- Marcelo Ramos Fedora Core 5 | 2.6.16 Socio UYLUG Nro 125 From mackstevenson at hotmail.com Wed May 17 00:36:30 2006 From: mackstevenson at hotmail.com (MackS) Date: 16 May 2006 21:36:30 -0700 Subject: assignment in a for loop Message-ID: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> Hello everyone Consider the following >>> l = [1,2] >>> for i in l: ... i = i + 1 ... >>> l [1, 2] I understand (I think!) that this is due to the fact that in Python what looks like "assignment" really is binding a name to an object. The result is that inside the loop I am creating an object with value (i+1) and then "pointing" the name i at it. Therefore, the object to which i previously pointed (an element of list l) remains unchanged. Two brief questions: 1) Is what I wrote above (minimally) correct? 2) Independently of the answer to 1, is there a way for me to assign to elements of a list inside a loop and without resorting to C-style ugliness of for i in range(len(l)) l[i] = l[i] + 1 ? (Note: not using a list comprehension.) Thanks in advance Mack From seannakasone at yahoo.com Thu May 11 20:16:38 2006 From: seannakasone at yahoo.com (seannakasone at yahoo.com) Date: 11 May 2006 17:16:38 -0700 Subject: glob() that traverses a folder tree In-Reply-To: <4463983a$1_1@newspeer2.tds.net> References: <1147308393.712592.233200@j73g2000cwa.googlegroups.com> <1147324439.841992.132710@q12g2000cwa.googlegroups.com> <4463983a$1_1@newspeer2.tds.net> Message-ID: <1147392998.832390.74690@v46g2000cwv.googlegroups.com> awesome. thanks. From godoy at ieee.org Mon May 8 08:48:41 2006 From: godoy at ieee.org (Jorge Godoy) Date: Mon, 08 May 2006 09:48:41 -0300 Subject: Designing Plug-in Systems in Python References: <1146893983.268034.206080@e56g2000cwe.googlegroups.com> Message-ID: <1216282.hxAPsKr42P@jupiter.g2ctech> mystilleef wrote: > > Are there any good tutorials on how to design good plug-in > systems with Python, or any language? What are the best > practices for designing plug-in systems in Python? How would > you go about designing one? What are common pitfalls in > designing one? Any pointers, suggestions, resources and > advice is welcome. I am liking to use setuptools and its entry points. With this, your program can check for a specific thing and load all modules that provides something like "myapp.plugins". Take a look at it. -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From john at castleamber.com Fri May 19 17:09:35 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 21:09:35 GMT Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> Message-ID: "akameswaran at gmail.com" wrote: > John Bokma wrote: >> "akameswaran at gmail.com" wrote: >> >> > But if a 1 person, using 1 language, with the same set of tools >> > withing a 3 month period implements the same algo without bugs - >> > I'll bet you the shorter one was theone written second. >> >> You might lose that bet very often. I see often that additional >> checks are added to algorithms to handle special cases overlooked, or >> documentation added because a co-worker had problems with the >> notation. > > I am not the one generalizing my statement. Adding the things above, > does not count as implementing the same thing. It would implementing > a new thing. And what you describe could be just be more bloat - not > indicating quality. Yes, like the shorter version might be overlooking many real world situations and is naive code. As for generalization, if you bet that the shorter one is later written, that's to me a generalization. I agree that there is a change that after reexamining the code, and algorithm can be written shorter, but I have also seen algorithms refactored for better readability. > Two points here. I have since the beginning stating a HYPOTHESIS - a > theory. One which my experince leads me think MIGHT be true. Enough to bet on it ;-) >> Yup, and this is exactly what frightens me the whole time in this >> thread. People looking for quality rules based on line count. It's >> wrong. > > Please note my original hypothesis was maintainability - not quality! Aren't those closely related? > important important distinction - and one I may have muddles myself as > I got drawn into the conversation. > And what frightens me are people who are so dogmatically convinced > becasue of their long 10 years of experience - that they know exactly > what does and doesn't matter, and have no intellectual curiosity > anymore. There are no objective tests for maintainability that I am > aware of. Because it depends a lot on the skill level of the maintainer. By just counting lines and characters you can't measure quality IMO. It's a naive way of measuring and it reminds me of the early days of search engines. And if you mistake understanding that it's not a good way to measure things as having no intellectual curiosity, you're again mistaken. -- 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 max at alcyone.com Sun May 7 03:42:01 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 May 2006 00:42:01 -0700 Subject: python rounding problem. In-Reply-To: References: Message-ID: <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> chun ping wang wrote: > Hey i have a stupid question. > > How do i get python to print the result in only three decimal place... > > Example>>> round (2.995423333545555, 3) > 2.9950000000000001 > > but i want to get rid of all trailing 0's..how would i do that? Floating point arithmetic is inherently imprecise. This is not a Python problem. If you want to print it to only three digits, then use something like:: >>> '%.3f' % 2.995423333545555 '2.995' -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Whoever contends with the great sheds his own blood. -- Sa'di From mivabe at nospam.invalid Tue May 16 06:32:43 2006 From: mivabe at nospam.invalid (Mivabe) Date: Tue, 16 May 2006 12:32:43 +0200 Subject: Python script windows servcie Message-ID: I'm using a Python script om my Wildfire XMPP server to connect to external transports (for instantce MSN) I configured the script as a windows service with 'srvany' and 'instrv" and everything seems te work fine. The service starts with the system, but as soon as an local useraccount (remote desktop) logs off on the server the script vanishes. Google helped me discovering that it has something to do something with 'CTRL_LOGOFF_EVENT'. I know what it means but i don't know how to solve it. Is that something i have to configure in the script? I'n totally new to Python so maybe someone can point me to the right direction? :D Regards, Mivabe -- No line here today .... Posted by news://news.nb.nu From nobody at 127.0.0.1 Wed May 17 19:58:44 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 23:58:44 GMT Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <_2Jag.88816$dW3.57801@newssvr21.news.prodigy.com> Message-ID: Terry Hancock wrote: > Now, of course, the data I provide is nasty, mean, poorly-formatted > data, abhorable by space-zealots and tab-libertines alike (;-)), but the > point is, unless you have set up your editor to syntax color spaces > and tabs differently, you won't see the difference in the original > editor. Sure, mixed tabs and spaces were not part of my use case. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From bencvt at gmail.com Wed May 10 22:47:45 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 10 May 2006 19:47:45 -0700 Subject: reusing parts of a string in RE matches? References: <1147306546.383277.11820@j33g2000cwa.googlegroups.com> <1147313413.738430.121890@g10g2000cwb.googlegroups.com> Message-ID: <1147315665.449631.136650@y43g2000cwc.googlegroups.com> Murali wrote: > > Yes, and no extra for loops are needed! You can define groups inside > > the lookahead assertion: > > > > >>> import re > > >>> re.findall(r'(?=(aba))', 'abababababababab') > > ['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba'] > > Wonderful and this works with any regexp, so > > import re > > def all_occurences(pat,str): > return re.findall(r'(?=(%s))'%pat,str) > > all_occurences("a.a","abacadabcda") returns ["aba","aca","ada"] as > required. Careful. That won't work as expected for *all* regexps. Example: >>> import re >>> re.findall(r'(?=(a.*a))', 'abaca') ['abaca', 'aca'] Note that this does *not* find 'aba'. You might think that making it non-greedy might help, but: >>> re.findall(r'(?=(a.*?a))', 'abaca') ['aba', 'aca'] Nope, now it's not finding 'abaca'. This is by design, though. From http://www.regular-expressions.info/lookaround.html (a good read, by the way): """As soon as the lookaround condition is satisfied, the regex engine forgets about everything inside the lookaround. It will not backtrack inside the lookaround to try different permutations.""" Moral of the story: keep lookahead assertions simple whenever possible. :-) --Ben From onurb at xiludom.gro Fri May 12 12:23:52 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 18:23:52 +0200 Subject: NEWBIE: Tokenize command output In-Reply-To: References: <44648ed3$0$12812$636a55ce@news.free.fr> Message-ID: <4464b6fb$0$6828$636a55ce@news.free.fr> Duncan Booth wrote: > bruno at modulix wrote: > > >>>Otherwise, just to be informed, what advantage does rstrip() have over >>>[:-1] (if the two cases are considered uneventfully the same)? >> >>1/ if your line doesn't end with a newline, line[:-1] will still remove >>the last caracter. >> > > In particular, if the last line of the file doesn't end with a newline then > the last line you read won't have a newline to be stripped. Thanks - I knew there was a corner case for files, but couldn't remember it exactly. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From pmartin at snakecard.com Thu May 11 08:24:34 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 11 May 2006 07:24:34 -0500 Subject: Python editor recommendation. References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1147263448.737381.198050@j73g2000cwa.googlegroups.com> Message-ID: <72G8g.9552$B42.2576@dukeread05> Looking at their flash demo made me want to try it, but after all dependencies installed, I get "Fatal Python error: can't initialise module gtksourceview Aborted (core dumped)" Is it stable ? Philippe mystilleef wrote: > The powerful no-nonsense, no-frills, no-hassle, no-fuzz editor, > Scribes. Supports everything you'd want in an editor, it's nimble, fast > and agile, and it has virtually no learning curve. > > http://scribes.sourceforge.net/ > > http://scribes.sourceforge.net/snippets.htm (Flash Demo) > > http://www.minds.nuim.ie/~dez/images/blog/scribes.html (GIF Demo) From onurb at xiludom.gro Fri May 19 10:37:37 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 16:37:37 +0200 Subject: open file with whitespaces In-Reply-To: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> References: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> Message-ID: <446dd899$0$8108$626a54ce@news.free.fr> mardif wrote: > Hi guys. > I've a very big big big problem: I think a lot of people in the world would not find it so big wrt/ their own situation... > I've in my windows computer a file named cicciobello.html, located in > c:\documents and settings\username\desktop\cicciobello.html. > > Now, I MUST open this file with os.spawn(os.P_WAIT ...., because I must > wait the user cancel the explorer window, ok? > And so, I write: > > import os > os.spawnl(os.P_WAIT, "c:\programmi\internet explorer\iexplorer.exe", > "c:\documents and settings\username\desktop\cicciobello.html") take care of the meaning of the antislash in strings... What do you thing "c:\toto" or "c:\nothing" will expand to ?-) import os.path help(os.path) Or at least, and IIRC, "c:/something/" should work. > the python process don't fail, but explorer don't visualize correctly > the file opened: i receive an "not found" error message. > > I've found that the whitespaces in file path are the problem. > If you see to explorer address bar, you will find the address > completely wrong... Not using Windows, I won't find anything. So what's the result ?-) Anyway, you may find urllib.urlencode useful for, well, encoding urls... HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bignose+hates-spam at benfinney.id.au Wed May 17 00:47:45 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 14:47:45 +1000 Subject: A Unicode problem -HELP References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <1147839615.973950.54770@y43g2000cwc.googlegroups.com> Message-ID: <87hd3pp89a.fsf@benfinney.id.au> "manstey" writes: > I'm a newbie at python, so I don't really understand how your answer > solves my unicode problem. Since your replies fail to give any context of the existing discussion, I could only go by the content of what you'd written in that message. I didn't see a problem with anything Unicode -- I saw three objects being added together, which you told us were function objects. That's the problem I pointed out. -- \ "When a well-packaged web of lies has been sold to the masses | `\ over generations, the truth will seem utterly preposterous and | _o__) its speaker a raving lunatic." -- Dresden James | Ben Finney From chris at kateandchris.net Sun May 7 10:04:47 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Sun, 7 May 2006 10:04:47 -0400 Subject: How to get client's IP address in the threaded case of SimpleXMLRPCServer? In-Reply-To: <1146862977.26323.146.camel@bombe> References: <1146862977.26323.146.camel@bombe> Message-ID: <20060507140447.GA20209@kateandchris.net> On Fri, May 05, 2006 at 05:02:57PM -0400, Eirikur Hallgrimsson wrote: > Okay, I've banged my head against this for about three days on and off. > > The client's IP is passed to my handler in the non-threaded case. > > It's not in the threaded case, which is actually rather different with a > couple of mixin classes mixing things up. I'm not confused, it's not > passed. > > I can't figure out how to get the client IP address at all from inside > my program. I can reach the socket object via my server object, but the > connection has been dropped before my handler is called. > > Any help or pointers would be appreciated. At this point I think I > would need to make changes in SimpleXMLRPCServer, or write a > replacement, which doesn't appeal to me. Your handler object should be getting set up with the client_address property. If not you need to show us some small subset of your app that demonstrates the issue. You can also inherit from SimpleXMLRPCServer and override verify_request, from BaseServer, if you want the option of blocking requests based on source address. -Chris From steve at holdenweb.com Wed May 17 04:45:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 May 2006 09:45:39 +0100 Subject: New blog In-Reply-To: <446441FD.6070507@hcl.in> References: <446441FD.6070507@hcl.in> Message-ID: vinu wrote: > Hi all, > http://pyadmin.blogspot.com/ > THis is my blog and This is related to python utilities for system and > network administration.plz comment on this > regards > Vineesh Kumar > The biggest problem seems to be the failure of indentation in the published code, which will make the code hard to read and impossible to copy-and-paste should anyone wish to use it. I run code through a colorizer program before publishing it (do a Google search for "colorize.py") in my blog - see for example: http://holdenweb.blogspot.com/2006/04/test-driven-development.html With space indentation rather than tabs, it seems to copy-and-paste quite nicely. The only other question I have is related to your use of strings instead of comments. Where you want them to be the docstring for a function or class or method you should have them at the first line of the body, as in: def func(x): """This is the first line of a multi-line docstring. The second and subsequent lines, if any, should appear indented like this.""" You also seem to use strings rather than comments at the end of statements. It appears these have been added after the fact, since they introduce syntax errors, as in sleeptime=15 """The time to wait for getting a response from the router""" It's always a good idea to take published code and verify that it will indeed compile and run as published. It's so easy to make mistakes in any of the transcription steps. (Having written a book helps in this respect, as there are myriad ways that publishers can screw up perfectly good code and you learn *all* about them int he authorship process). I'm sure that there are lots of net and sys admins who would love to be able to get their hands on these simple but helpful programs, so I'd encourage you to polish up your code and keep helping to make Python more popular. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From paul at wolfbone.ath.cx Sat May 27 01:26:35 2006 From: paul at wolfbone.ath.cx (P.L.Hayes) Date: Sat, 27 May 2006 06:26:35 +0100 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <447479A1.8050809@hotORgooMAIL.invalid> <3j0dg.27$u4.11@newsread1.news.pas.earthlink.net> <87slmwbhx5.fsf@wolfbone.ath.cx> Message-ID: <87irnsavhw.fsf@wolfbone.ath.cx> "Mike Schilling" writes: > "P.L.Hayes" wrote in message > news:87slmwbhx5.fsf at wolfbone.ath.cx... >> >> I agree. I have already written to Dreamhost and I hope more people >> will do so. I have found some of what has been posted here quite >> astonishing and the actions of certain people to be reprehensible: by >> far the most serious violation of netiquette I see here is this >> thoroughly wrong-headed campaign to try to censor Xah by appealing to >> his service provider. > > No one that I know of is trying to censor Xah. It's the form his postings > take that cause problems, not the content. > Having read through the threads in question, I cannot agree on either point. If form alone had been the problem, Xah's sporadic cross-posting to a handful of related newsgroups would presumably be the sole cause for complaint and yet that hardly seems to me to justify complaining to his ISP or to Google, let alone to his _web_hosting company. But that is not what has happened anyway: complainers have referred to Xah's posts as being off-topic - in some cases, "drivel" and "rants" - an opinion not shared by many more than half those who have posted to the threads. Fair enough - one is entitled to one's opinion - but it would be a mischaracterisation of what the complainers have actually written in their posts and have claimed to have written in their complaints to Dreamhost to say that form alone has been the issue. If you believe that what Xah has done was such a serious breach of netiquette and caused such serious problems that the appropriate course of action was to demand that his ISP and even his website host deny him access to the Internet, then having done so would not, strictly speaking, have been an attempt to censor Xah. But to maintain such a premise is, as others have opined, rather eccentric and overblown and if those who have written complaints about Xah to his ISP or to his website host have not deliberately meant to censor him, that is beside the point and no good reason to support their actions. I find it rather difficult anyway to believe that there is no deliberate attempt at censorship in the light of threads such as this one: http://groups.google.co.uk/group/comp.lang.perl.misc/browse_frm/thread/8fec378b74263f25/29458dc7da626a27?lnk=st&q=Bokma+Xah+Lee&rnum=3#29458dc7da626a27 "I rather account kill by ISP :-D." >> In my opinion it is that, not anything Xah has >> done, which comes any where near deserving any sort of termination of >> access to the Internet. > > Bringing facts to their attention? If Dreamhost has given him notice of > termination, it's for violating their policies, not because people have told > them "I don't like him". Exactly. Such underhand and manipulative behaviour is what makes this whole business so distasteful and why I find the actions of those who have tried to remedy perceived 'problems' in this way quite despicable. >> Since Xah's website is hosted by Dreamhost, >> the unwarranted censorship will be compounded by an act of gratuitous >> vandalism, potentially depriving people of useful resources: > > He's free to find another ISP and *not* violate their rules. Oh! Well that's okay then. Paul. From bencvt at gmail.com Thu May 25 22:54:16 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 25 May 2006 19:54:16 -0700 Subject: __getattr__ and functions that don't exist In-Reply-To: <447648ab$1@nntp.zianet.com> References: <44762cf8$1@nntp.zianet.com> <1148596303.833301.15190@g10g2000cwb.googlegroups.com> <447648ab$1@nntp.zianet.com> Message-ID: <1148612056.667641.181480@u72g2000cwu.googlegroups.com> Erik Johnson wrote: > Thanks for your reply, Nick. My first thought was "Ahhh, now I see. That's > slick!", but after playing with this a bit... > > >>> class Foo: > ... def __getattr__(self, attr): > ... def intercepted(*args): > ... print "%s%s" % (attr, args) > ... return intercepted > ... > >>> f = Foo() > >>> f > __repr__() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: __repr__ returned non-string (type NoneType) > > > my thought is "Oooooh... that is some nasty voodoo there!" Especially > if one wants to also preserve the basic functionality of __getattr__ so that > it still works to just get an attribute where no arguments were given. > > I was thinking it would be clean to maintain an interface where you > could call things like f.set_Spam('ham') and implement that as self.Spam = > 'ham' without actually having to define all the set_XXX methods for all the > different things I would want to set on my object (as opposed to just making > an attribute assignment), but I am starting to think that is probably an > idea I should just simply abandon. Well, you could tweak __getattr__ as follows: >>> class Foo: ... def __getattr__(self, attr): ... if attr.startswith('__'): ... raise AttributeError ... def intercepted(*args): ... print "%s%s" % (attr, args) ... return intercepted But abandoning the whole idea is probably a good idea. How is defining a magic set_XXX method cleaner than just setting the attribute? Python is not C++/Java/C#. Accessors and mutators for simple attributes are overkill. Keep it simple, you'll thank yourself for it later when maintaining your code. :-) > I guess I don't quite follow the error above though. Can you explain > exactly what happens with just the evaluation of f? Sure. (Note, this is greatly simplified, but still somewhat complex.) The Python interpreter does the following when you type in an expression: (1) evaluate the expression, store the result in temporary object (2) attempt to access the object's __repr__ method (3) if step 2 didn't raise an AttributeError, call the method, output the result, and we're done (4) if __getattr__ is defined for the object, call it with "__repr__" as the argument (5) if step 4 didn't raise an AttributeError, call the method, output the result, and we're done (6) repeat steps 2 through 5 for __str__ (7) as a last resort, output the default "" string In your case, the intepreter hit step 4. f.__getattr__("__repr__") returned the "intercepted" function, which was then called. However, the "interpreted" function returned None. The interpreter was expecting a string from __repr__, so it raised a TypeError. Clear as mud, right? Cutting out the __getattr__ trickery, here's a simplified scenario (gets to step 3 from above): >>> class Bar(object): ... def __repr__(self): ... return None ... >>> b = Bar() >>> b Traceback (most recent call last): File "", line 1, in ? TypeError: __repr__ returned non-string (type NoneType) Hope that helps! One other small thing... please avoid top posting. --Ben From herraotic at googlemail.com Wed May 24 11:19:46 2006 From: herraotic at googlemail.com (herraotic at googlemail.com) Date: 24 May 2006 08:19:46 -0700 Subject: Python Programming Books? In-Reply-To: References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> Message-ID: <1148483986.822220.287590@i39g2000cwa.googlegroups.com> I borrowed Learning Python 2nd edtion from a library once and it felt condensed with information and I didn't think I could start with it "yet" as I want a book made for a beginner programmer and I don't think Learning Python 2nd edtion is made for my audience. I want something that explains programming fundamentals and explains it in general while also showing the reason in practise and from reading some free PDF's of "Python Programming: An Introduction to Computer Science" I think it fit the bill perfectly, I would have it already but i'm only 15 and my dad is a bit weary of using his credit card online :-). From andrew.arobert at gmail.com Mon May 22 17:47:15 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 22 May 2006 17:47:15 -0400 Subject: Class probkem - getting msg that self not defined In-Reply-To: <44722a01$0$17368$636a55ce@news.free.fr> References: <12740frcoaju883@corp.supernews.com> <44722a01$0$17368$636a55ce@news.free.fr> Message-ID: <1274cbtiq2ukc36@corp.supernews.com> Hey Bruno, Although I have not tested it, this appears to be it exactly. Some confusion though. > import struct > > class TriggerMessage(object): > def __init__(self,data): > """ > Unpacks the passed binary data based on the > MQTCM2 format dictated in > the MQ Application Programming Reference > """ I am okay up to here :). After that, well.. What does the _ before the variables mean? Why are you defining _format and _data here? I would have thought it belongs in the decode section. I think it is very slick but I would like to try and understand your approach. Also, why assert in calculating the struct size? Very cool how you did this. > self._format = '4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' > self._data = data > > (self.version, > self.qname, > self.processname, > self.triggerdata, > self.appltype, > self.applid, > self.envdata, > self.userdata, > self.qmgr) = self._decode() > > def _decode(self): > assert len(self._data) == struct.calcsize(self._format) > return struct.unpack(self._format, self._data) > > # test code > # data = ??? > test=TriggerMessage(data) > var = test.qname From john at castleamber.com Fri May 26 16:57:28 2006 From: john at castleamber.com (John Bokma) Date: 26 May 2006 20:57:28 GMT Subject: OT: Quote ? [was: John Bokma harassment] References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <87ejyjv40w.fsf@rpi.edu> <4476efed$2$649$bed64819@news.gradwell.net> <7QJdg.17594$fb2.11320@newssvr27.news.prodigy.net> Message-ID: "Mike Schilling" wrote: > > "John Bokma" wrote in message > news:Xns97CF757E136D6castleamber at 130.133.1.4... >> "Chris Uppal" wrote: >> >>> [apologies to the whole flaming crowd for sending this to the whole >>> flaming crowd...] >>> >>> Geoffrey Summerhayes wrote: >>> >>>> After you kill Navarth, will it be nothing but gruff and deedle >>>> with a little wobbly to fill in the chinks? >>> >>> Where does that come from ? It sounds like a quote, and Navarth is >>> a Jack Vance name (and /what/ a character), but I don't remember the >>> rest of it occurring in Vance. >> >> Navarth is very present in "the palace of dreams" (Demon princes >> series) > > Nitpick: _The Palace of Love_ Aargh! The only excuse I can give for that huge mistake is that I am currently reading "In the net of dreams" :-( -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From paul at boddie.org.uk Sun May 21 19:19:37 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 21 May 2006 16:19:37 -0700 Subject: dynamic drawing in web page References: <1148245752.728480.238540@u72g2000cwu.googlegroups.com> Message-ID: <1148253577.595049.222370@y43g2000cwc.googlegroups.com> barbaros wrote: > > I need to put some dynamic drawings on my web page. More precisely, I > need to draw a number of geometric figures (circles, rectangles) which > evolve into a graphics windows according to some law (a little bit like > the solar system). I need also to have several fields aside the window, > where the visitor can change values for several significant parameters > (like the mass of each body). > > Could you please suggest a solution (preferably not involving hundreds > of lines of code) ? The computations should be performed on the client > machine. In the context of recent Flash-related discussions and the usage of open Web standards, I searched for 'animation SVG "solar system"' and discovered this example: http://www.svgelves.com/svg/L_chrisa_02.svg Sadly, it only works in Opera amongst the browsers I have. Konqueror displays the initial frame but doesn't animate the scene, although later versions of that browser might support animation. I have an old version of Firefox which doesn't support SVG at all. Paul From bdesth.quelquechose at free.quelquepart.fr Fri May 26 19:00:48 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 27 May 2006 01:00:48 +0200 Subject: sort a dictionary by keys in specific order In-Reply-To: References: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> Message-ID: <44775946$0$1747$626a54ce@news.free.fr> Tim Chase a ?crit : (snip) > >> list = [key2, key3, key1] > > 1) it's bad practice to shadow the list() command... s/command/type/ > funky stuff can happen. indeed, if you shadow it with a non-compatible object !-) From DustanGroups at gmail.com Fri May 19 17:49:16 2006 From: DustanGroups at gmail.com (Dustan) Date: 19 May 2006 14:49:16 -0700 Subject: Which is More Efficient? In-Reply-To: References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1148036087.843911.307990@u72g2000cwu.googlegroups.com> Message-ID: <1148075356.525042.253100@j33g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > > The task manager says "CPU Usage: 100%" when the program is running, > > and only when the program is running. > > > > Efficiency is a measure of 2 things: CPU usage and time. If you measure > > just time, you're not necessarily getting the efficiency. > > are you for real? And what exactly is that supposed to mean? > > From yairchu at gmail.com Wed May 10 04:02:44 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 10 May 2006 01:02:44 -0700 Subject: Multi-line lambda proposal. In-Reply-To: <445fe772$1@nntp0.pdx.net> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> Message-ID: <1147248164.805219.295970@y43g2000cwc.googlegroups.com> multi-line lambdas, had it been added to python a long time ago, would had reduced a lot of complexity in the language. for example - with multi-line lambdas - decorators are unneccesary. just give the multi-line lambda as an argument to a function - no need for special syntax.. the alternative decorators would also be simpler. currently when you want to create a "decorator-that-accepts-additional- arguments" you gotta make a funtion that gets those additional-arguments and returns a function that will be the decorator. From fabiofz at gmail.com Wed May 24 16:01:03 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 24 May 2006 17:01:03 -0300 Subject: Pydev 1.0.8 released Message-ID: Hi All, Pydev and Pydev Extensions 1.0.8 have been released Check http://www.fabioz.com/pydev for details on Pydev Extensions and http://pydev.sf.net for details on Pydev This is a 'single-bugfix' release because of a major bug that could cause Pydev to hang when making a new line under certain condations. 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 vbgunz at gmail.com Sun May 7 14:19:17 2006 From: vbgunz at gmail.com (vbgunz) Date: 7 May 2006 11:19:17 -0700 Subject: Python CHM Doc Contains Broken Links on Linux in xCHM. Message-ID: <1147025957.253391.125240@i40g2000cwc.googlegroups.com> Hello! this is the main error: http://img406.imageshack.us/img406/5218/screenshotxchmerror1ae.png navigation link images broken here: http://img406.imageshack.us/img406/2822/screenshotxchmv12python24docum.png when I first open up the docs, the main page and Global Module Index links in the tree are unaccessible. They give me errors. While navigating a page like found at 2.3.7 (Set Types), the "See Also" link to the module 'sets' is broken also. Is this a problem with the chm docs themselves OR is it a problem with xCHM? The same chm works just fine on Windows whereas on Linux I am having problems. Anyone experiencing the same? is a fix coming? Thank you! From ivoras at __yahoo__.com_ Wed May 3 20:11:14 2006 From: ivoras at __yahoo__.com_ (Ivan Voras) Date: Thu, 04 May 2006 02:11:14 +0200 Subject: Fastest quoting Message-ID: What is the fastest way (execution speed) to backslash-escape characters from a specific set? Specifically: \r, \n and \0? (i.e. I need "some\r\nstring\0" to become "some\\r\\nstring\\0") From rschroev_nospam_ml at fastmail.fm Mon May 1 06:57:33 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 01 May 2006 10:57:33 GMT Subject: ending a string with a backslash In-Reply-To: <44557f3f$0$5357$c3e8da3@news.astraweb.com> References: <445546c8$0$13341$c3e8da3@news.astraweb.com> <44557f3f$0$5357$c3e8da3@news.astraweb.com> Message-ID: John Salerno schreef: > Edward Elliott wrote: >> John Salerno wrote: >>> Obviously the single backslash at the end of 'path' will cause a >>> problem, and escaping it with a backslash seems to fix this problem, but >>> how does escaping work when I already have it as a raw string? >> see the first two items here: >> http://www.ferg.org/projects/python_gotchas.html > > #2 was very helpful. But if I want to use forward slashes instead, can I > just replace the backslashes with them, or must I use the > os.path.normcase() function to do it? You can just replace them: all internal Windows functions accept forward slashed instead of backslashes in path names. I think this is also the right time to mention os.path.join. It takes any number of path components and joins them, taking care of placing path delimiters between them. That means you could have written your code as follows: path = os.path.join(r'C:\Documents and Settings\John Salerno\My Documents\My Webs\1and1\johnjsalerno.com', subdomain) It also handles the case where there is a trailing backslash: >>> os.path.join('foo', 'bar') 'foo\\bar' >>> os.path.join('foo\\', 'bar') 'foo\\bar' Greatly simplifies concatenating path components IMO. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From larry.bates at websafe.com Tue May 9 15:36:16 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 09 May 2006 14:36:16 -0500 Subject: Progress bar in web-based ftp? In-Reply-To: References: Message-ID: <17idnffXt_eDcv3ZRVn-sg@comcast.com> CatDude wrote: > I've got an application that prompts the user to select a file from his > local computer, checks the user's selection, then sends the file via >
enctype="multipart/form-data"> > > In the python code that receives the files I've got a section that does > the following: > > if not os.path.isfile(filePath): > file(filePath, 'wb').write(str(form[name].value)) > else: > print "File already exists - deleting" > os.unlink(filePath) > file(filePath, 'wb').write(str(form[name].value)) > > after error checking, etc. > > My question is whether anyone has ideas as to how I could implement a > progress bar. When I send a large file this way it can take a long time, > and I'd like to be able to reassure the user that something really is > happening. > > Turns out that this is more difficult than you might think. The problem is you must have the client communicate with the server in some way and have the server know what the progress is at any point. HTML POST action=upload doesn't give you anything to work with to provide such information to the client's browser (if it does I'm not aware of it anyway). It also would take something like JavaScript and XMLRPC on the client to make the round trip to get updated progress information. -Larry Bates From andrew.arobert at gmail.com Sat May 13 21:28:28 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sat, 13 May 2006 21:28:28 -0400 Subject: Question regarding checksuming of a file Message-ID: <126d1u4ke4itg7f@corp.supernews.com> Good evening, I need to generate checksums of a file, store the value in a variable, and pass it along for later comparison. The MD5 module would seem to do the trick but I'm sketchy on implementation. The nearest I can see would be import md5 m=md5.new() contents = open(self.file_name,"rb").read() check=md5.update(contents) However this does not appear to be actually returning the checksum. Does anyone have insight into where I am going wrong? Any help you can provide would be greatly appreciated. Thanks From exarkun at divmod.com Thu May 25 15:08:47 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Thu, 25 May 2006 15:08:47 -0400 Subject: Telnet linebreaks In-Reply-To: <28dc07920605250931w4d8dfa00p2e31dc00795b8876@mail.gmail.com> Message-ID: <20060525190847.28682.888156736.divmod.quotient.5263@ohm> >>On 5/24/06, Patrick M. Nielsen wrote: >> > >> > Hey guys. >> > >> > I have begun playing with the Simple MUD server example from the >> > Stackless website >> > ( http://www.stackless.com/Members/rmtew/code/mud.py ) >> > and it's all good so far, however, I've come to notice something that I >> > remember from back >> > in the days (some old mud code), but I don't remember what I did to fix >> > it. >> > >> > While the MUD reads lines from Telnet clients just fine, clients such as >> > Gmud are practically ignored, >> > probably because Gmud doesn't send Telnet-valid data ('\x08'?). \x08 is \b is backspace. Servers support this character so that clients that don't actually delete the previous input character when you hit backspace will work as the user expects. Gmud doesn't send it because Gmud has a GUI input area and actually deletes characters when you hit backspace. >> > >> > However, a MUD that is not accessible to one such client or others isn't >> > much good, so I'd appreciate >> > some help in pinpointing the problem. I don't think you've correctly identified the root cause of the problem. >> > >> > These are the code blocks that need modification (I believe) >> > >> > def read(self): # TELNET >> > ret = self.readChannel.receive() >> > if self.echo: >> > if ret == '\x08': >> > self.send(ret+" ") Here the server takes extra pains to actually erase the "deleted" character that the client sent. >> > self.send(ret) >> > return ret >> > >> > def readline(self): # TELNET >> > buf = self.readBuffer >> > >> > while True: >> > if buf.find('\r\n') > -1: # MUD clients that aren't using >> > the telnet protocol >> > i = buf.index('\r\n') # need to be able to do stuff. >> > ret = buf[:i+2] >> > self.readBuffer = buf[i+2:] >> > while '\x08' in ret: >> > i = ret.index('\x08') >> > if i == 0: >> > ret = ret[1:] >> > else: >> > ret = ret[:i-1]+ret[i+1:] >> > return ret And here it deletes it from the input which it is actually processing, so that a user who types "wield sq\bword" will wield their sword instead of being told they don't have a "sq\bword" to wield (which will probably be rendered as "sword" on their terminal, which would be pretty confusing). >> > >> > buf += self.read() >> > >> > I'm suspecting that Gmud doesn't send '\x08', since from looking at some >> > old DIKU code, >> > I see that the if '\n' || '\r' are there as well, but there is no check >> > for '\x08'. If this is indeed >> > the cause of my problem, how would I go about doing it? It sounds to me as though the cause of the problem lies elsewhere. Twisted includes a rather complete telnet implementation (as well as an SSH implementation and a VT102 implementation). You may want to take a look at it, either to use for your server, or at least to see the correct way to gather input from your clients. Jean-Paul From keith at cgcreator.com Tue May 30 10:24:14 2006 From: keith at cgcreator.com (Keith Lackey) Date: Wed, 31 May 2006 00:24:14 +1000 Subject: webbrowser problems Message-ID: <200605301424.k4UEOEhh014101@smtp1.adl2.internode.on.net> I'm having trouble trying to pass arguments to a file path url. ie c:/testPython/test.html?testArg=testValue import webbrowser webbrowser.open("c:/testPython/test.html") # Works webbrowser.open("c:/testPython/test.html?testArg=testValue") # Doesn't Work webbrowser.get() # Returns a WindowsDefault instance I looked into the webbrowser python command, and see that windows default just does a os.filestart(url) call. If I use the command prompt to try and mimic this it also errors out which is what I would expect. But if I run this from the command line. it seems to work fine: c:\Program Files\Internet Explorer\iexplore.exe c:/testPython/test.html?testArg=testValue I assume this is because the url is being passed as an argument to the iexplore.exe instead of trying to find a file call that url. I guess what I need to do is try and find the file path to the default browser so that I can build my own string to execute via command line. But I have no clue as to how I would go about getting that. and also I want to make sure its still going to be cross platform compatible. Any help? Ideas? Thanks Keith -------------- next part -------------- An HTML attachment was scrubbed... URL: From akameswaran at gmail.com Thu May 18 17:05:36 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 14:05:36 -0700 Subject: python vs perl lines of code In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> Message-ID: <1147986336.050431.51180@y43g2000cwc.googlegroups.com> I am trying to understand why Edwards post generated such a negative response. I am neither agreeing or disagreeing with his statement - because I don't think he is making one. He posted a data point, and asked others to post the samething. About the only thing he could say, is that for his coding style, Python appears to be more terse. He went out of his way to describe mitigating factors and didn't draw any general conclusions. It seems to me the discussion could actually be beneficial. If several different coders gave similar responses, ie code line/character count comparisons, we might be able to see if there is a trend of any sort - the more "anecdotes" given and we start to have trends - or maybe we don't. The UFO comparison is silly, UFO sightings being based on time and space coordinates are inherently unreviewable. Ed's code and his analysis methods can be repeated (didn't say they were repeated, just they can be). Perhaps some ppl who switched from python to perl could do something similar, reversing the skill bias Edward admitted too? If we wanted to pursue more study of the phenomenon we could choose some stylistic rules about perl and python for test code, etc to help normalize the data. Lastly, Ed - can you post the code? That may be putting your head in the lion's mouth so to speak and make the whole thread even worse - and your coding style will get shredded by perl advocates... ok nevermind don't post it.' Ok I'm going to end with a flamebait - but I would posit, ALL OTHER THINGS BEING EQUAL - that a smaller number of characters and lines in code is more maintainable than larger number of characters and lines in the code. From aleax at mac.com Tue May 9 02:15:54 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 8 May 2006 23:15:54 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> Message-ID: <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> M Jared Finder wrote: ... > Any time you want an anonymous function (or class, or type, or number) > it would be because that thing is sufficiently small and simple that the > best name for it is the code itself. In one game I worked on, there was That's not what I see happen in practice in the real world -- please check this thread for the guy who pointed me at some Lisp code of his to draw pictures, and how each anonymous function is code returned had a nice little comment (which would yield a perfectly suitable name, as I showed in a Python translation of one of them). In the real world, people don't choose anonymous functions only in these alleged cases where anonymous is best -- if anonymous functions are available, they're used in even more cases where naming would help (just as, again in the real world, plenty of "magic numbers" sully the code which SHOULD be named... but just don't GET named). BTW, in your case canPerformQueuedAction seems a good name to me (I'd probably eliminate the 'Action' part, since the _argument_ is an Action, but I'd need to see more context to suggest the best name). Alex From ptmcg at austin.rr._bogus_.com Mon May 22 20:41:17 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 23 May 2006 00:41:17 GMT Subject: global name not defined References: <1148336761.776348.260450@j33g2000cwa.googlegroups.com> <1148340731.742024.270290@j73g2000cwa.googlegroups.com> Message-ID: "NetKev" wrote in message news:1148340731.742024.270290 at j73g2000cwa.googlegroups.com... > You are probably right and I think I will do so but just for the sake > of my understanding of python...I noticed somthing. process_log takes > two arguments when called but it's definition has 3 and one of them is > "self". So I'm thinking if I modify my warn_Admin definition to > include "self" and then call it from process_log with > self.warn_Admin... it will work. This explains why I was getting the > "too many arguments" error. > Yes. When you invoke self.warn_Admin(x), it calls warn_Admin with 2 args, self and x. The reason I did not suggest this is becaus it looked like warn_Admin didn't really use anything inside self, so why make it a method? Looks like you are getting the method/function concepts straight. (I'm not trying to confuse you, but you could also make warn_Admin a staticmethod within the class, using the @staticmethod decorator. Static methods do not pass the self argument, so making warn_Admin into a static method would be another way to resolve this problem. But only do this if your class, whatever it is, has something inherently about it that wants its own warn_Admin method - otherwise, just make it a global function.) -- Paul From 63q2o4i02 at sneakemail.com Tue May 16 02:49:03 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 15 May 2006 23:49:03 -0700 Subject: Using python for a CAD program Message-ID: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Hi, I'm interested in using python to start writing a CAD program for electrical design. I just got done reading Steven Rubin's book, I've used "real" EDA tools, and I have an MSEE, so I know what I *want* at the end of this; I just have never taken on a programming task of this magnitude. I've seen that some are using python as a utility language for existing CAD environments, and I've also found some guy who's writing a 2d drafting tool with python, which is cool. I've been playing with python recently and so far have a SPICE parser half-written (it'll do production rules, but no syntax trees yet...) I'm wondering if the python experts can provide some opinion on python's efficiency/utility in the following areas, and perhaps where some things will need to be in C++ and/or pyrex: 1. Databases. I don't mean sql type database, but design databases, which contain all the components for any given design, including schematics, layout, simulation parameters, etc. I'm not concerned about python's ability to do fancy data structures, but I'm wondering how it'll go in terms of efficiency when things get really big. If the alternative is home-brewed C++ linked-lists, attributes, arrays, binary trees, memory management, etc., it looks like python's ability to do all this neatly without all the bugs waiting to happen if I did this myself are well worth the efficiency loss that may result from its uber-generality. 2. GUI. Yes, I know you can do guis with qt, gtk, tkinter, etc. I'm talking of fancy guis that do alpha blending, animations, nice shading/gradients, etc. in a quick, smooth, and slick way, such that moving a scroll bar or jiggling the mouse yields fast game-like response time, and which gives this program the feeling that you're actually in the 21st century... ie this is an *interactive* environment, and I f***king hate crass-hatching, so real colors is a must. Can this be portable between linux and windows? Is it possible to "do the whole thing" in opengl, even the 2d stuff? I guess I dont know enough about guis here. My fear is that my app will turn into x-hell if I try to do more than 8-bit colors in linux, with flashing background windows and complaints from the server about bit planes. Maybe I need to play with linux a bit more from the development side before commenting on this, since I get the feeling I'm working on old information here... 3. Computational stuff. I imagine the really heavy computing needs to be done in c++, especially if I'm stupid enough to write my own simulator, which my brain seems to want to do (I'm imagining a small homer simpson brain with a mind of its own telling me what to do...). But what about other things like rules and constraints about layout, routing, compaction, undo/redo, etc? These aren't really computationally expensive, I don't think, but do munge about quite a bit with the database. Is it likely I'll write something faster in C++? (answer: no). 4. Programmability. I imagine this is a slam-dunk, relatively speaking, to have a python interpreter as part-and-parcel of the design system. But how do I customize the command window to do custom things like adding special shortcuts (eg '?' brings up help, or help on commands a la Matlab), or making an API into the CAD program? I'm not sure conceptually how to merge an embedded python interpreter into the rest of the CAD program in an intelligent way, so some stuff is exposed, but not all, and which interacts dynamically with the graphical portion so that, for instance, context-sensitive help is available in the console window, or so you can access information about the currently selected object, or so you can do stuff from the command line that is based on your current graphical context. 5. Threads and parallelism. One of the things about this is that I'd like there to be some real-time simulator running so when you change the values of parts, the output changes, and I'd like to be able to take advantage of mulitple processors, or dual-core, or whatever. I've seen fake multi-threading in python (read about it, but I haven't done it), but that doesn't really use any extra cycles from a separate processor. So why am I thinking about this? I've used a few "real" CAD systems, and from using them, it's obvious the modus is to kludge shit together over 20 years and screw the user experience. So basically I'd like to take over the world with my nifty new python-based cad system because it's so beautiful and fun to use, and so flexible that my time to market for any given new idea is 5x shorter than the existing tools. Any comments on the above from people who've actually written stuff would be greatly appreciated! :) thanks ms From jstroud at ucla.edu Tue May 2 15:33:26 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 02 May 2006 12:33:26 -0700 Subject: Python & SSL Message-ID: Hello All, I have been trying to make an https client with python, but it seems that, to do this, one needs to have the socket module compiled with ssl. This is not the default. So I have a couple of questions. 1. Where do I specify to compile socket with ssl? I found no obvious option in configure or setup.py or several other files I checked. 2. Is there a way to do this without re-compiling all of python? Also, I have done numerous combinations of searches with ssl, https, & python as terms, but I haven't found a page outlining the steps to make a certificate and key that python understands. Has anyone been successful at this? Did you use openssl? I want to make sure I am doing this part correctly. Thanks in advance for any help. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From __peter__ at web.de Thu May 11 12:26:05 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 11 May 2006 18:26:05 +0200 Subject: find all index positions References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <1147363447.657331.224450@i40g2000cwc.googlegroups.com> Message-ID: alisonken1 wrote: > ========== > def getAllIndex(aString=None, aSub=None): > t=dict() > c=0 > ndx=0 > while True: > try: > ndx=aString.index(aSub, ndx) > t[c]=ndx > ndx += 1 > c += 1 > except ValueError: > break > return t > =========== > > This will return a dictionary of what was found; i.e., > >>>> getAllIndex('abcd 1234 efgh 1234 ijkl', '1234') > {0: 5, 1: 15} Consecutive integers starting at 0 as keys? Looks like you want a list instead of a dict. Peter From diffuser78 at gmail.com Mon May 8 21:15:02 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 8 May 2006 18:15:02 -0700 Subject: Memory leak in Python Message-ID: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> I have a python code which is running on a huge data set. After starting the program the computer becomes unstable and gets very diffucult to even open konsole to kill that process. What I am assuming is that I am running out of memory. What should I do to make sure that my code runs fine without becoming unstable. How should I address the memory leak problem if any ? I have a gig of RAM. Every help is appreciated. From felipe.lessa at gmail.com Tue May 16 16:34:39 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Tue, 16 May 2006 17:34:39 -0300 Subject: calling upper() on a string, not working? In-Reply-To: References: Message-ID: <1147811679.6220.11.camel@kenshin.CASA> Em Ter, 2006-05-16 ?s 20:25 +0000, John Salerno escreveu: > it doesn't seem to work. The full code is below if it helps to understand. Why doesn't it work? What does it do, what did you expect it to do? >>> ''.join(set('hi')) 'ih' >>> ''.join(set('HI')) 'IH' >>> ''.join(set('hiHI')) 'ihIH' >>> ''.join(set('hiHI'.upper())) 'IH' -- Felipe. From tdw at tdw.net Mon May 8 05:40:34 2006 From: tdw at tdw.net (Tim Williams) Date: Mon, 8 May 2006 10:40:34 +0100 Subject: data entry tool In-Reply-To: References: <445f038f@news.maxnet.co.nz> Message-ID: <9afea2ac0605080240p197c938cw6c9604e76e14b2f2@mail.gmail.com> On 08/05/06, Diez B. Roggisch wrote: > > Make it a webapp. That will guarantee to make it runnable on the list of > OSses you gave. Use Django/TurboGears/ZOPE for the application itself- > whichever suits you best. based on the comment: > I'm not a programmer and have only done a few little python > scripts that run from the command line. Using Karrigell as the webserver / framework may be preferrable. Its much simpler to learn and use, and as long as there aren't a *huge* number of users it will be up to the task. HTH :) From iainking at gmail.com Tue May 2 06:03:45 2006 From: iainking at gmail.com (Iain King) Date: 2 May 2006 03:03:45 -0700 Subject: returning none when it should be returning a list? In-Reply-To: <4455A4A1.7020807@lexicon.net> References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> <4455A4A1.7020807@lexicon.net> Message-ID: <1146564225.815477.137750@u72g2000cwu.googlegroups.com> John Machin wrote: > > # Doh! Looks like recursion not necessary. Google 'eliminate tail > recursion' :-) > I did, and found this: http://www.biglist.com/lists/dssslist/archives/199907/msg00389.html which explains that the Scheme compiler optimises (obvious) tail recursion into iterative code. I'm wondering if the python compiler does the same? Iain From fccoelho at gmail.com Sat May 13 19:03:16 2006 From: fccoelho at gmail.com (Flavio) Date: 13 May 2006 16:03:16 -0700 Subject: cx_freeze and matplotlib Message-ID: <1147561396.641012.139940@y43g2000cwc.googlegroups.com> I am trying to freeze an application which imports matplotlib. It all works fine on the machine where it was frozen. The executable runs without a glitch. But when I move the directory containing the frozen executable and other libs to a new machine, I get the following error: Traceback (most recent call last): File "/home/fccoelho/Downloads/cx_Freeze-3.0.2/initscripts/Console.py", line 26, in ? File "epigrass.py", line 5, in ? File "Epigrass/manager.py", line 7, in ? File "Epigrass/simobj.py", line 4, in ? File "/usr/lib/python2.4/site-packages/matplotlib/__init__.py", line 457, in ? try: return float(s) File "/usr/lib/python2.4/site-packages/matplotlib/__init__.py", line 245, in wrapper if level not in self.levels: File "/usr/lib/python2.4/site-packages/matplotlib/__init__.py", line 319, in _get_data_path Return the string representing the configuration dir. If s is the RuntimeError: Could not find the matplotlib data files Matplotlib can't find its data files. Apparently this problem comes up in py2exe as well and it is handled like this: from distutils.core import setup import glob import py2exe data = glob.glob(r'C:\Python23\share\matplotlib\*') data.append(r'C:\Python23\share\matplotlib\matplotlibrc') setup( console = ["simple_plot.py"], data_files = [("matplotlibdata", data)], ) This is the only thing I need to solve before I can distribute my frozen package, so please help me here. There must be a way since the frozen works in the original machine but not on the new Which also has the same version of matplotib installed. From raathm at gmail.com Thu May 4 08:29:13 2006 From: raathm at gmail.com (Mike) Date: 4 May 2006 05:29:13 -0700 Subject: HTMLParseError: EOF in middle of construct error Message-ID: <1146745753.568267.166130@v46g2000cwv.googlegroups.com> Me again. I'm getting this error when parsing an external URL - I understand that a common cause of this is badly formed HTML (or XHTML) and that's fair enough, but is there any way to turn the parser into forgiving mode? As I'm getting this error from documents over which I have no control, I need to be able to recover from this situation. Is there a way to clean the document before parsing it, or have the parser ignore the issue and proceed (which would probably be ok in my case)? Mike From Sebastien.Boisgerault at gmail.com Sun May 28 14:16:19 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 28 May 2006 11:16:19 -0700 Subject: (mostly-)POSIX regular expressions In-Reply-To: <1148838196.463101.210180@i39g2000cwa.googlegroups.com> References: <1148764193.962418.192750@j73g2000cwa.googlegroups.com> <1148838196.463101.210180@i39g2000cwa.googlegroups.com> Message-ID: <1148840179.753478.207310@i40g2000cwc.googlegroups.com> Very good hint ! I wouldn't have found it alone ... I have to study the doc, but the "THE DFA MATCHING ALGORITHM" may do what I need Obviously, I didn't expect the Perl-Compatible Regular Expressions to implement "an alternative algorithm, provided by the pcre_dfa_exec() function, that operates in a different way, and is not Perl-compatible". Maybe the lib should be renamed in PCREWSO for: Perl-compatible regular expressions ... well, sort of :) Cheers, SB From johnjsal at NOSPAMgmail.com Wed May 17 14:46:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 18:46:36 GMT Subject: creating a new database with mysqldb Message-ID: Since the connect method of mysqldb requires a database name, it seems like you can't use it without having a database already created. So is there a way to connect to your mysql server (without a specified database) in order to create a new database (i.e., the CREATE DATABASE query)? Thanks. From jjl at pobox.com Fri May 5 06:35:01 2006 From: jjl at pobox.com (John J. Lee) Date: 05 May 2006 11:35:01 +0100 Subject: unittest.main-workalike that runs doctests too? Message-ID: ...I wrote something to do this once, but didn't do as good a job as I might have done and wondered if anybody else has done it properly. I know about nose, but it seems just a little too magical for my tastes, and includes stuff I don't really need. John From __peter__ at web.de Tue May 16 06:05:03 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 May 2006 12:05:03 +0200 Subject: problem with namespaces using eval and exec References: <1147770312.756392.147920@i39g2000cwa.googlegroups.com> Message-ID: Jens wrote: > has anyone an idea why the following code does not work. > s = """ > def a(n): > return n*n > def b(t): > return a(t) > """ > ns = {} > exec(s, {}, ns) Here you are providing a local namespace into which all toplevel names (a and b) are inserted. > eval("b(2)", ns, {}) Here you provide a global (the former local) namespace containing an 'a'. Function b(), however is carrying its global namespace with it and will look for 'a' in that namespace and not the one you provide. This is similar to module x.py def b(t): return a(t) module y.py import x def a(t): return n * n x.b(2) # error, will not find the function a() you just defined Instead you could explicitly update b's global namespace: global_ns = {} local_ns = {} exec s in global_ns, local_ns global_ns["a"] = local_ns["a"] print eval("b(2)", local_ns) or (better, I think) model the situation of an ordinary module where globals() and locals() are identical: global_ns = {} exec s in global_ns print eval("b(2)", global_ns) Peter From paul at eval.ca Thu May 18 10:45:34 2006 From: paul at eval.ca (Paul Osman) Date: Thu, 18 May 2006 10:45:34 -0400 Subject: Python Install In-Reply-To: <1147962608.945821.226220@i40g2000cwc.googlegroups.com> References: <1147962608.945821.226220@i40g2000cwc.googlegroups.com> Message-ID: On 18-May-06, at 10:30 AM, D wrote: > I'm sure this is an easy question for most here, but it's throwing me > for a loop at the moment - I need to upgrade RHEL 3 with the latest > version of Python. I downloaded the source and installed, but we're > still having problems (i.e. some Python apps don't work, Add/Remove > Applications console errors out and doesn't open, etc.). My guess is > that it's using old libraries or otherwise conflicting with the old > Python version, but I'm not sure how to remove the original version. > Any help would be greatly appreciated! RHEL uses python for distro specific tools pretty extensively iirc. I'd stay away from source installs and stick to rpms / yum / up2date / whatever RH uses these days. Cheers, Paul Osman http://www.eval.ca From lance at augustmail.com Wed May 17 18:50:38 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Wed, 17 May 2006 17:50:38 -0500 Subject: excel centering columns Message-ID: <446ba8bd$0$61161$ae4e5890@news.nationwide.net> Hey all, Having problems centering a column Can someone explain how to center a column using python? import win32com.client import re import codecs import win32com.client.dynamic import time import datetime from win32com.client.dynamic import Dispatch from win32com.client import constants t2 = win32com.client.Dispatch("Excel.Application") t2.Visible=1 wb = t2.Workbooks.Open (path + xltrack) sh2 = wb.Worksheets (sheet) lastcol = sh2.UsedRange.Columns.Count sh2.Columns(lastcol).HorizontalAlignment = xlCenter Traceback (most recent call last): File "", line 1, in ? NameError: name 'xlCenter' is not defined sh2.Columns(lastcol).HorizontalAlignment = constant.xlCenter Traceback (most recent call last): File "", line 1, in ? NameError: name 'constant' is not defined sh2.Columns(lastcol).HorizontalAlignment = -4108 Traceback (most recent call last): File "", line 1, in ? File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 455, in __getattr__ return self._ApplyTypes_(*args) File "C:\Python24\Lib\site-packages\win32com\client\__init__.py", line 446, in _ApplyTypes_ return self._get_good_object_( com_error: (-2146827864, 'OLE error 0x800a01a8', None, None) From nnorwitz at gmail.com Thu May 18 03:07:42 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 18 May 2006 00:07:42 -0700 Subject: Any pointers/advice to help learn CPython source? In-Reply-To: <1147886150.819254.158880@i40g2000cwc.googlegroups.com> References: <1147886150.819254.158880@i40g2000cwc.googlegroups.com> Message-ID: <1147936062.293223.233820@y43g2000cwc.googlegroups.com> seberino at spawar.navy.mil wrote: > Anyone have any good advice to someone interested in learning about > innards of Python implementation? > > e.g. What is best place to start? > > Where can I get a 10,000 ft. overview of general structure? > > Anyone written docs on helping do this? > > How did other people successfully make it through? Depends on what you want to get out of it. There are only a handful of top level directories that are interesting: Include - include files Objects - all Python objects (list, dict, int, float, functions, and many others) Python - core interpreter and other support facilities Lib - Python stdlib (Lib/test is the test suite) Modules - C extension modules Parser - simple parser/tokenizer The last three probably aren't interesting. However, if you are interested in the GC (or SRE) implementation, then you should look under Modules as gcmodule.c and _sre.c are there. So are a bunch of others. Include/ isn't particularly interesting. Objects/ isn't too interesting either from the standpoint of learning about the interpreter. Although the object implementations may be interesting in their own right. Each object is in an unsurprising file named something like: listobject.c or intobject.c. That leaves Python/ which is where the real innards are. If you are interested in the interpreter, then Python/ceval.c is pretty much it. The compiler is primarly in Python/compile.c, but also see Python/ast.c (2.5 only) and Python/symtable.c. All the global builtin functions are in Python/bltinmodule.c. Import support is in Python/import.c. Most of the other files in Python/ are small and/or platform specific. They probably aren't as interesting in general. n From admin at angerona.cult.cu Thu May 4 16:55:49 2006 From: admin at angerona.cult.cu (=?iso-8859-1?Q?Tom=E1s_Rodriguez_Orta?=) Date: Thu, 4 May 2006 14:55:49 -0600 Subject: how Can I programater in python similar to Delphi Message-ID: <002201c66fbd$1f98d690$0000fea9@zeus> Hello, friends. I can programter in python similar to delphi, enveloper form for capture ther data from user. some help. sincerely TOMAS ------------------------------------------------------------------------- Este correo fue escaneado en busca de virus con el MDaemon Antivirus 2.27 en el dominio de correo angerona.cult.cu y no se encontro ninguna coincidencia. -------------- next part -------------- An HTML attachment was scrubbed... URL: From rpdooling at gmail.com Sat May 20 19:12:40 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 May 2006 16:12:40 -0700 Subject: FAQ for XML with Python In-Reply-To: <3esbg.19024$Lm5.1740@newssvr12.news.prodigy.com> References: <3esbg.19024$Lm5.1740@newssvr12.news.prodigy.com> Message-ID: <1148166760.877011.309480@y43g2000cwc.googlegroups.com> I have one suggestion. It's a beautiful page, and one day I'll know enough to appreciate the help it provides, but until then it's always a big help to the novice (in many fields of knowledge) if the first use of an acronym includes the words it stands for in parenthesis. In law and medicine and many other fields, this is a quick, unobtrusive way to enlighten anyone who doesn't know what SAX or DOM stand for. Think of it as initializing the acronym or defining the variable or whatever: you do it only once, but it really helps the new kids. Thanks, rick From barrynyc at gmail.com Mon May 29 14:40:36 2006 From: barrynyc at gmail.com (Barry) Date: Mon, 29 May 2006 14:40:36 -0400 Subject: summarize text In-Reply-To: <1148914353.156936.309040@g10g2000cwb.googlegroups.com> References: <1148903386.095226.249270@38g2000cwa.googlegroups.com> <1148914353.156936.309040@g10g2000cwb.googlegroups.com> Message-ID: <759fdc8f0605291140u50555318kafeb656b7833c6ab@mail.gmail.com> On 29 May 2006 07:52:33 -0700, gene tani wrote: > > > robin wrote: > > hello list, > > > > does anyone know of a library which permits to summarise text? i've > > been looking at nltk but haven't found anything yet. any help would be > > unclear what you're asking, maybe look at: > http://www.cs.waikato.ac.nz/~ml/weka/index.html > > http://www.kdnuggets.com/software/suites.html > http://www.ailab.si/orange > > http://mallet.cs.umass.edu/index.php/Main_Page > http://minorthird.sourceforge.net/ > http://www.dia.uniroma3.it/db/roadRunner/ > > http://www.lemurproject.org/ > > -- > http://mail.python.org/mailman/listinfo/python-list > Text summarization is a big problem, unlikely to be solved by calling on an established library. Although it's not entirely clear what you are hoping to do, the links above are for document searching, document classification, or data mining. But if you mean something like a news brief or a plot summary, check out the Document Understanding Conferences, http://duc.nist.gov/ -------------- next part -------------- An HTML attachment was scrubbed... URL: From bdesth.quelquechose at free.quelquepart.fr Fri May 26 19:03:20 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 27 May 2006 01:03:20 +0200 Subject: sort a dictionary by keys in specific order In-Reply-To: <1148665851.182749.101720@g10g2000cwb.googlegroups.com> References: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> <1148665851.182749.101720@g10g2000cwb.googlegroups.com> Message-ID: <447759de$0$1747$626a54ce@news.free.fr> spohle a ?crit : > how do i get the result back into the dictionary ? > Python dicts (like almost any known hash-table) are *not* ordered. If you need an ordered dict, roll your own - this is quite easy. From bdesth.quelquechose at free.quelquepart.fr Wed May 3 00:31:01 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 06:31:01 +0200 Subject: assignment in if In-Reply-To: References: <87iroodnqz.fsf@localhost.localdomain> Message-ID: <44580352$0$4903$626a54ce@news.free.fr> Edward Elliott a ?crit : > Roy Smith wrote: > (snip) >>The lack of embedded assignments leads to slightly more verbose code in >>situations like this, but on the other hand, it avoids the typical C >>disaster of writing a whole function as a one liner. > > Writing disasters in python just takes a little more creativity. ;) > +1 QOTW From lloyd at fusion.net.nz Sun May 21 18:09:48 2006 From: lloyd at fusion.net.nz (Lloyd Weehuizen) Date: Mon, 22 May 2006 10:09:48 +1200 Subject: WeakrefValueDictionary of Callables? In-Reply-To: References: <446FD83E.2000007@fusion.net.nz> Message-ID: <4470E52C.7080700@fusion.net.nz> Thanks for that, I had a feeling that was the problem. Is there anyway around this? I'd prefer not to have to assume the method name on the object. This could be solved by passing the object and method name in as two separate parameters to the Bind function. But ideally I'd like to extract this information somehow from the bound method and give the external API a more natural feel. Is that possible? Steve Holden wrote: > Lloyd Weehuizen wrote: >> Hey >> >> I'm trying to set up a WeakrefValueDictionary of callables however as >> soon as my method that adds the callable to the dictionary exits the >> value is removed? Is there any way around this? > > > I believe your problem is that the bound method references aren't > being retained (i.e. referenced) anywhere else. A bound method is an > object its own right, and can cease to exist at any time - > particularly in your > case when the weak reference is the only reference to it! > > Consider that the following code actually appears to work: > >import weakref >TEST_EVENT = 1 > >class TestBinder: > def __init__(self): > self.entries = weakref.WeakValueDictionary() > > def BindFunction(self, event_id, obj): > self.entries[event_id] = obj > > def CallFunction(self, event_id, *args): > self.entries[event_id].TestFunction(*args) From Serge.Orlov at gmail.com Mon May 29 08:47:29 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 29 May 2006 05:47:29 -0700 Subject: why not in python 2.4.3 References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> <1148851375.148311.320780@g10g2000cwb.googlegroups.com> <1148870627.058561.12800@y43g2000cwc.googlegroups.com> <1148897123.135779.91870@j33g2000cwa.googlegroups.com> Message-ID: <1148906849.894298.323790@g10g2000cwb.googlegroups.com> Rocco wrote: > Also with ascii the function does not work. Well, at least you fixed misconfiguration ;) Googling for 1F8B (that's two first bytes from your strange python 2.4 result) gives a hint: it's a beginning of gzip stream. Maybe urllib2 in python 2.4 reports to the server that it supports compressed data but doesn't decompress it when receives the reply? From greg at cosc.canterbury.ac.nz Fri May 26 04:33:03 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Fri, 26 May 2006 20:33:03 +1200 Subject: Creating instances of untrusted new-style classes In-Reply-To: References: <1148605569.607231.41640@j73g2000cwa.googlegroups.com> Message-ID: <4dnsopF1b3cgeU1@individual.net> Michael Spencer wrote: > >>> class A(object): > ... > >>> b = object.__new__(A) Note that you'll need to be a bit cleverer if the class might be derived from some other built-in type: >>> class A(list): ... pass ... >>> b = object.__new__(A) Traceback (most recent call last): File "", line 1, in ? TypeError: object.__new__(A) is not safe, use list.__new__() >>> b = list.__new__(A) >>> b [] I'm not sure what is the easiest way to figure out what base class to use, though. One way would be to work your way backwards along the __mro__ until one of them succeeds, but there's probably a more direct way. -- Greg From yaronb at telus.net Thu May 18 16:39:54 2006 From: yaronb at telus.net (Yaron Butterfield) Date: Thu, 18 May 2006 13:39:54 -0700 Subject: Python, Mysql, insert NULL In-Reply-To: <446CD4D2.3040109@telus.net> References: <446CD4D2.3040109@telus.net> Message-ID: <446CDB9A.5020308@telus.net> I figured this out. Because I am using InnoDB, I need to add the commit statement. Phew. Yaron Butterfield wrote: > Hi, > > I've been having problems using Python to insert data into a MySQL > database. I've donw web searches and pulled my hairs out getting it > to work but cannot. I have no trouble doing select queries, but when I > use Python to insert, though I do not receive any errors from python, > the table does not get populated. > > I've just followed the information from here by Steve Holden: > http://mail.python.org/pipermail/python-list/2005-October/302405.html > > to the tee. No errors and the same output as shown in the above > example. Yet, there isn't any data in my table. > Am I missing something so obvious?? Please help! This has frustrated > me for days now. > > regards, > Yaron > From maxerickson at gmail.com Tue May 16 16:36:50 2006 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 16 May 2006 20:36:50 +0000 (UTC) Subject: Option parser question - reading options from file as well as command line References: <126k3273j7kb28f@corp.supernews.com> <126k6ed517nf73e@corp.supernews.com> Message-ID: Andrew Robert wrote in news:126k6ed517nf73e at corp.supernews.com: > Any ideas? I don't know much about optparse, but since I was bored: >>> help(o.parse_args) Help on method parse_args in module optparse: parse_args(self, args=None, values=None) method of optparse.OptionParser instance parse_args(args : [string] = sys.argv[1:], values : Values = None) -> (values : Values, args : [string]) Parse the command-line options found in 'args' (default: sys.argv[1:]). Any errors result in a call to 'error()', which by default prints the usage message to stderr and calls sys.exit() with an error message. On success returns a pair (values, args) where 'values' is an Values instance (with all your option values) and 'args' is the list of arguments left over after parsing options. >>> o.parse_args('seven') Traceback (most recent call last): File "", line 1, in ? o.parse_args('seven') File "C:\bin\Python24\lib\optparse.py", line 1275, in parse_args stop = self._process_args(largs, rargs, values) File "C:\bin\Python24\lib\optparse.py", line 1322, in _process_args del rargs[0] TypeError: object doesn't support item deletion >>> That's the result of poking an optionParser instance in Idle. parse_args is expecting something that looks like sys.argv[1:], which is a list. You are passing it a string. max From phleum_nospam at chello.se Thu May 11 14:53:56 2006 From: phleum_nospam at chello.se (Carl) Date: Thu, 11 May 2006 20:53:56 +0200 Subject: pythoncode in matlab References: <4cgogmF15ljumU1@news.dfncis.de> <1147363274.990265.163990@i39g2000cwa.googlegroups.com> Message-ID: patrick.d.hull at gmail.com wrote: > check out PyMat: > http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html > > I've never used it but I believe it should work for your needs. > However, I highly recommend taking a look at SAGE: > http://modular.math.washington.edu/sage/ > which has an interface to octave. > > -ph PyMat will not help you! PyMat works the other way around, ie it allows for Matlab calls from Python. Basically you need to build a Python extension which includes calls to the matlab engine (see the Python and Matlab manuals). Another way is to make a shell call Python directly via "!python -c 'myscript.py'" and possibly save the results on a file, for further processing by Matlab. If you know about Scilab (which is a free and very capable Matlab clone, www.scilab.org) you can take a look at its Matlab-equivalent perl command (ie a Matlab script that calls perl). You can use this perl command for building a python command in Matlab. Carl From r.s at ZZmindspring.com Thu May 18 20:04:30 2006 From: r.s at ZZmindspring.com (r.e.s.) Date: Fri, 19 May 2006 00:04:30 GMT Subject: number of different lines in a file References: Message-ID: "Tim Chase" wrote ... > 2) use a python set: > > s = set() > for line in open("file.in"): > s.add(line.strip()) > return len(s) > > 3) compact #2: > > return len(set([line.strip() for line in file("file.in")])) > > or, if stripping the lines isn't a concern, it can just be > > return len(set(file("file.in"))) > > The logic in the set keeps track of ensuring that no > duplicates get entered. > > Depending on how many results you *expect*, this could > become cumbersome, as you have to have every unique line in > memory. A stream-oriented solution can be kinder on system > resources, but would require that the input be sorted first. Thank you (and all the others who responded!) -- set() does the trick, reducing the job to about a minute. I may play later with the other alternatives people mentionsed (dict(), hash(),...), just out of curiosity. I take your point about the "expected number", which in my case was around 0-10 (as it turned out, there were no dups). BTW, the first thing I tried was Fredrik Lundh's program: def number_distinct(fn): return len(set(s.strip() for s in open(fn))) which worked without the square brackets. Interesting that omitting them doesn't seem to matter. From david at david-steuber.com Sun May 21 20:15:08 2006 From: david at david-steuber.com (David Steuber) Date: 21 May 2006 20:15:08 -0400 Subject: Software Needs Less Idiots References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148204984.990918.237770@u72g2000cwu.googlegroups.com> Message-ID: <878xou5303.fsf@david-steuber.com> "PofN" <7abc at sogetthis.com> writes: > Xah Lee wrote: > > Software needs philosophers. > > No, software neds less idiots. So please take your medication and > change profession. Perhaps fewer would do. -- http://www.david-steuber.com/ 1998 Subaru Impreza Outback Sport 2006 Honda 599 Hornet (CB600F) x 2 Crash & Slider The lithobraker. Zero distance stops at any speed. From george.sakkis at gmail.com Sun May 21 17:40:33 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 21 May 2006 14:40:33 -0700 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: References: <200605211711.25043.me+python@modelnine.org> <1148237544.579470.43420@i40g2000cwc.googlegroups.com> Message-ID: <1148247633.377696.157820@38g2000cwa.googlegroups.com> Felipe Almeida Lessa wrote: > Em Dom, 2006-05-21 ?s 11:52 -0700, gangesmaster escreveu: > > > Today you can archive the same effect (but not necessarily with the same > > > performance) with: > > > > > > for node in (x for x in tree if x.haschildren()): > > > > > > > true, but it has different semantic meanings > > > > I know, that's also why I don't oppose the PEP. > > -- > Felipe. I guess the main objections will be that: 1) It doesn't buy you much compared to: for node in tree: if node.haschildren(): 2) "There should be one and preferably only one way to do it." List/genexp comprehensions don't allow larger statement blocks anyway, so that's not a problem for them. George From skip at pobox.com Thu May 25 15:42:33 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 25 May 2006 14:42:33 -0500 Subject: list comprehensions put non-names into namespaces! In-Reply-To: <1148577813.000229.225330@y43g2000cwc.googlegroups.com> References: <1148577813.000229.225330@y43g2000cwc.googlegroups.com> Message-ID: <17526.2217.502721.413299@montanaro.dyndns.org> Lonnie> List comprehensions appear to store their temporary result in a Lonnie> variable named "_[1]" (or presumably "_[2]", "_[3]" etc for Lonnie> nested comprehensions) Known issue. Fixed in generator comprehensions. Dunno about plans to fix it in list comprehensions. I believe at some point in the future they may just go away or become syntactic sugar for a gen comp wrapped in a list() call. Skip From fd.calabrese at gmail.com Sat May 27 03:41:06 2006 From: fd.calabrese at gmail.com (cesco) Date: 27 May 2006 00:41:06 -0700 Subject: matplotlib and numpy installation Message-ID: <1148715666.148775.85390@i39g2000cwa.googlegroups.com> Hi, I wanted to install python, numpy and matplotlib on Linux Ubuntu. I installed python with the following commands ./configure --enable-unicode=ucs4 make make install and then I installed numpy running python setup.py install Finally I came to matplotlib, that for the installation requires the commands python setup.py build python setup.py install but when I run the first (python setup.py build) I got the following output that I copied partially below. What am I doing wrong? Can anyone help? I had previously another version of python located in usr/bin while the current is in usr/local/bin. I guess I could remove the previous by the deleting the relative folder and now if I run the command 'which python' it actually says 'usr/local/bin/python' so I hope I done it correctly. If not, how can I uninstall any previous version of python? Do you think that somehow the error I get is caused by an unclean removal of that previous version? Thanks and regards Francesco Here follows the output: ----------------------------------- GTK requires pygtk TKAgg requires TkInter GTKAgg requires pygtk running build running build_py running build_ext building 'matplotlib.backends._ns_backend_agg' extension gcc options: '-pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall -Wstrict-prot\ otypes -fPIC' compile options: '-I/usr/local/lib/python2.4/site-packages/numpy/core/include -\ I/usr/include -I. -Isrc -Iswig -Iagg23/include -I. -I/usr/include -I. -I/usr/lo\ cal/lib/python2.4/site-packages/numpy/core/include/freetype2 -I/usr/include/fre\ etype2 -I./freetype2 -Isrc/freetype2 -Iswig/freetype2 -Iagg23/include/freetype2\ -I./freetype2 -I/usr/include/freetype2 -I./freetype2 -I/usr/local/include/pyth\ on2.4 -c' extra options: '-DSCIPY=1' gcc: src/_image.cpp src/_image.cpp:5:17: png.h: No such file or directory In file included from /usr/local/include/python2.4/Python.h:8, from src/_image.cpp:7: /usr/local/include/python2.4/pyconfig.h:835:1: warning: "_POSIX_C_SOURCE" redef\ ined In file included from /usr/include/c++/3.3/i486-linux/bits/os_defines.h:39, from /usr/include/c++/3.3/i486-linux/bits/c++config.h:35, from /usr/include/c++/3.3/iostream:44, from src/_image.cpp:1: /usr/include/features.h:131:1: warning: this is the location of the previous de\ finition src/_image.cpp: In member function `Py::Object Image::write_png(const Py::Tuple&)': src/_image.cpp:626: error: `png_structp' undeclared (first use this function) src/_image.cpp:626: error: (Each undeclared identifier is reported only once for each function it appears in.) src/_image.cpp:626: error: parse error before `;' token src/_image.cpp:627: error: `png_infop' undeclared (first use this function) src/_image.cpp:628: error: aggregate `png_color_8_struct sig_bit' has incomplete type and cannot be defined src/_image.cpp:629: error: `png_uint_32' undeclared (first use this function) src/_image.cpp:629: error: parse error before `=' token src/_image.cpp:632: error: `png_bytep' undeclared (first use this function) src/_image.cpp:632: error: `row_pointers' undeclared (first use this function) src/_image.cpp:632: error: parse error before `[' token src/_image.cpp:634: error: `row' undeclared (first use this function) src/_image.cpp:645: error: `png_ptr' undeclared (first use this function) src/_image.cpp:645: error: `PNG_LIBPNG_VER_STRING' undeclared (first use this function) src/_image.cpp:645: error: `png_create_write_struct' undeclared (first use this\ function) src/_image.cpp:653: error: `info_ptr' undeclared (first use this function) src/_image.cpp:653: error: `png_create_info_struct' undeclared (first use this function) src/_image.cpp:657: error: `png_destroy_write_struct' undeclared (first use this function) src/_image.cpp:662: error: `setjmp' undeclared (first use this function) src/_image.cpp:670: error: `png_init_io' undeclared (first use this function) src/_image.cpp:673: error: `PNG_COLOR_TYPE_RGB_ALPHA' undeclared (first use this function) src/_image.cpp:673: error: `PNG_INTERLACE_NONE' undeclared (first use this function) src/_image.cpp:674: error: `PNG_COMPRESSION_TYPE_BASE' undeclared (first use this function) ... From llosee at gmail.com Wed May 17 16:53:32 2006 From: llosee at gmail.com (Lou Losee) Date: Wed, 17 May 2006 16:53:32 -0400 Subject: creating a new database with mysqldb In-Reply-To: References: Message-ID: On 5/17/06, Philippe Martin wrote: > > John Salerno wrote: > > > Since the connect method of mysqldb requires a database name, it seems > > like you can't use it without having a database already created. So is > > there a way to connect to your mysql server (without a specified > > database) in order to create a new database (i.e., the CREATE DATABASE > > query)? > > > > Thanks. > > I'm no expert but: can't you spawn mysql with a script/scheme ? > > Philippe > > MySQLdb.connect does not require a database name. ie.: >>> import MySqlDB >>> db = MySQLdb.connect(host='localhost', user='root', passwd='xxxx') >>> csr = db.cursor() >>> csr.execute('''show databases''') 6L >>> for d in csr.fetchall(): print d ('cc',) ('cc_41',) ('mysql',) ('purchaseorder',) ('test',) ('xsldb',) >>> csr.execute('''create database newdb''') 1L >>> csr.execute('''show databases''') 7L >>> for d in csr.fetchall(): print d ('cc',) ('cc_41',) ('mysql',) ('newdb',) ('purchaseorder',) ('test',) ('xsldb',) >>> Later, Lou -- Artificial Intelligence is no match for Natural Stupidity -------------- next part -------------- An HTML attachment was scrubbed... URL: From NA at NA.com Thu May 11 19:40:39 2006 From: NA at NA.com (N/A) Date: Fri, 12 May 2006 07:40:39 +0800 Subject: which windows python to use? In-Reply-To: References: Message-ID: hi, if mathematical and numerical algorithm are all you need, then just go for Enthought distribution + Matplotlib. The Enthought distribution provides all packages you need and handy for insatllation! My combo: 1. Enthought Distribution 2. Matplotlib 3. EmEditor Brian Blais wrote: > Hello, > > Are there any recommendations for which Windows python version to use? > I'd like to see a pros-and-cons description of each, given that > different uses might dictate different versions. The versions I know > (and there are surely more) are: > > 1) download from www.python.org > 2) enthought > 3) activepython > > Are there advantages/disadvantages? I have used enthought before, but > it seems as if they are not at 2.4, and may lag behind in versions > (which may not be a bad thing). > > Any other recommendations? > > > thanks, > > Brian Blais > > From digitalorganics at gmail.com Sun May 28 23:34:52 2006 From: digitalorganics at gmail.com (Cloudthunder) Date: Sun, 28 May 2006 23:34:52 -0400 Subject: Method Delegation To Subinstances In-Reply-To: References: Message-ID: I could then fill the getattr function with different conditional statements as needed, cool. Thanks Steve! On 5/27/06, Steve Holden wrote: > > Cloudthunder wrote: > > In the example: > > > > class Boo: > > def __init__(self, parent): > > self.parent = parent > > print self.parent.testme > > def run(): > > print "Yahooooo!" > > > > class Foo: > > testme = "I love you!" > > def __init__(self): > > test = Boo(self) > > > > A = Foo() > > > > > > How can I set up method delegation so that I can do the following: > > > > A.run() > > > > and have this call refer to the run() method within the boo instance? > > Also, what if I have tons of functions like run() within the boo > > instance and I want all them to be directly accessible as if they were > > part of their parent (the Foo instance)? > > > The usual way is to provide a __getattr__ method, since this is invoked > after the usual mechanisms have failed to produce a sought attribute. > > class Boo: > def run(self): > print "Yahooooo!" > def identify(self): > print repr(self) > > class Foo: > testme = "I love you!" > def __init__(self): > self.test = Boo() > def __getattr__(self, attname): > return getattr(self.test, attname) > > A = Foo() > B = Boo() > > B.run() > B.identify() > A.run() > A.identify() > > sholden at bigboy ~/Projects/Python > $ python test49.py > Yahooooo! > <__main__.Boo instance at 0x186c002c> > Yahooooo! > <__main__.Boo instance at 0x186b9d4c> > > regards > Steve > -- > Steve Holden +44 150 684 7255 +1 800 494 3119 > Holden Web LLC/Ltd http://www.holdenweb.com > Love me, love my blog http://holdenweb.blogspot.com > Recent Ramblings http://del.icio.us/steve.holden > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From ullrich at math.okstate.edu Mon May 8 10:00:13 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Mon, 08 May 2006 09:00:13 -0500 Subject: A critic of Guido's blog on Python's lambda References: <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> Message-ID: On Mon, 08 May 2006 08:05:38 -0500, David C. Ullrich wrote: >[...] > >def acall(cell, value): > cell.owner.slots['b'].value = value + 1 Needing to say that sort of thing every time you define a callback isn't very nice. New and improved version: """PyCells.py""" class Cell: def __init__(self, name, owner, callback): self.name = name self.callback = callback self.owner = owner def onchange(self, value): self.value = value self.callback(self, value) def __setitem__(self, name, value): self.owner.slots[name].value = value class Cells: def __init__(self): self.__dict__['slots'] = {} def __setattr__(self, name, value): self.slots[name].onchange(value) def __getattr__(self, name): return self.slots[name].value def AddCell(self, name, callback): self.slots[name] = Cell(name, self, callback) Sample: cells = Cells() def acall(cell, value): cell['b'] = value + 1 cells.AddCell('a',acall) def bcall(cell, value): cell['a'] = value - 1 cells.AddCell('b',bcall) cells.a = 42 print cells.a, cells.b cells.b = 24 print cells.a, cells.b #OR you could give Cell a __setattr__ so the above #would be cell.a = value - 1. I think I like this #version better; in applications I have in mind I #might be iterating over lists of cell names. ************************ David C. Ullrich From johnjsal at NOSPAMgmail.com Wed May 10 15:25:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 19:25:24 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: <1147287162.914661.237370@i39g2000cwa.googlegroups.com> References: <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> Message-ID: mpeters42 at gmail.com wrote: >>>> string = 'abababababababab' >>>> pat = 'aba' >>>> [pat for s in re.compile('(?='+pat+')').findall(string)] > ['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba'] Wow, I have no idea how to read that RE. First off, what does it match? Should something come before the parentheses, and that will be what matches? Also, what are the '+'s doing? Are they literal +s or still being used as RE syntax? From oliver at first.in-berlin.de Thu May 18 14:31:53 2006 From: oliver at first.in-berlin.de (Oliver Bandel) Date: Thu, 18 May 2006 20:31:53 +0200 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147963328.479963.4390@j33g2000cwa.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> <1147796116.826750@elch.in-berlin.de> <1147905290_7@news-east.n> <87ves3wpuy.fsf@thalassa.informatimago.com> <1147963328.479963.4390@j33g2000cwa.googlegroups.com> Message-ID: <1147977108.251598@elch.in-berlin.de> Jonathon McKitrick wrote: > Pascal Bourguignon wrote: > >>(defun ???? (&key (????? 10) (?? 1) (???? 0)) >> (loop :for i :from ???? :to ????? :by ?? :collect i)) > > > How do you even *enter* these characters? My browser seems to trap all > the special character combinations, and I *know* you don't mean > selecting from a character palette. Didn't you heard of that big keyboards? 12 meter x 2 meter wide I think.... you need a long stick (maybe if you play golf, that can help). The you have all UTF-8 characters there, that's fine, but typing needs some time. But it's good, because when ready with typing your email, it's not necessary to go to sports after work. So your boss can insist that you longer stay at work. Ciao, Oliver ;-) From spam at me.please Tue May 2 08:01:59 2006 From: spam at me.please (Skink) Date: Tue, 02 May 2006 14:01:59 +0200 Subject: pyqt v3.* and v4.* Message-ID: Hi, Is it possible to have both versions of pyqt (in my case 3.14.1 and 4.0)? Version 3 is built using sip 4.2.1, version 4 is built using sip 4.4.3 When I run pyqt 4.0 (but with installed sip 4.2.1) I get: from PyQt4 import QtCore, QtGui TypeError: invalid argument to sipBadCatcherResult() When I run pyqt 3.14 (but with installed sip 4.4.3) I get: import qt Segmentation fault Both 3.14 and 4.0 work, but not when installed together. skink From johnjsal at NOSPAMgmail.com Mon May 1 10:33:39 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 01 May 2006 14:33:39 GMT Subject: ending a string with a backslash In-Reply-To: References: <445546c8$0$13341$c3e8da3@news.astraweb.com> <44557f3f$0$5357$c3e8da3@news.astraweb.com> Message-ID: <7%o5g.2017$No6.43931@news.tufts.edu> Roel Schroeven wrote: > I think this is also the right time to mention os.path.join. Yeah, I ended up using this and it looks a lot nicer too. :) From grante at visi.com Wed May 3 15:42:05 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 03 May 2006 19:42:05 -0000 Subject: python strings References: <1146684876.311829.297280@i39g2000cwa.googlegroups.com> Message-ID: <125i1sdi2e0qkb7@corp.supernews.com> On 2006-05-03, mike7411 at gmail.com wrote: > Is it possible for python strings to contain a zero byte? Yes. -- Grant Edwards grante Yow! Actually, what at I'd like is a little toy visi.com spaceship!! From nobody at 127.0.0.1 Mon May 1 16:47:58 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 01 May 2006 20:47:58 GMT Subject: Add file to zip, or replace file in zip References: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> <1146257509.963417.250250@g10g2000cwb.googlegroups.com> <4455010f@nntp0.pdx.net> <4456464c$1@nntp0.pdx.net> Message-ID: <2uu5g.483$fb2.452@newssvr27.news.prodigy.net> Scott David Daniels wrote: > Edward Elliott wrote: >> Scott David Daniels wrote: >>>... > > ... You windows kids and your crazy data formats. > There were a few oth OS's than Linux and Windows. Maybe you > should call me "you crazy Tenex kid." Windows popularized the zip format, but if you insist: You crazy Tenex kids, with your char-at-a-time raw password checking and new-fangled virtual memory. Back in my day, all we had was Multics and we liked it that way. Despite having no memory prior to the Apple II, I do know a bit of history. > Knuth says, "the fastest > way to search is to know where to go." -- Zips have locations of > files, and you needn't read in a lot of a huge zip to find and > extract a couple of files. You whippersnappers and your random access, always in such a hurry to get your data. You want faster search, just wait a few machine generations. From michael.murr at gmail.com Sat May 27 21:33:09 2006 From: michael.murr at gmail.com (michael.murr at gmail.com) Date: 27 May 2006 18:33:09 -0700 Subject: run time linked attributes Message-ID: <1148779989.765319.58290@38g2000cwa.googlegroups.com> I've read a few posts about how to have attributes that are "linked" at run time. I've created a (simple) Python metaclass that accomplishes this with some behind-the-scenes __init__ redirection. I'm posting the code at the end in case anyone is interested. Problem background: Object a (an instance of class A) has an attribute that points to object b (which is an instance of class B). So A's __init__ might look something like this: __init__(self): self.b = B(arg1, arg2, arg3) The catch is, that instances of B() need to reference other attributes of A. The traditional way to do this is pass the instance of A as a parameter to B. So B's __init__ might look something like: __init__(self, creator, arg1, arg2, arg3): self.creator = creator; naturally, A's __init__ would now look something like: __init__(self): self.b = B(self, arg1, arg2, arg3) Essentially this creates two links: a = A(); a.b --> b a.b.creator -> a To hide the passing of the reference to the parent/creator, the metaclass below adds a method MakeLinkedAttribute. To hide the handling of the reference to the parent/creator, the metaclass below redirects B's __init__ when the class object is created, inserting a call to Meta__init__, which handles the processing of the parent/creator element. The original __init__ is then called. See the module's docstring for an example... I'm curious to hear feedback about the code, especially any dangers that can occur from redirecting/hijacking __init__. Cheers! LinkedAttribute.py: """ Metaclass for making linked attributes The LinkedAttribute class allows you to (at run time) have objects that have references back to the object that created them. Any class that has LinkedAttribute as it's metaclass will have a MakedLinkedAttribute() method to make linked attributes. To accomplish this hackery, we use the metaclass to hijack the __init__ method, replacing it with our own. The new __init__ method (defined as Meta__init__) sets up the _creator attribute (if it was passed in) and then calls the original __init__ function. The original __init__ function gets renamed to _old__init__. The reason for including the class name in the first part of the redefinition is so that sub classes that call super(...).__init__ won't enter an infinite loop. The restriction to using this metaclass is that the classes that you call MakeLinkedAttribute on must also have LinkedAttribute as a metaclass. If you use this metaclass, make sure to give credit where credit is due :) (e.g. in a comment or docstring) There are other ways of solving the same problem (including passing the parent to __init__ explicitly). The software is provided AS IS, use this software at your own risk. There is no warranty. By using this software you agree to hold the author(s) harmless of any damage whether direct, incidental, consequently and otherwise. In no event shall the author(s) of this code be liable for any damages whatsoever incurred by this code. (c) 2006 Michael Murr [mmurr at code-x d0t net] e.g.: ----- from LinkedAttribute import LinkedAttribute class a(object): def __init__(self): self.linked_b = self.MakeLinkedAttribute(b, "this is a linked b") self.plain_b = b("this is a plain b") __metaclass__ = LinkedAttribute class b(object): def __init__(self, text): self.text = text if hasattr(self, "_creator"): print "I have a creator!" else: print "I am a standalone!" __metaclass__ = LinkedAttribute if __name__ == "__main__": objectA = a() objectB = b("created directly") print objectA.linked_b.text print objectA.plain_b.text print objectB.text yields: ------- I have a creator! I am a standalone! I am a standalone! this is a linked b this is a plain b created directly """ class LinkedAttribute(type): def __new__(klass, klassName, klassBases, klassDict): # Method to make a new linked child def MakeLinkedAttribute(self, childClass, *args, **kwds): return(childClass(_creator=self, *args, **kwds)) # MakeLinkedAttribute(self, childClass, *args, **kwds): # Run time hijacking of __init__ so we can make # a _creator BEFORE the original __init__ is called # # We use klassName + "_hijacked__init__" so sub classes # who call super(...).__init__ won't enter infinite # loops # # Note: All your __init__ are belong to us :) def Meta__init__(self, *args, **kwds): # If we don't have _creator keyword do nothing if kwds.has_key("_creator"): self._creator = kwds["_creator"] del kwds["_creator"] # kwds.has_key("_creator"): # If we don't have an old init, do nothing if hasattr(self, klassName + "_hijacked__init__"): attr = getattr(self, klassName + "_hijacked__init__") attr(*args, **kwds) # hasattr(self, klassName + "_hijacked__init__"): # Meta__init__(self, *args, **kwds): # If we have an init, we need to save it if klassDict.has_key("__init__"): klassDict[klassName + "_hijacked__init__"] = klassDict["__init__"] # Hijack (redirect) __init__ for our [evil] purposes :) klassDict["__init__"] = Meta__init__ instance = super(LinkedAttribute, klass).__new__(klass, klassName, klassBases, klassDict) instance.MakeLinkedAttribute = MakeLinkedAttribute return(instance) # __new__(klass, klassName, klassBases, klassDict): # LinkedAttribute(type): From john at castleamber.com Wed May 24 11:26:12 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:26:12 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> Message-ID: "Ant" wrote: > I have no particular affinity for Xah's views, but what does get up my > nose is usenet Nazism. That's because you're clueless. -- 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 bignose+hates-spam at benfinney.id.au Fri May 19 20:51:13 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 May 2006 10:51:13 +1000 Subject: problem with import autotest ... References: <1148042219.334648.183790@38g2000cwa.googlegroups.com> Message-ID: <87fyj5jz7i.fsf@benfinney.id.au> "bravegag" writes: > I have a script that works just fine on linux but when I try to > debug from Windows using Eclipse and PyDEV plugin then it does not > work. The Python version is the same 2.3.x , and command line is > roughly the same. 2.3.x is not a version. Which versions are you using on each? >>> import sys >>> sys.version '2.3.5 (#2, Sep 4 2005, 22:01:42) \n[GCC 3.3.5 (Debian 1:3.3.5-13)]' > The point is that from Linux the "import autotest" works as intended > i.e. just allow the importing module use some functions but from > Windows it autoruns itself just by importing it, I do not get why or > how? >>> import autotest Traceback (most recent call last): File "", line 1, in ? ImportError: No module named autotest What is this 'autotest' module? Where are you expecting it to come from? -- \ "If it ain't bust don't fix it is a very sound principle and | `\ remains so despite the fact that I have slavishly ignored it | _o__) all my life." -- Douglas Adams | Ben Finney From jmcmonagle at velseis.com.au Wed May 24 23:49:37 2006 From: jmcmonagle at velseis.com.au (rimmer) Date: 24 May 2006 20:49:37 -0700 Subject: Unexpected extension module behaviour In-Reply-To: <4475247E.5090506@lexicon.net> References: <1148522952.022925.229350@u72g2000cwu.googlegroups.com> <4475247E.5090506@lexicon.net> Message-ID: <1148528977.574929.301460@j55g2000cwa.googlegroups.com> Thanks for the help John. Indeed, changing <= to < has it licked. From johnjsal at NOSPAMgmail.com Fri May 19 16:22:14 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 20:22:14 GMT Subject: altering an object as you iterate over it? In-Reply-To: <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> Message-ID: Paul McGuire wrote: > Your coding style is a little dated - are you using an old version of > Python? This style is the old-fashioned way: I'm sure it has more to do with the fact that I'm new to Python, but what is old-fashioned about open()? Does file() do anything different? I know they are synonymous, but I like open because it seems like it's more self-describing than 'file'. > Now to your question about why '\n' lines persist into your new list. The > answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!! Doh! I see that now! :) > You might also want to strip whitespace from your lines Another good hint. Thanks for the reply! From reply.in.the.newsgroup at my.address.is.invalid Sun May 28 17:08:41 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 28 May 2006 23:08:41 +0200 Subject: why not in python 2.4.3 References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> Message-ID: Rocco: >but does not work with 2.4.3. Define "does not work". -- Ren? Pijlman From tsaar2003 at yahoo.com Wed May 3 03:41:12 2006 From: tsaar2003 at yahoo.com (tsaar2003 at yahoo.com) Date: 3 May 2006 00:41:12 -0700 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> Message-ID: <1146642072.934453.268870@e56g2000cwe.googlegroups.com> Yes, I know that "constant" A will also be modified as the b[0] points to A. Obviously the [] should be marked as immutable, as A is declared to be constant thus immutable. If somebody tries to modify this immutable object an error would occur. When I further thought about this problem with constant objects (and values), I run into this scenario: What if I want to use a constant object/value as a template (or predefined value/class) for a variable: constant A = ['1'] # let's declare A as immutable constant value/object b = A # let's assign b some default value b.append('2') # and let's play with b, but I wouldn't want to change A What I'd like to see here is that b gets a copy of A so that the original A won't be modified as we play with b. However, as we assign a constant value A to b, I wouldn't want to restrict myself from playing with b. Of course, I could write something like b = list(A) to get a copy of A assigned to b. However, in this situation I have to know the class name of A. But this is something that I would no like to have to know if we want to take modules as some kind of black boxes. Br, T.S. From haraldarminmassa at gmail.com Mon May 29 04:04:32 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 29 May 2006 01:04:32 -0700 Subject: Last Call - proposals for talks in the business and application track at EP 2006 Message-ID: <1148889871.975685.197580@y43g2000cwc.googlegroups.com> In 2006, EuroPython will be from the 3rd to the 5th of July at CERN, near Geneva in Switzerland. In business & applications we want to hear about how you made your fortune with Python. Show us YOUR interesting released Python applications. Describe your fabulous business models with Open Source Software. Report about your pub cashier solution in Python and how you solved the challenges of longer opening hours. Narrate the background stories about your next generation search engine which has just gone live. Explain us the technique, tell us the story, paint your business model! Show us how YOU got affluent, opulent, pecunious, proliferative, prosperous and wealthy - all using Python! Do you use Python to make big business in the lumber sawing or porn industrie? Let us know how! Move up to http://www.europython.org/sections/tracks_and_talks/announcements/call-for-proposals and submit your proposal. DEADLINE is 2006-05-31 - so do not hesitate any further! ---------------- All who still need to know how to get rich and improve their love life using Python: you are heartly invited to register for EuroPython 2006 via the website http://www.europython.org The "normal fee" is 190? for three days of seminars and a fine conference dinner. In addition to our great conference, you have the possibility to visit CERN! Maybe you read about it in Angel & Demons ("Illuminati" in German) from Dan Brown; maybe you know that Sir Tim Berners-Lee invented the World Wide Web there. You will have the chance to eat in canteens with the highest probability anywhere in the world to stand in queue with a future or past Nobel Prize Winner. You can learn about the technologies that will power Web 2.5 and above at the place where Web 0.1 up to Web 1.0 were developed. CERN says about itself: "The world's largest particle physics laboratory ... where the web was born!". As a German you are culturally obligued to go the place where they try to find out "was die Welt / in ihrem innersten zusammenh?lt". (So that I may perceive whatever holds / The world together in its inmost folds (Faust I)) - learn about that place at www.cern.ch Harald Armin Massa persuadere et programmare From SSchukat at dspace.de Tue May 23 07:16:12 2006 From: SSchukat at dspace.de (Stefan Schukat) Date: Tue, 23 May 2006 12:16:12 +0100 Subject: COM Server crashing when returning large arrays Message-ID: <1B3F2E002D9AD04BBC1A27B370F29EB9022E58@exchange2003.dspace.de> Hello Alistair, which version of pythoncom you are using? In the newer versions there is an support for a "native" safearray (the data type Excel is providing). In older versions the complete array was converted to a tuple which is very time and memory consuming. during this conversion you could run out of memory since you have the Python objects and the COM data in your process. I think in 207 the patch was included. 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 Alastair Alexander > Sent: Monday, May 22, 2006 6:27 PM > To: python-list at python.org > Subject: COM Server crashing when returning large arrays > > Hi ... I'm using pythoncom to create a python COM server > application that needs to be able to return large arrays to > COM client apps. For example, I need to be able to return an > array to Excel that is 500 by 10, with each element of the > array holding a 32 byte string. > > If I run the code for smaller arrays, say 10 by 10, it works > fine. If I allow the server to try to return the entire 500 > by 10 array, pythonw.exe causes a memory access violation and > dies and I get an "automation exception" error message in the > client app. > > I assume I'm violating some upper limit for data transfer > from pythoncom into COM. Anyone know if such limitations > exist? Is there a way around them? > Can anyone point me in the right direction? > > Thanks > > Alastair > > > p.s. 1st message on comp.lang.python, indeed 1st message on > any news group > > > -- > http://mail.python.org/mailman/listinfo/python-list > From johnjsal at NOSPAMgmail.com Fri May 26 11:34:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 26 May 2006 15:34:15 GMT Subject: hide python window, con'td In-Reply-To: References: Message-ID: Bell, Kevin wrote: > Great! And now that it's hiding w/ .pyw, how would I kill it if I want? > Just log off, or is there a better way? > > Kevin > > Close it in the Task Manager? From scott.daniels at acm.org Wed May 17 20:15:14 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 17 May 2006 17:15:14 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <446bb897$1@nntp0.pdx.net> glomde wrote: > i I would like to extend python so that you could create hiercical > tree structures (XML, HTML etc) easier ... > With syntactical sugar: > > # build a tree structure > root = ET.Element("html") > *!*root: > *!*head("head"): > *!*title("title): > *=*text = "Page Title" > *!*body("body"): > *=*bgcolor = "#ffffff" > *=*text = "Hello, World!" Hunt up PyYAML. It might be what you want. --Scott David Daniels scott.daniels at acm.org From onurb at xiludom.gro Tue May 9 08:43:59 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 14:43:59 +0200 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <1147142046.458555.261870@j33g2000cwa.googlegroups.com> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> <1147142046.458555.261870@j33g2000cwa.googlegroups.com> Message-ID: <44608ef0$0$30109$636a55ce@news.free.fr> vbgunz wrote: > to throw fire on the fuel (:P), you can get the value back to an > in-place mutable change with a single expression... > > mylist = [2,3,4,1] > print mylist.sort() or mylist > > might not be too pythonic or maybe it is. I guess depends on what side > of the glass you might wish to view the solution :) Anyway, please do us a favor : avoid using such a thing in production code !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jared at hpalace.com Thu May 11 01:48:03 2006 From: jared at hpalace.com (M Jared Finder) Date: Wed, 10 May 2006 22:48:03 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hf42xy.1ue69gu1is75oxN%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> <87ac9r1tem.fsf@snobis.de> <1hf26zk.1uqniari93h7fN%aleax@mac.com> <1ZadnfwKY5_XG_zZRVn-sg@speakeasy.net> <1hf42xy.1ue69gu1is75oxN%aleax@mac.com> Message-ID: Alex Martelli wrote: > M Jared Finder wrote: > ... >> Your reasoning, taken to the extreme, implies that an assembly language, >> by virtue of having the fewest constructs, is the best designed language > > Except that the major premise is faulty! Try e.g. > and count the > number of distinct instructions -- general purpose, floating point, > SIMD, MMX, SSE, SSE2, OS support... there's *hundreds*, each with its > own rules as to what operand(s) are allowed plus variants such as (e.g.) > cmovbe{w,l,q} for "conditional move if below or equal" for word, long, > quadword (no byte variant) -- but e.g cmpxchg{b,w,l,q} DOES have a byte > variant too, while setbe for "set if below or equal" ONLY has a byte > variant, etc, etc -- endless memorization;-). > > When you set up your strawman arguments, try to have at least ONE of the > premises appear sensible, will you?-) > > I never argued against keeping languages at a high level, of course > (that's why your so utterly unfounded argument would be a "strawman" > even if it WAS better founded;-). > >> prone, code. I think the advantages of anonymous functions: > ... >> e) making the language simpler to implement > > Adding one construct (e.g., in Python, having both def and lambda with > vast semantic overlap, rather than just one) cannot "make the language > simpler to implement" -- no doubt this kind of "reasoning" (?) is what > ended up making the instruction-set architecture of the dominant > families of CPUs so bizarre, intricate, and abstruse!-) It sure can. First, let's cover the cost. I'll be measuring everything in terms of lines of code, with the assumption that the code has been kept readable. Here's an implementation of lambda (anonymous functions) in Lisp based on flet (lexically scoped functions): (defmacro lambda (args &rest body) (let ((name (gensym))) `(flet ((,name ,args , at body)) (function ,name)))) That's three lines of code to implement. An almost trivial amount. Now by using anonymous functions, you can implement many other language level features simpler. Looping can be made into a regular function call. Branching can be made into a regular function call. Defining virtual functions can be made into a regular function call. Anything that deals with code blocks can be made into a regular function call. By removing the special syntax and semantics from these language level features and making them just pain old function calls, you can reuse the same evaluator, optimizer, code parser, introspector, and other code analyzing parts of your language for these (no longer) special constructs. That's a HUGE savings, well over 100 lines of code. Net simplification, at least 97 lines of code. For a concrete example of this in action, see Smalltalk. -- MJF From nobody at 127.0.0.1 Tue May 16 13:20:59 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 16 May 2006 17:20:59 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> Message-ID: <%Rnag.27589$4L1.8094@newssvr11.news.prodigy.com> achates wrote: > A tab is not equivalent to a number of spaces. It is a character > signifying an indent, just like the newline character signifies the end > of a line. This link posted over in comp.lang.perl.misc expands on that: http://numeromancer.dyndns.org/~timothy/tab-width-independence/description.html To me, tabs are like gotos. In the wrong hands, they can be abused. Novices will do the most hideous things with them. So do we just ban gotos alogether? No - we structure their use to avoid the most obnoxious mistakes and live with the rest in a power/abuse tradeoff. Before you object that modern languages don't use gotos, think again. Break and continue are merely restricted forms of goto, as are exceptions. Don't throw the baby out with the bathwater. Make better tools that allow the good uses and prevent the bad. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From tim.leeuwvander at nl.unisys.com Wed May 17 04:47:39 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 17 May 2006 01:47:39 -0700 Subject: Time to bundle PythonWin In-Reply-To: References: <1147388148.406918.76040@q12g2000cwa.googlegroups.com> Message-ID: <1147855659.304748.189690@j73g2000cwa.googlegroups.com> John Bokma wrote: > "Robert Hicks" wrote: > > > No it isn't. > > Learn to quote when you use Google's Usenet garbage. > I don't know why you consider it 'garbage', using it myself for this 'contribution', but quoting isn't hard using google groups. Just clicking the right links instead of the 'reply' link beneath the message. On-Topic: I'd welcome PythonWin added to the Python Windows MSI installer too, for purposes similar to the O-Ps. Do not possess the necessary skill to write patches, but still voting in favor. --Tim From bnblazer at gmail.com Tue May 23 19:40:24 2006 From: bnblazer at gmail.com (Brian) Date: 23 May 2006 16:40:24 -0700 Subject: performance difference between OSx and Windows In-Reply-To: <1148421261.164171.3310@g10g2000cwb.googlegroups.com> References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> <1148421261.164171.3310@g10g2000cwb.googlegroups.com> Message-ID: <1148427623.839043.208960@u72g2000cwu.googlegroups.com> dfj225 at gmail.com wrote: > Hi Brian, > > You may have already considered this, but since I didn't see it > mentioned in your post, I'll reply anyway. > > I believe the Python binaries that Apple includes with OS X are always > slightly behind the latest that you can get from the official sources. > I'm not infront of my Mac right now, so I can't tell you the disparity. You are right. Apple is quite far behind. I upgraded to 2.4.2 from 2.3.x. The MS box has the same version. > > One thing I would suggest would be to normalize the versions of Python > accross the two machines. I find that using Fink > (http://fink.sourceforge.net/) on OS X is the easiest way to install a > new version of Python (as well as much other open source software). I have explored fink but have not put it to use. Thanks for the tip. Brian From Serge.Orlov at gmail.com Mon May 8 18:29:18 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 8 May 2006 15:29:18 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1147127358.081356.8560@y43g2000cwc.googlegroups.com> OlafMeding at gmail.com wrote: > Tried importing win32api instead of time and using the > win32api.GetTickCount() and win32api.Sleep() methods. What about win32api.SleepEx? What about WaitForMultipleObjects WaitForMultipleObjectsEx WaitForSingleObject WaitForSingleObjectEx when the object is not expected to produce events and the function timeouts? From DierkErdmann at mail.com Tue May 16 08:37:27 2006 From: DierkErdmann at mail.com (DierkErdmann at mail.com) Date: 16 May 2006 05:37:27 -0700 Subject: Google-API Bad-Gateway-Error Message-ID: <1147783046.944898.43470@i39g2000cwa.googlegroups.com> Hi, I am trying to query google from within a python script using the Google-Api (pygoogle). The following piece of codes gives me a "SOAPpy.Errors.HTTPError: ", the full Traceback is shown below. I am aware of the incompatibilities between the Google-Api and older versions of the SOAP-Library; I do have installed a recent version of SOAP (v. 0.11.3) which is said to be supported by Google-API. Can someone help? TIA Dierk Source-Code: ###### import google google.setLicense('xxxxxxxxxxxxxxxxx') ##removed ;-) data = google.doGoogleSearch('python') data.meta.searchTime data.results[0].URL data.results[0].title ######## Full Traceback: ############# Traceback (most recent call last): File "test.py", line 3, in ? data = google.doGoogleSearch('python') File "/windows/g/Download/webcrawler/pygoogle-0.6/google.py", line 421, in doGoogleSearch outputencoding ) File "/usr/lib/python2.4/site-packages/SOAPpy/Client.py", line 421, in __call__ return self.__r_call(*args, **kw) File "/usr/lib/python2.4/site-packages/SOAPpy/Client.py", line 443, in __r_call self.__hd, self.__ma) File "/usr/lib/python2.4/site-packages/SOAPpy/Client.py", line 345, in __call config = self.config) File "/usr/lib/python2.4/site-packages/SOAPpy/Client.py", line 249, in call raise HTTPError(code, msg) SOAPpy.Errors.HTTPError: ############# From http Mon May 15 17:34:22 2006 From: http (Paul Rubin) Date: 15 May 2006 14:34:22 -0700 Subject: my cryptogram program References: <4468f2c4$0$7135$626a54ce@news.free.fr> Message-ID: <7xfyjbrmzl.fsf@ruckus.brouhaha.com> Bruno Desthuilliers writes: > def convert_quote(quote): > return make_code(quote).split('|', 1) I thought about suggesting that, but it's semantically different than the original since it fails to raise an error if no vertical bar is present. I don't know if that's good or bad. From steve at holdenweb.com Sat May 27 06:51:43 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 27 May 2006 11:51:43 +0100 Subject: Python - Web Display Technology In-Reply-To: References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> Message-ID: Edward Elliott wrote: > foxtree at gmail.com wrote: > > >>Flash also behaves consistently cross-browser, cross/platform -- and >>features cannot be disabled by the user. > > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > And that's a good thing? Maybe for Macromedia, not for us. This smells > like astroturf. > > > >>Flash can load and play external MP3 audio. >>Flash can render text... >>Flash can load/parse/serialize/send XML. >>Flash can access you webcam, allowing you to create your own video >>chat/IM app. >>Flash can programatically-build vector shapes, gradients, and fills. > > > It dices! It splices! Flash can heat your coffee, walk your dog, and > change your baby! It's the stupendous, miraculous, fantabulous app you > can't live without! > > > >>Flash can #animate# stuff!!! >> >>Flash is like a 2 MB download that works in almost *every* browser out >>there. ...it's pretty phenomenal that all those features could have >>been crammed into it. (like: a built-in interpreter for a >>late-version-EcmaScript-compliant scripting language -- that, in many >>ways, is far more capable than what is available w/ JavaScript in most >>browsers!) >> >>*** This feature can be used for a web-based CMS! It would blow-away >>anything (non-Java) now available for managing and uploading assets. >>- Show quoted text - > > > Ugh, definitely astroturf. > The most telling thing of all is that most of the web sites with a Flash intro find it necessary to provide a "bypass intro" button. People quickly tire of this stuff. It's just, well, flashy :-) Unfortunately it's difficult to get someone who's in love with a proprietary technology to admit that open standards are preferable. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From webraviteja at gmail.com Mon May 22 02:01:59 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 21 May 2006 23:01:59 -0700 Subject: Web based application in python In-Reply-To: References: Message-ID: <1148277719.718600.27620@i39g2000cwa.googlegroups.com> >> I would like to know whether it is possible to develop web based application using Python. Any general purpose language may be used for developing web applications. Even your favorite shell language. You should really at least read the python.org main page before asking this question. It points you to http://wiki.python.org/moin/WebProgramming >> If yes, what are the challenges or areas I've to concentrate. There are no challenges. Python is an easy language. There are plenty of web frameworks. Don't ask which one. That entirely depends on what you want the framework to do for you. Everyone has their favorite and other people's favorites might not apply to you. >> How would be the performance, handling hits, scalability etc? These mostly depend on you and the framework, not Python. For example, CGI model will be slower than app server model. Caching will improve scalability. >> What are the pros and cons of using python in place of JAVA or J2EE? Pros: 1.) Better language 2.) You won't be adding any extra complexity to your application, something that all J2EE solutions seem to love to add and solve problems that few have in the first place. Provided you are a half-descent programmer, you will be able to learn most web frameworks in a few hours and get started (Notable exception: Zope). Cons: 1.) No Fancy IDE and commercial tool support - you won't need them anyway since the frameworks are often very simple in themselves. 2.) Your co-workers will look strangely at you if you say you are using Karrigell instead of Tomcat. From bdesth.quelquechose at free.quelquepart.fr Sun May 28 14:58:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 May 2006 20:58:10 +0200 Subject: dynamic type changing In-Reply-To: <1148803636.370761.55540@j33g2000cwa.googlegroups.com> References: <1148740408.226975.318050@u72g2000cwu.googlegroups.com> <44787bc6$0$19572$636a55ce@news.free.fr> <1148803636.370761.55540@j33g2000cwa.googlegroups.com> Message-ID: <4479c35d$0$19570$636a55ce@news.free.fr> andychambers2002 at yahoo.co.uk a ?crit : >>>I'm working on a "TempFile" class that stores the data in memory until >>>it gets larger than a specified threshold (as per PEP 42). Whilst >>>trying to implement it, I've come across some strange behaviour. Can >>>anyone explain this? > > >>>The test case at the bottom starts a TempFile at size 50 and prints its >>>type. It then increases the size to the threshold at which point >>>"self" is changed to being a TemporaryFile. > >>Changed how ?-) > > Just by being assigned with a TemporaryFile object. > > I thought that if > you do > > instance = TempFile() > > that "instance" and "self" defined in the Class They are not defined "in the class". > were the same thing so > that if you changed the class of self, > the class of instance would also > change. Yes, of course - but you didn't change the class of 'self' !-) Python's "variable" are really just names "bound to" (referring to) objects. Rebinding (ie: assignment) does not impact the object (well, not directly), it just associate the name to another object. This is totally different from changing the state of the object. There's nothing magical about the name 'self' - FWIW, you could replace it by any other valid python identifier. In Python, a method is just a plain function that takes the instance as the first argument. This function is wrapped into a method descriptor (google for python's descriptor protocol - it's the same thing that is used for properties) that takes care of feeding the function with the instance. FWIW, given: class Obj(object): def someMethod(self): pass obj = Obj() then obj.someMethod() is the same as Obj.someMethod(obj) or also: obj.someMethod.im_func(obj) So, inside someMethod's code, normal scoping rules apply. This means that 'self' is a *local* name, and rebinding it only affect the local scope. And it doesn't "change the type" of the object (previously) bound to 'self', it really re-bind 'self' to another object (IOW: makes 'self' a reference to another object). Just like it does in any other Python code. As I wrote, to dynamicall change the class of an object, you must rebind obj.__class__ to another class, ie: class Other(object): def __init__(self, name): self.name = name obj = Obj() print type(obj) obj.__class__ = Other print type(obj) Now a big warning : this is not garanteed to work seamlessly ! 'obj' will keep it's original instance attributes, and the instance attributes normally set up by the new class (here, 'Other') won't exist since the class initializer won't be called. So, while this may not be a problem if the original and new classes are designed to be used that way (which makes a very straightforward implementation of the state pattern), it's usually not a good idea to do such a thing. FWIW, it's usually simpler and safer - evn if a bit less elegant - to implement the state pattern just like I did in the example: by using composition/delegation. > Thanks very much for your example. votre humble serviteur, Messire > It has solved my problem and helped > me understand a new pattern at the same time. FWIW, there's no clear, well defined boudary between State and Strategy - the main difference depends mostly on the intention. Your use case could also be viewed as a State pattern, with 2 states : buffer < capacity, and buffer >= capacity. But the intention is not to know in which state is the object - on the contrary, you're trying to hide away the chosen implementation (StringIO or TemporayFile) - so it's really a Strategy IMHO. From danb_83 at yahoo.com Tue May 9 18:26:10 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 May 2006 15:26:10 -0700 Subject: python rounding problem. References: <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> <125v9g8q00o1d52@corp.supernews.com> <125vedc9n2q3m55@corp.supernews.com> <1147203401.653076.109230@i39g2000cwa.googlegroups.com> <1261sj7q7lsli24@corp.supernews.com> Message-ID: <1147213570.605525.134810@j33g2000cwa.googlegroups.com> Grant Edwards wrote: > On 2006-05-09, Dan Bishop wrote: > > Grant Edwards wrote: > > ... > >> Did they actually have 60 unique number symbols and use > >> place-weighting in a manner similar to the arabic/indian system > >> we use? > > > > The Bablyonians did use a place-value system, but they only had two > > basic numerals: a Y-like symbol for 1 and a <-like symbol for ten. > > These were combined to make base-60 digits. For example, 59 was > > represented by > > > > < YYY > > < < YYY > >< < YYY > > > > Zero (used as a placeholder, but not as a number in itself) was > > represented by a space. > > And they also (acording to the web pages I found) used base-60 > floating point notation, but without an actual symbol to > represent the sexagesimal point. Which seems really ambiguous -- > even to somebody who does know how to use a slide rule. Yes, it was. ("Our spy's message says that Cyrus the Great has '6 ' troops. Does that mean 360 or 21,600?") From aleax at mac.com Sun May 28 20:04:31 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 28 May 2006 17:04:31 -0700 Subject: itertools.count() as built-in References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> <1148860241.048549.269330@j73g2000cwa.googlegroups.com> Message-ID: <1hg24o2.18odi4uzoiraoN%aleax@mac.com> jantod at gmail.com wrote: > I have a project of around 6000 lines where I used count() 20 times. It > has 14 modules, 10 of which I needed an explicit import. > > Many of the usages are of the form: > > for item, n in zip(items, count(N)): > dostuff > > Around half of these are due to using pylab.subplot(x,y.n), which > requires values for n>=1. So I want N=1. The enumerate builtin starts > from 0. Hmmm, makes me wonder if enumerate should grow optional arguments for starting and stepping... I've found myself in similar situations, using "x*i+y" on the i returned by enumerate, or zipping an xrange instead... Alex From klaus at seistrup.dk Wed May 24 11:40:47 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Wed, 24 May 2006 15:40:47 +0000 (UTC) Subject: How to find out a date/time difference References: Message-ID: Nico Grubert skrev: > you could do this: > > >>> a = datetime.datetime(2006, 5, 24, 16, 1, 26) > >>> b = datetime.datetime(2006, 5, 20, 12, 1, 26) > >>> a-b > datetime.timedelta(4) > # 4 days Or #v+ >>> print (a-b).days 4 >>> #v- Mvh, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From pac at fernside.com Thu May 18 22:22:59 2006 From: pac at fernside.com (pac) Date: 18 May 2006 19:22:59 -0700 Subject: Script to make Windows XP-readable ZIP file Message-ID: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> I'm preparing to distribute a Windows XP Python program and some ancillary files, and I wanted to put everything in a .ZIP archive. It proved to be inordinately difficult and I thought I would post my solution here. Is there a better one? Suppose you have a set of files in a directory c:\a\b and some additional files in c:\a\b\subdir. Using a Python script, you would like to make a Windows-readable archive (.zip) that preserves this directory structure, and where the root directory of the archive is c:\a\b. In other words, all the files from c:\a\b appear in the archive without a path prefix, and all the files in c:\a\b\subdir have a path prefix of \subdir. This looks like it should be easy with module zipfile and the handy function os.walk. Create a zip file, call os.walk, and add the files to the archive like so: import os import zipfile z = zipfile.ZipFile(r"c:\a\b\myzip.zip",mode="w",compression=zipfile.ZIP_DEFLATED) for dirpath,dirs,files in os.walk(r"c:\a\b"): for a_file in files: a_path = os.path.join(dirpath,a_file) z.write(a_path) # Change, see below z.close() This creates an archive that can be read by WinZip or by another Python script that uses zipfile. But when you try to view it with the Windows compressed folder viewer it will appear empty. If you try to extract the files anyway (because you know they are really there), you get a Windows Security Warning and XP refuses to decompress the folder - XP is apparently afraid it might be bird flu or something. If you change the line marked #Change to "z.write(a_path,file)", explicitly naming each file, now the compressed folder viewer will show all the files in the archive. XP will not treat it like a virus and it will extract the files. However, the archive does not contain a subdirectory; all the files are in a single directory. Some experimentation suggests that Windows does not like any filename in the archive that begins with either a drive designator like c:, or has a path containing a leading slash like "\a\b\afile.txt". Relative paths like "subdir\afile.txt" are okay, and cause the desired behavior when the archive is extracted, e.g., a new directory subdir is created and afile.txt is placed in it. Since the method ZipFile.write needs a valid pathname for each file, the correct solution to the original problem entails messing around with the OS's current working directory. Position the CWD in the desired base directory of the archive, add the files to the archive using their relative pathnames, and put the CWD back where it was when you started: import os import zipfile z = zipfile.ZipFile(r"c:\a\b\myzip.zip",mode="w",compression=zipfile.ZIP_DEFLATED) cwd = os.getcwd() os.chdir(base_dir) try: for dirpath,dirs,files in os.walk(''): # This starts the walk at the CWD for a_file in files: a_path = os.path.join(dirpath,a_file) z.write(a_path,a_path) # Can the second argument be omitted? z.close() finally: os.chdir(cwd) This produces an archive that can be extracted by Windows XP using its built-in capability, by WinZip, or by another Python script. Now that I have the solution it seems to make sense, but it wasn't at all obvious when I started. Paul Cornelius From john at castleamber.com Thu May 25 20:35:09 2006 From: john at castleamber.com (John Bokma) Date: 26 May 2006 00:35:09 GMT Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148599852.040381.290030@y43g2000cwc.googlegroups.com> Message-ID: "Luis M. Gonz?lez" wrote: > Free online resources for learning Python: > > To get started, I strongly suggest Josh Cogliati's "Non-Programmers > Tutorial for Python" ( http://honors.montana.edu/~jjc/easytut/easytut/ > ). > I learned programming with this little tutorial, which is a very good > introduction. > > After that, you could check these ones: > "A Byte of Python" by Swaroop CH > "Learning to Program" by Alan Gauld > (http://www.freenetpages.co.uk/hp/alan.gauld/) > > The last one is specially good to grasp the basics of object oriented > programming. It has a very good example of a banking application that > was a real eye opener to me. How to Think Like a Computer Scientist: Learning with Python Haven't read it myself yet though. Thanks for the links, have added them to my local wiki :-D. -- 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 andrew.arobert at gmail.com Sat May 13 21:43:35 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sat, 13 May 2006 21:43:35 -0400 Subject: Question regarding checksuming of a file In-Reply-To: <126d1u4ke4itg7f@corp.supernews.com> References: <126d1u4ke4itg7f@corp.supernews.com> Message-ID: <126d2qf9e20b4d6@corp.supernews.com> Actually, I think I got it but would like to confirm this looks right. import md5 checksum = md5.new() mfn = open(self.file_name, 'r') for line in mfn.readlines(): checksum.update(line) mfn.close() cs = checksum.hexdigest() print cs The value cs should contain the MD5 checksum or did I miss something? Any help you can provide would be greatly appreciated. Thanks From sven at spam.pri.ee Mon May 15 10:20:51 2006 From: sven at spam.pri.ee (Sven Suursoho) Date: Mon, 15 May 2006 17:20:51 +0300 Subject: Iterating generator from C In-Reply-To: <446887C8.4070705@stackless.com> References: <446887C8.4070705@stackless.com> Message-ID: Mon, 15 May 2006 16:53:12 +0300, Christian Tismer : >> I am working on project that has embedded python interpreter to run >> user-specified python procedures. Those procedures might return any >> iterable object with set of result data -- basically everything for >> which iter() returns valid object (list, tuple, dict, iterator etc) >> It works ok, except generator under Python 2.4 with debugging enabled >> (see >> http://sourceforge.net/tracker/index.php?func=detail&aid=1483133&group_id=5470&atid=105470). >> Is there any way to rewrite following program to handle returned >> generator without hitting this bug? > > I found this bug as well, and I think the fix should be > back-ported. > This problem can only show up when you are comiling a C > extension, anyway. > Why don't you just apply the fix and compile your own? > It is just a wrong assertion, anyway. Unfortunately, this is not an option because I can't control used environment: I'm trying to improve PostgreSQL's stored procedure language PL/Python and this software can be used everywhere. At first I tried to block using generators if Py_DEBUG is defined. But this wouldn't work because of another, overlapping bug in Fedora Core 4's RPM packaging system (didn't check other versions) -- it disables Py_DEBUG but strips -DNDEBUG from compiler's command-line i.e. no Py_DEBUG and still active asserts(). See: http://archives.postgresql.org/pgsql-patches/2006-05/msg00042.php http://archives.postgresql.org/pgsql-patches/2006-05/msg00105.php -- Sven Suursoho From gherron at islandtraining.com Wed May 17 11:47:39 2006 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 17 May 2006 08:47:39 -0700 Subject: Process forking on Windows In-Reply-To: <126mgi2j7fl4b4b@corp.supernews.com> References: <126mgi2j7fl4b4b@corp.supernews.com> Message-ID: <446B459B.5000709@islandtraining.com> Andrew Robert wrote: >Hi everyone, > > >I have a python program that will need to interact with an MQSeries >trigger monitor. > >It does this fine but it hogs the trigger monitor while it executes. > >I'd like to fork the program off and terminate the parent process so >that the trigger monitor frees up. > > >Does anyone how this can be accomplished on a Windows platform? > >I've looked at doing this via the subprocess module but this doesn't >look like the correct approach. > >Any help you can provide would be greatly appreciated. > >Thanks > > The "subprocess" module gives a (mostly) platform independent way for one process to start another. It provides a number of bells and whistles, and is the latest module on a long history of older modules to provide such functionality. Gary Herron From bedouglas at earthlink.net Wed May 3 11:25:26 2006 From: bedouglas at earthlink.net (bruce) Date: Wed, 3 May 2006 08:25:26 -0700 Subject: Need Plone Information Message-ID: <235c01c66ec5$ce70f600$0301a8c0@Mesa.com> Hi.... I've never used Python/Plone, and am wondering if I can talk with anyone who's used Plone. I'm trying to determine if Plone could be easily used for a potential application. -bruce bedouglas at earthlink.net From webraviteja at gmail.com Fri May 26 04:58:43 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 26 May 2006 01:58:43 -0700 Subject: Parsing python dictionary in Java using JPython In-Reply-To: References: Message-ID: <1148633923.428032.294760@y43g2000cwc.googlegroups.com> > I have a python dictionary file. I want to create a map of that dictionary and want to use the same in my Java Program. > Can anybody please tell me how to use the same python dictionary in Java as well as in Python. Try a JSON parser for Java http://www.json.org/ http://www.json.org/java/simple.txt http://developer.berlios.de/projects/jsontools/ http://www.json.org/java/index.html From userprogoogle-139 at yahoo.co.uk Mon May 22 11:10:10 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 22 May 2006 08:10:10 -0700 Subject: Win32: Detecting when system is locked or sleeping References: <1148308038.487624.201690@i40g2000cwc.googlegroups.com> Message-ID: <1148310610.707825.97740@j33g2000cwa.googlegroups.com> Yes, I mean just a good old fashioned screen lock (for security) initiated by the user. 'Sadly' there has been nothing as exciting as a blue-screen of death as yet, not even when the app swells to 400MB. Best, rod From andrew.arobert at gmail.com Thu May 25 14:33:00 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 14:33:00 -0400 Subject: regex/lambda black magic In-Reply-To: References: <127be5or10v59e9@corp.supernews.com> <127bnkqc8pdoef5@corp.supernews.com> Message-ID: <127bu3vklr0g56e@corp.supernews.com> Hi Everyone, Thanks for all of your patience on this. I finally got it to work. Here is the completed test code showing what is going on. Not cleaned up yet but it works for proof-of-concept purposes. #!/usr/bin/python import re,base64 # Evaluate captured character as hex def ret_hex(value): return '%'+base64.b16encode(value) # Evaluate the value of whatever was matched def enc_hex_match(match): return ret_hex(match.group(0)) def ret_ascii(value): return base64.b16decode(value) # Evaluate the value of whatever was matched def enc_ascii_match(match): arg=match.group() #remove the artifically inserted % sign arg=arg[1:] # decode the result return ret_ascii(arg) def file_encoder(): # Read each line, pass any matches on line to function for # line in file.readlines(): output=open(r'e:\pycode\sigh.new','wb') for line in open(r'e:\pycode\sigh.txt','rb'): output.write( (re.sub('[^\w\s]',enc_hex_match, line)) ) output.close() def file_decoder(): # Read each line, pass any matches on line to function for # line in file.readlines(): output=open(r'e:\pycode\sigh.new2','wb') for line in open(r'e:\pycode\sigh.new','rb'): output.write(re.sub('%[0-9A-F][0-9A-F]',enc_ascii_match, line)) output.close() file_encoder() file_decoder() From invalidemail at aerojockey.com Sun May 28 15:49:18 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 28 May 2006 12:49:18 -0700 Subject: why not in python 2.4.3 In-Reply-To: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> Message-ID: <1148845758.329310.260280@u72g2000cwu.googlegroups.com> Rocco wrote: > hi > I made the upgrade to python 2.4.3 from 2.4.2. > I want to take from google news some atom feeds with a funtion like > this > import urllib2 > def takefeed(url): > request=urllib2.Request(url) > request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; > Windows NT') > opener = urllib2.build_opener() > data=opener.open(request).read() > return data > url='http://news.google.it/?output=rss' > d=takefeed(url) > This woks well with python 2.3.5 but does not work with 2.4.3. > Why? Define "woks [sic] well". It works fine for me on 2.4.3 (and by "works fine" I mean it ran without an exception and it returned what appeared to be RSS data). If you would give us an exception trace it would help a lot. Maybe Google's server (or your ISP's) was down. That happens sometimes. Carl From tchur at optushome.com.au Fri May 26 16:33:20 2006 From: tchur at optushome.com.au (Tim Churches) Date: Sat, 27 May 2006 06:33:20 +1000 Subject: OLAP and pivot tables In-Reply-To: <44770F61.7070705@waypointdatasolutions.com> References: <1148611731.916187.198330@i40g2000cwc.googlegroups.com> <44770F61.7070705@waypointdatasolutions.com> Message-ID: <44776610.8060901@optushome.com.au> Ben Stroud wrote: > George Sakkis wrote: > >> After a brief search, I didn't find any python package related to OLAP >> and pivot tables. Did I miss anything ? To be more precise, I'm not so >> interested in a full-blown OLAP server with an RDBMS backend, but >> rather a pythonic API for constructing datacubes in memory, slicing and >> dicing them, drilling down or up dimensions and exposing them in some >> suitable form to a presentation layer. I've hacked a first cut of a >> pivot table implementation and an XHTML generator that produces >> hierarchical html tables but it's not particularly general or easily >> extensible so far. Is there any interest at all on a pythonic version >> of something like JOLAP or XMLA ? >> > I'd be interested as well. I posted a similar question to the ruby > mailing list a few months ago to no avail. Ideally, someone much more > talented than myself would create a open OLAP library in C that could be > interfaced with dynamic languages easily (I ordered some OLAP books and > started in on this, and decided I was in over my head for now). As far > as free software, all I've been able to find is java-based Mondrian. > Maybe it could serve as a reference implementation for someone. The NetEpi Analysis project - see http://sourceforge.net/projects/netepi , although not strictly an OLAP or datacube engine, might offer some of the things you are looking for. It is intended for exploratory epidemiological analysis of (potentially large) health-related datasets, but should work with most types of data for which an OLAP engine would be useful. Underneath there is a vertically-disaggregated, ordinally-mapped, set-theoretic data selection and summarisation engine, which is a pompous way of saying that it holds data column-wise in memory-mapped Numpy (Numeric Python) arrays, and uses some fast (custom-written) set functions on inverted indexes on the ordinal positions of column values to select and summarise data (entirely at run-time, cf most OLAP engines, which rely on a degree of pre-summarisation along pre-chosen dimensions). It is all Python and thus has a Python(ic) API, including an SQL-like WHERE clause parser for data selection (OK, SQL is not Pythonic, but that's just for data subsetting). It includes quite a few statistical functions and nice graphics courtesy of R (http://www.r-project.org) (which is embedded via RPy - http://rpy.sourceforge.net/). Full support for missing values and weighted datasets is provided (but not full support for survey data with complex sample designs - that's forthcoming). Currently it works well with datasets in the 5-10 million row range, but the basic design lends itself easily to parallelisation if you have bigger datasets, and preliminary work indicates good speed improvements - something we want to pursue given all these multi-core CPUs which are now available at reasonable cost. Be warned that NetEpi Analysis is currently only of beta quality, and is a bit of a pig to install, on Linux/Unix/Mac OS X only at present. We hope to be able to ready a production-ready Version 1.0 by the end of 2006, possibly with MS-Windows support as well. However, the core data summarisation/subsetting engine is thought to be sound (and there are some unit tests to attest to that). Probably not quite what you were after but I thought it worth a mention. Please post follow-ups, if any, to the NetEpi mailing list: http://sourceforge.net/mail/?group_id=123700 Tim C > > Cheers, > Ben From miki.tebeka at gmail.com Sun May 28 05:20:17 2006 From: miki.tebeka at gmail.com (Miki) Date: 28 May 2006 02:20:17 -0700 Subject: Running External Commands + Seeing when they are Finished In-Reply-To: <1148707745.744045.77770@g10g2000cwb.googlegroups.com> References: <1148707745.744045.77770@g10g2000cwb.googlegroups.com> Message-ID: <1148808017.090240.301590@j55g2000cwa.googlegroups.com> Hello Tommy, Use the subprocess module (http://docs.python.org/lib/module-subprocess.html). for app in MY_APPLICATION_LIST: pipe = Popen(app) pipe.wait() HTH, http://pythonwise.blogspot.com/ From rpdooling at gmail.com Tue May 9 09:07:01 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 9 May 2006 06:07:01 -0700 Subject: Python editor recommendation. References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1147180021.852065.121200@u72g2000cwu.googlegroups.com> I'm on Windows XP, and I like Komodo a lot. It does php, html, perl, python, ruby etc. It's just a tad slow to load (takes about 10 seconds on my AMD Athlon 2700), but I usually leave it on all day, so I don't notice. If you're on Linux you might ask others. rpd From Serge.Orlov at gmail.com Sun May 28 22:43:47 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 28 May 2006 19:43:47 -0700 Subject: why not in python 2.4.3 References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> <1148851375.148311.320780@g10g2000cwb.googlegroups.com> Message-ID: <1148870627.058561.12800@y43g2000cwc.googlegroups.com> Rocco wrote: > >>> import sys > >>> sys.getdefaultencoding() > 'latin_1' Don't change default encoding. It should be always ascii. From mblume at socha.net Fri May 12 13:38:51 2006 From: mblume at socha.net (Martin Blume) Date: Fri, 12 May 2006 19:38:51 +0200 Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> <44644a76$0$290$626a54ce@news.free.fr> <4464959f$1$13578$5402220f@news.sunrise.ch> Message-ID: <4464c789$1$13566$5402220f@news.sunrise.ch> "Sybren Stuvel" schrieb > Martin Blume enlightened us with: Don't know if I enlightened anybody ... :-) > > Another question: Isn't decorating / wrapping > > usually done at runtime, so that the @deco > > notation is pretty useless (because you'd > > have to change the original code)? > > Please explain why that would make the @deco > notation pretty useless. > Well, if you're changing the original module, you might as well insert the needed functionality in the original function, no? Or rename the original function, write a function having this original name and calling from it the original functionality? Isn't the point of a decorator to change the behavior externally, at runtime, possibly changing it in different ways at different places at different times? So why this @deco notation? Can you apply it externally? Meaning to import module first, then @deco(module.func) somewhere later? Martin From andrew.arobert at gmail.com Thu May 18 18:40:12 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 18 May 2006 18:40:12 -0400 Subject: number of different lines in a file In-Reply-To: References: Message-ID: <126ptuv5hbs3e99@corp.supernews.com> r.e.s. wrote: > I have a million-line text file with 100 characters per line, > and simply need to determine how many of the lines are distinct. > > On my PC, this little program just goes to never-never land: > > def number_distinct(fn): > f = file(fn) > x = f.readline().strip() > L = [] > while x<>'': > if x not in L: > L = L + [x] > x = f.readline().strip() > return len(L) > > Would anyone care to point out improvements? > Is there a better algorithm for doing this? Take a look at http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52560 It is a python approach to the uniq command on *nix. From johnjsal at NOSPAMgmail.com Tue May 16 16:48:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 20:48:26 GMT Subject: calling upper() on a string, not working? In-Reply-To: References: Message-ID: Michal Kwiatkowski wrote: > And here you're translating 'original' (which contains a lot of > lowercase letters) with use of trans_table that maps only uppercase > characters. This return should be: > > return original.upper().translate(trans_table) Thank you!!! :) From akameswaran at gmail.com Wed May 31 15:35:34 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 31 May 2006 12:35:34 -0700 Subject: using import * with GUIs? In-Reply-To: References: Message-ID: <1149104134.583234.36020@i39g2000cwa.googlegroups.com> John Salerno wrote: > Hi all. Quick question (but aren't they all?) :) > > Do you think it's a good idea to use the 'from import *' > statement when using a GUI module? It seems on wxPython's site, they > recommend using import wx nowadays, but I wonder if that advice is > followed. Also, I'm still reading some Tkinter docs that seem to use > 'from Tkinter import *' a lot. > > I understand the danger of doing this, but is it safer in these cases, > given the more specific names that GUI frameworks tend to use > (sometimes!)? Or should you still qualify all your calls with the module? The python style guide takes no position on this. Personally I prefer explicit to implicit, and typing wx. is not really that much to type is it? From bj_666 at gmx.net Fri May 26 18:21:58 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 27 May 2006 00:21:58 +0200 Subject: Modify one character in a string References: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> Message-ID: In , Roy Smith wrote: >> Also, how do I do this when dealing with a file ; which file mode >> should I use and what function should I use to modify a single >> character once in that file mode? > > This is a much more complicated question, because it depends on the details > of the operating system you're using. On Unix, you can seek to a specific > place in a file, write a single character, seek to EOF, and you've done an > in-place single character edit of the file. Why seeking to EOF after writing the byte? Ciao, Marc 'BlackJack' Rintsch From fredrik at pythonware.com Wed May 3 02:23:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 08:23:05 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com><4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> Message-ID: tsaar2003 at yahoo.com wrote: > For example: > > >>> A = [] # let's declare a "constant" here > >>> b = A # and let's assign the constant here > >>> b.append('1') # OOPS! > >>> c = A > >>> print A > ['1'] > >>> print b > ['1'] > >>> print c > ['1'] > > As you can see, the "constant" A can be modified this easily. But if > there were an intuitive mechanism to declare a symbol to be immutable, > then there won't be this problem. why are you using mutable objects as constants? (insert obligatory "it hurts when I do this" joke here) btw, given a hypothetical "object that symbol points to is immutable" syntax, what would you expect this to do ? >>> constant A = [] >>> b = [A] >>> # much later >>> b[0].append('1') From NOatkinwSPAM at rpi.edu Sat May 6 19:27:07 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 19:27:07 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> Message-ID: <87mzdurayc.fsf@rpi.edu> aleaxit at yahoo.com (Alex Martelli) writes: > Ken Tilton wrote: > ... >> Looks like dictionaries are no match for the ambiguity of natural >> language. :) Let me try again: it is Python itself that cannot scale, as >> in gain "new power and capability", and at least in the case of lambda >> it seems to be because of indentation-sensitivity. > > In my opinion (and that of several others), the best way for Python to > grow in this regard would be to _lose_ lambda altogether, since named > functions are preferable (and it's an acknowledged Python design > principle that there should ideally be just one obvious way to perform a > task); GvR used to hold the same opinion, but changed his mind recently, > alas, so we'll keep the wart. > > But, quite apart from the whole issue of whether it's desirable to > languages to change massively ("add new power and capability" meaning > new enriched features in the language itself), your whole argument is > bogus: it's obvious that _any_ fundamental design choice in an artefact > will influence the feasibility and desirability of future design choices > in future releases of that same, identical artefact. At a syntax-sugar > level, for example, Lisp's choice to use parentheses as delimiter means > it's undesirable, even unfeasible, to use the single character '(' as an > ordinary identifier in a future release of the language. Considering > this to mean that Lisp "cannot scale" is just as ridiculous as > considering that Python "cannot scale" by not having an elegant way to > make lambdas heavier and richer -- totally laughable and idiotic. ``An > unneeded feature "cannot" be added (elegantly) in future releases of the > language'' is just as trivial and acceptable for the unneded feature > ``allow ( as an ordinary single-character identifier'' as for the > unneded feature ``allow unnamed functions with all the flexibility of > named ones''. Not so infeasible: (let ((|bizarrely(named()symbol| 3)) (+ |bizarrely(named()symbol| 4)) ;; => 7 And in any case, enforced indentation is a policy with vastly more serious consequences than the naming of identifiers. >> By contrast, in On Lisp we see Graham toss off Prolog in Chapter 22 and > > Oh, is that the same Graham who writes: > > """ > A friend of mine who knows nearly all the widely used languages uses > Python for most of his projects. He says the main reason is that he > likes the way source code looks. That may seem a frivolous reason to > choose one language over another. But it is not so frivolous as it > sounds: when you program, you spend more time reading code than writing > it. You push blobs of source code around the way a sculptor does blobs > of clay. So a language that makes source code ugly is maddening to an > exacting programmer, as clay full of lumps would be to a sculptor. > """ > ...? [[ I suspect that friend is in fact a common friend of mine and > Graham's, the guy you also mention later in your post, and who > introduced Graham and me when G recently came talk at Google (we had > "brushed" before, speaking in the same sessions at conferences and the > like, but had never "met", as in, got introduced and _talked_...;-). ]] > > But, no matter, let's get back to Graham's point: significant > indentation is a large part of what gives Python its own special beauty, > uncluttered by unneeded punctuation. And while you, I, Graham, and that > common friend of ours, might likely agree that Lisp, while entirely > different, has its own eerie beauty, most people's aesthetics are poles > apart from that (why else would major pure-FP languages such as *ML and > Haskell entirely reject Lisp's surface syntax, willingly dropping the > ease of macros, to introduce infix operator syntax etc...? obviously, > their designers' aesthetics weigh parenthesized prefixsyntax negatively, > despite said designers' undeniable depth, skill and excellence). > > > Alex -- This is a song that took me ten years to live and two years to write. - Bob Dylan From robert.kern at gmail.com Fri May 19 12:32:28 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 19 May 2006 11:32:28 -0500 Subject: WTF? Printing unicode strings In-Reply-To: References: Message-ID: John Salerno wrote: > AFAIK, I'm all ASCII (at least, I never made explicit changes to the > default Python install), so how am I able to print out the character? Because sys.stdout.encoding isn't determined by your Python configuration, but your terminal's. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From dale at riverhall.nospam.co.uk Mon May 22 11:03:58 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Mon, 22 May 2006 16:03:58 +0100 Subject: Win32: Detecting when system is locked or sleeping References: <1148308038.487624.201690@i40g2000cwc.googlegroups.com> Message-ID: skip at pobox.com wrote: > > rod> I have written an application which works perfectly when the > rod> machine is operating under normal conditions, however when the > rod> screen becomes locked it imediately starts to fill up several > rod> hundred MB's of memory. > > What do you mean by "locked"? Unresponsive to mouse or keyboard activity? > Blue screen? What is your application doing while it's filling up memory? > Which memory, disk or RAM? I think he means locked by the user for security. Keyboard/mouse lock. As in ctrl-alt-del -> [Lock Computer] Not the blue-screen, hung, rogered type of lock which is not voluntary and rather more frequent. -- Dale Strickland-Clark Riverhall Systems www.riverhall.co.uk We're recruiting. See the web site for details. From skip at pobox.com Tue May 16 15:58:11 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 May 2006 14:58:11 -0500 Subject: Using python for a CAD program In-Reply-To: <1147807050.375537.297430@j73g2000cwa.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <1147807050.375537.297430@j73g2000cwa.googlegroups.com> Message-ID: <17514.11987.38074.930361@montanaro.dyndns.org> Someone anonymous wrote: >> Cool. thanks for the links. I've already looked around quite a bit, >> and am very hesitant to just write more shit on top of other shit. That seems like a gratuitously unkind way to refer to tools you haven't tried. Have you checked out PythonCAD? . I don't use it, but the guy's been trickling out new releases periodically for the past four years or so (30 so far). Might be worth a peek. Skip From tjreedy at udel.edu Fri May 5 01:13:00 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 May 2006 01:13:00 -0400 Subject: Swaying A Coder Away From Python References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com><9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> <9afea2ac0605040604h6e72a41bm10f50d703644238b@mail.gmail.com> Message-ID: "Tim Williams" wrote in message news:9afea2ac0605040604h6e72a41bm10f50d703644238b at mail.gmail.com... > idea how large its user-base is. As I said, the email was forwarded > to someone who thought I would be interested. Well, it got Fredrik to post the link to a really nice intro to Django, which I had not seen before. So thanks to you both ;-) tjr From OlafMeding at gmail.com Wed May 3 23:01:15 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 20:01:15 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <125ir8gpofq3i1c@corp.supernews.com> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> <125ir8gpofq3i1c@corp.supernews.com> Message-ID: <1146711675.327183.256040@j73g2000cwa.googlegroups.com> Grant > Having sleep() take orders of magnitude longer than it should I seen a few times where sleep returns after some seconds or even after tens of seconds (my code above check for that). But most of the time it gets stuck forever. Olaf From Serge.Orlov at gmail.com Fri May 5 04:32:08 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 5 May 2006 01:32:08 -0700 Subject: Embedding Python: How to run compiled(*.pyc/*.pyo) files using Python C API? References: Message-ID: <1146817928.591686.41270@j33g2000cwa.googlegroups.com> Shankar wrote: > Hello, > > I am trying to run compiled Python files (*.pyc and *.pyo) using Python C > API. > > I am using the method PyRun_FileFlags() for this purpose. > > The code snippet is as follows:- > > PyCompilerFlags myFlags; > myFlags.cf_flags=1; // I tried all values 0, 1 and 2 > PyRun_FileFlags(script, file, Py_file_input, globals, locals, &myFlags); > > But unfortunately I get the following exception:- > "DeprecationWarning: Non-ASCII character '\xf2' in file E:\test.pyc on line > 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html > for details" Note, it's not an exception, it's a warning. > > When I run the .py file, then things work fine. > The .py file contains only one statement, > print "Hello World" > > Which Python C API should I use to run compiled Python files(*.pyc and > *.pyo) in the scenario where the source file (*.py) is not present. I believe it's PyImport_ImportModule("test") From robert.kern at gmail.com Fri May 12 12:44:53 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 12 May 2006 11:44:53 -0500 Subject: which windows python to use? In-Reply-To: References: Message-ID: Don Taylor wrote: > Robert Kern wrote: > >>In what way? Does the mingw gcc that we distribute interfere with Cygwin's gcc? > > Robert: > > Which C compiler will you be using for the Enthought 2.4 Windows release? Define "using". We build Python with whatever compiler the official build is compiled with. In this case, MSVC 7., I think . For this release, we will ship the latest available gcc available for mingw. Some of the extension modules will be built with this gcc. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From __peter__ at web.de Tue May 2 03:09:43 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 May 2006 09:09:43 +0200 Subject: strip newlines and blanks References: <1146551463.451811.266960@j73g2000cwa.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: Mick, you should be a bit more patient. Allow for some time for an answer to arrive. Minor edits of your question don't warrant a repost. > i have a file test.dat eg > > abcdefgh > ijklmn > <-----newline > opqrs > tuvwxyz > > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all w/o the newlines..? and what is the > proper way to skip printing blank lines while iterating file contents? The end of the file is signalled by an empty string, and a blank line with the trailing "\n" stripped off is an empty string, too. Therefore you have to perform the line == '' test before the stripping. Here's an alternative approach: for line in f: line = line.rstrip() if line: print line This will ignore any lines containing only whitespace and remove trailing whitespace from the non-white lines. Peter From hymort at hotmail.com Mon May 1 18:42:53 2006 From: hymort at hotmail.com (hymort at hotmail.com) Date: 1 May 2006 15:42:53 -0700 Subject: set partitioning In-Reply-To: <1146522121.798317.206180@i39g2000cwa.googlegroups.com> References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> <1146522121.798317.206180@i39g2000cwa.googlegroups.com> Message-ID: <1146523373.778624.142510@y43g2000cwc.googlegroups.com> Hello, Not quite what I'm looking for. I would like a list of all partitions with each partition having k or less elements, not just one instance. aaronwmail-use... at yahoo.com wrote: > Something like this, or am I missing something? > > def partition(List, n, m, k): > if n!=m*k: > raise "sorry, too many or too few elts" > D = {} > for x in List: > D[x] = 1 > if len(D)!=n: > raise "sorry (2) you lied about the number" > List2 = D.keys() > result = [] > for i in range(m): > result.append( List2[i*k: i*k+k] ) > return result > ? > > If this was a take home exam problem, > you should be ashamed of yourself! > -- Aaron Watters > > === > > It's easy. All you have to do is hit > the right keys at the right time and > the organ plays itself. -- J.S. Bach From telesphore4 at gmail.com Sat May 20 02:57:48 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 19 May 2006 23:57:48 -0700 Subject: Using metaclasses to inherit class variables References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> <-JednSk_j70VNvPZRVn-sg@comcast.com> Message-ID: <1148108268.434634.178800@i39g2000cwa.googlegroups.com> Hmm. setattr() only does a shallow search. Good to know. Your if not name in dict: setattr(cls, name, value) is a more succinct/better way of writing if not cls.__dict__.has_key(var): setattr(cls, var, val) Which i tested a fair bit. OK it appears that both are working for the simple types. However, if I do: >>> class SetClassVars(type): ... cvars = dict(lst=[], desc=None) ... def __init__(cls, name, bases, classdict): ... for name, value in SetClassVars.cvars.iteritems(): ... if not name in classdict: setattr(cls, name, value) >>> class C(object): ... __metaclass__ = SetClassVars ... desc = 'foo' ... >>> class D(C): ... desc = bar >>> C.lst.append('ccccc') >>> D.lst.append('dddd') >>> C.lst ['ccccc', 'dddd'] >>> D.lst ['ccccc', 'dddd'] I get the piling on behavior. OK. So it seems to be a problem only with the mutable list. I made the mistake of thinking that the list behavior was the same as for non-mutables. This must be a newbie mistake and it is probably documented somewhere. *Ding* I'll bet it is the same one that bites newbies when they define functions like: def myfunc(lst=[]): Looking for complicated problems with metaclasses when simple mistakes about mutables are the issue. Occam wags his finger at me. Thank you. That helped. t4 From johnjsal at NOSPAMgmail.com Fri May 12 11:48:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 12 May 2006 15:48:21 GMT Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: References: Message-ID: <9729g.2092$No6.45966@news.tufts.edu> CatDude wrote: > On Fri, 12 May 2006 14:01:51 +0000, John Salerno wrote: > >> Ok, I've been browsing through the MySQLdb docs, and I *think* I know >> the kind of code I need to write (connect, cursor, manipulate data, >> commmit, etc. -- although I probably need to get more familiar with >> actual SQL commands too), but here's my problem: I don't know where >> these scripts are supposed to be executed, or how they are supposed to >> 'find' the database. > > I'm kind of a noob myself, but I'll see if I can't offer some useful info > anyhow. Thanks very much for the info! I'll give the 'localhost' a try again and see if I was creating problems elsewhere, perhaps with the commands themselves. (All I know for sure is that I created a MySQL database and filled it with baseball statistics, so I know *that* exists, at least! But it was created from the MySQL prompt itself, not using Python.) I'll also read over those links, they seem like the kind of thing I need to really get going with it. :) From alanalan at newsgroup.nospam Thu May 4 12:02:52 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 4 May 2006 12:02:52 -0400 Subject: Python for Perl programmers Message-ID: Hi, Is there any efficient online resource or book that help experienced Perl programmers to Python? Thank you, Alan From trepca at gmail.com Sat May 13 03:44:02 2006 From: trepca at gmail.com (Sebastjan Trepca) Date: Sat, 13 May 2006 09:44:02 +0200 Subject: Slovenian Python User Group Message-ID: Hi! just wanted to send a notice about a new portal/group for Slovenian Python fans here :) http://soup.zen.si (btw, it's in slovene lang) Sebastjan From http Sat May 6 21:05:39 2006 From: http (Paul Rubin) Date: 06 May 2006 18:05:39 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> Message-ID: <7xac9uhcf0.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > > (|(| "your Lisp /is/ rusty.") > > Interestingly, the SECOND lisper to prove himself unable to read the > very text he's quoting. Reread carefully, *USE THE ***SINGLE*** > CHARACTER* ... *AS AN ORDINARY IDENTIFIER*. What makes you read a > ``PART OF'' that I had never written? You've shown how to use the > characters as *PART* of an identifier [[and I believe it couldn't be the > very start]], and you appear to believe that this somehow refutes my > assertion? The identifier there is a single paren. The vertical bars are used to escape the paren, so that the reader doesn't get confused. The Pythonic equivalent would be something like \( = 5 where the backslash escapes the paren. In real Python you could say: locals()['('] = 5 In Lisp you could get rid of the need to escape the paren if you wanted, using suitable read macros. Whether that's a good idea is of course a different matter. > Yes, we are, because the debate about why it's better for Python (as a > language used in real-world production systems, *SCALABLE* to extremely > large-scale ones) to *NOT* be insanely extensible and mutable is a > separate one -- Python's uniformity of style allows SCALABILITY of > teams, and teams-of-teams, which is as crucial in the real world ... My current take on Lisp vs Python is pretty close to Peter Norvig's (http://www.norvig.com/python-lisp.html): Python has the philosophy of making sensible compromises that make the easy things very easy, and don't preclude too many hard things. In my opinion it does a very good job. The easy things are easy, the harder things are progressively harder, and you tend not to notice the inconsistencies. Lisp has the philosophy of making fewer compromises: of providing a very powerful and totally consistent core. This can make Lisp harder to learn because you operate at a higher level of abstraction right from the start and because you need to understand what you're doing, rather than just relying on what feels or looks nice. But it also means that in Lisp it is easier to add levels of abstraction and complexity; Lisp makes the very hard things not too hard. > > It's hard to attribute feelings to a programming language, but, if you > really must, I'd say Pyton aspires to be *useful* -- if all you need is > "just a scripting language", it will be content to be one for you, and > if your need SCALE, well then, PYTHON IS SCALABLE, and will remain a > *SIMPLE, CLEAN, LITTLE AND POWERFUL LANGUAGE* (letting nobody do > anything INSANE to it;-) while scaling up to whatever size of project(s) > you need (including systems so large that they redefine the very concept > of "large scale" -- believe me, once in a while at a conference I make > the mistake of going to some talk about "large scale" this or that, and > invariably stagger out once again with the realization that what's > "large scale" to the world tends to be a neat toy-sized throwaway little > experiment to my current employer). I've heard many times that your current employer uses Python for all kinds of internal tools; I hadn't heard that it was used in Very Large projects over there. I'd be interested to hear how that's been working out, since the biggest Python projects I'd heard of before (e.g. Zope) are, as you say, toy-sized throwaways compared to the stuff done regularly over there at G. From deets at nospam.web.de Tue May 9 05:27:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 May 2006 11:27:11 +0200 Subject: two of pylab.py References: <87bqu75zrb.fsf@localhost.localdomain> Message-ID: <4cb5jmF15873jU1@uni-berlin.de> Gary Wessle wrote: > Hi > > I use debian/testing linux Linux debian/testing 2.6.15-1-686 > > I found some duplicate files in my system, I don't if the are both > needed, should I delete one of the groups below and which one? Do you have any problems related to pylab? Or are you concerned about disk consumption? > -rw-r--r-- 1 root root 80375 2006-01-24 00:28 > /usr/lib/python2.3/site-packages/matplotlib/pylab.py -rw-r--r-- 1 root > root 96202 2006-05-07 13:44 > /usr/lib/python2.3/site-packages/matplotlib/pylab.pyc -rw-r--r-- 1 root > root 96202 2006-05-07 13:45 > /usr/lib/python2.3/site-packages/matplotlib/pylab.pyo > -rw-r--r-- 1 root root 31 2004-12-10 03:05 > /usr/lib/python2.3/site-packages/pylab.py > -rw-r--r-- 1 root root 160 2006-05-07 13:44 > /usr/lib/python2.3/site-packages/pylab.pyc > -rw-r--r-- 1 root root 160 2006-05-07 13:45 > /usr/lib/python2.3/site-packages/pylab.pyo > > > my sys.path shows that /usr/lib/python2.3/site-packages/ is present. > > **************************************************************** > $cat /usr/lib/python2.3/site-packages/pylab.py > from matplotlib.pylab import * > **************************************************************** > > This imports all names except those beginning with an underscore (_). So it appears to be some sort of alias for matplotlib.pylab. And unless you want to risk that other packages that rely on the import import pylab to fail, you should keep things as they are. Diez From rdjdvd at inwind.it Sat May 13 17:59:50 2006 From: rdjdvd at inwind.it (.) Date: 13 May 2006 14:59:50 -0700 Subject: LocaWapp 09 - localhost web applications Message-ID: <1147557590.815914.70260@v46g2000cwv.googlegroups.com> http://daviderognoni.blogspot.com?locawapp - MAIN NEWS =========== * add thread * add "Request" object * new "locawapp_main" function * fixed files.py * ... http://daviderognoni.blogspot.com?locawapp From kent at kentsjohnson.com Wed May 24 08:07:49 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 24 May 2006 08:07:49 -0400 Subject: NEWB: how to convert a string to dict (dictionary) In-Reply-To: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> References: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> Message-ID: <44744bc6$1_2@newspeer2.tds.net> manstey wrote: > Hi, > > How do I convert a string like: > a="{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}" > > into a dictionary: > b={'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'} Try this recipe: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/364469 From jared at hpalace.com Tue May 9 01:47:57 2006 From: jared at hpalace.com (M Jared Finder) Date: Mon, 08 May 2006 22:47:57 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> Message-ID: Alex Martelli wrote: > Joe Marshall wrote: > ... >> If you language allows unnamed integers, unnamed strings, unnamed >> characters, unnamed arrays or aggregates, unnamed floats, unnamed >> expressions, unnamed statements, unnamed argument lists, etc. why >> *require* a name for trivial functions? > > I think it's reasonable to make a name a part of functions, classes and > modules because they may often be involved in tracebacks (in case of > uncaught errors): to me, it makes sense to let an error-diagnosing > tracebacks display packages, modules, classes and functions/methods > involved in the chain of calls leading to the point of error _by name_. > > I think it's reasonable to make a name a part of types for a different > reason: new types are rarely meant to be used "just once"; but also, if > during debugging any object is displayed, it's nice to be able to show, > as part of the display, "this object is of type X and ...", with X shown > as a name rather than as a complete (thus lengthy) description. (any > decent interactive shell/debugger will let you drill down into the > details as and when you need to, of course, but a well-chosen name can > be often sufficient during such interactive exploration/debugging > sessions, and therefore save time and effort). Any time you want an anonymous function (or class, or type, or number) it would be because that thing is sufficiently small and simple that the best name for it is the code itself. In one game I worked on, there was a function named canPerformAction_and_isNotActionInQueue. It was a simple, one line function: bool canPerformAction_and_isNotActionInQueue( Action action ) { return canPerformAction( action ) && !isActionInQueue( action ); } There was no better, more abstract name, as the design required this logic for a completely arbitrary reason -- so arbitrary it changed multiple times in development. For a little while it was used in two places. Then one of those places changed to have only the isActionInQueue part. There was no useful abstraction to be made, and it is in cases like these (which come up a lot when using functions as parameters) where anonymous functions are a win. -- MJF From spudtheimpaler at hotORgooMAIL.invalid Wed May 24 12:11:34 2006 From: spudtheimpaler at hotORgooMAIL.invalid (Mitch) Date: Wed, 24 May 2006 17:11:34 +0100 Subject: John Bokma harassment In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <447479A1.8050809@hotORgooMAIL.invalid> Message-ID: <447485B6.4070507@hotORgooMAIL.invalid> John Bokma wrote: > Mitch wrote: > >> John Bokma wrote: >> [...] >>> You're mistaken. All you need to do is report it. After some time Xah >>> will either walk in line with the rest of the world, or has found >>> somewhere else to yell. As long as it's not my back garden and not >>> around 4AM, I am ok with it. >>> >> Walk in line with the rest of the world? Pah. >> >> This is no-ones back garden. > > Funny how people who always think they can "change Usenet" have no clue > about what Usenet is and how it works in the first place. Who said anything about changing it? I like it just the way it is. > > Usenet is just that, each server participating can be thought of as being > the back yard of the news master. Sure, each server has terms and conditions that apply, doesn't mean you should be able to ban people from speaking just because you don't like what they say. My point is that this isn't *your* back garden, it isn't *my* back garden. It isn't something I own, and it *IS* something I can filter and/or ignore. Someone shouting in your back garden is a whole different ball game where your desires prevail. Not here. You know what you are getting into when you sign in, and it is your responsibility to deal with those you don't agree with personally. I understand you consider his writings spam, and so can see why you have reported him. All I'm saying is that as long as the articles are remotely on topic, I believe he has a right to post his opinions here. > If you have no clue about how Usenet works, first read up a bit. What a > Usenet server is, a feed, and how Usenet is distributed. > > And then come back if you finally have something to say that you can back > up. > Thankfully I'm aware enough of all the above that I don't feel the need. As these are all opinions, I don't see any need to "back up" any of it. From piet at cs.uu.nl Wed May 24 09:43:55 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Wed, 24 May 2006 15:43:55 +0200 Subject: getattr for modules not classes References: <5f56302b0605211252k79b642efl5ff4653fe7d17768@mail.gmail.com> Message-ID: >>>>> Heiko Wundram (HW) wrote: >HW> y.py >HW> --- >HW> from x import test >HW> print test.one >HW> print test.two >HW> print test.three >HW> --- Or even: import x x = x.test print x.one print x.two print x.three -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From vinayakchitre at gmail.com Fri May 19 08:37:10 2006 From: vinayakchitre at gmail.com (Vinayakc) Date: 19 May 2006 05:37:10 -0700 Subject: Encode exception for chinese text In-Reply-To: <1148039929.462581.51770@i40g2000cwc.googlegroups.com> References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> <1148039929.462581.51770@i40g2000cwc.googlegroups.com> Message-ID: <1148042230.341700.151410@y43g2000cwc.googlegroups.com> Yes serge, I have removed the first character but it is still giving encoding exception. From aleaxit at yahoo.com Sat May 6 18:37:43 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 15:37:43 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> Message-ID: <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> Ken Tilton wrote: ... > Looks like dictionaries are no match for the ambiguity of natural > language. :) Let me try again: it is Python itself that cannot scale, as > in gain "new power and capability", and at least in the case of lambda > it seems to be because of indentation-sensitivity. In my opinion (and that of several others), the best way for Python to grow in this regard would be to _lose_ lambda altogether, since named functions are preferable (and it's an acknowledged Python design principle that there should ideally be just one obvious way to perform a task); GvR used to hold the same opinion, but changed his mind recently, alas, so we'll keep the wart. But, quite apart from the whole issue of whether it's desirable to languages to change massively ("add new power and capability" meaning new enriched features in the language itself), your whole argument is bogus: it's obvious that _any_ fundamental design choice in an artefact will influence the feasibility and desirability of future design choices in future releases of that same, identical artefact. At a syntax-sugar level, for example, Lisp's choice to use parentheses as delimiter means it's undesirable, even unfeasible, to use the single character '(' as an ordinary identifier in a future release of the language. Considering this to mean that Lisp "cannot scale" is just as ridiculous as considering that Python "cannot scale" by not having an elegant way to make lambdas heavier and richer -- totally laughable and idiotic. ``An unneeded feature "cannot" be added (elegantly) in future releases of the language'' is just as trivial and acceptable for the unneded feature ``allow ( as an ordinary single-character identifier'' as for the unneded feature ``allow unnamed functions with all the flexibility of named ones''. > By contrast, in On Lisp we see Graham toss off Prolog in Chapter 22 and Oh, is that the same Graham who writes: """ A friend of mine who knows nearly all the widely used languages uses Python for most of his projects. He says the main reason is that he likes the way source code looks. That may seem a frivolous reason to choose one language over another. But it is not so frivolous as it sounds: when you program, you spend more time reading code than writing it. You push blobs of source code around the way a sculptor does blobs of clay. So a language that makes source code ugly is maddening to an exacting programmer, as clay full of lumps would be to a sculptor. """ ...? [[ I suspect that friend is in fact a common friend of mine and Graham's, the guy you also mention later in your post, and who introduced Graham and me when G recently came talk at Google (we had "brushed" before, speaking in the same sessions at conferences and the like, but had never "met", as in, got introduced and _talked_...;-). ]] But, no matter, let's get back to Graham's point: significant indentation is a large part of what gives Python its own special beauty, uncluttered by unneeded punctuation. And while you, I, Graham, and that common friend of ours, might likely agree that Lisp, while entirely different, has its own eerie beauty, most people's aesthetics are poles apart from that (why else would major pure-FP languages such as *ML and Haskell entirely reject Lisp's surface syntax, willingly dropping the ease of macros, to introduce infix operator syntax etc...? obviously, their designers' aesthetics weigh parenthesized prefixsyntax negatively, despite said designers' undeniable depth, skill and excellence). Alex From kentilton at gmail.com Mon May 15 13:10:41 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 15 May 2006 13:10:41 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147689991.541829.129550@u72g2000cwu.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <44681F95.9040400@gmail.com> <1147689991.541829.129550@u72g2000cwu.googlegroups.com> Message-ID: Ben wrote: > > Nothing you have described sounds that complicated, and you never come > up with concrete objections to other peoples code (apart that it took > 10 years to write in Lisp, so it must be really hard) Oh, now I have to spend an hour dissecting any code you people toss-off that does no more than pick the low-hanging fruit? I do not spend enough time on Usenet already? :) > > Why are you running a SoC project for PyCells... You do not even know what Cells are and have not taken the trouble to understand, so i will save my breath. Pythonistas will love PyCells, I promise. Please recall that it is not just me, there is a ton of prior and current art. > if you dislike the > language so much. There is a difference between disliking a language and thinking PyCells might end up persuading folks that macros and/or true lambda might be worth the trouble to extend the language. Try to think a little more precisely, OK? Thx. > People who do like Python can implement it if they > need it (which I haven't seen any good examples that they do) > > Please don't force a student to create a macro system just to port a > system to Python, You are getting hysterical, sit down, breathe. I asked a question, because (unlike you) I can see where this is going. But as you say... > There are already plenty of ways to hide > complicated functionality, I know. And that is why the mentor is a Pythonista, not me. I made a simple inquiry as to the options available should Python have trouble hiding the wiring. just looking ahead a little (as are the student and mentor). Something wrong with thinking ahead a few moves? You on the other hand have made up your mind about something you admit you do not understand, have now ascribed to me a half dozen sentiments I do not hold, and are feeling absolutely miserable because you think this is a flamewar. No, we are just discussing language synatx and how it impacts language semantics, which has led inadvertently to a few of us starting an SoC project to put together a Python version of a very successful dataflow hack I did for Lisp. I use it every day, and it just plain makes me smile. I wrote more code than you can imagine Before Cells, and have now used them intensively and in more ways than you can imagince since. Even if the wiring cannot be hidden, the productivity win will be trememndous. Note that this translates ineluctably to "programming will be more fun". Even you will love them. :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From python.list at tim.thechases.com Tue May 23 07:53:49 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 23 May 2006 06:53:49 -0500 Subject: Valid SQL? In-Reply-To: <1148383118.187847.197700@j33g2000cwa.googlegroups.com> References: <1148383118.187847.197700@j33g2000cwa.googlegroups.com> Message-ID: <4472F7CD.4070900@tim.thechases.com> > I have this string that I am sending via a Cursor.execute() using > MySQLdb: > > insert into table Ping82_eb13__elearn__ihost__com (`dateTime`, > `values`) values( > "Fri May 12 11:39:02 2006", "1") > > Does anyone see anything wrong with this SQL syntax? While this is the *python* list, rather than a SQL list... It looks like you're using two diff. styles of quoting. And using back-quotes at that. IIRC, ANSI-SQL (nebulous standard as it is, implemented to taste by each vendor) calls for using single-quotes as strings. Some RDBMS engines support the double-quote (MySQL does). None that I know of support the back-tick. Unless it's an RDBMS scheme for surrounding column or table-names that might have spaces in them (or might be SQL keywords). You might also want to make sure that your RDBMS doesn't have a column data-type of "datetime" (MySQL does) which might choke matters too...having a column-name that potentially clashes with the name of a datatype is just asking for trouble :) Additionally, the syntax for INSERT INTO statements usually leaves the word TABLE as optional. I think this is the first time I've seen someone opt for it :) Most SQL I've seen just does INSERT INTO tblFoo (field1, field2) VALUES ('value1', 'value2') You don't include the DDL that defines the structure of the table into which you're shoving matters, so it's somewhat hard to tell what's going on. Are primary keys being violated? Are data-types awry? Lastly, you don't include the text of the error message that you're getting back...most error messages try to be helpful, and in this case, it would certainly be helpful. :) Just a few thoughts, -tkc From nobody at 127.0.0.1 Mon May 15 13:07:34 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 15 May 2006 17:07:34 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: Harry George wrote: > This has been discussed repeatedly, and the answer is "If you only > work alone, never use anyone else's code and no one ever uses your > codes, then do as you please. The answer is "Do what works best for your project". Smart people can agree on and use whatever convention they want without trouble. The key is consistency. > Otherwise use tab-is-4-spaces." Tab is not 4 spaces. Tab is 1 level of indentation. The confusion that tabs equals some fixed width, or can/should be set to some fixed width, is the entire problem hampering their use. It implies that conversion between tabs and spaces is straightforward when it is not. They are not comparable entities. > When you do Agile Programming with people using emacs, vim, nedit, > xedit, wordpad, eclipse, and who knows what else, the 4-spaces rule is > necessary for survival. IOW reward programmers for being sloppy and using poor tools. Anyone who programs in wordpad/xedit has far bigger problems than worrying about tabs vs spaces (as do projects who let people program in wordpad/xedit). Editors which are designed for programming handle tabs and spaces cleanly. > The reason is simple: People get confused, and accidentally get the > wrong tab indents when they move among editors or among settings on > the same editor. Sounds like PEBCAK to me. :) If everyone uses tabs for indent, then it doesn't matter if Joe's vim showed them as 3 spaces while Mary's emacs showed them at 6. You can't get the 'wrong tab indents' when everything is a tab indent. Mixing tabs and spaces is where you get problems. > In most languages this is an irritation, requiring > some cleanup. In Python it is a disaster requiring re-inventing the > coded algorithms. Use the -tt flag to the Python interpreter and you'll catch inconsistencies immediately. Voila, no disaster. Again, you're not complaining about using tabs, you're complaining about mixing tabs and spaces. I completely agree with you that the latter is way too much hassle to even attempt. All I'm saying is that using tabs on their own is perfectly viable and a bit cleaner. I'm not trying to force that preference on anyone else, just get everyone to recognize that one is just as rational and salubrious as the other. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From sjmachin at lexicon.net Tue May 30 18:55:03 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 May 2006 08:55:03 +1000 Subject: F2G bug (was Re: How to calc easier the "long" filesize from nFileSizeLow and nFileSizeHigh) In-Reply-To: <1148961044_33775@sp6iad.superfeed.net> References: <1148961044_33775@sp6iad.superfeed.net> Message-ID: <447CCD47.3070205@lexicon.net> On 30/05/2006 1:55 PM, Roger Upole *top-posted*: > Shift nFileSizeHigh by 32 and add FileSizeLow. Uh-ohh. Here we have yet another manifestation of the Y2K bug's little sibling, the F2G bug. The above doesn't work for 2GB <= filesize < 4GB, 6GB <= filesize < 8GB, etc. See below. > > Roger > > "DurumDara" wrote in message news:mailman.6311.1148917245.27775.python-list at python.org... >> Hi ! >> >> I get the file datas with FindFilesW. >> I want to calc the filesize from nFileSizeLow and nFileSizeHigh with easiest as possible, without again calling os.getsize(). >> How to I do it ? I need good result ! >> >> Thanx for help: >> dd > Those two items are defined as int (that's *signed* int) -- so if the punter has a 3 GB file, nFileSizeHigh will be zero and nFileSizeLow will be -1073741824. *Minus* 1 GB? Hey, d00d, who stole my file-system? Try this: fsz = (hi << 32) + lo if lo < 0: fsz += 0x100000000 This problem is described in the first article found by googling for "nFileSizeHigh", as I suggested to the OP. Here is some evidence: C:\junk>dir gb3.txt [snip] 31/05/2006 07:59 AM 3,221,225,472 gb3.txt [snip] C:\junk>python Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. |>>> import win32file |>>> d = win32file.FindFilesW(u'gb3.txt') |>>> d [(32, , , , 0, -1073741824, 0, 0, u'gb3.txt', u'')] |>>> hi, lo = d[0][4:6] |>>> hi, lo (0, -1073741824) |>>> fsz = (hi << 32) + lo |>>> fsz -1073741824 |>>> # if lo < 0: |... fsz += (1 << 32) |>>> |>>> fsz 3221225472L |>>> Cheers, John From Serge.Orlov at gmail.com Wed May 17 07:48:09 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 May 2006 04:48:09 -0700 Subject: Python script windows servcie References: Message-ID: <1147866489.128112.100710@y43g2000cwc.googlegroups.com> Mivabe wrote: > Mivabe formulated the question : > > > > Google helped me discovering that it has something to do something with > > 'CTRL_LOGOFF_EVENT'. I know what it means but i don't know how to solve it. > > Is that something i have to configure in the script? > > > > I'n totally new to Python so maybe someone can point me to the right > > direction? :D > > > > Regards, Mivabe > > No-one who can help me or did i visit the wrong group for this > 'problem'? Indeed. Next time you'd better ask in a windows specific list: http://mail.python.org/mailman/listinfo/python-win32 You need to ignore CTRL_LOGOFF_EVENT. Take a look for example at http://mail.zope.org/pipermail/zope-checkins/2005-March/029068.html From petr at tpc.cz Wed May 3 19:11:35 2006 From: petr at tpc.cz (Petr Jakes) Date: 3 May 2006 16:11:35 -0700 Subject: milliseconds are not stored in the timestamp KInterbasDB + Firebird In-Reply-To: <1146587888.770947.162440@v46g2000cwv.googlegroups.com> References: <1146587888.770947.162440@v46g2000cwv.googlegroups.com> Message-ID: <1146697895.326244.50580@e56g2000cwe.googlegroups.com> to provide feedback: David Rushby (the autor of the KInterbasDB) has solved the problem applying such a future in the code. Thank you David. snapshots: http://kinterbasdb.sourceforge.net/snapshots/3.2/kinterbasdb-3.2_pre_20060503.src.tar.gz http://kinterbasdb.sourceforge.net/snapshots/3.2/kinterbasdb-3.2_pre_20060503.win32-FB-2.0-py2.4.exe Petr Jakes From tim.golden at viacom-outdoor.co.uk Fri May 19 06:40:42 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 19 May 2006 11:40:42 +0100 Subject: Windows Registry Dump Message-ID: [Dirk Hagemann] | I want to do some analysis (as always ;-) ) and for that | reason I think | it's more practical to go trough a text-file. I can produce this | text-file also by right-click on the key (the folder) in the registry | and select "Export". There one can select Text-File and the | place where | to save the text-file. This I want to be done by python automatically. Well, unless you want to go to the effort of recreating the .reg file format, it's probably worth trying to call regedit with a param or two: http://www.windowsitlibrary.com/Content/237/2.html suggests that something like: regedit /e c:\temp\desktop.reg "HKEY_CURRENT_USER\Control Panel\Desktop" will do the business. (And it worked for me a on a simple test run). 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 apgwoz at gmail.com Tue May 9 09:45:37 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Tue, 9 May 2006 09:45:37 -0400 Subject: clear memory? how? In-Reply-To: References: Message-ID: <2C007D32-83C4-4626-A195-B3AA896E7DAE@gmail.com> Glad to see you're trying Python instead of Matlab. Python was never meant to be a replacement for Matlab. It's a general purpose programming language like Java, or C#. Though it has very little in common with either of those languages. Since Python is a general purpose language, if you want Matlab like functionality, you need to rely on some other libraries that exist out there. Matplotlib, NumPy to name a few will make your Matlab- to Python transition go much more smoothly. You might also want to check out ipython, which is just a different interface to the python toplevel. On May 9, 2006, at 4:27 AM, N/A wrote: > Hi all, > I am learning Python. Just wondering how to clear saved memory in > Python? Like in Matlab I can simply use "clear all" to clear all saved > memory. > > Thank u! > -- > http://mail.python.org/mailman/listinfo/python-list --- Andrew Gwozdziewycz apgwoz at gmail.com http://www.23excuses.com http://ihadagreatview.org http://and.rovir.us From http Sat May 20 00:42:10 2006 From: http (Paul Rubin) Date: 19 May 2006 21:42:10 -0700 Subject: DO NOT USE file() (was Re: altering an object as you iterate over it?) References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <446e8a54$0$5326$c3e8da3@news.astraweb.com> Message-ID: <7x3bf58fz1.fsf@ruckus.brouhaha.com> "Tim Peters" writes: > In 2.5 `file` is unchanged but `open` becomes a function: > > >>> file > > >>> open > So which one are we supposed to use? From detlev at die-offenbachs.de Mon May 8 12:32:31 2006 From: detlev at die-offenbachs.de (Detlev Offenbach) Date: Mon, 08 May 2006 18:32:31 +0200 Subject: ANN: eric3 3.9.0 released References: <1146969457.495258.226730@j33g2000cwa.googlegroups.com> Message-ID: J. A. Gaeta Mendes wrote: > Petr Jakes wrote: > >> I think you can get the answer on >> http://www.die-offenbachs.de/detlev/eric3-mailinglist.html >> rather then here. >> >> HTH >> >> Petr Jakes > Thanks Petr, I've got help there. > To those interested, the problem was PyKDE was missing. > To correct the answer. PyKDE was installed in an incompatible version than the installed sip. If PyKDE wouldn't have been installed, eric3 wouldn't have tried to import it. So, everybody seeing the same problem should check for an old PyKDE somewhere. Regards, Detlev -- Detlev Offenbach detlev at die-offenbachs.de From vinay_sajip at yahoo.co.uk Tue May 9 18:49:18 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 9 May 2006 15:49:18 -0700 Subject: logging module: add client_addr to all log records References: <1147125271.065354.66180@j73g2000cwa.googlegroups.com> Message-ID: <1147214957.960232.300860@g10g2000cwb.googlegroups.com> Joel.Hedlund at gmail.com wrote: > Hi! > > I'm writing a server and I want to use the logging module for logging > stuff. I want to log all transactions in detail, and if everything goes > haywire I want to know which client did it. Therefore I want to affix > the client address to every single log item. > > I would like to do the following: > Formatter("[%(client_addr)s]: %(message)s") > ... > logger.critical("Offal Barrage Detected: Running Away", client_addr = > 'french.knights.org') > > I've written something that accomplishes this (example below), but I > have this nagging feeling that this could have been done in a better > way. Any ideas? > > When test.py executes it prints this: > [WARNING|2006-05-08 23:44:57,421|internal]: Unable to Pronounce 'ni!' > [WARNING|2006-05-08 23:44:57,421|french.knights.nu]: Incoming Bovine > Detected > > I'm grateful for any advice. > > Cheers! > /Joel Hedlund > See a very similar example which uses the new 'extra' keyword argument: http://docs.python.org/dev/lib/module-logging.html The example is for a similar use case to yours - showing the IP address of a client in a logging message. Best regards, Vinay Sajip From mensanator at aol.com Wed May 24 18:17:37 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 May 2006 15:17:37 -0700 Subject: Compiling Python from Sources In-Reply-To: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> References: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> Message-ID: <1148509057.542733.217230@i39g2000cwa.googlegroups.com> rwr wrote: > As a newbie I am having problems/errors configuring Python after > unpacking the Python archive: > > # ./configure > checking MACHDEP... linux2 > checking EXTRAPLATDIR... > checking for --without-gcc... no > checking for --with-cxx=... no > checking for c++... no > checking for g++... no > checking for gcc... gcc > checking for C++ compiler default output file name... configure: error: > C++ compiler cannot create executables > See `config.log' for more details. > > Any help on my current dilemma??? Did you look in config.log for more details? Would you like to share them? > TIA, > rwr From andy at neotitans.com Wed May 17 10:14:51 2006 From: andy at neotitans.com (Andy Sy) Date: Wed, 17 May 2006 22:14:51 +0800 Subject: Tabs versus Spaces in Source Code In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <4468B996.5000407@sweetapp.com> Message-ID: Peter Decker wrote: > Spaces look like crap, too, when using proportional fonts. ... and people who would even think that using proportional fonts for viewing/editing source code is anywhere remotely near being a good idea ... That's an even more advanced version of the i-think-tabs-are-good disease... LOL! From ToddLMorgan at gmail.com Sat May 13 08:46:43 2006 From: ToddLMorgan at gmail.com (ToddLMorgan) Date: 13 May 2006 05:46:43 -0700 Subject: Is it possible to set the date/time of a directory in windows with Python? If so how? References: <1147509953.594320.172890@d71g2000cwd.googlegroups.com> <1147512711_6767@sp6iad.superfeed.net> Message-ID: <1147524403.547888.36470@u72g2000cwu.googlegroups.com> Thanks very much for that roger :-) I changed my code to filehandle = win32file.CreateFile(file, win32file.GENERIC_WRITE, win32file.FILE_SHARE_WRITE, None, win32con.OPEN_ALWAYS, win32con.FILE_FLAG_BACKUP_SEMANTICS, None) nowWin32=pywintypes.Time(theTime) win32file.SetFileTime(filehandle, nowWin32, nowWin32, nowWin32) ie FILE_FLAG_BACKUP_SEMANTICS and everything works fine Just for the sake of completeness ... I'd just thought of another solution ... to have python determine the modification date for the directory based upon the oldest contained file (I'm guessing windows does the opposite - ie the newest file mod) to give me the effect of having a directory with an older date. The virtual file system idea didn't work either ... files had the correct dates but the dirs didn't as doing the extraction with python libs is subject to the same constraints ... and I didn't think that altering the ZipInfo time entries would have any affect as they appear to only represent files and not directories. I could have spawned a command line to do the extraction but I lost interest at that point. thanks again From 3dbernard at gmail.com Fri May 26 13:17:17 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 26 May 2006 13:17:17 -0400 Subject: Running Python scripts under a different user In-Reply-To: <447725C3.2000901@designaproduct.biz> References: <4dolv4F1b8m87U1@uni-berlin.de> <447725C3.2000901@designaproduct.biz> Message-ID: <61d0e2b40605261017l367b4642i5bd0e2208ea502eb@mail.gmail.com> On 5/26/06, Laszlo Nagy wrote: > For Windows, you can use the 'runas.exe' program. But it requires a > password too. > > From what you wrote, I think that you need to change architecture. You > should write your own service rather than write tricky programs. This > way you can develop your own security system, and restrict access to > specific files/programs. You can write tools that can connect to your > service. The service program can be ran on the background, with > sufficient privileges. How does it sound? [Bermard] Any ressource you could point me to as to write services? I'm totally unexperienced with that. Thanks a bunch. Bernard From haraldarminmassa at gmail.com Thu May 18 07:00:45 2006 From: haraldarminmassa at gmail.com (Harald Armin Massa) Date: 18 May 2006 04:00:45 -0700 Subject: Europython 2006 call for proposals Message-ID: <1147950045.478601.252080@j33g2000cwa.googlegroups.com> Hello, I am writing this supporting the Python in Business Track. We are looking for talks proposals concerning the usage of Python in doing business. So, if you have a story to tell... Maybe you have written a webcrawler in Python and founded a search engine? Or you are using Python to organize all those HTTPS-certificates, selling your company and flying to space, all with programming Python? Or are you up to more challenging aspects of daily life, like using Python to organize the ticket sales for a cinema-chain? Or even to do Point-Of-Sale stuff with some retailers? Or you have done something else interesting with Python in your Business? Please, come to EuroPython 2006 and tell others how you got prosperous programming in Python! (Just to remind you: Switzerland is one of the most well known places to take care of your money matters) Did Python give you inspiration to make Javascript suck less? Did you write a famous Python book, got hired by a company and live happily ever after? Cone to CERN, Switzerland, from 3. to 5. July 2006 - tell your story! Learn about Web 2.5 and up at the place Web 0.1-1.0 were developed! Be at the place famous for creating the antimatter to blow up Vatican! Have food in THE cafeteria with the highest likelyhood to queue together with a future or past Nobel Prize winner. Go to www.europython.org - and don't miss the talk submission deadline on 2006-05-31 [on a special note to Italians who are only allowed to travel to conferences with the possibility of recruitment: there will be some highly qualified PyPys at the conference; and just have a look at the timescale of PyPy founding by the European Union] Harald From vbgunz at gmail.com Thu May 25 13:02:32 2006 From: vbgunz at gmail.com (vbgunz) Date: 25 May 2006 10:02:32 -0700 Subject: how to clear up a List in python? In-Reply-To: <4475d96b$0$15788$14726298@news.sunsite.dk> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <4475d96b$0$15788$14726298@news.sunsite.dk> Message-ID: <1148576552.832444.115900@j73g2000cwa.googlegroups.com> > No, he'll have 100 items in the slice... 300, 301,... 399 that's 100 items. you're right, sorry. [300:400] would return 100 items but the item at index 400 would not return. I suggested if he wanted it to try [300:401] as the last slice index is excluded from the return. Thanks for that :) From s.schmeier at gmail.com Mon May 8 13:03:18 2006 From: s.schmeier at gmail.com (s.schmeier at gmail.com) Date: 8 May 2006 10:03:18 -0700 Subject: advanced number recognition in strings? Message-ID: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> Hi everybody, we want extract numbers from strings and wonder if there is already a module around for doing this. An example in our case would look like this: 0.032 +/- 0.5 x 10(-4) it would even be helpful to have a routine which does not recognise the +/- , but at least the 10(-4). Thank you for your help. Sebastian From samschul at pacbell.net Wed May 24 21:56:17 2006 From: samschul at pacbell.net (sam) Date: 24 May 2006 18:56:17 -0700 Subject: IronPython 1.0 Beta 7 Released In-Reply-To: <1148518396.856710.173810@g10g2000cwb.googlegroups.com> References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> <1148518396.856710.173810@g10g2000cwb.googlegroups.com> Message-ID: <1148522177.748892.79490@j55g2000cwa.googlegroups.com> vbgunz: When you download IronPython,the tutorial directory has some examples of interfacing With the .NET environment i.e.: 1: IronPython -> C# 2: C# -> IronPython 3: IronPython -> VB 4: VB -> IronPython Sam Schulenburg From carol.chisholm at gmail.com Mon May 29 02:07:23 2006 From: carol.chisholm at gmail.com (carol.chisholm at gmail.com) Date: 28 May 2006 23:07:23 -0700 Subject: Python for my mum References: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> <1148644991.633948.32260@j55g2000cwa.googlegroups.com> <5opjk3-dam.ln1@lairds.us> <1148669959.938843.177550@j73g2000cwa.googlegroups.com> Message-ID: <1148882843.581771.43010@g10g2000cwb.googlegroups.com> Many thanks for the helpful links. I don't think she's going to start programming, but at least she can run her French grammar program. From tim.peters at gmail.com Sun May 7 00:07:14 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sun, 7 May 2006 00:07:14 -0400 Subject: python 2.5a2, gcc 4.1 and memory problems In-Reply-To: References: Message-ID: <1f7befae0605062107v3d037ca2x8b0aa21b928af1d5@mail.gmail.com> [Michele Petrazzo] > I'm doing some tests on my debian testing and I see a very strange > memory problem with py 2.5a2 (just downloaded) and compiled with gcc > 4.1.0, but not with the gcc 3.3.5: > > My test are: > > #--test.py > import sys > if sys.version.startswith("2.3"): > from sets import Set as set > b=set(range(5000000)) > a=set(range(100000)) > c = b-a > > for i in 3 4 5; do echo "python 2.$i" && time python2.$i test.py; done > > My configure args for compile py 2.5a2 are: > ... > Then I execute my test. The memory usage of 2.5a2 and gcc 3.3 that I see > with "top", is the same (about VIRT: 260 MB and RES: 250MB ) that with > the py 2.3 and 2.4, but then I recompile with 4.1 and execute the same > test, my system "stop to work"... with "top" I can see that it use VIRT: > 2440 MB and RES: 640MB RAM (I think all that I have into my pc) FYI, here are stats I saw running the test program on Windows: Python \ VM size at end (KB) peak mem use (KB) ------ ------------------- ----------------- 2.3.5 262 313 2.4.3 262 313 trunk 196 230 "trunk" should be very close to 2.5a2 in memory use. "How much memory" the OS thinks you're using greatly depends on the platform C's malloc/free implementation, so I'd suspect a relevant difference in glibc (assuming that's the C library you're using). As the results on Windows show, it's unlikely that Python is _directly_ "consuming more memory" here; it's quite possible that the platform free() is hanging on to temp memory where in a different implementation it returned that temp memory to the OS. From peace.is.our.profession at gmx.de Tue May 9 03:44:19 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Tue, 09 May 2006 09:44:19 +0200 Subject: Import data from Excel In-Reply-To: References: Message-ID: Hi, > Is it possible to import data from Excel for > doing numerical analysis in Python? If so how? use John Machins glamouros 'xlrd' http://www.lexicon.net/sjmachin/xlrd.htm form his documentation: import xlrd book = xlrd.open_workbook("myfile.xls") print "The number of worksheets is", book.nsheets print "Worksheet name(s):", book.sheet_names() sh = book.sheet_by_index(0) print sh.name, sh.nrows, sh.ncols print "Cell D30 is", sh.cell_value(rowx=29, colx=3) for rx in range(sh.nrows): print sh.row(rx) This module is (imho) quite useful. No need for installed Windows or Office. Regards Mirco From deets at nospam.web.de Tue May 30 17:49:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 May 2006 23:49:20 +0200 Subject: Way to get an array of latitude/longitude points (tuples) from a trip In-Reply-To: <1148991896.430571.33700@j55g2000cwa.googlegroups.com> References: <1148991896.430571.33700@j55g2000cwa.googlegroups.com> Message-ID: <4e3sv1F1cvehrU1@uni-berlin.de> kbperry schrieb: > I am not sure if this is the right place for this, but I thought it was > worth a shot. > > What I want: > Enter a From: street address and a To: street address, and then specify > > an interval (say every half mile). Then, I click a submit button, and > it gives me latitude and longitude points (in order) from the beginning > > of my trip to the end of my trip in 1/2 mile increments. > > > I can't seem to find anything to simulate this, and I am not sure how > to go about coding this either. > > > BTW - I have used Yahoo geocoding service (to my delight), and while it > > is a good service, I don't see a way to do this unless we knew every > street address in 1/2 mile increments. > > Are there any Python modules that would assist with dealing with > latitude and longitude? > Can anyone out there help? The problem is not the latitude/longitude. It would be trivial to compute the great circle, thus the length of the trip between A and B and divide it in smaller pieces to get 1-mile-distances. But unless you own an Aircraft & are important enough to take flights the direct route without air traffic control getting mad at you (aka: you are George W. Bush or some other bigwig goverment guy), this won't do you much good. What you needed would be a vectormap of the streets so that you could do route planning. Which is expensive to get. So I guess you are better off trying to find someone who offers that as part of the service. Diez Diez From peace.is.our.profession at gmx.de Mon May 8 09:54:47 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Mon, 08 May 2006 15:54:47 +0200 Subject: Python's regular expression? In-Reply-To: <445F4985.10707@lexicon.net> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> <445F4093.4070505@lexicon.net> <445F4985.10707@lexicon.net> Message-ID: Hi John >> But what would be an appropriate use >> of search() vs. match()? When to use what? > > ReadTheFantasticManual :-) >From the manual you mentioned, i don't get the point of 'match'. So why should you use an extra function entry match(), re.match('whatever', t): which is, according to the FM, equivalent to (a special case of?) re.search('^whatever', t): For me, it looks like match() should be used on simple string comparisons like a 'ramped up C-strcmp()'. Or isn't ist? Maybe I dont get it ;-) Thanks Mirco From chris.cavalaria at free.fr Fri May 19 03:54:30 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 19 May 2006 09:54:30 +0200 Subject: Complex evaluation bug In-Reply-To: References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> Message-ID: <446d79da$0$7144$626a54ce@news.free.fr> Gary Herron a ?crit : > of wrote: > >> a = 1+3j >> complex(str(a)) >> >> Why does this not work ? It should >> >> > Says who? > By normal conventions in Python, "str" attempts only to make a "nice" > human readable representation. The function "repr" is usually expected > to provide output that can be parsed back into the original object. > (Although for the numeric complex type the two produce identical results.) > > Further, constructors are rarely expected to parse a string > representation to return an object. The function "eval" is usually > expected to provide that functionality. > > So, putting them together, you could expect > eval(repr(a)) > to reproduce a, and in fact it does so. Says who ? Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> repr(1+3j) '(1+3j)' >>> complex(repr(1+3j)) Traceback (most recent call last): File "", line 1, in ? ValueError: complex() arg is a malformed string >>> From iddw at hotmail.com Fri May 5 10:41:45 2006 From: iddw at hotmail.com (Dave Hansen) Date: Fri, 05 May 2006 09:41:45 -0500 Subject: Tuple assignment and generators? References: <1146821724.732068.268960@g10g2000cwb.googlegroups.com> <1146824577.242547.315600@y43g2000cwc.googlegroups.com> <4c0o60F13ut8cU1@uni-berlin.de> <1146826136.746268.4060@i40g2000cwc.googlegroups.com> <445b3960$1_3@news.bluewin.ch> <1146831804.396839.316070@v46g2000cwv.googlegroups.com> Message-ID: <2omm52h95b24gc15sesekfe4oapud53ok3@4ax.com> On 5 May 2006 05:23:24 -0700 in comp.lang.python, "vdrab" wrote: >> Are you telling us that you *had* read that doc, >> and tripped because it says "depending on the implementation", >> when it should say "at the choice of the implementation" ? > >no. >let's see, where to start ... ? >let's say there's a certain property P, for the sake of this loooong >discussion, something >more or less like a class or type's property of "having immutable >values, such that any instance with value X has a single, unique >representation in memory and any two instantiations of objects with >that value X are in fact references to the same object". IOW, property P is "(x == y) => (x is y)" (read "=>" as "implies"). Note that only immutable objects can have property P. > >Then, for example, python strings have property P whereas python lists >do not: > >>>> x = "test" >>>> y = "test" >>>> x is y >True >>>> x = [] >>>> y = [] >>>> x is y >False >>>> Note this last relationship is _guaranteed_. Lists are not immutable, and therefore can not have property P. > >Now, as it turns out, whether or not python integers have property P >_depends_on_their_value_. >From the zen, I believe this falls out from "practicality beats purity." >For small values, they do. For large values they don't. Yes, I Even that's not necessarily true. The implementation is free to always create a new immutable object, even for small values. >understand about the interpreter optimization. I didn't know this, and >I find it neither evident nor consistent. I don't think the above post >explains this, regardless of how you read "implementation". Think about implementation for a moment. Consider the statement x = some_arbitrary_integer() Do you really want the interpreter to go through all the existing integer objects in the program to see if that particular value exists, just to guarantee some some later statement x is y returns True if x == y? OK, maybe we can change the "is" operator on immutable objects such that x is y returns True if x == y. But then you can encounter a situation where "x is y" but "id(x) != id(y)" Now what? Perhaps the solution would be to disable the "is" operator and "id" function for immutable objects. But then _they_ lose generality. There doesn't seem to be a way to win. So it all comes down to "who cares?" Immutable objects are immutable. You can't change them. Object identity is a non-issue. This is not the case for mutable objects. Consider a = [1,2,3] b = [1,2,3] c = a a==b a==c b==c a is not b b is not c c is a c.append(4) > >In fact, the whole string of replies after my initial question reminded >me of something I read not too long ago, but didn't quite understand at >the time. >source : >http://www.oreillynet.com/ruby/blog/2006/01/a_little_antiantihype.html > [...whinge elided...] > >taking this rant with the proverbial grain of salt, I did think it was >funny. Your original post in its entirety (ignoring the example) was "what the...? does anybody else get mighty uncomfortable about this? " The first response (paraphrased) was "No. Why should I? With immutable objects, I care about ==, not is." Your response seemed to want to cast doubt on the integrity of the entire language: "Given this though, what other such beauties are lurking in the interpreter, under the name of 'implementation accidents'?" > >Anyway, thanks for all the attempts to show me. >I will get it in the end. I will ignore the double entendre, and simply hope I was of help, and wish you luck. Regards, -=Dave -- Change is inevitable, progress is not. From tchur at optushome.com.au Mon May 22 17:08:18 2006 From: tchur at optushome.com.au (Tim Churches) Date: Tue, 23 May 2006 07:08:18 +1000 Subject: Software Needs Philosophers In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <44722842.1050403@optushome.com.au> Xah Lee wrote: > Software Needs Philosophers > > by Steve Yegge, 2006-04-15. > > Software needs philosophers. > > People don't put much stock in philosophers these days. The popular > impression of philosophy is that it's just rhetoric, just frivolous > debating about stuff that can never properly be answered. ?Spare me > the philosophy; let's stick to the facts!? > > The funny thing is, it's philosophers who gave us the ability to think > rationally, to stick to the facts. If it weren't for the work of > countless philosophers, facts would still be getting people tortured > and killed for discovering and sharing them. Paging Dr Mertz... (http://www.gnosis.cx) Tim C From onurb at xiludom.gro Thu May 4 04:22:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 10:22:04 +0200 Subject: stripping unwanted chars from string In-Reply-To: References: <44598a93$1@news.eftel.com> Message-ID: <4459ba08$0$14029$626a54ce@news.free.fr> Edward Elliott wrote: > Bryan wrote: > >> >>> keepchars = set(string.letters + string.digits + '-.') > > > Now that looks a lot better. Just don't forget the underscore. :) > You may also want to have a look at string.translate() and string.maketrans() -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fraca7 at free.fr Mon May 15 10:12:20 2006 From: fraca7 at free.fr (fraca7) Date: Mon, 15 May 2006 16:12:20 +0200 Subject: pythoncom and IDispatch Message-ID: <44688c2a$0$7047$636a55ce@news.free.fr> Hello. I got a little problem while using pythoncom to automate IE; for some reason, changing the 'selectedIndex' on an instance of IHTMLSelectElement doesn't fire the 'onchange' event (I guess this is a bug in mshtml). So, I tried to get the 'onchange' event handler and call it myself. According to the docs, this is a simple IDispatch implementation and calling Invoke() should do the trick; I actually have a working example of this in Delphi. But I can't manage to get it work in Python; the following code idisp = pythoncom.WrapObject(elt.onchange) idisp.Invoke(pythoncom.DISPID_VALUE, 0x400, # LOCALE_USER_DEFAULT pythoncom.DISPATCH_METHOD, False) fails with an AttributeError: Traceback (most recent call last): File "C:\Python22\Lib\site-packages\win32com\server\policy.py", line 283, in _ Invoke_ return self._invoke_(dispid, lcid, wFlags, args) File "C:\Python22\Lib\site-packages\win32com\server\policy.py", line 288, in _ invoke_ return S_OK, -1, self._invokeex_(dispid, lcid, wFlags, args, None, None) File "C:\Python22\Lib\site-packages\win32com\server\policy.py", line 581, in _ invokeex_ return func(*args) File "ietest.py", line 44, in OnDocumentComplete self.deleg.onDocumentComplete(Dispatch(disp), url) File "ietest.py", line 122, in onDocumentComplete self.current.onDocumentComplete(self, browser, url) File "ietest.py", line 141, in onDocumentComplete sink.nextStep() File "ietest.py", line 96, in nextStep self.current.onStart(self) File "ietest.py", line 191, in onStart False) pywintypes.com_error: (-2147352567, 'Exception occurred.', (0, 'Python COM Serve r Internal Error', 'Unexpected Python Error: exceptions.AttributeError: _Invoke_ ', None, 0, -2147467259), None) Did I miss something ? TIA From incall at msn.com Tue May 23 09:55:58 2006 From: incall at msn.com (Pablo) Date: 23 May 2006 06:55:58 -0700 Subject: Use of lambda functions in OOP, any alternative? Message-ID: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> Hello all, sorry if this is a faq... Problem: The intended effect is to override the method 'getattr' in a way that i dont need to override the property explicitly too. class Base(object): def __init__(self, attr): self._attr = attr def getattr(self): return self._attr attr = property(fget=getattr) class Derived(Base): def getattr(self): return 2*self._attr if __name__ == "__main__": b = Base(4) d = Derived(4) print b.attr, d.attr output>> 4 8 ... so this does not work as i would like it to. First solution: This is not what i want. class Derived(Base): def getattr(self): return 2*self._attr attr = property(fget=getattr) Second solution: This is what i want, but... class Base(object): def __init__(self, attr): self._attr = attr def getattr(self): return self._attr attr = property(fget=lambda self: self.getattr()) class Derived(Base): def getattr(self): return 2*self._attr Question: Isn't there an *alternative* way to do it without the lambda function? Thanks in advance! From eligottlieb at gmail.com Wed May 24 10:13:11 2006 From: eligottlieb at gmail.com (Eli Gottlieb) Date: Wed, 24 May 2006 14:13:11 GMT Subject: John Bokma harassment In-Reply-To: <1148470149.596188.18500@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> Message-ID: Tim N. van der Leeuw wrote: > ilitzroth at gmail.com wrote: > >>I agree there are limits to you right to free speech, but I believe Xah >>Lee is not crossing >>any boundaries. If he starts taking over newspapers and TV stations be >>sure to notify me, >>I might revise my position. >>Immanuel > > > Perhaps he's not crossing boundaries of free speech, but he's > repeatedly crossing boundaries on usenet nettiquette, even though > repeatedly he's being asked not to do so. (Extensive crossposting to > various usenetgroups / mailing lists, for instance). > > If he would just post his stuff on a blog and find a why to get people > to visit hist blog, without crossposting to 10 usenest groups for each > post he makes to his blog, then nobody would mind him expressing his > opinions, and those interested could discuss them wildly on the blog. > > But I've repeatedly seen people telling him not to crosspost his essays > to so many newsgroups, yet he continues doing it. > If that's enough to quit his subscription with his ISP I don't know, > but since I've stopped following threads originated by him I don't know > what other grounds there would be. > > Cheers, > > --Tim > Who reads blogs? They're well known for housing crackpots far worse than Xah, and I estimate he doesn't want to associate himself with that sort. -- The science of economics is the cleverest proof of free will yet constructed. From grflanagan at yahoo.co.uk Mon May 15 07:25:43 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 15 May 2006 04:25:43 -0700 Subject: comparing values in two sets In-Reply-To: <1147682127.720957.200550@y43g2000cwc.googlegroups.com> References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> <1147682127.720957.200550@y43g2000cwc.googlegroups.com> Message-ID: <1147692343.247269.48860@j55g2000cwa.googlegroups.com> Gerard Flanagan wrote: > John Salerno wrote: > > I'd like to compare the values in two different sets to test if any of > > the positions in either set share the same value (e.g., if the third > > element of each set is an 'a', then the test fails). > > > > I have this: > > > > def test_sets(original_set, trans_letters): > > for pair in zip(original_set, trans_letters): > > if pair[0] == pair[1]: > > return False > > return True > > > > > > zip() was the first thing I thought of, but I was wondering if there's > > some other way to do it, perhaps a builtin that actually does this kind > > of testing. > > > > Thanks. > > 'enumerate' is another possibility: > > s1 = 'abcd' > s2 = 'zzzz' > s3 = 'zbzz' > s4 = 'zzbz' > > def are_itemwise_different( L1, L2 ): > #if len(L1) != len(L2): return True > for idx, value in enumerate(L1): > if value == L2[idx]: > return False > return True > > #after Peter Otten > def are_itemwise_different( L1, L2 ): > return True not in ( val == L2[idx] for idx, val in enumerate(L1) ) > > assert are_itemwise_different(s1,s2) > assert not are_itemwise_different(s1,s3) > assert are_itemwise_different(s1,s4) > s1 = 'abcd' s2 = 'zzzz' s3 = 'zbzz' s4 = 'zzbz' s5 = 'xbxx' def itemwise_intersect( L1, L2 ): return [value for idx, value in set(enumerate(L1)) & set(enumerate(L2))] assert itemwise_intersect(s1,s2) == [] assert itemwise_intersect(s1,s3) == ['b'] assert itemwise_intersect(s1,s4) == [] def itemwise_intersect( *args ): s = set(enumerate(args[0])) for t in ( set(enumerate(X)) for X in args[1:]): s.intersection_update(t) return [val for i,val in s] assert itemwise_intersect(s1,s3,s5) == ['b'] Gerard From t.buehler at codeforge.ch Wed May 31 06:17:35 2006 From: t.buehler at codeforge.ch (t.buehler at codeforge.ch) Date: Wed, 31 May 2006 12:17:35 +0200 Subject: Best Python Editor In-Reply-To: References: Message-ID: <20060531121735.6ux5xd6yvjvowgcw@webmail.codeforge.ch> PyScripter is small and fast. http://mmm-experts.com/Products.aspx?ProductId=4 > > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. > > Thank You, > -Manoj- > > > "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - > SURVEY 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" > > SASKEN BUSINESS DISCLAIMER > This message may contain confidential, proprietary or legally > Privileged information. In case you are not the original intended > Recipient of the message, you must not, directly or indirectly, use, > Disclose, distribute, print, or copy any part of this message and you > are requested to delete it and inform the sender. Any views expressed > in this message are those of the individual sender unless otherwise > stated. Nothing contained in this message shall be construed as an > offer or acceptance of any offer by Sasken Communication Technologies > Limited ("Sasken") unless sent with that express intent and with due > authority of Sasken. Sasken has taken enough precautions to prevent > the spread of viruses. However the company accepts no liability for > any damage caused by any virus transmitted by this email > -- > http://mail.python.org/mailman/listinfo/python-list > From http Sat May 6 10:36:49 2006 From: http (Paul Rubin) Date: 06 May 2006 07:36:49 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> <445c8812$0$31639$e4fe514c@news.xs4all.nl> Message-ID: <7xhd43qkxq.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > and clients make it quite scalable. For example, I'm creating a > xmlrpcserver that returns a randomized cardlist, but I because of > fail-over I needed some form of scalability , my solution was to first > randomize the deck then marshal it and dump the file on a ZFS > partition, giving back the client a ticket number, the client can then > connect with the ticket number to receive the cardlist (read the file > - unmarshal it). This is a weird approach. Why not let the "ticket" by the (maybe encrypted) PRNG seed that generates the permutation? > While this is overkill for 1 server, I needed multiple because of > fail-over and load-balancing, in this case I have 3 'crypto' boxes > (with hardware crypto engines using OpenBSD) doing only the > randomizing and 4 solaris machines doing the zfs and distribution of > the list. I don't know what good that hardware crypto is doing you, if you're then writing out the shuffled deck to disk in the clear. From dongdonglove8 at hotmail.com Fri May 19 09:29:59 2006 From: dongdonglove8 at hotmail.com (python) Date: 19 May 2006 06:29:59 -0700 Subject: about py2exe, I installed it, but can't find py2exe.exe in my computer. Message-ID: <1148045399.833782.106910@g10g2000cwb.googlegroups.com> I installed it, but can't find py2exe.exe in my computer. why? And , when I execute "python setup.py py2exe" under command line, it prompt error:wrong command "py2exe" . From hslee911 at yahoo.com Tue May 9 15:34:05 2006 From: hslee911 at yahoo.com (James) Date: 9 May 2006 12:34:05 -0700 Subject: How to recast integer to a string In-Reply-To: References: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> Message-ID: <1147203245.870258.64860@u72g2000cwu.googlegroups.com> Christoph Haas wrote: > On Tue, May 09, 2006 at 12:17:34PM -0700, James wrote: > > How to recast an integer to a string? > > > > something like > > n = 5 > > str = str + char(n) > > str(n) > > Kindly > Christoph In python2,4, I 've got TypeError: 'str' object is not callable J.L From g.brandl-nospam at gmx.net Tue May 16 03:08:57 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Tue, 16 May 2006 09:08:57 +0200 Subject: C API: getting sys.argv In-Reply-To: <1147750469.993824.112780@g10g2000cwb.googlegroups.com> References: <1147748640.699770.285430@g10g2000cwb.googlegroups.com> <1147749997.535248.71490@g10g2000cwb.googlegroups.com> <1147750469.993824.112780@g10g2000cwb.googlegroups.com> Message-ID: williams.jasonscott at gmail.com wrote: > John Machin wrote: >> > PyObject *_argv = PyImport_ImportModule("sys.argv"); >> >> What does the name of the function tell you? You can't do that in one >> hit. Start with >> PyObject *_sys = PyImport_ImportModule("sys"); >> then you need to get the module's argv attribute. > > I just figured this out, doh. Thanks. > >> However a better design might be have your extension module have an arg >> which can be *any* list of strings. That makes it more flexible, at the >> expense of making the caller pass sys.argv. But it would save you >> having to muck about with importing "sys", then plucking out the >> module's argv attribute. > > but this is great advice. Actually, use can use PySys_GetObject("argv") instead. Georg From sam at nuevageorgia.com Mon May 22 11:12:10 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 22 May 2006 08:12:10 -0700 Subject: Python - Web Display Technology In-Reply-To: References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> Message-ID: <1148310730.537959.265430@j55g2000cwa.googlegroups.com> "I guess for better or worse, Flash is a very different mindset and approach to the web." I do find it interesting that Flash folks readily will acknowledge that Flash has shortcomings, yet anti-Flash folks seem to have great difficulty acknowledging Flash's positive features over HTML. Such situations always make me suspicious Ludditism is at work. From arv.nntp at gmail.com Tue May 2 11:50:46 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Tue, 02 May 2006 17:50:46 +0200 Subject: ConfigParser and multiple option names In-Reply-To: References: Message-ID: Florian Lindner escribi?: > I think the best solution would be to use a seperation character: > > dir="/home/florian, /home/john, home/whoever" RCS uses , in filenames > What do you think? Any better ideas? A bit ugly, but probably safer and simpler than adding arbitrary separators: [section] dir_1=/home/florian dir_2=/home/john dir_3=/home/whoever a s(a|i)mple implementation to give you the idea, it has some bugs: import ConfigParser import re class ConfigParserWithLists(ConfigParser.ConfigParser): def setlist(self, section, option, value) : for i, v in enumerate(value) : self.set(section, '%s_%i' % (option, i + 1), v) def getlist(self, section, option) : res = [] m = re.compile('^' + option + '_\d+$').match for oo in self.options(section) : if m(oo) : res.append(self.get(section, oo)) return res HTH From spam4bsimons at yahoo.ca Sun May 28 15:23:52 2006 From: spam4bsimons at yahoo.ca (Brendan) Date: 28 May 2006 12:23:52 -0700 Subject: Serializing / Unserializing datetime In-Reply-To: <4478E634.8060001@lexicon.net> References: <1148751427.204676.238100@g10g2000cwb.googlegroups.com> <4478E634.8060001@lexicon.net> Message-ID: <1148844232.605364.192760@i40g2000cwc.googlegroups.com> Thanks John. I've discovered that datetime.strptime will be available in 2.5, (http://docs.python.org/dev/whatsnew/modules.html) but your example will work in the meantime. BJ From dont-email-me at nomail.org Fri May 26 13:14:34 2006 From: dont-email-me at nomail.org (Frank Goenninger DG1SBG) Date: Fri, 26 May 2006 19:14:34 +0200 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <1hfv0or.1krs4uf1704ou8N%wrf3@stablecross.com> Message-ID: John Bokma writes: > wrf3 at stablecross.com (Bob Felts) wrote: > >> Count me among the clueless, then. I just wrote to DreamHost and asked >> that they reverse their decision to terminate his account. > > I am sure that DreamHost has quite a nice /dev/null for clueless idiots > like you and your sock puppets :-D. > > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html John Bokma not following netiquette. Killfiled. If I can find out how to report this to the relevant ISP I will do so. Frank From rpw3 at rpw3.org Wed May 10 05:47:41 2006 From: rpw3 at rpw3.org (Rob Warnock) Date: Wed, 10 May 2006 04:47:41 -0500 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <1147194791.809735.251500@g10g2000cwb.googlegroups.com> <1hf33s3.1bdn2e4juoow0N%aleax@mac.com> Message-ID: Ketil Malde wrote: +--------------- | Sometimes the best documentation is the code itself. | Sometimes the best name for a function is the code itself. +--------------- And there's no reason that an anonymous LAMBDA [even if compiled] couldn't store its source code in the "name" slot for debugging printouts [e.g., stack backtraces]. -Rob ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From no.offline.contact.please at nospam.com Fri May 5 23:49:23 2006 From: no.offline.contact.please at nospam.com (Rhino) Date: Fri, 5 May 2006 23:49:23 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Message-ID: "I V" wrote in message news:pan.2006.05.06.01.59.38.15904 at gmail.com... > On Fri, 05 May 2006 17:26:26 -0700, Xah Lee wrote: >> Regarding the lambda in Python situation... conceivably you are right >> that Python lambda is perhaps at best left as it is crippled, or even >> eliminated. However, this is what i want: I want Python literatures, >> and also in Wikipedia, to cease and desist stating that Python supports >> functional programing. (this is not necessarily a bad publicity) And, I > > What does lambda have to do with supporting or not supporting functional > programming? > What does any of this have to do with Java? -- Rhino From agr at fq.uniovi.es Mon May 15 07:47:33 2006 From: agr at fq.uniovi.es (=?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?=) Date: Mon, 15 May 2006 13:47:33 +0200 Subject: List of lists of lists of lists... References: Message-ID: Robert Kern wrote: > James Stroud wrote: > http://numeric.scipy.org > Thanks! That's anotehr solution, yes! -- ?ngel Guti?rrez Rodr?guez - agr at fq.uniovi.es Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiation Facility - Grenoble - France Postal adress: Departamento de Qu?mica F?sica y Anal?tica Universidad de Oviedo - c/Juli?n Claver?a 8 33006 - Oviedo Asturias - Spain E-mail: agr at fq.uniovi.es Telf.: +34-985103687 From tjreedy at udel.edu Fri May 5 14:02:09 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 May 2006 14:02:09 -0400 Subject: Is this a good use of __metaclass__? References: Message-ID: "Joel Hedlund" wrote in message news:e3f96d$3oi$1 at news.lysator.liu.se... > Below, you'll find some background info and an executable code example. > > In the code example I have two ways of doing the same thing. The problem > is > that the "Neat" version doesn't work, and the "Ugly" version that works > gives > me the creeps. To me, your Ugly version is easier to read and understand than the so-called Neat version. You change an attribute of a class to change its behavior without changing its identity. I can imagine ways to hide this, but I would leave it simple and explicit. Terry Jan Reedy From lists at fabis-site.net Sat May 20 03:07:15 2006 From: lists at fabis-site.net (Fabian Steiner) Date: Sat, 20 May 2006 09:07:15 +0200 Subject: hidden file detection In-Reply-To: <1148078067.570279.116300@j33g2000cwa.googlegroups.com> References: <1148078067.570279.116300@j33g2000cwa.googlegroups.com> Message-ID: <446EC023.4050809@fabis-site.net> Lenny G. wrote: > What's the best way to do cross-platform hidden file detection? I want > to do something like weed-out the files that should be 'hidden' from > os.listdir() (which would be files that start with '.' under Unix, > files that have the hidden attribute set on windows, and whatever it is > that makes Mac files hidden). Is there a util or lib that does this > for me? > > Thanks, > Gary > From larry.bates at websafe.com Tue May 16 11:36:04 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 16 May 2006 10:36:04 -0500 Subject: constucting a lookup table In-Reply-To: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> References: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> Message-ID: <9aCdnR10Sej7bPTZnZ2dnUVZ_sidnZ2d@comcast.com> mhodkin at comcast.net wrote: > I'm new to Python and want to contruct a "lookup table" which would be > similar to a spreadsheet in that a value is read along the first > column, then along the top row, and the intersection of the two gives a > value that is hard-coded, i.e. not mathmatically related. An example > would be a table with HEIGHT in the first column, WEIGHT in the first > row, and estimated SUITSIZE with the body of the table. > > Which Python type would be most appropriate and/or efficient? > > thanks > I would not worry about being "efficient" at this point. There are not enough combinations of height/weight to make even a linear search through a list be a performance problem. One way would be to set up a dictionary that is keyed on height/weight and have it return suit size. To work properly you would need to express height in inches and weight in pounds (in US measurements). Something like: hwdict={(60, 80): , (61, 80): , (62, 80): , . . . (88, 400): } This would be fast because lookup would consist of only (not tested): try: suitsize=hwdict[(heightininches, weightinpounds)] except IndexError: print "height/weight combination not found in lookup table" -Larry Bates From roy at panix.com Mon May 8 11:26:24 2006 From: roy at panix.com (Roy Smith) Date: Mon, 8 May 2006 15:26:24 +0000 (UTC) Subject: which is better, string concatentation or substitution? References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> Message-ID: John Salerno wrote: >Roy Smith wrote: > >> One may be marginally faster, but they both require copying the source >> string, and are thus both O(n). > >Sorry, I'm not familiar with the O(n) notation. OK, here's a quick tutorial to "big-oh" notation. It's a way of measuring algorithmic complexity. The O stands for "on the Order of". For any algorithm, if you process n things (in the case of the strings we're talking about, n would be the total number of characters in all the strings), you can compute the number of steps it takes to complete all the processing as some function of n. For example, let's say a given algorithm took 4n^2 + 5n + 17 steps to complete. It doesn't take much experimentation to prove to yourself that for all but the very smallest values of n, the constant 17 is completely insignificant. In fact, n doesn't have to get very big before the 5n term becomes insignificant too. To a reasonable approximation, you could say that the algorithm takes 4n^2 steps and be close enough. For small values of n, this will be a bad approximation, but it doesn't really matter for small values of n. For large values of n (think hundreds, thousands or even millions), it's just fine. So, the first rule of O() notation is that when looking at how fast an algorithm runs, you need only consider the highest order term (i.e. the one with the biggest exponent). But, it gets even better. Let's compare two algorithms, the one above, which takes (approximately) 4n^2 steps, and another one which takes 10n steps, for varous values of n: n 10n 4n^2 --- ------ ------ 1 10 4 2 20 16 3 30 36 4 40 64 5 50 100 6 60 144 7 70 196 8 80 256 9 90 324 10 100 400 11 110 484 12 120 576 13 130 676 14 140 784 15 150 900 16 160 1024 17 170 1156 18 180 1296 19 190 1444 20 200 1600 Notice that it doesn't take long for the fact that n^2 grows a lot faster than n to swamp the fact that 10 is bigger than 4. So the next step in simplification is to say that not only don't the lower-order terms matter, but the coefficient on the highest order term doesn't even matter. For a large enough n, all that matters is the exponent (for the moment, I'm making a further simplification that all algorithms can be described by polynomials with integer exponents). So, we get things like: O(n^0), which is almost always written as O(1). This is a "constant time" algorithm, one which takes the same amount of steps to execute no matter how big the input is. For example, in python, you can write, "x = 'foo'". That assignment statement takes the same amount of time no matter how long the string is. All of these execute in the same number of steps: x = '' x = 'foo' x = 'a very long string with lots and lots of characters' We can say that "assignment is constant time", or "assignment is O(1)". The next step up is O(n). This is "linear time" algorithm. It takes a number of steps which is directly proportional to the size of the input. A good example might be "if 'x' in 'bar'". The obvious way to implement this (and, I assume, the way it is implemented in Python), is to loop over the string, comparing 'x' to each character in 'bar', one by one. This takes as many steps as there are characters in the string. Next comes O(n^2), also knows as "quadratic time". This means if your input is of size n, the algorithm will take n^2 steps to run. Quadratic algorithms are generally considered very slow, and to be avoided if at all possible. Once you get used to thinking like this, it's easy to look at a piece of code and say, "oh, that's quadratic", or "that's linear", and instantly know which is faster for some some large input. And once you've started thinking like that, you've made one of the big jumps from thinking like a coder to thinking like a computer scientist (or, if you prefer, like a software engineer). Google "algorithmic complexity" or "big o notation" (perhaps spelled "big oh") for more info. I would normally recommend Wikipedia, but I just took a quick look at their "Big O notation" article, and noticed it's full of formal mathematical gobbledygook which just serves to obscure what is really a fairly easy concept. From tdw at tdw.net Thu May 4 07:57:08 2006 From: tdw at tdw.net (Tim Williams) Date: Thu, 4 May 2006 12:57:08 +0100 Subject: Swaying A Coder Away From Python In-Reply-To: References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> Message-ID: <9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> > (and why do you > seem to think that this matters, btw ?) I actually think it is complete twaddle, for the same reasons as you. It was forwarded to me by someone who knows I use Python, and I thought it might be of interest to a balanced list, especially as it shows an external perspective of Python. Are we not allowed to post negative things about Python anymore or did I miss the point ?? From bdesth.quelquechose at free.quelquepart.fr Mon May 15 19:46:05 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 May 2006 01:46:05 +0200 Subject: common practice for creating utility functions? In-Reply-To: <7xd5efdstn.fsf@ruckus.brouhaha.com> References: <7xd5efdstn.fsf@ruckus.brouhaha.com> Message-ID: <4468e3af$0$7129$626a54ce@news.free.fr> Paul Rubin a ?crit : > John Salerno writes: > >>So my first question is this: should I make a Cryptogram class for >>this, or are functions fine? If the latter, then back to my original >>point: can I do something like this: >> >>def convert_quote(quote): >> return make_code(quote) > > > It's fine to do that if it expresses your intentions more clearly. Then it would be better to just alias it: # def convert_quote(quote): # return make_code(quote) convert_quote = make_code About the "fine to do" part, remember that Python's function calls are rather expansive... From maxerickson at gmail.com Thu May 25 11:13:54 2006 From: maxerickson at gmail.com (Max Erickson) Date: Thu, 25 May 2006 15:13:54 +0000 (UTC) Subject: regex/lambda black magic References: <127be5or10v59e9@corp.supernews.com> Message-ID: Andrew Robert wrote: > ValueError: invalid literal for int(): % > > Does anyone see what I am doing wrong? > Try getting rid of the lamba, it might make things clearer and it simplifies debugging. Something like(this is just a sketch): def callback(match): print match.group() return chr(int(match.group(),16)) % ord(match.group()) output.write(re.sub('r([^\w\s])', callback, line) It looks like your match.group is a '%' character: >>> int('%', 16) Traceback (most recent call last): File "", line 1, in ? int('%', 16) ValueError: invalid literal for int(): % >>> max From cristian.codorean at gmail.com Fri May 12 04:17:32 2006 From: cristian.codorean at gmail.com (Cristian.Codorean) Date: 12 May 2006 01:17:32 -0700 Subject: String concatenation performance In-Reply-To: <4463a4f7$0$286$636a55ce@news.free.fr> References: <1147355908.655992.5720@g10g2000cwb.googlegroups.com> <4463a4f7$0$286$636a55ce@news.free.fr> Message-ID: <1147421852.598683.203860@u72g2000cwu.googlegroups.com> Thanks guys ! Growing and learning :) From onurb at xiludom.gro Fri May 5 13:32:56 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 19:32:56 +0200 Subject: to thine own SELF be true... In-Reply-To: References: Message-ID: <445b8ca5$0$1491$626a54ce@news.free.fr> Mark Harrison wrote: > Is there a way to do something equivalent to "import * from self"? (snip) > > Is there a way to get rid of those the "self." references, No. > or is this > just something I need to get my brain to accept? Yes. And FWIW, "from somemodule import *" is usually considered bad style. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mahs at telcopartners.com Wed May 17 15:20:00 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 17 May 2006 12:20:00 -0700 Subject: How to add columns to python arrays In-Reply-To: References: <1147882432.166728.207820@j55g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > "CC" wrote in message > news:1147882432.166728.207820 at j55g2000cwa.googlegroups.com... >> I wanna compile a 6000x1000 array with python. The array starts from >> 'empty', each time I get a 6000 length list, I wanna add it to the >> exist array as a column vector. Is there any function to do so? >> >> Or, I can add the list as a rows, if this is easier, and transpose the >> whole array after all the rows are setup. > > Python does not come with a 2D array type either as a builtin type or as a > standard library module. You can only simulate one with a sequence of > sequences (list of lists, for instance). You could initialize as follows: > > aray = [] > for l6000 in source(): aray.append(l6000) > > While this will print as a list of rows, you are free to think of it as a > list of columns. > > That said, I suspect you should use the 3rd party NumPy package which > defines multiple-dimensional arrays of several base types. > > Terry Jan Reedy > > > If you're just looking for a multi-dimensional array type, and don't need maximum speed or the vast range of array-processing that numpy offers, then *pyarray* provides a pure-python single module solution. the latest pyarray is available with tests and documentation at: http://svn.brownspencer.com/pyarray/trunk/ Introduction ============ pyarray is a pure-Python implementation of a multi-dimensional array type. pyarray.ListView and pyarray.ArrayView offer a substantial subset of numpy.ArrayType functionality, by wrapping standard python 'list' and 'array.array' respectively. Key features include: * Views: all subscripting operations apart from individual cell access access return views to existing 'live' data * Extended Indexing: slicing, arbitrary 'takes', index arrays etc... * Unlimited re-shaping: while still addressing one data-source * Elementwise binary operations: all basic arithmetic and comparison operations * Data broadcasting: allows assignment and binary operations between views of different shapes * Friendly __repr__: work safely with big arrays at the interactive prompt Regards Michael From clpy at russellsalsbury.com Mon May 1 16:10:01 2006 From: clpy at russellsalsbury.com (Russ Salsbury) Date: 1 May 2006 13:10:01 -0700 Subject: stdin: processing characters References: <2Bd4g.21380$tN3.16246@newssvr27.news.prodigy.net> <1146423801.634307.100970@g10g2000cwb.googlegroups.com> <1146486777.878616.319980@y43g2000cwc.googlegroups.com> Message-ID: <1146514201.750329.237970@e56g2000cwe.googlegroups.com> Serge Orlov wrote: > Kevin Simmons wrote: > > Looks reasonable if you don't need portability. But you may want to > refactor it a little bit to make sure terminal setting are always > restored: > > try: > do_all_the_work() > finally: > os.system("stty cooked") > IIRC You need to do "stty raw" first. The last time I had to do this was in the '80's, so take for what it's worth. Russ From lonetwin.nospam at yahoo.com Thu May 18 13:08:28 2006 From: lonetwin.nospam at yahoo.com (Steve) Date: Thu, 18 May 2006 22:38:28 +0530 Subject: [silly] Does the python mascot have a name ? References: Message-ID: Carl J. Van Arsdall wrote: > John D Salt wrote: >> >>>>> hon-list/2003-September/185612.html >>>>> >>>> "Odi" must be the Dutch for "Monty". >>>> >>> Nope. If it was Dutch it would probably be Odie >>> >> Damn. >> >> > Odi(e) was a punk. I'm gonna be a rebel without a cause and stay with > Monty ;) Yes ! Monty sounds much better ! ...also imagine the expression on the PHB's face if this were to happen ... PHB: So, why is the language called python ? DEV: Well, it is named after Monty Python. PHB: Eh, but you just said the mascot was called Monty. Do you mean the language was named after it's mascot ??!!?? DEV: Eh, yeah. They spent a lot of time deciding the mascot and naming it, before they designed the language. Regards Steve From andrew.arobert at gmail.com Sat May 13 21:55:13 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sat, 13 May 2006 21:55:13 -0400 Subject: Question regarding checksuming of a file In-Reply-To: References: <126d1u4ke4itg7f@corp.supernews.com> Message-ID: <126d3g8tkfovs19@corp.supernews.com> Roy Smith wrote: >> >> However this does not appear to be actually returning the checksum. >> >> Does anyone have insight into where I am going wrong? > > After calling update(), you need to call digest(). Update() only updates > the internal state of the md5 state machine; digest() returns the hash. > Also, for the code above, it's m.update(), not md5.update(). Update() is a > method of an md5 instance object, not the md5 module itself. > > Lastly, the md5 algorithm is known to be weak. If you're doing md5 to > maintain compatability with some pre-existing implementation, that's one > thing. But, if you're starting something new from scratch, I would suggest > using SHA-1 instead (see the sha module). SHA-1 is much stronger > cryptographically than md5. The Python API is virtually identical, so it's > no added work to switch to the stronger algorithm. Hi Roy, This is strictly for checking if a file was corrupted during transit over an MQSeries channel. The check is not intended to be used for crypto purposes. From piet at cs.uu.nl Mon May 15 04:49:15 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Mon, 15 May 2006 10:49:15 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> Message-ID: >>>>> Edward Elliott (EE) wrote: >EE> Piet van Oostrum wrote: >>>>>>>> tsaar2003 at yahoo.com (T) wrote: >>> >T> As you can see, the "constant" A can be modified this easily. But if >T> there were an intuitive mechanism to declare a symbol to be immutable, >T> then there won't be this problem. >>> >>> Mutability is not a property of symbols but of values. So it doesn't make >>> sense to declare an identifier to be immutable. And mutability is tied to >>> the object's type, not to individual instances. >EE> I think he meant immutable binding, not immutable symbol. So >EE> rebinding/overshadowing a "constant" A would raise an error, but >EE> mutating the underlying object A refers to would not (unless it too >EE> were immutable). The way I understood it was that he meant both. -- Piet van Oostrum URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From __peter__ at web.de Tue May 2 07:24:48 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 May 2006 13:24:48 +0200 Subject: string.find first before location References: <87hd49m0xc.fsf@localhost.localdomain> <87zmi0emhd.fsf@localhost.localdomain> Message-ID: Gary Wessle wrote: >> These days str methods are preferred over the string module's functions. >> >> >>> text = "abc abc and Here and there" >> >>> here_pos = text.find("Here") >> >>> text.rfind("abc", 0, here_pos) >> 4 >> >> Peter > > and what about when python 3.0 is released and those depreciated > functions like find and rfind are not supported. is there another > solution which is more permanent? I think the functions may go away, the methods will stay; so I'm confident the above will continue to work. Peter From http Sat May 6 13:41:00 2006 From: http (Paul Rubin) Date: 06 May 2006 10:41:00 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> <445c8812$0$31639$e4fe514c@news.xs4all.nl> <7xhd43qkxq.fsf@ruckus.brouhaha.com> <445cb8e6$0$31641$e4fe514c@news.xs4all.nl> Message-ID: <7x3bfnvyoj.fsf@ruckus.brouhaha.com> "Martin P. Hellwig" writes: > > This is a weird approach. Why not let the "ticket" by the (maybe > > encrypted) PRNG seed that generates the permutation? > > Because the server that handles the generate request doesn't need to > be the same as the one that handles the request to give the client > that deck. Wait a sec, are you giving the entire shuffled deck to the client? Can you describe the application? I was imagining an online card game where clients are playing against each other. Letting any client see the full shuffle is disastrous. > But if the ticket is given to the client, than any other server can > serve back that ticket to give the shuffled deck, unless the ZFS dies > of course but then again thats why I use ZFS so I can mirror them om 4 > different machines in 2 different locations. > > I don't know what good that hardware crypto is doing you, if you're > > then writing out the shuffled deck to disk in the clear. > > It's not about access security it's more about the best possible > randomness to shuffle the deck. Depending on just what the server is for, access security may be a far more important issue. If I'm playing cards online with someone, I'd be WAY more concerned about the idea of my opponent being able to see my cards by breaking into the server, than his being able to cryptanalyze a well-designed PRNG based solely on its previous outputs. From bigblueswope at gmail.com Sun May 21 17:32:13 2006 From: bigblueswope at gmail.com (BJ Swope) Date: Sun, 21 May 2006 17:32:13 -0400 Subject: Slicing Issues In-Reply-To: <200605212301.35778.me+python@modelnine.org> References: <200605212301.35778.me+python@modelnine.org> Message-ID: On 5/21/06, Heiko Wundram wrote: > > Am Sonntag 21 Mai 2006 22:52 schrieb BJ Swope: > > district_combo=line[85:3] > > This returns the slice from character 85 to character 3 in the string, > read > forwards. Basically, as Python slices are forgiving (because the borders > are > actually "illogical"), this amounts to nothing, but could also amount > to: "your indexing boundaries are invalid." > > Basically, what you want is: > > district_combo = line[85:88] > > where 88 = 85 + 3 (3 being the length). Read up on Python slices... > > --- Heiko. > -- > http://mail.python.org/mailman/listinfo/python-list > Heiko, Thank you. I was thinking like mysql for the indexs. Thinking start at 85 and go for 3 characters instead of like python start at x and go up to and including y. The pages I had googled showed examples that were less than clear ;) BJ -- We are all slave to our own paradigm. -- Joshua Williams -------------- next part -------------- An HTML attachment was scrubbed... URL: From johnjsal at NOSPAMgmail.com Wed May 17 16:10:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 20:10:31 GMT Subject: creating a new database with mysqldb In-Reply-To: References: <1147893204.503850.225770@j73g2000cwa.googlegroups.com> Message-ID: Heiko Wundram wrote: > Of course, you need to log on with a user who is allowed to create databases. yeah, this is where I'm stuck. The only "logging on" i know how to do is with the connect method, but that requires a database to exist already From michele.simionato at gmail.com Wed May 10 12:20:18 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 May 2006 09:20:18 -0700 Subject: New tail recursion decorator In-Reply-To: <1147272325.625020.108840@y43g2000cwc.googlegroups.com> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <1147272325.625020.108840@y43g2000cwc.googlegroups.com> Message-ID: <1147278018.379814.85300@j33g2000cwa.googlegroups.com> Michele Simionato wrote: > Using my decorator module 'tail_recursive' can even be turned in a > signature-preserving > decorator. I think I will add this great example to the documentation > of the next version > of decorator.py! > > Michele Simionato Done: see http://www.phyast.pitt.edu/~micheles/python/decorator.zip and http://www.phyast.pitt.edu/~micheles/python/documentation.html From DustanGroups at gmail.com Thu May 18 18:35:43 2006 From: DustanGroups at gmail.com (Dustan) Date: 18 May 2006 15:35:43 -0700 Subject: Which is More Efficient? In-Reply-To: References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> <1147990753.406649.80150@y43g2000cwc.googlegroups.com> Message-ID: <1147991742.990761.144730@j73g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > >> 2. Measure it. > > > > Tell me how and I will; I'm not nearly that much of a geek > > unfortunately. > > do you have to be a geek to be able to measure how much time > something takes? Obviously it takes a geek to know you have to time it, as opposed to any other task you could be talking about. > > From a.schmolck at gmail.com Thu May 11 18:03:23 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 11 May 2006 23:03:23 +0100 Subject: Matplotlib in Python vs. Matlab, which one has much better graphical pressentation? References: Message-ID: N/A writes: > Hi all, > > Can I have your opinions on Matlab vs. Matplotlib in Python in terms of 2D and > 3D graphical presentation please. > > > Matplotlib in Python vs. Matlab, which one has much better graphical > pressentation? As far as 2D plots are concerned I think matplotlib has been superior for some time now, but 3D plot support is only in the making (other options do exist, but I haven't tried MayaVi and co). However, if you've got a license for matlab anyway, you can also fairly easily use it from python and mix and match as required (see my mlabwrap module at ). E.g. do do a pretty surface plot from python, try: >>> from mlabwrap import mlab; from scipy import * >>> xx = arange(-2*pi, 2*pi, 0.2) >>> mlab.surf(subtract.outer(sin(xx),cos(xx))) Once matplotlib is up to the task, it should be easy to get rid of matlab dependencies in you code. 'as From gsocks at gmail.com Fri May 19 01:21:23 2006 From: gsocks at gmail.com (gsocks at gmail.com) Date: 18 May 2006 22:21:23 -0700 Subject: import woe Message-ID: <1148016083.020020.40660@u72g2000cwu.googlegroups.com> hello, i have a problem. i would like to import python files above and below my current directory. i'm working on /home/foo/bar/jar.py i would like to import /home/foo/car.py and /home/foo/bar/far.py how can i do this? thank you, bob ps: i want to scale, so i do not want to edit the python path From larry.bates at websafe.com Mon May 8 09:26:47 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 08 May 2006 08:26:47 -0500 Subject: reading a column from a file In-Reply-To: <87y7xd83rc.fsf@localhost.localdomain> References: <87y7xd83rc.fsf@localhost.localdomain> Message-ID: <445F4717.9080103@websafe.com> Check out the csv module. -Larry Bates Gary Wessle wrote: > Hi > > I have a file with data like > location pressure temp > str floot floot > > I need to read pressure and temp in 2 different variables so that I > can plot them as lines. is there a package which reads from file with > a given formate and returns desired variables? or I need to open, > while not EOF read, parse, build list, return? > > thanks From kay.schluehr at gmx.net Wed May 10 05:36:16 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 10 May 2006 02:36:16 -0700 Subject: New tail recursion decorator In-Reply-To: <4cdnouF15dmjfU1@uni-berlin.de> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> Message-ID: <1147253776.042505.34430@j73g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > Kay Schluehr wrote: > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > > Neat. > > Diez Hi Diez, for all those who already copied and pasted the original solution and played with it I apologize for radical changes in the latest version ( the recipe is on version 1.5 now ! ). The latest implementation is again a lot faster than the previous one. It does not only get rid of exceptions but also of stack-frame inspection. Regards, Kay From Serge.Orlov at gmail.com Sun May 7 02:17:34 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 6 May 2006 23:17:34 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> Message-ID: <1146982654.897283.293390@y43g2000cwc.googlegroups.com> Ken Tilton wrote: > It is vastly more disappointing that an alleged tech genius would sniff > at the chance to take undeserved credit for PyCells, something probably > better than a similar project on which Adobe (your superiors at > software, right?) has bet the ranch. This is the Grail, dude, Brooks's > long lost Silver Bullet. And you want to pass????? > > C'mon, Alex, I just want you as co-mentor for your star quality. Of > course you won't have to do a thing, just identify for me a True Python > Geek and she and I will take it from there. > > Here's the link in case you lost it: > > http://www.lispnyc.org/wiki.clp?page=PyCells > > :) > > peace, kenny > > ps. flaming aside, PyCells really would be amazingly good for Python. > And so Google. (Now your job is on the line. ) k Perhaps I'm missing something but what's the big deal about PyCells? Here is 22-lines barebones implementation of spreadsheet in Python, later I create 2 cells "a" and "b", "b" depends on a and evaluate all the cells. The output is a = negate(sin(pi/2)+one) = -2.0 b = negate(a)*10 = 20.0 =================== spreadsheet.py ================== class Spreadsheet(dict): def __init__(self, **kwd): self.namespace = kwd def __getitem__(self, cell_name): item = self.namespace[cell_name] if hasattr(item, "formula"): return item() return item def evaluate(self, formula): return eval(formula, self) def cell(self, cell_name, formula): "Create a cell defined by formula" def evaluate_cell(): return self.evaluate(formula) evaluate_cell.formula = formula self.namespace[cell_name] = evaluate_cell def cells(self): "Yield all cells of the spreadsheet along with current values and formulas" for cell_name, value in self.namespace.items(): if not hasattr(value, "formula"): continue yield cell_name, self[cell_name], value.formula import math def negate(x): return -x sheet1 = Spreadsheet(one=1, sin=math.sin, pi=math.pi, negate=negate) sheet1.cell("a", "negate(sin(pi/2)+one)") sheet1.cell("b", "negate(a)*10") for name, value, formula in sheet1.cells(): print name, "=", formula, "=", value From j.paston.cooper at gmail.com Mon May 15 09:26:40 2006 From: j.paston.cooper at gmail.com (j.paston.cooper at gmail.com) Date: 15 May 2006 06:26:40 -0700 Subject: Web development with python. Message-ID: <1147699600.770756.123120@v46g2000cwv.googlegroups.com> Is Plone analoguous to ASP.NET? Is it a python web developing platform? I am confused on what Turbogears is aswell because of the lack of documentation for it. From jjl at pobox.com Thu May 4 13:51:55 2006 From: jjl at pobox.com (John J. Lee) Date: 04 May 2006 17:51:55 +0000 Subject: Python for Perl programmers References: Message-ID: <87wtd1k79g.fsf@pobox.com> "A.M" writes: > Is there any efficient online resource or book that help experienced Perl > programmers to Python? Worry instead about how you're going to keep maintaining your Perl code after you've developed an allergic response to it. <0.5 wink> John From ljelmore_ at comcast.net Wed May 24 20:29:11 2006 From: ljelmore_ at comcast.net (Larry Elmore) Date: Wed, 24 May 2006 19:29:11 -0500 Subject: John Bokma harassment In-Reply-To: <87ejyjv40w.fsf@rpi.edu> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <87ejyjv40w.fsf@rpi.edu> Message-ID: Bill Atkins wrote: > John Bokma writes: > > >>Ken Tilton wrote: >> >> >>>Ben Bullock wrote: >>> >>>>"Xah Lee" wrote in message >>>>news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... >>>> >>>> >>>>>If you believe this lobbying to my webhosting provider is unjust, >>>>>please write to my web hosting provider abuse at dreamhost.com >>>> >>>> >>>>Why don't you just change your provider? It would take less time than >>>>this. >>> >>>Are you joking. "Just change your provider?" Do you have a little >>>button on your computer that says "Change provider"? Cool! :) >> >>No, it will cost Xah money. In the end he will be with a bullet proof >>hoster, like other kooks on Usenet, or get the message. >> >> >>>C'mon, John Bokma (and everyone else dumb enough to crosspost their >>>shushing to every group on the crosspost list -- why do they do that? >> >>So other people can read that reporting Xah *does* have an effect. A lot >>of people think that a kill file is the only solution. > > > You win my unofficial contest for "Usenet Tool of the Year." It is > not difficult to skip to the next file or to add a sender to a > killfile. It is certainly less of a hassle than all this complaining > you do. No shit. Lately it seems that for every "spam" post of Xah's, there's at three or more by John *to all the same newsgroups* bitching about Xah's use of bandwidth. Pot, meet kettle. I'm killfiling Xah for being a useless twit and killfiling John for being a prick about it. --Larry From onurb at xiludom.gro Fri May 5 12:01:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 18:01:22 +0200 Subject: Is this a legal / acceptable statement ? In-Reply-To: <35K6g.8733$B42.4422@dukeread05> References: <2AI6g.10201$9c6.5375@dukeread11> <-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> <445b67bb$0$16736$626a54ce@news.free.fr> <35K6g.8733$B42.4422@dukeread05> Message-ID: <445b7730$0$23440$626a54ce@news.free.fr> Philippe Martin wrote: > bruno at modulix wrote: > > >>Philippe Martin wrote: >>(snip) >> >>>l_init really is a boolean parameter and l_value a value that _might_ >>>exist in a shelve. >>> >>>So I just want to have a parameter to a method so if the first value >>>tested is false (l_init) then the second (l_value) does not get tested >>>... because it is the second in the statement and only seems to get >>>evaluated if the first one is true. >> >>s/seems to get/is/ >> >>But this is a really unpythonic way to do things IMHO. Either use a >>try/except block (probably the most straightforward solution), or, as in >>Larry's post, test for the existence of 'l_value' in locals(). >> >>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('@')])" > > > Well, that was the question - I wanted to avoid that because I'm already in > a try/except and do not like to imbricate them too much. Then reads Fredrik's answer and this: ''' Help on module shelve: (...) DESCRIPTION A "shelf" is a persistent, dictionary-like object. (...) """ What about : if shelf.has_key('l_value'): ... ?-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From grflanagan at yahoo.co.uk Tue May 23 16:12:20 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 23 May 2006 13:12:20 -0700 Subject: UPDATE: Generating Cutter numbers References: <1148114166.590393.176250@u72g2000cwu.googlegroups.com> Message-ID: <1148415140.448561.147760@38g2000cwa.googlegroups.com> Gerard Flanagan wrote: > All > > would anyone happen to have code to generate Cutter Numbers: > > eg. http://www1.kfupm.edu.sa/library/cod-web/Cutter-numbers.htm > > or is anyone looking for something to do?-) (I'm under pressure!) > > def cutter(lname, fname, book_title): > > (maybe more to it than that). > > > cheers > > Gerard Just for the archives - used a Cutter-Sanborn table obtained by html-scraping (BeautifulSoup). The final Cutter will depend on the Cutters of existing books on the same shelf. ------------------------------------------------------------------------------------------- from urllib import urlopen from BeautifulSoup import BeautifulSoup as Soup baseurl = 'http://www.librarian.or.kr/reference/mark/cutter%s.htm' out = open('cutter2.txt','w') try: for i in range(1,10): html = urlopen(baseurl % i).read() soup = Soup(html) for pre in soup('pre'): for line in pre.string.split('\n'): out.write(line.strip().replace(' ', ' ') + '\n') finally: out.close() ------------------------------------------------------------------------------------------- 111 Aa 112 Aal 113 Aar 114 Aars 115 Aas 116 Aba 117 Abal 118 Abar 119 Abat 121 Abau 122 Abb 123 Abbat 124 Abbe 125 Abbo ... 86 Zol 87 Zon 88 Zop 89 Zot 91 Zou 92 Zs 93 Zu 94 Zuc 95 Zun 96 Zur 97 Zw 98 Zwi 99 Zy From robert.kern at gmail.com Sun May 21 02:13:14 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 May 2006 01:13:14 -0500 Subject: Feature request: sorting a list slice In-Reply-To: References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > Robert Kern wrote: >>I believe that John was asking George for a use case rather than asking Fredrik >>what a use case was. > > In which case, as I pointed out, John would have done better to quote a > little more context. No argument 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 alanalan at newsgroup.nospam Wed May 31 12:38:21 2006 From: alanalan at newsgroup.nospam (A.M) Date: Wed, 31 May 2006 12:38:21 -0400 Subject: Oracle Data Access in Python Message-ID: Hi, I am familiar with Perl's DBI programming. In Python, do we access to Oracle by using DBI? Is Oracle DBD driver included with Python distributions? What is the most common strategy for accessing to Oracle data through Python? Any help would be appreciated, Alan From imckmavuks at mailinator.com Wed May 24 06:35:19 2006 From: imckmavuks at mailinator.com (Alan) Date: 24 May 2006 03:35:19 -0700 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <1148466919.006694.191310@u72g2000cwu.googlegroups.com> With apologies to Voltaire: If Xah Lee did not exist, it would be necessary for John Bokma to invent him. Xah and Bokma are both idiots, they truly deserve each other. The sooner you killfile these two clowns, the happier you'll be. From chris at foote.com.au Wed May 17 09:28:20 2006 From: chris at foote.com.au (Chris Foote) Date: Wed, 17 May 2006 22:58:20 +0930 Subject: Large Dictionaries In-Reply-To: <1147818548.532882.94180@i39g2000cwa.googlegroups.com> References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> Message-ID: <1147874585.728471@teuthos> Klaas wrote: >> 22.2s 20m25s[3] > > 20m to insert 1m keys? You are doing something wrong. Hi Mike. I've put together some simplified test code, but the bsddb module gives 11m for 1M keys: Number generator test for 1000000 number ranges with a maximum of 3 wildcard digits. Wed May 17 22:18:17 2006 dictionary population started Wed May 17 22:18:26 2006 dictionary population stopped, duration 8.6s Wed May 17 22:18:27 2006 StorageBerkeleyDB population started Wed May 17 22:29:32 2006 StorageBerkeleyDB population stopped, duration 665.6s Wed May 17 22:29:33 2006 StorageSQLite population started Wed May 17 22:30:38 2006 StorageSQLite population stopped, duration 65.5s test code is attached. > With bdb's it is crucial to insert keys in bytestring-sorted order. For the bsddb test, I'm using a plain string. (The module docs list a string being the only datatype supported for both keys & values). > Also, be sure to give it a decent amount of cache. The bsddb.hashopen() factory seems to have a bug in this regard; if you supply a cachesize argument, then it barfs: ... File "bsddb-test.py", line 67, in runtest db = bsddb.hashopen(None, flag='c', cachesize=8192) File "/usr/lib/python2.4/bsddb/__init__.py", line 288, in hashopen if cachesize is not None: d.set_cachesize(0, cachesize) bsddb._db.DBInvalidArgError: (22, 'Invalid argument -- DB->set_cachesize: method not permitted when environment specified') I'll file a bug report on this if it isn't already fixed. Cheers, Chris -------------- next part -------------- A non-text attachment was scrubbed... Name: bsddb-test.py Type: text/x-python Size: 3387 bytes Desc: not available URL: From rzvncj at gmail.com Mon May 8 05:13:36 2006 From: rzvncj at gmail.com (Razvan Cojocaru) Date: 8 May 2006 02:13:36 -0700 Subject: Python CHM Doc Contains Broken Links on Linux in xCHM. In-Reply-To: <1147025957.253391.125240@i40g2000cwc.googlegroups.com> References: <1147025957.253391.125240@i40g2000cwc.googlegroups.com> Message-ID: <1147079616.383506.257220@j73g2000cwa.googlegroups.com> > Is this a problem with the chm docs themselves OR is it a problem with > xCHM? The same chm works just fine on Windows whereas on Linux I am > having problems. Anyone experiencing the same? is a fix coming? It's already been fixed. You're running an old version (the screenshot says 1.2). The latest official release version is 1.7.1. I believe that problem has been fixed since 1.7. From vbgunz at gmail.com Mon May 8 22:27:50 2006 From: vbgunz at gmail.com (vbgunz) Date: 8 May 2006 19:27:50 -0700 Subject: Memory leak in Python In-Reply-To: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> Message-ID: <1147141670.020009.168290@e56g2000cwe.googlegroups.com> how big is the set? 100MB, more? what are you doing with the set? do you have a small example that can prove the set is causing the freeze? I am not the sharpest tool in the shed but it sounds like you might be multiplying your set in/directly either permanently or temporarily on purpose or accident. From gunsupancar at yahoo.co.uk Thu May 25 04:09:40 2006 From: gunsupancar at yahoo.co.uk (gunsupancar) Date: Thu, 25 May 2006 08:09:40 -0000 Subject: access to TimesTen using python Message-ID: is there any module to access TimesTen in-memory database using python? From raims at dot.com Mon May 8 03:09:44 2006 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 08 May 2006 09:09:44 +0200 Subject: Why list.sort() don't return the list reference instead of None? References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> <1147071499.135783.193610@e56g2000cwe.googlegroups.com> Message-ID: <87r7359emf.fsf@voodoo.myself> "ankyhe at gmail.com" writes: > However, I wonder why L.sort() don't return the reference L, the > performance of return L and None may be the same. It's not "the same". sort() does not return anything. > Why? I've just explained to you and so the others: by default operations on mutable objects are in place. s = "abc" s.upper() does return another string. String are immutable references. -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From gshepherd281281 at yahoo.com Wed May 3 15:25:00 2006 From: gshepherd281281 at yahoo.com (ProvoWallis) Date: 3 May 2006 12:25:00 -0700 Subject: NewB question on text manipulation In-Reply-To: References: <1146634624.622224.323010@u72g2000cwu.googlegroups.com> <1146677395.523919.319760@i39g2000cwa.googlegroups.com> Message-ID: <1146684300.362421.321370@u72g2000cwu.googlegroups.com> Thanks again and sorry about the lack of examples. It didn't even occur to me that my example wasn't comprehensive enough when I posted my first message but I can see the issue now. Your solution is really helpful for me to see. I can't tell you how much I apprecaite it. I thought that adding more values to the tuple was the way to go but couldn't get my mind around how to capture the info that I needed. Thanks! From trebucket at gmail.com Tue May 16 21:51:19 2006 From: trebucket at gmail.com (trebucket at gmail.com) Date: 16 May 2006 18:51:19 -0700 Subject: help with this simple DB script References: <446a7849$0$1901$c3e8da3@news.astraweb.com> Message-ID: <1147830679.941943.310290@i40g2000cwc.googlegroups.com> This is probably causing a problem: !#/usr/bin/python It should be "#!", not "!#". If that doesnt' work, add this line at the top of your script, to check that the script is begin executed: print "Content-Type: text/html\n\n" print "Hello, World!" If you still get an Internal Server Error put the following before you import MySQLdb: import cgitb; cgitb.enable() Hope this helps, - Alex Ross From ptmcg at austin.rr._bogus_.com Tue May 9 12:04:36 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 09 May 2006 16:04:36 GMT Subject: What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY? References: <1147175821.309279.271730@j33g2000cwa.googlegroups.com> Message-ID: "glomde" wrote in message news:1147175821.309279.271730 at j33g2000cwa.googlegroups.com... > Hi I would like to extend python so that you could create hiercical > tree structures (XML, HTML etc) easier and that resulting code would be > more readable. > > The syntax i would like is something like the below: > > # Example creating html tree > > '*!*' is an operator that creates an new node > '*=*' is an operator that sets an attribute. > It's not quite so syntactically sugary, but it looks like much of the functionality you are looking for is in elementTree, which will be incorporated into 2.5 (or you can download and install yourself from http://www.effbot.org/downloads/#elementtree). -- Paul From petr at tpc.cz Sat May 6 22:37:37 2006 From: petr at tpc.cz (Petr Jakes) Date: 6 May 2006 19:37:37 -0700 Subject: ANN: eric3 3.9.0 released In-Reply-To: References: Message-ID: <1146969457.495258.226730@j33g2000cwa.googlegroups.com> I think you can get the answer on http://www.die-offenbachs.de/detlev/eric3-mailinglist.html rather then here. HTH Petr Jakes From no-spam at no-spam-no-spam.com Tue May 16 16:48:55 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Tue, 16 May 2006 22:48:55 +0200 Subject: SystemError: ... cellobject.c:22: bad argument to internal ? In-Reply-To: <1147546829.738347.16630@d71g2000cwd.googlegroups.com> References: <1147546829.738347.16630@d71g2000cwd.googlegroups.com> Message-ID: nnorwitz at gmail.com wrote: > robert wrote: > >>From the trace of a 2.3.5 software i got: >> >>\'SystemError: >>C:\\\\sf\\\\python\\\\dist23\\\\src\\\\Objects\\\\cellobject.c:22: bad >>argument to internal >>function\\n\'] > > > ... > > >>Will there be another bug-fix release of Python 2.3 ? > > > No, is this still a problem in 2.4? 2.4.4 is planned to be released ( Am bound to py2.3 for this app - as py2.4 more than doubled distributable app sizes with MSVCRTL71, CJK codecs in core etc... ) > this summer. Can you post the entire code (that doesn't reference > anything outside the stdlib) that causes this problem? > Solved - no Python error. The bug turned out to be a refcount bug in PythonWin's win32ui.HookMessage internals: the Python callback upon WM_TIMER didn't INCREF the called function object itself. When the function removed itself from the hook list (indirectly), the executing functions closure/cells.. were recycled while the function was still executing. https://sourceforge.net/tracker/index.php?func=detail&aid=1489690&group_id=78018&atid=551954 -robert From onurb at xiludom.gro Tue May 16 10:08:41 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 16 May 2006 16:08:41 +0200 Subject: Python script for remotely shutting down Windows PC from Linux ? In-Reply-To: <1147787216.421492.323520@y43g2000cwc.googlegroups.com> References: <1147784786.317200.238780@v46g2000cwv.googlegroups.com> <4cu2dcF17t9juU1@uni-berlin.de> <1147787216.421492.323520@y43g2000cwc.googlegroups.com> Message-ID: <4469dd4f$0$7018$636a55ce@news.free.fr> diffuser78 at gmail.com wrote: >>ssh Admin at IP_ADDR shutdown -s > > > Than indeed worked....Thanks > > > use the subprocess module or shellutils to execute the above. > > I am a python newbie and how easy or difficult it is using the sub > process module and shell utils. It's as difficult as : 1. read the doc 2. write some code 3. test it 4. if you're in trouble, go back to 1. 5. if you're still in trouble, post here with relevant infos -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tjreedy at udel.edu Wed May 31 15:42:13 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 May 2006 15:42:13 -0400 Subject: using import * with GUIs? References: Message-ID: "John Salerno" wrote in message news:R2mfg.2200$No6.47332 at news.tufts.edu... > Hi all. Quick question (but aren't they all?) :) > > Do you think it's a good idea to use the 'from import *' > statement when using a GUI module? It seems on wxPython's site, they > recommend using import wx nowadays, but I wonder if that advice is > followed. Also, I'm still reading some Tkinter docs that seem to use > 'from Tkinter import *' a lot. > > I understand the danger of doing this, but is it safer in these cases, > given the more specific names that GUI frameworks tend to use > (sometimes!)? Or should you still qualify all your calls with the module? If I were to use Tkinter, I would 'import Tkinter as tk'. From robert.kern at gmail.com Thu May 11 00:11:25 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 10 May 2006 23:11:25 -0500 Subject: segmentation fault in scipy? In-Reply-To: <1147318499.764838.243020@u72g2000cwu.googlegroups.com> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> Message-ID: conor.robinson at gmail.com wrote: > Im using rprop (not dependent on error function in this case ie. > standard rprop vs. irprop or arprop) for an MLP tanh, sigmod nnet as > part of a hybrid model. I guess I was using a little Matlab thought > when I wrote the SSE funtion. My batches are about 25,000 x 80 so my > absolute error (diff between net outputs and desired outputs) when > using *one* output unit is shape(~25000,), am I wrong to assume > trace(error*transpose(error)) is the sum of the squared errors which > should be an shape(1,)? I'm afraid you're using terminology (and abbreviations!) that I can't follow. Let me try to restate what's going on and you can correct me as I screw up. You have a neural net that has 80 output units. You have 25000 observations that you are using to train the neural net. Each observation vector (and consequently, each error vector) has 80 elements. Judging by your notation, you are using the matrix subclass of array to change * to matrix multiplication. In my message you are responding to (btw, please quote the emails you respond to so we can maintain some context), I gave an answer for you using regular arrays which have * as elementwise multiplication. The matrix object's behavior gets in the way of the most natural way to do these calculations, so I do recommend avoiding the matrix object and learning to use the dot() function to do matrix multiplication instead. But if you want to continue using matrix objects, then you can use the multiply() function to do element-wise multiplication. The answer I gave also used the wrong name for the result. It seems that you want the sum of the squared errors across all of the observations. In this case, you can use axis=None to specify that every element should be summed: SSE = sum(multiply(error, error), axis=None) trace(dot(error, transpose(error))) wastes a *huge* amount of time and memory since you are calculating (if your machine was capable of it) a gigantic matrix, then throwing away all of the off-diagonal elements. The method I give above wastes a little memory; there is one temporary matrix the size of error. -- 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 Serge.Orlov at gmail.com Sun May 7 18:43:05 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 7 May 2006 15:43:05 -0700 Subject: the tostring and XML methods in ElementTree In-Reply-To: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> References: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> Message-ID: <1147041785.742679.257740@e56g2000cwe.googlegroups.com> mirandacascade at yahoo.com wrote: > O/S: Windows XP Home > Vsn of Python: 2.4 [snip fighting with unicode character U+2019 (RIGHT SINGLE QUOTATION MARK) ] I don't know what console you use but if it is IDLE you'll get confused even more because it is buggy and improperly handles that character: >>> print repr(u'I'm confused') u'I\x92m confused' I'm using Lightning Compiler to run snippets of code and in the editor tab it handles that character fine: >>> print repr(u'I'm confused') u'I\u2019m confused' But in the console tab it produces the same buggy result :) It looks like handling unicode is like rocket science :) From ruby at no.spam Tue May 16 16:43:12 2006 From: ruby at no.spam (Michal Kwiatkowski) Date: Tue, 16 May 2006 22:43:12 +0200 Subject: calling upper() on a string, not working? References: Message-ID: John Salerno wrote: > def encrypt_quote(original): > original_letters = filter_letters(original) You call filter_letters() which makes upper() on all letters, so original_letters contain only uppercase letters. > new_letters = list(string.ascii_uppercase) > while True: > random.shuffle(new_letters) > trans_letters = ''.join(new_letters)[:len(original_letters)] > if test_code(original_letters, trans_letters): > trans_table = string.maketrans(original_letters, > trans_letters) break > return original.translate(trans_table) And here you're translating 'original' (which contains a lot of lowercase letters) with use of trans_table that maps only uppercase characters. This return should be: return original.upper().translate(trans_table) mk -- . o . >> http://joker.linuxstuff.pl << . . o It's easier to get forgiveness for being wrong o o o than forgiveness for being right. From vbgunz at gmail.com Sat May 6 07:14:45 2006 From: vbgunz at gmail.com (vbgunz) Date: 6 May 2006 04:14:45 -0700 Subject: Replace In-Reply-To: References: Message-ID: <1146914085.870757.3890@y43g2000cwc.googlegroups.com> pay attention to Ryan. Do not use 'str' as an identifier as you will over write the built-in doing so. this seems easiest so far. s = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" s = s.replace('=', '=#') print s # -> tyrtrbd =#ffgtyuf =#=# =#tyryr =#u=#p ttttff From ishoej at gmail.com Mon May 1 17:18:04 2006 From: ishoej at gmail.com (Holger) Date: 1 May 2006 14:18:04 -0700 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> Message-ID: <1146518284.210504.319960@i40g2000cwc.googlegroups.com> I guess I deserved that. :-( I *did* read the tutorial, but then I forgot and didn't notice... My brain is getting is slow - so thx for the friendly slap in the face ;-) From rpdooling at gmail.com Fri May 26 09:00:01 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 26 May 2006 06:00:01 -0700 Subject: Python for my mum References: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> Message-ID: <1148648400.975493.276700@j55g2000cwa.googlegroups.com> First be sure she needs to install Python, if so, try: 7 Minutes To Hello World http://www.richarddooling.com/index.php/category/geekophilia These instructions are for people on Windows XP who don't even know what a commandline is. They seem popular, based on the traffic they attract. Try them and suggest changes using the comments if she falls down at any point. rd From Alain.Picard at memetrics.com Thu May 18 05:46:10 2006 From: Alain.Picard at memetrics.com (Alain Picard) Date: Thu, 18 May 2006 19:46:10 +1000 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147873879.818361.10040@i40g2000cwc.googlegroups.com> Message-ID: <87ejyrvf6l.fsf@memetrics.com> "Bill Pursell" writes: > In my experience, the people who complain about the use > of tabs for indentation are the people who don't know > how to use their editor, and those people tend to use > emacs. HA HA HA HA HA HA HA HA HA HA HA HA .... Tee, hee heee.... snif! Phew. Better now. That was funny! Thanks! :-) From jjl at pobox.com Sat May 6 20:43:05 2006 From: jjl at pobox.com (John J. Lee) Date: 07 May 2006 00:43:05 +0000 Subject: Python Eggs Just install in *ONE* place? Easy to uninstall? References: <1146936395.028140.15640@i39g2000cwa.googlegroups.com> Message-ID: <87bqua8y1y.fsf@pobox.com> "seberino at spawar.navy.mil" writes: > It appears that apps distributed as Python Eggs are either a single > compressed > blob in site-packages directory or a directory under site-packages > directory. > > Is this ALWAYS true? No. > So by just erasing stuff under site-packages > I can do a COMPLETE uninstallation of an Egg? Essentially, yes -- if that's where you installed it. (but there's also an entry in easy-install.pth) OTOH, python setup.py install *will* in general install other stuff, outside of site-packages (or whatever directory you picked). There's no uninstall command (although Phillip Eby is planning on implementing just that in setuptools/easy_install 0.7, and of course today you can already use e.g. bdist_wininst or bdist_rpm and use a system package manager to install and uninstall -- IIUC those commands will install (and uninstall) eggs if the setup.py uses setuptools). Eggs are not an installation format: and other formats do exist -- for example, "python setup.py develop" on a setuptools-based project will give you an egg installed via an .egg-link file. By the way, the distutils-sig mailing list is a good place to ask these questions. John From gherron at islandtraining.com Sun May 7 12:31:41 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 07 May 2006 09:31:41 -0700 Subject: printing list In-Reply-To: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> References: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> Message-ID: <445E20ED.4080104@islandtraining.com> compboy wrote: >How do you print elements of the list in one line? > >alist = [1, 2, 5, 10, 15] > >so it will be like this: >1, 2, 5, 10, 15 > >because if I use this code > >for i in alist: > print i > >the result would be like this > >1 >2 >5 >10 >15 > >Thanks. > > Well, first, if you just print alist you'll get [1, 2, 5, 10, 15] which may be good enough. If that's not what you want then you can suppress the automatic RETURN that follows a print's output by adding a trailing comma to the print statement, like this for i in alist: print i, 1 2 5 10 15 Gary Herron From deets at nospam.web.de Wed May 3 05:10:12 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 May 2006 11:10:12 +0200 Subject: Can subprocess point to file descriptor 5? References: Message-ID: <4brac4F12faelU1@uni-berlin.de> Steve Quezadas wrote: > Hello, > > I tried posting this to the web forums without much luck. > > I have some simple subprocess code here: > output = subprocess.Popen([/usr/bin/program"], > stdout=subprocess.PIPE).communicate()[0] > > However, /usr/bin/prgram also outputs not only to stdout and stderr but > to file descriptor [5]. Can I redirect this output to either a file or a > variable? I doubt it writes to fd 5 - instead, it will open a few files/sockets/pipes and writes to them. One of them happens to get the 5 assigned as filedescriptor. Figure out which one (I guess you used strace to get that number the firest hand?), and if it's a file, just read the contents of it. If its anything else, I'm pretty much out of ideas, but maybe others aren't. Diez From onurb at xiludom.gro Fri May 19 10:31:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 16:31:21 +0200 Subject: memory error with zipfile module In-Reply-To: <1148047956.998124.47790@u72g2000cwu.googlegroups.com> References: <446dbe4d$0$8013$626a54ce@news.free.fr> <1148047956.998124.47790@u72g2000cwu.googlegroups.com> Message-ID: <446dd721$0$5149$626a54ce@news.free.fr> jordan.taylor2 at gmail.com wrote: > Take a look at the pywin32 extension, which I believe has some lower > level memory allocation and file capabilities that might help you in > this situation. But then the solution would not be portable, which would be a shame since the zlib module (on which ZipFile relies for compression / decompression) already has everything needed to handle streams. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From chris at foote.com.au Tue May 16 05:05:36 2006 From: chris at foote.com.au (Chris Foote) Date: Tue, 16 May 2006 18:35:36 +0930 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> Message-ID: <1147772420.405097@teuthos> Claudio Grondi wrote: > Chris Foote wrote: >> p.s. Disk-based DBs are out of the question because most >> key lookups will result in a miss, and lookup time is >> critical for this application. >> > Python Bindings (\Python24\Lib\bsddb vers. 4.3.0) and the DLL for > BerkeleyDB (\Python24\DLLs\_bsddb.pyd vers. 4.2.52) are included in the > standard Python 2.4 distribution. However, please note that the Python bsddb module doesn't support in-memory based databases - note the library documentation's[1] wording: "Files never intended to be preserved on disk may be created by passing None as the filename." which closely mirrors the Sleepycat documentation[2]: "In-memory databases never intended to be preserved on disk may be created by setting the file parameter to NULL." It does actually use a temporary file (in /var/tmp), for which performance for my purposes is unsatisfactory: # keys dictionary metakit bsddb (all using psyco) ------ ---------- ------- ----- 1M 8.8s 22.2s 20m25s[3] 2M 24.0s 43.7s N/A 5M 115.3s 105.4s N/A Cheers, Chris [1] bsddb docs: http://www.python.org/doc/current/lib/module-bsddb.html [2] Sleepycat BerkeleyDB C API: http://www.sleepycat.com/docs/api_c/db_open.html [3] Wall clock time. Storing the (long_integer, integer) key in string form "long_integer:integer" since bsddb doesn't support keys that aren't integers or strings. From gilham at snapdragon.csl.sri.com Thu May 25 17:41:56 2006 From: gilham at snapdragon.csl.sri.com (Fred Gilham) Date: Thu, 25 May 2006 14:41:56 -0700 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: Dale King <"DaleWKing [at]gmail [dot] com"> writes: > Therefore you do not have the "right" to do what you want with > Usenet. You have a responsibility to use Usenet in a way that benefits > the group as a whole (e.g. asking interesting questions that educate > others). ...or at least, in a way that follows the TOS of your ISP. The problem is that every time Xah posts, there are dozens and maybe even hundreds of postings that get provoked. One might say, "Don't feed the troll," but it's clear that this spate of posting happens no matter what anyone says. It happens in every newsgroup I've ever read. It's recognized that trollish behaviour such as cross posting irrelevant messages to many newsgroups causes this response. So instead of whacking dozens or hundreds of people with a clue stick, which is probably the right thing to do but which is impossible, it's better to thrash the one who has actually started it all by violating USENET etiquette in the first place. Xah's postings are occasionally (*very* occasionally) interesting in a warped sort of way, but I would much rather see him post pointers to his web site. It would be even better if he actually figured out the groups his messages were relevant to before posting them. BTW, one time I tried a little social engineering to get rid of an irrelevant cross-posted thread. I replied to the messages in the thread (an irrelevant political thread posted in rec.audio.tubes) with (somewhat) inflammatory replies but deleted my newsgroup from the follow-up line. I kept doing this for a day or two to every message that showed up in rec.audio.tubes. The result was that the threads actually died out pretty fast in that newsgroup. Unfortunately (but understandably) people in the other newsgroups got pretty mad and complained to some authority figure somewhere. The authority figure had no authority over me but was nice about it, so I stopped. I decided my method was a bad idea. Or rather, a good idea but dangerous. :-) -- Fred Gilham gilham at csl.sri.com ``This is mere entertainment featuring fictional characters. No real human relationships were shattered in the making of this TV series.'' From john at castleamber.com Thu May 11 19:45:15 2006 From: john at castleamber.com (John Bokma) Date: 11 May 2006 23:45:15 GMT Subject: Time to bundle PythonWin References: <1147388148.406918.76040@q12g2000cwa.googlegroups.com> Message-ID: "Robert Hicks" wrote: > No it isn't. Learn to quote when you use Google's Usenet garbage. -- 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 fabio.pliger at gmail.com Wed May 17 09:46:12 2006 From: fabio.pliger at gmail.com (Mr BigSmoke) Date: 17 May 2006 06:46:12 -0700 Subject: using wxPython events inside a loop Message-ID: <1147873572.398048.188890@g10g2000cwb.googlegroups.com> I'm writting an applicatio that that does something like this: class batchSpy(wx.Frame): def __init__(self, parent): wx.Frame.__init__( self, None, -1, "Batch Spy", pos = (0,0), size = mySize) .... do layout ... self.searchAlarms() def searchAlarms(self): for alm in self.alarms: # self.alarms is a list of strings self.almBox.WriteText(alm) #Alm box is a wx.TextCtrl widget... self.Refresh() I Know that writing like this my wxFrame just freeze. I've tried usind wxTimer event but it doesn't help... Any hint? TNX From fredrik at pythonware.com Fri May 5 10:45:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 May 2006 16:45:05 +0200 Subject: Tuple assignment and generators? References: <1146826136.746268.4060@i40g2000cwc.googlegroups.com><445b3960$1_3@news.bluewin.ch><1146831804.396839.316070@v46g2000cwv.googlegroups.com> <1146839183.981537.216320@y43g2000cwc.googlegroups.com> Message-ID: "vdrab" wrote: > I guess the take-away lesson is to steer clear from any reliance on > object identity checks, if at all possible. Are there any other such > "optimizations" one should like to know about? so in your little world, an optimization that speeds things up and saves memory isn't really an optimization ? good luck with your future career in programming. *plonk* From john at castleamber.com Tue May 16 21:30:08 2006 From: john at castleamber.com (John Bokma) Date: 17 May 2006 01:30:08 GMT Subject: python vs perl lines of code References: Message-ID: Edward Elliott wrote: > This is just anecdotal, but I still find it interesting. Take it for > what it's worth. I'm interested in hearing others' perspectives, just > please don't turn this into a pissing contest. Without seeing the actual code this is quite meaningless. -- 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 kevin at netkev.com Mon May 22 19:07:43 2006 From: kevin at netkev.com (NetKev) Date: 22 May 2006 16:07:43 -0700 Subject: global name not defined In-Reply-To: <1148336530.868187.60290@j55g2000cwa.googlegroups.com> References: <1148336530.868187.60290@j55g2000cwa.googlegroups.com> Message-ID: <1148339262.985880.58630@i39g2000cwa.googlegroups.com> google groups told me it had a "server error" the first time i posted this. Sorry for the dupe. Anyways the second one is more complete. Also, I made a mistake in my vocabulary. These are methods and not functions. From kentilton at gmail.com Sun May 7 12:36:12 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sun, 07 May 2006 12:36:12 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> Message-ID: <0mp7g.600$4q2.70@fe12.lga> Ken Tilton wrote: > > > Serge Orlov wrote: > >> Ken Tilton wrote: >> >>> It is vastly more disappointing that an alleged tech genius would sniff >>> at the chance to take undeserved credit for PyCells, something probably >>> better than a similar project on which Adobe (your superiors at >>> software, right?) has bet the ranch. This is the Grail, dude, Brooks's >>> long lost Silver Bullet. And you want to pass????? >>> >>> C'mon, Alex, I just want you as co-mentor for your star quality. Of >>> course you won't have to do a thing, just identify for me a True Python >>> Geek and she and I will take it from there. >>> >>> Here's the link in case you lost it: >>> >>> http://www.lispnyc.org/wiki.clp?page=PyCells >>> >>> :) >>> >>> peace, kenny >>> >>> ps. flaming aside, PyCells really would be amazingly good for Python. >>> And so Google. (Now your job is on the line. ) k >> >> >> >> Perhaps I'm missing something... > > > yes, but do not feel bad, everyone gets confused by the /analogy/ to > spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a > brief period I swore off the analogy because it was so invariably > misunderstood. Even Graham misunderstood it. > > But it is such a great analogy! > >> but what's the big deal about PyCells? >> Here is 22-lines barebones implementation of spreadsheet in Python, >> later I create 2 cells "a" and "b", "b" depends on a and evaluate all >> the cells. The output is >> >> a = negate(sin(pi/2)+one) = -2.0 >> b = negate(a)*10 = 20.0 > > > Very roughly speaking, that is supposed to be the code, not the output. > So you would start with (just guessing at the Python, it has been years > since I did half a port to Python): > > v1 = one > a = determined_by(negate(sin(pi/2)+v1) > b = determined_by(negate(a)*10) > print(a) -> -2.0 ;; this and the next are easy > print(b) -> 20 > v1 = two ;; fun part starts here > print(b) -> 40 ;; of course a got updated, too > > The other thing we want is (really inventing syntax here): > > on_change(a,new,old,old-bound?) print(list(new, old, old-bound?) > > Then the print statements Just Happen. ie, It is not as if we are just > hiding computed variables behind syntax and computations get kicked off > when a value is read. Instead, an underlying engine propagates any > assignment throughout the dependency graph before the assignment returns. > > My Cells hack does the above, not with global variables, but with slots > (data members?) of instances in the CL object system. here it is: (in-package :cells) (defmodel useless () ;; defmodel is CLOS defclass plus Cells wiring ((one :initform nil :accessor one :initarg :one) (a :initform nil :accessor a :initarg :a) (b :initform nil :accessor b :initarg :b))) ;; defobserver defines a CLOS method just the right way (defobserver one (self new-value old-value old-value-bound-p) (print (list :observing-one new-value old-value old-value-bound-p))) (defobserver a (self new-value old-value old-value-bound-p) (print (list :observing-a new-value old-value old-value-bound-p))) (defobserver b (self new-value old-value old-value-bound-p) (print (list :observing-b new-value old-value old-value-bound-p))) ;; c-in and c? hide more Cells wiring. The long names are c-input and c-formula, btw (progn (print :first-we-make-a-useless-instance) (let ((u (make-instance 'useless :one (c-in 1) ;; we want to change it later, so wrap as input value :a (c? (- (+ (sin (/ pi 2)) (one self)))) ;; negate(sin(pi/2)+one) :b (c? (* (- (a self) 10)))))) ;; negate(a)*10 (print :now-we-change-one-to-ten) (setf (one u) 10))) #| output of the above :first-we-make-a-useless-instance (:observing-one 1 nil nil) (:observing-a -2.0d0 nil nil) (:observing-b -12.0d0 nil nil) :now-we-change-one-to-ten (:observing-one 10 1 t) (:observing-a -11.0d0 -2.0d0 t) (:observing-b -21.0d0 -12.0d0 t) |# kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From oliphant.travis at ieee.org Wed May 17 20:41:16 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 17 May 2006 18:41:16 -0600 Subject: ANN: NumPy 0.9.8 released Message-ID: NumPy 0.9.8 has been released. It can be downloaded from http://numeric.scipy.org The release notes are attached. Best regards, -Travis Oliphant -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: release-notes-0.9.8 URL: From robert.kern at gmail.com Sun May 21 21:44:02 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 May 2006 20:44:02 -0500 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1148251275.211468.221460@g10g2000cwb.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> <1148251275.211468.221460@g10g2000cwb.googlegroups.com> Message-ID: Jim Lewis wrote: >>and change "-lmsvcrt" to "-lmsvcr71". > > But then I get this error: Python was built with version 7.1 of Visual > Studio, and extensions need to be built with the same version of the > compiler, but it isn't installed. > I want to use mingw. You have to tell distutils to use mingw: python setup.py build_ext --compiler=mingw32 -- 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 mumia.w.18.spam+nospam.usenet at earthlink.net Tue May 30 06:14:15 2006 From: mumia.w.18.spam+nospam.usenet at earthlink.net (Mumia W.) Date: Tue, 30 May 2006 10:14:15 GMT Subject: John Bokma harassment In-Reply-To: <447bff02$0$38691$edfadb0f@dread12.news.tele.dk> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> <447bff02$0$38691$edfadb0f@dread12.news.tele.dk> Message-ID: Max M wrote: > John Bokma wrote: >> ilitzroth at gmail.com wrote: > >> Your first question should be: Is it alright that Xah harasses 5 >> newsgroups? Or maybe work on your spelling, harass is with one r, but >> maybe you didn't read the subject, which wouldn't amaze me, since you >> sound like you should be spending time on MySpace OMG!. > > > I assume that the single l in alright is the courteous misspelling that > should allways be in a posting, when correcting other peoples speling? > > I'm glad you caught the usage error and another fine example of Bokma hypocrisy. People need to point it out because Bokma's hypocrisy is invisible to him. :) Xah's posting on-topic messages to 5 newsgroups about two times per week isn't harassment, but Bokma's attempts to cut off Xah *are*. From nogradi at gmail.com Mon May 1 16:28:37 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 1 May 2006 22:28:37 +0200 Subject: [ANN] markup.py 1.4 - bugfix Message-ID: <5f56302b0605011328w7775641bie08319d875c2fc8e@mail.gmail.com> I'm terribly sorry but there was a crucial bug left in the 1.3 release announced today. Thanks to a user now it's fixed, and the new 1.4 release is available on http://markup.sourceforge.net/ which should be okay. Sorry for the inconvenience :) From mateus.justino at gmail.com Wed May 31 19:09:32 2006 From: mateus.justino at gmail.com (mateus) Date: 31 May 2006 16:09:32 -0700 Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> <1149083447.370584.197070@f6g2000cwb.googlegroups.com> Message-ID: <1149116972.201718.155660@h76g2000cwa.googlegroups.com> Well, one by one I checked for the presence of both sessions and session in the globals dictionary (within showReport(), but outside of the loops). Neither one of them existed previously, thus and I received the exception about them not being found: File "/home/mjpl/hct/repository/hct/tutoo.py", line 219, in loadNext self.loadStage(self.cur+1) File "/home/mjpl/hct/repository/hct/tutoo.py", line 195, in loadStage self.stageFrame.show() File "/home/mjpl/hct/repository/hct/stages/resultadoframe/resultadoframe.py", line 17, in show self.listView.showReport() File "/home/mjpl/hct/repository/hct/widgets/deviceview.py", line 54, in showReport print globals()['session'] KeyError: 'session' So, I tried using other variable names for the outer and inner loops with the only difference of one letter. I then got the expected message about the variable name not being encountered. I returned the variable names to 'sessions' and 'session' respectively, and I got the same error about the name 'session' not being founded. I can only assume that there was some type of cache problem. Could it have been in the .pyc? I thought that was recompiled every time a .py is run/set to be interpreted. I'm sure I got that last sentence wrong. hwiechers at gmail.com wrote: > mateus wrote: > > print "hello world" > > > > I have a nested loop where the outer loop iterates over key value pairs > > of a dictionary and the inner loop iterates over a list each list of > > which is a mapped value from the dictionary > > > > def showReport(self): > > for dev, sessions in self.logger.items(): > > for tree in session: > > self.addTestItem(self, tree) > > > > What I don't understand is why this executes w/o any problems when > > "sessions" was spelled as plural (sessionS) while later being spelled > > in the singular (session). > > > > Is there some type of name resolution of local variables where Python > > makes assumptions? > > I've never heard of a rule disregarding ending 's'es and I really doubt > one > exists. > > Are you sure session isn't a global variable? You can check using > globals(). From blair.bethwaite at gmail.com Mon May 8 00:23:48 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 7 May 2006 21:23:48 -0700 Subject: utility functions within a class? References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> Message-ID: <1147062228.849272.225110@j73g2000cwa.googlegroups.com> John Salerno wrote: > What I originally meant was that they would not be called from an > instance *outside* the class itself, i.e. they won't be used when > writing another script, they are only used by the class itself. Yep, so you want to encapsulate the functionality that those methods provide, which is the whole point of building them in a class in the first place. And you want them to be private to the class so that they do not form part of the classes public/external interface. In python, as discussed earlier :), you can make them semi-private by using the '__method_name' syntax. The thing is that python doesn't strictly enforce this privacy, code outside of your object can still call these methods because python just mangles the internal method name slightly. See http://docs.python.org/tut/node11.html#SECTION0011600000000000000000 for more detail. Cheers, -B From scott.daniels at acm.org Thu May 25 17:33:31 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 25 May 2006 14:33:31 -0700 Subject: Multi-dimensional list initialization trouble In-Reply-To: <1148592170.709560.307030@j55g2000cwa.googlegroups.com> References: <1148592170.709560.307030@j55g2000cwa.googlegroups.com> Message-ID: <44761e76$1@nntp0.pdx.net> jonkje at gmail.com wrote: > Hello I found this very strange; is it a bug, is it a "feature", am I > being naughty or what? > >>>> foo = [[0, 0], [0, 0]] >>>> baz = [ [0]*2 ] * 2 >... > Why on earth does foo and baz behave differently?? This is a frequently made mistake. try also: >>> bumble = [[0]*2 for 0 in xrange(2)] Think hard about why that might be. Then try: >>> [id(x) for x in foo] >>> [id(x) for x in baz] >>> [id(x) for x in bumble] Now check your upper scalp for lightbulbs. --Scott David Daniels scott.daniels at acm.org From tundra at tundraware.com Tue May 9 15:54:53 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: 09 May 2006 15:54:53 EDT Subject: Is Welfare Part of Capitalism? In-Reply-To: <1147200065.889769.76050@v46g2000cwv.googlegroups.com> References: <1147200065.889769.76050@v46g2000cwv.googlegroups.com> Message-ID: envyisevil at yahoo.com wrote: > This article is dedicated to: > But I am still confused: Is this a statement or an expression? From thomasbartkus at comcast.net Tue May 9 15:08:53 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Tue, 9 May 2006 14:08:53 -0500 Subject: python rounding problem. References: <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> <125v9g8q00o1d52@corp.supernews.com> <125vedc9n2q3m55@corp.supernews.com> Message-ID: "Grant Edwards" wrote in message news:125vedc9n2q3m55 at corp.supernews.com... > On 2006-05-08, Thomas Bartkus wrote: > > >> Or you can write 0.1 > >> 3 > >> > >> :) > > > > Ahhh! > > > > But if I need to store the value 1/10 (decimal!), what kind of > > a precision pickle will I then find myself while working in > > base 3? > > Then we're right back where we started. No matter what base > you choose, any fixed length floating-point representation can > only represent 0% of all rational numbers. > > So, clearly what we need are floating point objects with > configurable bases -- bases that automatically adjust to > maintain exact representation of calculation results. Which > probably exactly the same as just storing rational numbers as > numerator,denominator tuples as you suggest. > > > How much better for precision if we just learn our fractions > > and stick to storing integer numerators alongside integer > > denominators in big 128 bit double registers ? I completely overlooked the infinite (presumably!) length integer handling in Python. You can do integer arithmetic on integers of large and arbitrary lengths and if ultimate precision were indeed so important (and I can't imagine why!) then working with numerators and denominators stored as tuples is quite practical. Anyone old enough to remember Forth might remember the arguments about how unnecessary floating point is. True enough! Floating point is merely a convenience for which we sacrifice some (insignificant!) arithmetic precision to enjoy. > > Even the Nenets might become more computationally precise by > > such means ;-) And how does a human culture come to decide on > > base 9 arithmetic anyway? > > I've no clue, whatsoever. I just stumbled across that factoid > when I used Wikipedia to look up which civilizations used > base-60. For some reason I can never remember whether it was > one of the mesoamerican ones or one of the mesopotamian ones. I suspect a hoax or an urban legend here. A brief and casual googling brings up the Nenets but no mention of base 9 arithmetic which I would find rather astonishing. Look up the Tasaday tribe together with the word "hoax". A great joke on academic anthropologists really. On the other hand, the name "Nenet" is full of "N"s and so evocative of the number nine ;-) > > Even base 60 makes more sense if you like it when a lot of > > divisions come out nice and even. > > Did they actually have 60 unique number symbols and use > place-weighting in a manner similar to the arabic/indian system > we use? I don't know. I do know that we have 360 degrees in a circle for the simple reason that this is evenly divisible by so damned many integers. A significant and logical convenience if you have to do all your calculations on a wooden board using the chunk of charcoal you hold in your fist. Thomas Bartkus > > Do the Nenets amputate the left pinky as a rite of adulthood > > ;-) > > Nah, winters up there are so friggin' cold that nobody ever has > more than nine digits by the time they reach adulthood. > > -- > Grant Edwards grante Yow! Hello. Just walk > at along and try NOT to think > visi.com about your INTESTINES being > almost FORTY YARDS LONG!! From fredrik at pythonware.com Fri May 12 05:39:23 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 May 2006 11:39:23 +0200 Subject: Can Python installation be as clean as PHP? References: <1147238063.235221.13120@j73g2000cwa.googlegroups.com> <1147238466.485259.325310@i39g2000cwa.googlegroups.com> Message-ID: Ravi Teja wrote: > Python has zip imports (similar to Java's jar files). You can put all > your *.py files in a zip file and access them from it if this means so > much to you. Python also supports "frozen" modules, where the module bytecode is linked into a Python interpreter as data. by combining frozen modules and static linking of extension modules, it's relatively easy to create a single-file python interpreter. and to make things even simpler, you can get tools and ready-made single-file distributions for a variety of platforms here: http://www.egenix.com/files/python/mxCGIPython.html http://phd.pp.ru/Software/Python/misc/mxCGI/ From charl.loubser at gmail.com Sat May 13 04:22:51 2006 From: charl.loubser at gmail.com (Merrigan) Date: 13 May 2006 01:22:51 -0700 Subject: Sending mail with attachment... Message-ID: <1147508571.532690.292650@v46g2000cwv.googlegroups.com> Hi, I have now eventually finished my newbie-backup script and I'm very proud of the way it functions... Anyways, I am looking for an easy way to use smtplib to send an email with the output log of the script to multiple accounts. I need to use it with a smtp server, and cannot pipe it directly to sendmail. I have tried about 50 different ways that I have googled for in the last 6 hours, but none of them work, I keep on getting errors. The script runs on a Linux system. Thanks for any help. From rpdooling at gmail.com Fri May 5 12:03:33 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 5 May 2006 09:03:33 -0700 Subject: Best IDE for Python? References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> Message-ID: <1146845012.940673.288820@e56g2000cwe.googlegroups.com> >> Pardon if . . . already discussed Here is a link searching comp.lang.python for "best ide" http://tinyurl.com/qqtaf rick From lcaamano at gmail.com Mon May 15 20:11:58 2006 From: lcaamano at gmail.com (lcaamano) Date: 15 May 2006 17:11:58 -0700 Subject: Large Dictionaries In-Reply-To: <1147699064.107490@teuthos> References: <1147699064.107490@teuthos> Message-ID: <1147738318.330346.231310@j33g2000cwa.googlegroups.com> Sounds like PyTables could be useful. http://www.pytables.org -- lpc From bens_dev_lists at waypointdatasolutions.com Fri May 26 10:23:29 2006 From: bens_dev_lists at waypointdatasolutions.com (Ben Stroud) Date: Fri, 26 May 2006 10:23:29 -0400 Subject: OLAP and pivot tables In-Reply-To: <1148611731.916187.198330@i40g2000cwc.googlegroups.com> References: <1148611731.916187.198330@i40g2000cwc.googlegroups.com> Message-ID: <44770F61.7070705@waypointdatasolutions.com> George Sakkis wrote: >After a brief search, I didn't find any python package related to OLAP >and pivot tables. Did I miss anything ? To be more precise, I'm not so >interested in a full-blown OLAP server with an RDBMS backend, but >rather a pythonic API for constructing datacubes in memory, slicing and >dicing them, drilling down or up dimensions and exposing them in some >suitable form to a presentation layer. I've hacked a first cut of a >pivot table implementation and an XHTML generator that produces >hierarchical html tables but it's not particularly general or easily >extensible so far. Is there any interest at all on a pythonic version >of something like JOLAP or XMLA ? > >George > > > I'd be interested as well. I posted a similar question to the ruby mailing list a few months ago to no avail. Ideally, someone much more talented than myself would create a open OLAP library in C that could be interfaced with dynamic languages easily (I ordered some OLAP books and started in on this, and decided I was in over my head for now). As far as free software, all I've been able to find is java-based Mondrian. Maybe it could serve as a reference implementation for someone. Cheers, Ben From Bulkan at gmail.com Fri May 5 01:41:20 2006 From: Bulkan at gmail.com (placid) Date: 4 May 2006 22:41:20 -0700 Subject: Can I use python for this .. ?? In-Reply-To: <1146779044.307500.50810@u72g2000cwu.googlegroups.com> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146774288.904851.278130@i39g2000cwa.googlegroups.com> <1146779044.307500.50810@u72g2000cwu.googlegroups.com> Message-ID: <1146807680.232551.97460@y43g2000cwc.googlegroups.com> Petr Jakes wrote: > Why using Python? > What about? > 1. Open Power Options in Control Panel. (Click Start, click Control > Panel, and then double-click Power Options.) > 2.Click the Hibernate tab, select the Enable hibernate support check > box, and then click Apply. > (If the Hibernate tab is unavailable, your computer does not support > this feature.) When you hibernate/boot up/hibernate for a long time without a clean reboot, Windows becomes unstable... > > then: > 1: Click Start and Shut Down, > 2: Point the standby button and maintain the shift key pushed, > 3: A new hibernation button appears: click it while still holding the > shift key: voila your PC will hibernate (it mens computer will save > your current setting and will switch off). > > Petr Jakes From ericcngan at gmail.com Fri May 12 16:21:35 2006 From: ericcngan at gmail.com (vduber6er) Date: 12 May 2006 13:21:35 -0700 Subject: having trouble importing a module from local directory Message-ID: <1147465295.213844.284100@y43g2000cwc.googlegroups.com> First off this is in unix. I have a C file that has python embedded in it. In the script I have the following PyRun_SimpleString(code); where code = "import mymodule" however I get this error Traceback (most recent call last): File "", line 1, in ? ImportError: No module named mymodule Object not found Segmentation fault If i just run python from my local path then type "import mymodule" in the python prompt this is fine. I'm guessing when I am embedding my python script in the C code the local directory is no longer the directory where my C code resides. How can i tell python to load the module from my current local directory? Thanks. From michael at elehack.net Mon May 1 15:57:48 2006 From: michael at elehack.net (Michael Ekstrand) Date: Mon, 1 May 2006 14:57:48 -0500 Subject: How do I take a directory name from a given dir? In-Reply-To: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> References: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> Message-ID: <20060501195748.GC29422@localhost.localdomain> On Mon, May 01, 2006 at 12:42:58PM -0700, Merrigan wrote: > The issue I am currently having isto "extract" the directory name from > a given directory string. For example: from the string > "/home/testuser/projects/" I need to extract the "projects" part. The > problem is that the directory names that needs to be used will never be > the same lenght, so as far as my (very limited) knowledge stretches, > slicing and indicing is out of the question. Look at the os.path module, especially the basename and dirname functions. basename will extract the "base name", that is, the last component of a path. - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From junkytownMAKNI at gmail.com Mon May 29 09:46:46 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Mon, 29 May 2006 15:46:46 +0200 Subject: saving settings In-Reply-To: <4e07c8F1c7r6jU1@uni-berlin.de> References: <4e07c8F1c7r6jU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > SuperHik wrote: > >> aum wrote: >>> On Mon, 29 May 2006 09:05:36 +0200, SuperHik wrote: >>> >>>> Hi, >>>> >>>> I was wondering how to make a single .exe file, say some kind od clock, >>>> and be able to save some settings (alarm for example) into the same >>>> file? Basically make code rewrite it self... >>>> >>>> thanks! >>> Yikes!!! >>> >>> I'd strongly suggest you read the doco for ConfigParser, and load/save >>> your config file to/from os.path.join(os.path.expanduser("~")). >>> >>> Another option - save your stuff in the Windows Registry >>> >> but if I copy this file on the other computer settings will be lost... > > It _might_ come as a shock to you, but when you install e.g. Word on another > computer, there aren't any documents coming with it. Especially not the > ones you wrote on that other machine. that doesn't shock me :p anyway you're talking about instalation while I'm talkig about single standalone file. Besides, if it was neccessary I bet MS would make that option (and it wouldn't be a problem since installation is not done from a sinlge file but from the CD (should be CD-RW in that case) with lots of files and directories so they'd create just another directory on the installation CD, say \All Documents\ ) > > Seriously: Who is going to copy a executable around? Obviously I am. :D Do you know of any > other program that behaves like that? No, but for most programs I used I never bothered to check where did they put their settings. That's just the thing, I'm not a professional programmer so I was wondering is it possible to do it, and if it is how much trouble would it be. If nothing I will just make a config file right next to the executable.. > > Diez thanks! From johnjsal at NOSPAMgmail.com Tue May 9 10:16:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 14:16:52 GMT Subject: utility functions within a class? In-Reply-To: <4460594c$0$23806$626a54ce@news.free.fr> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <4460594c$0$23806$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > The convention for 'protected' > attributes (which should really be named 'implementation attributes') FWIW, I agree. When I hear 'protected attribute' I think of an attribute that can only be used within its class and subclasses of it. From http Fri May 26 13:36:12 2006 From: http (Paul Rubin) Date: 26 May 2006 10:36:12 -0700 Subject: sort a dictionary by keys in specific order References: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> Message-ID: <7x4pzczo1f.fsf@ruckus.brouhaha.com> "spohle" writes: > dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'} > > list = [key2, key3, key1] Is this what you want? dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'} keys = ['key2', 'key3', 'key1'] items = [dic[k] for k in keys] print items From onurb at xiludom.gro Fri May 12 05:56:20 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 11:56:20 +0200 Subject: deleting texts between patterns In-Reply-To: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> Message-ID: <44645c27$0$301$636a55ce@news.free.fr> micklee74 at hotmail.com wrote: > hi > say i have a text file > > line1 > line2 > line3 > line4 > line5 > line6 > abc > line8 <---to be delete > line9 <---to be delete > line10 <---to be delete > line11 <---to be delete > line12 <---to be delete > line13 <---to be delete > xyz > line15 > line16 > line17 > line18 > > I wish to delete lines that are in between 'abc' and 'xyz' and print > the rest of the lines. Which is the best way to do it? Should i get > everything into a list, get the index of abc and xyz, then pop the > elements out? Would be somewhat inefficient IMHO - at least for big files, since it implies reading the whole file in memory. > or any other better methods? Don't know if it's better for your actual use case, but this avoids reading up the whole file: def skip(iterable, skipfrom, skipuntil): """ example usage : >>> f = open("/path/to/my/file.txt") >>> for line in skip_print(f, 'abc', 'yyz'): >>> print line >>> f.close() """ skip = False for line in iterable: if skip: if line == skipuntil: skip = False continue else: if line == skipfrom: skip = True continue yield line def main(): lines = """ line1 line2 line3 line4 line5 line6 abc line8 <---to be delete line9 <---to be delete line10 <---to be delete line11 <---to be delete line12 <---to be delete line13 <---to be delete xyz line15 line16 line17 line18 """.strip().split() for line in skip(lines, 'abc', 'xyz'): print line HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From niemand.leermann at thomas-guettler.de Tue May 9 11:03:47 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Tue, 09 May 2006 17:03:47 +0200 Subject: Python editor recommendation. References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Am Tue, 09 May 2006 14:37:53 +0100 schrieb Dale Strickland-Clark: > Vim. > > Everything else is Notepad. Vi or vim are good for editing config files over ssh. For programming I use XEmacs. HTH, Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From bborcic at gmail.com Fri May 5 07:39:00 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 05 May 2006 13:39:00 +0200 Subject: Tuple assignment and generators? In-Reply-To: <1146826136.746268.4060@i40g2000cwc.googlegroups.com> References: <1146821724.732068.268960@g10g2000cwb.googlegroups.com> <1146824577.242547.315600@y43g2000cwc.googlegroups.com> <4c0o60F13ut8cU1@uni-berlin.de> <1146826136.746268.4060@i40g2000cwc.googlegroups.com> Message-ID: <445b3960$1_3@news.bluewin.ch> vdrab wrote: >> """ >> E.g., after "a = 1; >> b = 1", >> a and b may or may not refer to the same object with the value one, >> depending on the implementation, >> """ > > But when in a specific implementation this property _does_ hold for > ints having value 1, I expect the > same behaviour for ints with other values than 1. > I guess I'm kind of weird that way. > Are you telling us that you *had* read that doc, and tripped because it says "depending on the implementation", when it should say "at the choice of the implementation" ? That's indeed a bit weird, imo. From grante at visi.com Wed May 3 22:55:12 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 04 May 2006 02:55:12 -0000 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> Message-ID: <125ir8gpofq3i1c@corp.supernews.com> On 2006-05-04, OlafMeding at gmail.com wrote: > Please try. > > The sleep statement does not return! Never, or does it just take a long time? > And this should not happen. Dude, it's MS Windows. It does all _sorts_ of stuff that it shouldn't. Having sleep() take orders of magnitude longer than it should is not an uncommon complaint for MS Windows users. There was a fairly extensive thread in this group about that problem just a few weeks ago. IIRC, disabling some other program or service fixed it for one MS victem. > The code above does nothing special or unusual. The problem > only occurs if 2 threads use the sleep statement and > hyper-threading is enabled. That part is new. I'm pretty sure other people who complained about sleep() not returning in a reasonable amount of time saw it all of the time. -- Grant Edwards grante Yow! I was giving HAIR at CUTS to th' SAUCER PEOPLE visi.com ... I'm CLEAN!! From sybrenUSE at YOURthirdtower.com.imagination Thu May 4 03:48:37 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 4 May 2006 09:48:37 +0200 Subject: Python & SSL References: <4457B74A.2000208@benjiyork.com> Message-ID: Edward Elliott enlightened us with: > Encryption has multiple meanings. In the general sense, it > encompasses all of cryptography and the information security > properties crypto provides. And if you already know who'll get the message, it's secure. I get it :) Thanks for the nice read ;-) > Of course if you control the server and serve a small clientele who > already trust you, you can have clients import your own cert so they > really can be sure who they're talking to -- as long as your master > key remains secret. I'm used to using it like that. My own graduation project uses SSL to thoroughly check the identity of both parties, without a web of trust. > The moral of this story is: computer security is an ugly, complex > business. Yup. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From noway at sorry.com Wed May 31 20:50:37 2006 From: noway at sorry.com (Giovanni Bajo) Date: Thu, 01 Jun 2006 00:50:37 GMT Subject: struct: type registration? Message-ID: Hello, given the ongoing work on struct (which I thought was a dead module), I was wondering if it would be possible to add an API to register custom parsing codes for struct. Whenever I use it for non-trivial tasks, I always happen to write small wrapper functions to adjust the values returned by struct. An example API would be the following: ============================================ def mystring_len(): return 20 def mystring_pack(s): if len(s) > 20: raise ValueError, "a mystring can be at max 20 chars" s = (s + "\0"*20)[:20] s = struct.pack("20s", s) return s def mystring_unpack(s): assert len(s) == 20 s = struct.unpack("20s", s)[0] idx = s.find("\0") if idx >= 0: s = s[:idx] return s struct.register("S", mystring_pack, mystring_unpack, mystring_len) # then later foo = struct.unpack("iilS", data) ============================================ This is only an example, any similar API which might fit better struct internals would do as well. As shown, the custom packer/unpacker can call the original pack/unpack as a basis for their work. I guess an issue with this could be the endianess problem: it would make sense if, when called recursively, struct.pack/unpack used by the default the endianess specified by the external format string. -- Giovanni Bajo From fredrik at pythonware.com Thu May 25 19:09:56 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 May 2006 01:09:56 +0200 Subject: how to clear up a List in python? In-Reply-To: <1148596003.879693.63250@i39g2000cwa.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> Message-ID: vbgunz wrote: >> if you don't know how to do things, you don't need to post. > > If this was the case who then would post any questions? you didn't post a question, you provided a ludicrously bad solution in response to a simple question. that's not a good way to promote Python. From no-spam at no-spam-no-spam.com Thu May 25 10:25:34 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Thu, 25 May 2006 16:25:34 +0200 Subject: "No handlers could be found for logger xxx" ? Message-ID: some packages like paramiko use the logging. I get this messages: "No handlers could be found for logger xxx" on stderr I don't want to deal with this logging at all so far - its useless in this case anyway. How can I make it quiet most easily and correctly? Why is un-initialized logging allowed to chatter at all? -robert From claird at lairds.us Mon May 29 11:40:36 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 29 May 2006 15:40:36 +0000 Subject: Any other config parsing modules besides ConfigParser ? References: <1148893750.356850.312400@i40g2000cwc.googlegroups.com> Message-ID: In article <1148893750.356850.312400 at i40g2000cwc.googlegroups.com>, Paddy wrote: >ConfigObj? > http://www.voidspace.org.uk/python/configobj.html . . . Depending on what the original questioner meant by "general", I'm always happy to recommend Python itself as a configuration-parsing mechanism . From robert.kern at gmail.com Thu May 18 19:14:36 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 May 2006 18:14:36 -0500 Subject: Subprocess or Process or OMG!! In-Reply-To: <1147992479.110490.41960@i40g2000cwc.googlegroups.com> References: <1147992479.110490.41960@i40g2000cwc.googlegroups.com> Message-ID: rh0dium wrote: > Needless to say this is much more complex than what I was "hoping" for. > Has anyone solved this in a generic approach.. > > #!/usr/bin/env python > > import os,sys,string > import subprocess > > argc = len(sys.argv) > > # Yes I move all exe's to the .bin direcotory > sys.argv[0]=os.path.join(os.getcwd() + "/.bin/" + > os.path.basename(sys.argv[0])) > > cmd = string.join(sys.argv," ") > subprocess.Popen( cmd ) > > This has several problems - least of which args aren't working.... Has > anyone really tried this approach? Did you read the documentation? It explains how to pass the command line (hint: it's a list, not a string). http://docs.python.org/lib/module-subprocess.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From siona at chiark.greenend.org.uk Wed May 31 06:17:58 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 31 May 2006 11:17:58 +0100 (BST) Subject: [OT] whitespace (was Re: stupid perl question) References: <44778C05.9020701@grads.ece.mcmaster.ca> <4477A74C.6080605@lexicon.net> <447cdc3d@news.eftel.com> Message-ID: <6uA*vT1hr@news.chiark.greenend.org.uk> John Machin wrote: > Whitespace is a silly term, anyway (IMHO); is there such a >thing as a space that is not white? Yes, if you go back to the term's origins in printshops. A solid block of ink is space, not print, but it's not whitespace. We've kept the word alive, even if the meaning's drifted (see also "tab"). And if we didn't say "whitespace", how would we distinguish between "space characters" meaning " " and "whitespace characters" meaning " \t\r\n\v"? (OK, has anyone met a "\v" in the wild?) -- \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 andrew at acooke.org Mon May 22 16:57:40 2006 From: andrew at acooke.org (andrew at acooke.org) Date: 22 May 2006 13:57:40 -0700 Subject: system(...) and unicode Message-ID: <1148331460.400964.158420@u72g2000cwu.googlegroups.com> Hi, I'm seeing the following error: ... system(cmd) UnicodeEncodeError: 'ascii' codec can't encode character u'\xe3' in position 57: ordinal not in range(128) and I think I vaguely understand what's going on - "cmd" is constructed to include a file name that is UTF-8 encoded (I think - it includes accents when I "ls" the file - this is on a recent Suse Linux with Python 2.4.2). So I guess I need to specify the encoding used, right? But (1) I don't know how to do this; (2) this string came from the filesystem in the first place, so how come it isn't managed in an internally consistent way?; and (3) I have no explicit uncode strings in my program. Looking at the docs (unicode howto) it seems like maybe I need to do system(cmd.encode(...)) but how do I know which locale and what if cmd isn't a unicode string (I didn't make it so!)? I could force an encoding as in the unicode howto ("filename.decode(encoding)"), but that seems to already be happening (or is it not - am I wrong in assuming that?). So can someone help me or point me to some more detailed instructions, please? At the CL "locale" says en_GB.UTF-8, but I'd like this code to work whatever the locale is, if that makes sense. Sorry for being stupid, Andrew From phoolimin at gmail.com Wed May 17 05:16:33 2006 From: phoolimin at gmail.com (phoolimin at gmail.com) Date: 17 May 2006 02:16:33 -0700 Subject: questions on python script compiling for embedding Message-ID: <1147857393.227432.279650@i40g2000cwc.googlegroups.com> Dear all, I am trying to embed python into another scripting language, to do this I need to solve a number of problems on importing or compiling python script. First let me state what exactly I want to do, that is, I want the following syntax to be supported in the host language which I am developing: ###################################################### # scripts in the host language routine Test() do println("printed by Test()"); end global astring = "ASTRING"; # begin python scripts: @begin(python) def PyTest( s ): print s return 1000; # access global variables from the host scripts pystring = astring; # call function defined in the host script: Test(); @end(python) # call a python function: n = PyTest( "invoke python function" ); ###################################################### So there are the following problems come out naturally: #1. can I compile a block of python script to get the list of variables, classes and functions etc. (or at least the names) without executing? Because I need the host script to see the python definitions. The Py_CompileStringFlags() seems to do the work. But it returns a code object, which I don't know exactly and if it is possible to get the list of variables, classes and functions from this kind of object. ##2. Can I pass a list global variables for such compiling? Because I need python scripts also see the variables functions etc. defined in the host scripts. ********* For these two problem, a C API like this would be pefect: PyObject* Py_CompileStringFlagsXXX( const char *str, const char *file, int start, PyObject *module, PyCompilerFlags *flags ); Different from Py_CompileStringFlags(), this function should take another parameter (Python module object), which serve as a **namespace**, to solve undefined names in the souce "str", and store global variables, functions and classes etc defined in this source string. So the third question is: ###3. Is there some way, or how to do such thing as Py_CompileStringFlagsXXX() would do??? Of course, I do not expect such API should be added soon or even added. Thanks a lot, Limin From ajones1 at gmail.com Wed May 17 17:19:51 2006 From: ajones1 at gmail.com (Adam Jones) Date: 17 May 2006 14:19:51 -0700 Subject: python vs perl lines of code In-Reply-To: References: Message-ID: <1147900791.372383.196520@i39g2000cwa.googlegroups.com> Without any more information I would say the biggest contributor to this dissimilarity is your experience. Having spent an additional five years writing code you probably are better now at programming than you were then. I am fairly confident that if you were to take another crack at these same programs in perl you would see similar results. One of the bigger differences might have been language changes over time. If you had written this in python five years ago (assuming the python rewrites are relatively current, otherwise this list gets bigger) you would not have generators, iterators, the logging package, built in sets, decorators, and a host of other changes. Some of these features you may not have used, but for every one you did python would have had more weight. Other than that it all boils down to how the algorithm is implemented. Between those three factors you can probably account for most of the differences here. The real important question is: what has perl done in the last five years to make writing these scripts easier? From jparlar at cogeco.ca Sun May 7 10:22:55 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Sun, 7 May 2006 10:22:55 -0400 Subject: How to doctest if __name__ already used? In-Reply-To: <4c226cF13sh8vU1@individual.net> References: <4c226cF13sh8vU1@individual.net> Message-ID: On May 5, 2006, at 10:33 PM, Leo Breebaart wrote: > I have a simple question (I hope), but one I'd love to get some > feedback on in case I am missing something obvious: > > If I have a Python script that is executable, and therefore > already uses '''if __name__ == "__main__"''' to call a function > of its own, what is then the easiest yet still most Pythonic way > to run doctest on the docstrings in the file? > > Trigger doctest.testmod() via a "--test" command-line option, is > what I'm thinking. But is that really the best way? > If it is just a single standalone script, then yeah, do it that way. Once your program becomes a few files though, you might want a separate "test" file that runs doctest.testmod on each of them. Jay P. From micklee74 at hotmail.com Thu May 4 00:12:20 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 3 May 2006 21:12:20 -0700 Subject: pythonic way to sort Message-ID: <1146715940.923869.91730@u72g2000cwu.googlegroups.com> hi I have a file with columns delimited by '~' like this: 1SOME STRING ~ABC~12311232432D~20060401~00000000 2SOME STRING ~DEF~13534534543C~20060401~00000000 3SOME STRING ~ACD~14353453554G~20060401~00000000 ..... What is the pythonic way to sort this type of structured text file? Say i want to sort by 2nd column , ie ABC, ACD,DEF ? so that it becomes 1SOME STRING ~ABC~12311232432D~20060401~00000000 3SOME STRING ~ACD~14353453554G~20060401~00000000 2SOME STRING ~DEF~13534534543C~20060401~00000000 ? I know for a start, that i have to split on '~', then append all the second columns into a list, then sort the list using sort(), but i am stuck with how to get the rest of the corresponding columns after the sort.... thanks... From http Sun May 7 19:13:25 2006 From: http (Paul Rubin) Date: 07 May 2006 16:13:25 -0700 Subject: md5 from python different then md5 from command line References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> <445e3a3b$0$22630$c3e8da3@news.astraweb.com> <7xd5epek9c.fsf@ruckus.brouhaha.com> <445e7f40$0$13351$c3e8da3@news.astraweb.com> Message-ID: <7xbqu9pgx6.fsf@ruckus.brouhaha.com> John Salerno writes: > Any reason you can't just read the whole file at once and update m? Yes, you could say print md5.new(file('foo.exe').read()).hexdigest() but that means reading the whole file into memory at once. If the file is very large, that could thrash or fail. > Also, doesn't the parameter for update have to be a string? If you're > reading the file in binary mode, would t still be a string? Yes, t would still be a string. You can have NUL bytes and so forth in Python strings: len('ab\0cd') ==> 5 From nobody at 127.0.0.1 Sun May 21 18:19:30 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 22:19:30 GMT Subject: Iterators: Would "rewind" be a good idea? References: <4470C2E5.1020004@earthlink.net> Message-ID: Roy Smith wrote: > Edward Elliott wrote: >> This is why the C++ STL has independent forward and backward iterator >> types. > > Let me see if I can paraphrase the difference between the Python design > philosophy and the C++ design philosophy about most things. Python says, > "Let's make things simple enough that it can be explained fully in a > couple of paragraphs, even if it means there are some things you can't > do". C++ says, "Let's make it possible to do anything, even if it makes > it complicated enough that it takes a shelf full of books to explain it > all". STL has its problems, complexity among them, but just because it's in the STL doesn't automatically make it a bad idea. They faced a similar problem, and this is how some very smart people solved it. There's always value in exploring that. It doesn't get much simpler than adding one method (prev) with symmetry to an existing method (next). > There may be value in restartable iterators, but comparing what we've got > now to STL isn't the way to convince people it's a good idea :-) BTW I never said backwards iterators were a good idea. I haven't decided yet. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From dreedmac at columbus.rr.com Wed May 10 18:43:13 2006 From: dreedmac at columbus.rr.com (David Reed) Date: Wed, 10 May 2006 18:43:13 -0400 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147297144.537106.161310@j73g2000cwa.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> <1147292178.325015.172460@y43g2000cwc.googlegroups.com> <1264k82rk3pvu26@corp.supernews.com> <1147297144.537106.161310@j73g2000cwa.googlegroups.com> Message-ID: <042446FD-BCD0-48BA-9235-0DC03841031E@columbus.rr.com> On May 10, 2006, at 5:39 PM, OlafMeding at gmail.com wrote: > Grant > >> You might want to run some memory tests. > > We have multiple identical boxes and they all have the same problem. > > Olaf They might all have flaky memory - I would follow the other poster's advice and run memtest86 on them. Dave From chrisBrat at gmail.com Fri May 26 06:39:11 2006 From: chrisBrat at gmail.com (chris brat) Date: 26 May 2006 03:39:11 -0700 Subject: how to clear up a List in python? In-Reply-To: References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148636521.026385.171410@y43g2000cwc.googlegroups.com> <1148638555.440810.277540@i40g2000cwc.googlegroups.com> Message-ID: <1148639951.075971.129640@y43g2000cwc.googlegroups.com> Cant we all just get along ? Sorry, couldn't resist. From NutJob at gmx.net Fri May 12 05:04:52 2006 From: NutJob at gmx.net (antred) Date: 12 May 2006 02:04:52 -0700 Subject: Threads In-Reply-To: References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> Message-ID: <1147424692.502720.206970@j73g2000cwa.googlegroups.com> Aww shoot, I never knew that!! LOL, I implemented my own worker thread class using a mutex protected job list and a pair of connected sockets for interprocess communication when I could just have used the darn Queue module instead. Grrrrr .... hehe. From sjmachin at lexicon.net Sun May 7 23:26:34 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 08 May 2006 13:26:34 +1000 Subject: evaluation of > In-Reply-To: <87bqu99qv7.fsf@localhost.localdomain> References: <87bqu99qv7.fsf@localhost.localdomain> Message-ID: <445EBA6A.7030407@lexicon.net> On 8/05/2006 12:45 PM, Gary Wessle wrote: > what does the i > a in this code mean. because the code below is > giving False for all the iteration. isn't suppose to evaluate each > value of i to the whole list? thanks But that's EXACTLY what it's doing; each integer value named i is notionally being compared to the whole list value named a. However as the types differ (int vs list), it doesn't even look at the actual values. Each (rather meaningless) comparison evaluates to False. Did you read section 5.9 (Comparisons) of the Reference Manual? Deep in the fine print, it says "objects of different types always compare unequal, and are ordered consistently but arbitrarily". The answers might have all been True. > > a = range(8) > i = 0 > while i < 11: > print i > a The print statement is your friend. Use it more effectively. print i, a, i > a > i = i + 1 > > False > False [snip] Perhaps if you tell us what you thought the code should do, and/or what you are investigating, or trying to achieve .... From diffuser78 at gmail.com Fri May 12 10:53:14 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 12 May 2006 07:53:14 -0700 Subject: listener program in Python Message-ID: <1147445594.747005.61620@y43g2000cwc.googlegroups.com> I want to write a simple clinet/server program that does the following. On Windows, the program listens to the request from linux box On Linux Box, client program send server a shutdown request and the program at server i.e windows shuts windows sown, I basically want to remotely shut down windows from linux and write such a program in python. Every help is appreciated. From kay.schluehr at gmx.net Thu May 25 11:17:01 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 25 May 2006 08:17:01 -0700 Subject: John Bokma harassment In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <87ejyjv40w.fsf@rpi.edu> Message-ID: <1148570221.386411.160660@j33g2000cwa.googlegroups.com> Dra?en Gemic wrote: > Larry Elmore wrote: > > No shit. Lately it seems that for every "spam" post of Xah's, there's > > at three or more by John *to all the same newsgroups* bitching about > > Xah's use of bandwidth. Pot, meet kettle. I'm killfiling Xah for being > > a useless twit and killfiling John for being a prick about it. > > There is a person on USENET, particularly in hr. hierarchy that > posts under three different accounts. Sometimes he argues with > himself, and sometimes event supports himself :-) Sounds like me. In rare moments I believe that I'm not alone on usenet but there are other people as well. I wanted to go to the doctor because I believed I had a multiple personality but than I discovered that the doctor was me too. Kay From miki.tebeka at gmail.com Mon May 15 07:15:20 2006 From: miki.tebeka at gmail.com (Miki) Date: 15 May 2006 04:15:20 -0700 Subject: Web framework to recommend In-Reply-To: References: Message-ID: <1147691720.836530.3250@j55g2000cwa.googlegroups.com> Hello Jacky, I found CherryPy + Cheeta a good solution. See (shameless plug) http://www.unixreview.com/documents/s=10075/ur0604h/ Miki http://pythonwise.blogspot.com From robert.kern at gmail.com Sun May 21 01:40:43 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 May 2006 00:40:43 -0500 Subject: Feature request: sorting a list slice In-Reply-To: References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> Message-ID: Steve Holden wrote: > The effbot wrote: > >>George Sakkis wrote: >> >>>>It would be useful if list.sort() accepted two more optional >>>>parameters >> >>useful for what? what's the use case ? > > John Machin then wrote, without quoting any context at all: > >>Use case? > > He means "under what circumstances do you see someone actually using the > proposed feature rather than just nodding and saying "that looks > useful". IOW, who would use the new feature, and why? I believe that John was asking George for a use case rather than asking Fredrik what a use case was. -- 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 lamthierry at gmail.com Mon May 15 12:09:03 2006 From: lamthierry at gmail.com (Thierry Lam) Date: 15 May 2006 09:09:03 -0700 Subject: Finding yesterday's date with datetime Message-ID: <1147709343.491705.276360@v46g2000cwv.googlegroups.com> Is there an easy way to determine the yesterday's date(year-month-day) from the python datetime library if I know today's date? Thanks Thierry From belred at gmail.com Tue May 9 10:32:09 2006 From: belred at gmail.com (Bryan) Date: Tue, 09 May 2006 07:32:09 -0700 Subject: lines of code per functional point Message-ID: in document, which is titled, "Java and programmer productivity", there is a table on page 4 which shows LOC/FP for several languages. unfortunately, python is the only language "dashed out" and has no value. i'm unable to google and find a source that shows this value for python, but i did find other sites that show java and c++ at 53 LOC/FP which is the same as this document. is it safe to assume that python's value would be similar to perl's value of 21 ? http://www.abo.fi/~kaisa/FN.pdf thanks, bryan From cfbolz at gmx.de Sun May 7 15:24:26 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 07 May 2006 21:24:26 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <87d5ep4rbt.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87mzdt4ri5.fsf@rpi.edu> <87d5ep4rbt.fsf@rpi.edu> Message-ID: Bill Atkins wrote: [snip] >>Here's how one of the cells examples might look in corrupted Python >>(this is definitely not executable): >> >> class FallingRock: >> def __init__(self, pos): >> define_slot( 'velocity', lambda: self.accel * self.elapsed ) >> define_slot( 'pos', lambda: self.accel * (self.elapsed ** 2) / 2, >> initial_position = cell_initial_value( 100 ) ) >> self.accel = -9.8 >> >> rock = FallingRock(100) >> print rock.accel, rock.velocity, rock.pos >> # -9.8, 0, 100 >> >> rock.elapsed = 1 >> print rock.accel, rock.velocity, rock.pos >> # -9.8, -9.8, -9.8 >> >> rock.elapsed = 8 >> print rock.accel, rock.velocity, rock.pos >> # -9.8, -78.4, -627.2 >> >>Make sense? The idea is to declare what a slot's value represents >>(with code) and then to stop worrying about keeping different things >>synchronized. >> >>Here's another of the examples, also translated into my horrific >>rendition of Python (forgive me): >> >> class Menu: >> def __init__(self): >> define_slot( 'enabled', >> lambda: focused_object( self ).__class__ == TextEntry and >> focused_object( self ).selection ) >> >>Now whenever the enabled slot is accessed, it will be calculated based >>on what object has the focus. Again, it frees the programmer from >>having to keep these different dependencies updated. >> >>-- >>This is a song that took me ten years to live and two years to write. >> - Bob Dylan > > > Oh dear, there were a few typos: > > class FallingRock: > def __init__(self, pos): > define_slot( 'velocity', lambda: self.accel * self.elapsed ) > define_slot( 'pos', lambda: self.accel * (self.elapsed ** 2) / 2, > initial_value = cell_initial_value( 100 ) ) > self.accel = -9.8 > > rock = FallingRock(100) > print rock.accel, rock.velocity, rock.pos > # -9.8, 0, 100 > > rock.elapsed = 1 > print rock.accel, rock.velocity, rock.pos > # -9.8, -9.8, 90.2 > > rock.elapsed = 8 > print rock.accel, rock.velocity, rock.pos > # -9.8, -78.4, -527.2 > you mean something like this? (and yes, this is executable python): class FallingRock(object): def __init__(self, startpos): self.startpos = startpos self.elapsed = 0 self.accel = -9.8 velocity = property(lambda self: self.accel * self.elapsed) pos = property(lambda self: self.startpos + self.accel * (self.elapsed ** 2) / 2) rock = FallingRock(100) print rock.accel, rock.velocity, rock.pos # -9.8, 0, 100 rock.elapsed = 1 print rock.accel, rock.velocity, rock.pos # -9.8, -9.8, 95.1 rock.elapsed = 8 print rock.accel, rock.velocity, rock.pos # -9.8, -78.4, -213.6 Cheers, Carl Friedrich Bolz From thakur.dheeraj at gmail.com Thu May 18 19:59:53 2006 From: thakur.dheeraj at gmail.com (cracker) Date: 18 May 2006 16:59:53 -0700 Subject: Opensource vs Microsoft, Wat do you think about opensource? Message-ID: <1147996793.841733.109020@j33g2000cwa.googlegroups.com> Microsoft has dominated the world of computing for many years, with its heavily guarded 'code' being beyond reach to many in the developing nations. In some of the poorest countries the cost of upgrading an operating system to keep up with the rest of the world amounts to a year's wages, and there are few legitimate options. In Thailand for example, 95 percent of software on computers is pirated. The poorest countries are now beginning to use free or open source software (FOSS), a software that parallels many of Microsoft's programmes but with the major difference being that they are distributed free of charge and can be altered by computer programmers who are allowed unfettered access to the 'source code'. These days lots of discussion going on about Open source software and Paid software like (Microsofts) So wat do u think about opensource software? and what is your view about Microsoft share your views with us! and let us know what do you think about opensource software. http://www.desi-tek.com/forum/index.php?showtopic=394&st= From diffuser78 at gmail.com Fri May 5 09:31:23 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 5 May 2006 06:31:23 -0700 Subject: cross platform libraries In-Reply-To: <1146802366.107685.299870@i40g2000cwc.googlegroups.com> References: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> <1146802366.107685.299870@i40g2000cwc.googlegroups.com> Message-ID: <1146835883.634415.55510@i39g2000cwa.googlegroups.com> Hi Ravi, Do you have any idea how to perform such triigers ? Every help is appreciated. Ravi Teja wrote: > No! That's not the way things work. Such code needs to run locally (in > this case, Windows). You can run this program as a daemon on Windows > with some nice simple remote interface (Eg: xmlrpc) and send a message > to trigger the shutdown. From rschroev_nospam_ml at fastmail.fm Mon May 1 07:06:44 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 01 May 2006 11:06:44 GMT Subject: critique this little script, if you like In-Reply-To: <44558158$0$13341$c3e8da3@news.astraweb.com> References: <44554a32$0$11750$c3e8da3@news.astraweb.com> <874q0aa8em.fsf@localhost.localdomain> <44557f93$0$13307$c3e8da3@news.astraweb.com> <44558158$0$13341$c3e8da3@news.astraweb.com> Message-ID: <8Zl5g.400973$nA6.11343984@phobos.telenet-ops.be> John Salerno schreef: > John Salerno wrote: >> Dave Jones wrote: >>> Hi John! >>> >>> About the path and the \'s, take a look at the os.path.join function. >>> The function is smart enough to add the correct slash when joining >>> directories. >>> >>> Dave >> Interesting, thanks! I was reading about the normcase() function, but >> your suggestion might be better. > > Excellent, works great! But one more question: do I need to import > os.path for this? I tried it with and without it, and it worked both > ways, so I'm a little uncertain about whether os.path is really a > separate module, or if it is still contained within os and doesn't need > to be imported separately (it seems like it doesn't, but it is listed > separately in the docs). I always thought I had to import it separately, but just yesterday I discovered import os and import os.path do the same thing. If I do one of the two, doesn't matter which one, I can access both os.listdir and os.path.join. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From mumia.w.18.spam+fbi.gov at earthlink.net Mon May 22 04:03:31 2006 From: mumia.w.18.spam+fbi.gov at earthlink.net (Mumia W.) Date: Mon, 22 May 2006 08:03:31 GMT Subject: Software Needs Philosophers In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > Software Needs Philosophers > > by Steve Yegge, 2006-04-15. > > Software needs philosophers. > > [...] > ---- > This post is archived at: > http://steve-yegge.blogspot.com/2006/04/software-needs-philosophers.html > > and > http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html > > This essay is reported with permission. > > Xah > xah at xahlee.org > ? http://xahlee.org/ > Remember that this was a blog post from Steve Yegge that Xah Lee got permission to repost. It was a little long, and I got bored in the middle, but I think I understand (a little) Steve's point. He thinks we need software philosophers to break programmers' religious-like devotion to their languages of choice. I don't agree with this. I'd say we need software philosophers to help us see where software is taking us so that we can avoid bad spots if necessary. After all, the computer might just be the cotton gin of our time. We might be virtually enslaved by our own information if we don't watch out. Philosophers have the ability to think long, to think big, and to think about the future, and to think about the consequences of actions in a rational manner. They would be able to warn us if we were about to do something stupid with our society. However, Steve Yegge's software philosophers only serve to eliminate programmer's passions for their programming languages. While removing irrational beliefs is a good thing, I see Yegge's philosophers moving through the software industry, destroying everyone's passions for programming, and, as a result, the software industry is destroyed. It's scary the way I see it. On the other hand, I support rational thinking, and part of supporting rational thinking is (presumably) having the courage to support rational thinking even when the results are not to your immediate liking. IOW, I have to support something that scares the bejeebers out of me. Yet on the other, other hand, if people think rationally, the quality of life can only improve. Boy, am I confused :) Fortunately, people have their passions, for both programming and life, and that's not going to change anytime soon. If it does, it'll be a very gray world indeed. Thanks again Xah for getting these brain cells working again. From iddw at hotmail.com Wed May 17 20:12:07 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 17 May 2006 19:12:07 -0500 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) References: <1147885294.044080.132570@38g2000cwa.googlegroups.com> <446B6AD1.4080104@mvista.com> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <1147907634.532463.63730@u72g2000cwu.googlegroups.com> Message-ID: On 17 May 2006 16:13:54 -0700 in comp.lang.python, "achates" wrote: >Carl J. Van Arsdall wrote: > >> The converse can also be said, "it's difficult to make sure everyone >> uses spaces and not tabs". >> >> I think we've just about beat this discussion to death... nice work >> everyone! > >Yeah - we've got to the repeating ourselves stage. > >But that's the problem with this issue: it's really hard to get the >space-indenters to actually think about it and to address what is being >said. Every time it comes up, there's always a few people trying to Look in the mirror. There is non so blind... >explain why tabs give are a good idea, facing a whole raft of others The problem is that TABs are a _bad_ idea. >spouting stuff like: > 'mixing spaces and tabs is bad so use spaces only' Mixing TABs and spaces is bad because it means using TABs. ;-) > 'tabs are x spaces and I like to use y spaces' I've not seen that argument. One of us needs to read closer. Although I have seen the converse used to defend TABs: x spaces is x spaces, and I like y spaces, > 'tabs are bad end of story' Works for me! ;-) >and these non-arguments are repeated over and over within the same >thread. At times it's like talking to a child - and not a bright one at >that. These "non-arguments" are your own straw men. Either that, or you need to work on reading comprehension. > >Does it matter? Perhaps not if we can use tools which enable us to >bridge the divide, like indent auto-detection in emacs and vim. I'm >prepared to do that in cases where I have to work with an existing >group of coders uasing spaces. It matters because not every programmer is willing to put in the time effort required to learn how to use a sophisticated editor like emacs or vim well. Or at all. It matters because in industry you get programmers with a wide range of skills, and you can't fire everyone who can't tell when there are spaces in front of a tab character. Often these people have unique and hard-to-find domain knowledge. > >But unfortunately the situation is worse than that: tab indentation >needs to be actively defended. Most of the coding 'style guides' you'll No, it needs to be stamped out. ;-) >find (including Python's) advocate spaces only. There are plenty of Hallelujah! >people who would like tabs removed from the language as an acceptable >indentation method - look at the responses to Guido's April Fools blog >entry last year. I would love to see the TAB character treated as a syntax error. I have no illusions that's going to happen, though. FWIW, I would be equally (well, almost, anyway) happy if Python said that the _only_ place a TAB character could appear was at the beginning of a line, and that the number of TAB characters _always_ indicated the indentation level (e.g., spaces do _not_ change indentation level, and all the lines in a multi-line statement had to be at the same indentation level). This would eliminate most of my objections to TABs. I have no illusions this will happen either. > >Unlikely perhaps. I hope so. It's a cruel irony that Python's creator >didn't appreciate the benefits that tab indentation would bring to his >own language - the only major language in which indentation levels >actually have semantic significance. The problem with TAB characters is that they look just like the equivalent number of space characters. This is, of course, their major feature as well. The problem, especially with Python, is that mistakes in the placement of TAB characters within a source file can silently change the _meaning_ of the code. TAB proponents seem to list one overriding advantage of using TAB characters for indentation: "I can use my preferred indent level, and everyone else can use theirs." I find this argument _very_ weak. I've seen misuse of TABs break code. I've never seen an enforced indentation level break a programmer. Regards, -=Dave -- Change is inevitable, progress is not. From onurb at xiludom.gro Fri May 12 07:43:31 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 13:43:31 +0200 Subject: compiling module from string and put into namespace In-Reply-To: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> References: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> Message-ID: <4464754a$0$306$626a54ce@news.free.fr> glomde wrote: > Hi, > > I want to create a function that preprocesses a file and then imports > the parsed file. > > What I found out is that you can do something like this: > > def ImportFile(fileName): > parsedCode = Parser(fileName).Parse() > module = new.module(name) > exec parsedCode in module.__dict__ > sys.modules[name] = module > import name > > But this works only if the ImportFile isnt loaded from a module. > Since the import is local. Look for __import__() (it's in the builtins) and sys.modules. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From johnjsal at NOSPAMgmail.com Mon May 1 17:37:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 01 May 2006 21:37:26 GMT Subject: using ftplib In-Reply-To: <4456743d$0$2563$ed2619ec@ptn-nntp-reader02.plus.net> References: <4456743d$0$2563$ed2619ec@ptn-nntp-reader02.plus.net> Message-ID: Dave Hughes wrote: > Indeed. FTP is a tricky (and _very_ old) protocol that does things in a > very different manner to the later (simpler) protocols like HTTP. Not > sure how familiar you are with FTP, so my apologies if I wind up > repeating stuff you know already: Thanks very much, all that information was great to have. > TYPE A indicates that an ASCII transfer is to take place. An ASCII > transfer is intended for use with text files and indicates that the > data should be transformed from the native text format on the client > platform to the native text format on the server platform. For example, > transferring a file from a DOS/Windows client to a UNIX/Linux platform > in ASCII mode would convert CRLF line endings (ASCII char 13 + ASCII > char 10) to LF line endings (ASCII char 10). > > There are other transfer modes as well, though I forget exactly what > they are (there's probably one for EBCDIC :-). > > Take a look at the storbinary, storlines, retrbinary and retrlines > methods of the FTP object: looks like they perform the appropriate TYPE > command for you, then pass the specified command to transfercmd. So if I already have files on the server and I want to change file permissions, do I need to mess with TYPE A/TYPE I commands, or are those strictly for when you *transfer* files? Because I just did a quick test of changing file permissions through my FTP program, and it still sent a TYPE A command in the process. I know that the retr and stor methods might do this automatically, but if I don't need to use those, and just need to use transfercmd (assuming this *is* the right method to use when changing file permissions), do I need to manually send a TYPE A/I command as well? From fredrik at pythonware.com Wed May 3 02:43:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 08:43:32 +0200 Subject: ImportError: No module named HTMLParser References: <1146636851.237957.92470@v46g2000cwv.googlegroups.com> Message-ID: Mike wrote: > I'm getting the above message on a server installation (2.4) of Python. > I don't get the error using my script on my own machine. I'm trying to > use the non-sgmllib one - the standard HTMLParser but it won't import > on the server. How can I go about checking which file should reside > where? are you sure you're running 2.4 on the server ? (or rather, that your Python programs are picking up the 2.4 installation, and not some older version). did you do the installation yourself ? have you checked the contents of the sys.path variable ? does the output from python -v -c "import HTMLParser" look correct (i.e. does it search for stuff where you actually installed it) ? From michele.simionato at gmail.com Tue May 23 06:27:54 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 23 May 2006 03:27:54 -0700 Subject: Name conflict in class hierarchy In-Reply-To: References: Message-ID: <1148380074.276062.281360@j33g2000cwa.googlegroups.com> Jeffrey Barish wrote: > I believe that the answer to my question is no, but I want to be sure that I > understand this issue correctly: Suppose that there are two classes > defined as follows: > > class A(object): > def f1(self): > print 'In A.f1, calling func' > self.func() > > def func(self): > print 'In A.func' > > class B(A): > def func(self): > print 'In B.func, calling A.f1' > A.f1(self) > > Class A was defined by someone else or it comes from a library, so I have no > prior information about what is in it. I subclass A to add some new > functionality, and I call the new function "func". The function B.func > uses A.f1, but unbeknownst to me, A.f1 uses A.func. Unfortunately, class B > overrides func, so the call in A.f1 to self.func actually invokes B.func, > resulting in this case in an infinite loop. Is there a way from B to > specify that A should use its own version of func and ignore the version in > B? I know that I could rename A.func to avoid the name clash, but since A > is actually in a library, I will lose that change when I upgrade the > library. I could rename B.func, but there is already a bunch of code that > calls it so I would have to update all the calls. That seems like the > correct solution, though. The other possibility is to use composition > rather than subclassing: > > class B: > def func(self): > print 'In B.func, calling A.f1' > a = A() > a.f1() > > but then B does not inherit other functions of A that I would like to use. > It struck me that this must be a common problem in OOP, so I'm wondering > whether there is a simple solution that I am missing. I was bitten by the same issue the first time I used Zope :-( This is my solution, a metaclass that warns you if you try to override an attribute defined in some ancestor: class Base(object): func = 1 class check_if_we_are_overriding_names(type): def __new__(mcl, name, bases, dic): for name, val in dic.iteritems(): if name.endswith("__"): continue if sum(hasattr(base, name) for base in bases): print "AlreadyDefinedNameWarning:", name return super(check_if_we_are_overriding_names, mcl).__new__( mcl, name, bases, dic) class MyClass(Base): __metaclass__ = check_if_we_are_overriding_names func = 2 # you will get a warning at this point Michele Simionato From llosee at gmail.com Mon May 15 16:09:24 2006 From: llosee at gmail.com (Lou Losee) Date: Mon, 15 May 2006 16:09:24 -0400 Subject: Aggregate funuctions broken in MySQLdb? In-Reply-To: References: <1147623011.319336.11820@v46g2000cwv.googlegroups.com> Message-ID: Try these: http://sourceforge.net/docman/?group_id=22307 and for the Python DB API overall: http://www.python.org/dev/peps/pep-0249/ Lou On 5/15/06, Lorenzo Thurman wrote: > > Thanks, that was my problem. Can you point me to some documentation on > MySQLdb? I've been googling to get answers and that obviously has not > been working. > > > > > In article <1147623011.319336.11820 at v46g2000cwv.googlegroups.com>, > "Wade Leftwich" wrote: > > > Works fine for me, and I certainly hope MySQLdb is ready for prime > > time, because I use the heck out of it. Maybe you're getting fooled by > > the fact that cursor.execute() returns the count of result rows. To > > actually see the result rows, you have to say cursor.fetchone() or > > fetchall() -- > > > > In [34]: cur.execute("select article_id from articles limit 10") > > Out[34]: 10L > > > > In [35]: cur.fetchall() > > Out[35]: ((3L,), (4L,), (5L,), (6L,), (7L,), (8L,), (9L,), (10L,), > > (11L,), (12L,)) > > > > In [36]: cur.execute("select count(article_id) from articles where > > article_id < 13") > > Out[36]: 1L > > > > In [37]: cur.fetchall() > > Out[37]: ((10L,),) > > > > In [38]: cur.execute("select sum(article_id) from articles where > > article_id < 13") > > Out[38]: 1L > > > > In [39]: cur.fetchone() > > Out[39]: (75.0,) > > > > In [40]: cur.execute("select avg(article_id) from articles where > > article_id < 13") > > Out[40]: 1L > > > > In [41]: cur.fetchone() > > Out[41]: (7.5,) > -- > http://mail.python.org/mailman/listinfo/python-list > -- Artificial Intelligence is no match for Natural Stupidity -------------- next part -------------- An HTML attachment was scrubbed... URL: From siona at chiark.greenend.org.uk Fri May 5 09:47:26 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 05 May 2006 14:47:26 +0100 (BST) Subject: Tuple assignment and generators? References: <1146826136.746268.4060@i40g2000cwc.googlegroups.com> <445b3960$1_3@news.bluewin.ch> <1146831804.396839.316070@v46g2000cwv.googlegroups.com> Message-ID: vdrab wrote: >let's say there's a certain property P, for the sake of this loooong >discussion, something >more or less like a class or type's property of "having immutable >values, such that any instance with value X has a single, unique >representation in memory and any two instantiations of objects with >that value X are in fact references to the same object". > >Then, for example, python strings have property P whereas python lists >do not: Er, no: >>> x = "test!" >>> y = "test!" >>> x == y True >>> x is y False Strings only get a unique instance if they are valid identifiers. Again, it's an optimisation issue. As with ints, it >_depends_on_their_value_. >I find it neither evident nor consistent. I don't think the above post >explains this, regardless of how you read "implementation". "Implementation dependent" => "Any behaviour you observe which is not explicitly documented is not to be relied upon". Also, "Implementation dependent" => "How this is implemented should be transparent and irrelevant to the normal user". No, it's not particularly consistent. Because it doesn't matter. -- \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 grante at visi.com Wed May 3 22:50:28 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 04 May 2006 02:50:28 -0000 Subject: Packet finding and clicking... References: <1146526807.262200.247870@u72g2000cwu.googlegroups.com> <1146705860.347800.219720@y43g2000cwc.googlegroups.com> Message-ID: <125iqvko53brtea@corp.supernews.com> On 2006-05-04, klauts wrote: > anyone have any help on this subjecT? I use tcpdump or ethereal for packet finding. For clicking, I use a logitech optical wheel mouse for desktops or the integrated touchpoint/touchpad on my IBM ThinkPad. -- Grant Edwards grante Yow! I want a VEGETARIAN at BURRITO to go... with visi.com EXTRA MSG!! From email at christoph-haas.de Thu May 18 15:55:29 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 18 May 2006 21:55:29 +0200 Subject: Sorting of list containing tuples In-Reply-To: <20060518195239.GC5309@workaround.org> References: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> <7x1wurcecw.fsf@ruckus.brouhaha.com> <20060518195239.GC5309@workaround.org> Message-ID: <20060518195529.GD5309@workaround.org> On Thu, May 18, 2006 at 09:52:39PM +0200, Christoph Haas wrote: > On Thu, May 18, 2006 at 12:38:55PM -0700, Paul Rubin wrote: > > Ronny Mandal writes: > > > And now I want to sort l reverse by the second element in the tuple, > > > i.e the result should ideally be: > > > > > > l = [(6,5),(2,3),(3,2)] > > > > sorted(l, key = lambda a: -a[1]) > > Or in Python <2.4: > > l.sort(lambda x,y: x[1]-y[1]) > > (Although that's not technically perfect. Sort expect a function that > returns -1, 0 or 1. Here we get positive integers and negative > integers. YMMV.) Crap... why do I always forget about cmp()? :) This should be it: l.sort(lambda x,y: cmp(x[1],y[1])) Kindly Christoph From OlafMeding at gmail.com Wed May 3 14:42:08 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 11:42:08 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled Message-ID: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> Below are 2 files that isolate the problem. Note, both programs hang (stop responding) with hyper-threading turned on (a BIOS setting), but work as expected with hyper-threading turned off. Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional. winmsd.exe shows: 2CPUs: x86 Family 15 Model 4 Stepping 1 GenuineIntel ~3000 MHz Version: 5.1.2600 Service Pack 2 Build 2600 Could someone with a hyper-threading (or dual/multicore) CPU please confirm this bug? Many Thanks Olaf # testsleep.py import threading import time class Task(threading.Thread): def __init__(self, n, t): threading.Thread.__init__(self) self.n = n self.t = t def run(self): print 'thread %d started' % self.n print 'sleep time:', self.t print time.clock() print time.clock() print time.clock() print count = 0 printCount = int(10 / self.t) while True: start = time.clock() time.sleep(self.t) stop = time.clock() if stop - start > 1.0: print 'thread', self.n, stop - start count += 1 if count > printCount: count = 0 print self.n, def test(): thread1 = Task(1, 0.01) thread2 = Task(2, 0.003) thread1.start() thread2.start() test() ------------------------------------------------------------------------ # testsleep2.py import thread import time import sys def run(n, t): print 'thread %d started' % n print 'sleep time:', t print time.clock() print time.clock() print time.clock() print count = 0 printCount = int(10 / t) while True: start = time.clock() time.sleep(t) stop = time.clock() if stop - start > 1.0: print 'thread', n, stop - start count += 1 if count > printCount: count = 0 print n, def test(): thread.start_new_thread(run, (1, 0.01)) thread.start_new_thread(run, (2, 0.003)) # Wait until the user presses the enter key. sys.stdin.read(1) test() From russell_turpin at hotmail.com Mon May 22 11:17:49 2006 From: russell_turpin at hotmail.com (Russell) Date: 22 May 2006 08:17:49 -0700 Subject: How does a generator object refer to itself? Message-ID: <1148311069.417177.254550@y43g2000cwc.googlegroups.com> This is more a Python 2.5 question, since it is the send() method that makes this so useful. The issue is how to write a generator that refers to its own generator object. This would be useful when passing control to some other function or generator that is expected to return control via a send(): def me(): .. nextVal = yield you(me.send) # This is wrong! That almost looks right, except that "me" isn't really the generator object that is executing, it is the function that produces the generator object. It seems somewhere I read that some keyword ("generator"?) would work in this context, but now I can't find where I read that. Maybe I imagined it. Thanks! From prouleau at impathnetworks.com Tue May 16 23:16:28 2006 From: prouleau at impathnetworks.com (Pierre Rouleau) Date: Tue, 16 May 2006 23:16:28 -0400 Subject: Is the only way to connect Python and Lua through a C interface? In-Reply-To: <3btk62hlopp7ou0g5upnarl5eail29lqms@4ax.com> References: <3btk62hlopp7ou0g5upnarl5eail29lqms@4ax.com> Message-ID: Casey Hawthorne wrote: > Is the only way to connect Python and Lua through a C interface? Take a look at Lunatic Python (http://labix.org/lunatic-python) -- Pierre Rouleau From bucodi at yahoo.fr.invalid Thu May 4 11:11:04 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 04 May 2006 17:11:04 +0200 Subject: Unicode code has no method float() ? References: Message-ID: Works, thank you > Le 04-05-2006, Rony nous disait: >> How can I get the value of a Unicode object ? >> >> When I do myobject.float() I get the error message that it doesn't have >> a float() attribute > > Try to use the float builtin function, as in: float(myobject) instead of > a method. -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From bignose+hates-spam at benfinney.id.au Fri May 19 20:33:17 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 May 2006 10:33:17 +1000 Subject: Exception style References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <446da180$0$10184$636a55ce@news.free.fr> <126rjus43k450df@corp.supernews.com> <9121k3-hjm.ln1@lairds.us> Message-ID: <87sln5k01e.fsf@benfinney.id.au> "Fredrik Lundh" writes: > Cameron Laird wrote: > > how do I know that the NameError means VARIABLE didn't resolve, > > rather than that it did, but that evaluation of > > commands.VARIABLE() itself didn't throw a NameError? My usual > > answer: umm, unless I go to efforts to prevent it, I *don't* know > > that didn't happen. > > two notes: > > 1) getattr() raises an AttributeError if the attribute doesn't > exist, not a NameError. > > 2) as you point out, doing too much inside a single try/except often > results in hard- to-find errors and confusing error messages. the > try-except-else pattern comes in handy in cases like this: > > try: > f = getattr(commands, name) > except AttributeError: > print "command", name, "not known" > else: > f() Gah. As is often the case, Frederick has avoided my mistakes and said what I wanted to say, better. -- \ "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 lorenzo at nospamthethurmans.com Thu May 11 11:28:25 2006 From: lorenzo at nospamthethurmans.com (Lorenzo Thurman) Date: Thu, 11 May 2006 10:28:25 -0500 Subject: NEWBIE: Tokenize command output Message-ID: This is what I have so far: // #!/usr/bin/python import os cmd = 'ntpq -p' output = os.popen(cmd).read() // The output is saved in the variable 'output'. What I need to do next is select the line from that output that starts with the '*' remote refid st t when poll reach delay offset jitter ========================================================================= ===== +ntp-1.gw.uiuc.e 128.174.38.133 2 u 479 1024 377 33.835 -0.478 3.654 +milo.mcs.anl.go 130.126.24.44 3 u 676 1024 377 70.143 1.893 1.296 *caesar.cs.wisc. 128.105.201.11 2 u 635 1024 377 29.514 -0.231 0.077 >From there, I need to tokenize the line using the spaces as delimiters. Can someone give me some pointers? Thanks From steve at holdenweb.com Tue May 30 17:04:53 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 May 2006 22:04:53 +0100 Subject: os.time() In-Reply-To: <4e2helF1cvdleU1@uni-berlin.de> References: <4e2helF1cvdleU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Anthony wrote: > > >>i have a problem with the os.times() command, on different Python >>versions, i get different printout: > > > >>and on the 3 servers, the linux command: $date >>returns the same value..... >> >>any suggestions??? >>what is the command that gives me the actual time? > > > time.time(), not os.times(). The latter is for process-times. No idea why it > can become _negative, though. > > Diez WANTED: reliable benchmarks to improve Python speed/performance estimation. REWARD: the thanks of the whole community. I spent some time at the recent Need For Speed sprint addressing benchmarking questions, and discovered that we need more benchmark tests for speed and perfomance. Sean Reifenshneider seems to be on the trail of one addition, but the, more the merrier. It's not easy to write good benchmarks ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From jstroud at ucla.edu Wed May 3 22:28:48 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 03 May 2006 19:28:48 -0700 Subject: Any useful benefit to a tiny OS written in Python? In-Reply-To: <1146707569.227486.278750@j73g2000cwa.googlegroups.com> References: <1146707569.227486.278750@j73g2000cwa.googlegroups.com> Message-ID: seberino at spawar.navy.mil wrote: > I was curious if there was any benefit to having an OS written > in Python. > > The only benefit I can think of is that maybe Python is easier > to audit for security bugs than C is. > > > Any other benefits? > > Chris > http://unununium.org/ -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From duncan.booth at invalid.invalid Mon May 8 09:04:38 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 May 2006 13:04:38 GMT Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> Message-ID: Mirco Wahab wrote: > Lets see - a really simple find/match > would look like this in Python: > > import re > > t = 'blue socks and red shoes' > p = re.compile('(blue|white|red)') > if p.match(t): > print t > > which prints the text 't' because of > the positive pattern match. > > In Perl, you write: > > use Acme::Pythonic; > > $t = 'blue socks and red shoes' > if ($t =~ /(blue|white|red)/): > print $t > > which is one line shorter (no need > to compile the regular expression > in advance). > There is no need to compile the regular expression in advance in Python either: t = 'blue socks and red shoes' if re.match('(blue|white|red)', t): print t The only advantage to compiling in advance is a small speed up, and most of the time that won't be significant. From jerry.levan at gmail.com Mon May 29 19:10:11 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 29 May 2006 16:10:11 -0700 Subject: How to use tk.call ? Message-ID: <1148944211.145450.46030@j33g2000cwa.googlegroups.com> Hi, I am trying to port one of my Tcl/Tk apps to Python ( 2.4.2/3). One task is to try to be able to use my wheel mouse to scroll a Tktable object. The tcl code looks like: #Support the MouseWheel bind $ui_vars(table) { $ui_vars(table) yview scroll -5 units } bind $ui_vars(table) { $ui_vars(table) yview scroll +5 units } bind $ui_vars(code) { $ui_vars(code) yview scroll -5 units } bind $ui_vars(code) { $ui_vars(code) yview scroll +5 units } $ui_vars(table) is the table and $ui_vars(code) is a text widget. on the python side I can get scrolling in the text widget by # Support for mouse wheel self.command.bind("",self.command.yview_scroll(-5 ,'units')) self.command.bind("",self.command.yview_scroll(5,'units')) Unfortunately the python Tkinter Table widget does not support the yview_scroll command. I have tried the following: self.table.bind("",self.table.tk.call(self.table._w,'yview','scroll',-5,'units') but, alas nothing happens.... I can't find how too use tk.call, can anyone give me a clue as to how to solve my problem? Thanks, Jerry From NOatkinwSPAM at rpi.edu Sun May 7 05:05:11 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 05:05:11 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1146990071.634244.83380@i39g2000cwa.googlegroups.com> Message-ID: <871wv6b3y0.fsf@rpi.edu> brian at sweetapp.com writes: > Bill Atkins wrote: >> Buh? The project doesn't have to be late for Brooks's law to hold; >> adding programmers, so goes Brooks reasoning, will always increase the >> time required to complete the project because of various communication >> issues. > > 1. This is not what Brooks says. Brooks was talking about late > projects. Please provide a supporting quote if you wish to continue > to claim that "adding programmers will always increase the time > required to complete the project". The "always" in my claim should not be there, I admit. Brooks didn't claim that. I refer you to pages 17 - 18 of The Mythical Man-Month: Since software construction is inherently a systems effort - an exercise in complex interrelationships - communication effort is great...Adding more men then lengthens, not shortens, the schedule. It is totally absurd to assume that, simply because a project has not yet passed its deadline, it will somehow become immune to the kinds of things Brooks is talking about. His thesis is that adding programmers to an already-in-progress project will cause a delay, because the new programmers must be brought up to speed. It does not matter if the project is eight weeks late or has only been active for a month. This issue still remains: The two new men, however competent and however quickly trained, will require training in the task by one of the experienced men. If this takes a month, 3 man-months will have been devoted to work not in the original estimate. (p. 24, TMM-M) Brooks's Law mentions only late projects, but the rest of his discussion applies to adding programmers in the middle of *any* project. Is this really so radical an idea? > 2. There has to be a mechanism where an organization can add > developers - even if it is only for new projects. Python advocates Obviously. > would say that getting developers up to speed on Python is easy > because: > > - it fits most programmers brains i.e. it is similar enough to > languages that most programmers have experience with and the > differences are usually perceived to beneficial (exception: > people from a Java/C/C++ background often perceive dynamic > typing as a misfeature and have to struggle with it) > - the language is small and simple > - "magic" is somewhat frowned upon in the Python community i.e. > most code can be taken at face value without needing to learn a > framework, mini-language, etc. (but I think that the Python > community could do better on this point) These are not things I look for in a programming language. > > I'm sure that smarter people can think of more points. > >> Fair enough. But what does Python offer above any garbage-collected >> language that makes it so scalable? > > See above point - you can more easily bring programmers online in your > organization because most programmers find Python easily learnable. > And, as a bonus, it is actually a pretty flexible, powerful language. > > Cheers, > Brian > -- This is a song that took me ten years to live and two years to write. - Bob Dylan From junkytownMAKNI at gmail.com Mon May 29 03:05:36 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Mon, 29 May 2006 09:05:36 +0200 Subject: saving settings Message-ID: Hi, I was wondering how to make a single .exe file, say some kind od clock, and be able to save some settings (alarm for example) into the same file? Basically make code rewrite it self... thanks! From larry.bates at websafe.com Tue May 9 15:42:14 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 09 May 2006 14:42:14 -0500 Subject: How to recast integer to a string In-Reply-To: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> References: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> Message-ID: James wrote: > How to recast an integer to a string? > > something like > n = 5 > str = str + char(n) > > > J.L > Two items: 1) Never use 'str' as a variable name as it will shadow the built in str function. If you do, this WILL jump up and bite you. 2) Either s=str(n) or s="%i" % n will return string containing '5' (without the quotes of course). Note: chr(n) would return character whose ASCII decimal value is 5 (ASCII ENQ). -Larry Bates From webraviteja at gmail.com Sun May 28 16:51:41 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 28 May 2006 13:51:41 -0700 Subject: html 2 plain text In-Reply-To: <1148840205.741356.209310@i40g2000cwc.googlegroups.com> References: <1148840205.741356.209310@i40g2000cwc.googlegroups.com> Message-ID: <1148849500.971718.273340@i40g2000cwc.googlegroups.com> > i remember seeing this simple python function which would take raw html > and output the content (body?) of the page as plain text (no <..> tags > etc) http://www.aaronsw.com/2002/html2text/ From rpdooling at gmail.com Fri May 5 16:25:00 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 5 May 2006 13:25:00 -0700 Subject: Best IDE for Python? In-Reply-To: References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> <288425520605050850i6f94518nafd34adb6ae6581e@mail.gmail.com> Message-ID: <1146860699.973545.326430@i39g2000cwa.googlegroups.com> Here's a shot of Komodo, albeit embedded in a pdf http://www.activestate.com/Products/Komodo/ActiveState_Komodo_datasheet.pdf From nobody at 127.0.0.1 Wed May 3 13:35:44 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 17:35:44 GMT Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> Message-ID: tsaar2003 at yahoo.com wrote: > What I'd like to see here is that b gets a copy of A so that the > original A won't be modified as we play with b. However, as we assign a > constant value A to b, I wouldn't want to restrict myself from playing > with b. If A is a list you can take a copy-slice liek this: >>> b = A[:] and changes to b won't affect A. For the general case where A isn't a list, you can use the copy module to make shallow or deep copies of A. http://docs.python.org/lib/module-copy.html It's not quite as simple or as strict as declaring A constant, but it works. Or you could look at properties, there's a thread in this group within the last couple weeks about making constants with properties. From Depcnb1 at aol.com Wed May 24 14:04:33 2006 From: Depcnb1 at aol.com (Depcnb1 at aol.com) Date: Wed, 24 May 2006 14:04:33 EDT Subject: perl to python Message-ID: <38e.3c50c70.31a5fa31@aol.com> This is Jeff Hutchinson -------------- next part -------------- An HTML attachment was scrubbed... URL: From mwilson-to at sympatico.ca Wed May 31 16:57:47 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Wed, 31 May 2006 16:57:47 -0400 Subject: using import * with GUIs? In-Reply-To: References: Message-ID: John Salerno wrote: > Hi all. Quick question (but aren't they all?) :) > > Do you think it's a good idea to use the 'from import *' > statement when using a GUI module? It seems on wxPython's site, they > recommend using import wx nowadays, but I wonder if that advice is > followed. Also, I'm still reading some Tkinter docs that seem to use > 'from Tkinter import *' a lot. > > I understand the danger of doing this, but is it safer in these cases, > given the more specific names that GUI frameworks tend to use > (sometimes!)? Or should you still qualify all your calls with the module? More specific? I dunno, I have trouble thinking of that huge multitude of names in wx as specific. Who knows what in all that might collide with names you devise? My formative experience came when I was looking at Python Imaging Library Demo code. Somebody did a simple call to open and got returned an entire Jpeg image object. I knew that open was destined to take arguments other than simple file paths, and return things other than simple files, but it seemed awfully soon. Then I got suspicious, looked at the top of the code, and saw "from Image import *" So a word, too, to people writing demo programs. Writing "from mycode import *" obscures which code is actually yours in the code following. Kind of defeats the purpose. Cheers, Mel. From bdesth.quelquechose at free.quelquepart.fr Wed May 3 00:01:08 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 06:01:08 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: <4457fc52$0$31159$636a55ce@news.free.fr> Edward Elliott a ?crit : > Bruno Desthuilliers wrote: > >>Edward, I know I told you so at least three times, but really, >>seriously, do *yourself* a favor : take time to read about descriptors >>and metaclasses - and if possible to experiment a bit - so you can get a >>better understanding of Python's object model. Then I'll be happy to >>continue this discussion (. > > Will do, if nothing else it will eliminate language barriers, which we may > be running into at this point (though you've indicated otherwise). You won't regret it anyway - my own experience is that you must go thru this to really take full advantage of Python's power, expressivity and flexibility. Oh, and, yes : it's definitively fun too !-) > I appreciate your > patience and willingness to engage in this discussion. Votre serviteur, Messire. > As a last ditch effort to get my point across: > > Compiler, interpreter, magic-codey-runny-thingy, whatever, at some point > something has to translate this source code > def method (self, a, b): something > into a function object (or whatever you're calling the runnable code this > week). AFAIK, this is done by partly by the compiler and partly by the interpreter. > Call this translator Foo. Whatever Foo is, it can insert 'self' > into the parameter list for method, This would have to happen before compilation - I'd say at parsing time. But then, constructs like: class Obj(object): def method(...): ... method = staticmethod(method) or it's newer syntactic-sugar-version would become somewhat more difficult to parse properly - but I admit that this is beyond my knowledge. > e.g. when it sees "def method (a,b)" This has to be in a class statement - else it's shouldn't be touched. > it > pretend like it saw "def method (self,a,b)" and proceed as usual. Once it > does that, everything is exactly the same as before. > > I can prove that assertion too: make a simple text processor that reads > Python source code and outputs the same source code with only one change: > insert the string 'self" as the first parameter of every "def somemethod". Not so simple: you have plain functions (outside class statements), and inner functions (inside def statements), and classmethods, and statict methods, and some other corner cases (like __new__()) to take into acccount... As I said, this requires more than a simple pre-processor and so would have to be done at parsing time since it requires parsing anyway. I don't know enough about Python's parser to tell if it could work and how hard this would be. > Next run the output source code with the normal Python interpreter. > Everything functions *exactly* as before because the code is *exactly* the > same as what you would have written if you'd put the 'self's in there > manually. Now make the Python interpreter invoke this text processor as > the first step in processing source code. Voila, python + implicit self. cf above. > No changes to the object model. seems not. > No changes to dynamic binding. idem > Same "runnable" code as before. seems so. > Where is the problem in this scheme? > Or (since I haven't read up on the object model yet) simply: Is there a > problem? Apart from the added complexity to the parser, I don't find one righ now - but note that there may as well be something obviously wrong that I fail to spot (it's very late here and I had a hard day !-). I of course don't take into account the fact that this would break all existing Python code, which is unavoidable for such a syntactic change. Well, I must admit that done this way (which is quite different from what I understood from your previous posts), this could *perhaps* (unless I missed something - any guru around here ?) work. At least it does not sound so crazy. Now is this something good is another point. I was about to argue that I don't like the implicitness of it, but 1/ this is how most OOPLs do (at least from a syntactic POV) and 2/ the fact is that the instance is implicitely passed at call time, so I guess I'm just way too intoxicated by so many years of Python programming to feel at ease with this !-) Since Python 3K is supposed to be the 'clean the warts and don't bother breaking compat' rewrite of Python, you may as well propose a PEP on this. You'll have to really prove it doesn't break anything else in the object model, have strong and articulate arguments to support your point (like proving this is really a common source of confusion for newbies), and I really doubt it'll be accepted anyway. But what... Ok, time to bed now - I'll re-read this when my one and only neuron left will be willing and able to do its job !-) From patrick.d.hull at gmail.com Thu May 11 17:07:41 2006 From: patrick.d.hull at gmail.com (patrick.d.hull at gmail.com) Date: 11 May 2006 14:07:41 -0700 Subject: pythoncode in matlab References: <4cgogmF15ljumU1@news.dfncis.de> <1147363274.990265.163990@i39g2000cwa.googlegroups.com> Message-ID: <1147381661.897379.202690@i40g2000cwc.googlegroups.com> > PyMat will not help you! PyMat works the other way around, ie it > allows for Matlab calls from Python. excuse my ignorance: but why would that not be helpful? I may be missing something blindingly stupid (very possible) but it seems to me using PyMat would be just as powerful (if not more) as building extensions... -ph From john at castleamber.com Wed May 24 11:07:11 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:07:11 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: Ken Tilton wrote: > Ben Bullock wrote: >> "Xah Lee" wrote in message >> news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... >> >>> If you believe this lobbying to my webhosting provider is unjust, >>> please write to my web hosting provider abuse at dreamhost.com >> >> >> Why don't you just change your provider? It would take less time than >> this. > > Are you joking. "Just change your provider?" Do you have a little > button on your computer that says "Change provider"? Cool! :) No, it will cost Xah money. In the end he will be with a bullet proof hoster, like other kooks on Usenet, or get the message. > C'mon, John Bokma (and everyone else dumb enough to crosspost their > shushing to every group on the crosspost list -- why do they do that? So other people can read that reporting Xah *does* have an effect. A lot of people think that a kill file is the only solution. > So Xah will hear them six times? No, they want everyone to see how > witty they are when they tell Xah off. So you haven't noticed that Xah does just hit & run posting? In short, you have no clue what this is about, or are one of the fans Xah seem to have? Get a clue Kenny. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From jparlar at cogeco.ca Fri May 5 07:57:31 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Fri, 5 May 2006 07:57:31 -0400 Subject: unittest.main-workalike that runs doctests too? In-Reply-To: References: Message-ID: On May 5, 2006, at 6:35 AM, John J. Lee wrote: > ...I wrote something to do this once, but didn't do as good a job as I > might have done and wondered if anybody else has done it properly. > > I know about nose, but it seems just a little too magical for my > tastes, and includes stuff I don't really need. > > > John > > -- > http://mail.python.org/mailman/listinfo/python-list > nose actually has very little magic, its operation is quite straightforward. I've played with its codebase before, and it's quite clean. And the new 0.9 branch uses a plugin system for some of the extra functionality, so you don't even have to install all the things it's capable of doing. Jay P. From Serge.Orlov at gmail.com Mon May 1 21:21:24 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 May 2006 18:21:24 -0700 Subject: Can Python kill a child process that keeps on running? References: Message-ID: <1146532884.872505.154370@i40g2000cwc.googlegroups.com> I. Myself wrote: > Suppose we spawn a child process with Popen. I'm thinking of an > executable file, like a compiled C program. > Suppose it is supposed to run for one minute, but it just keeps going > and going. Does Python have any way to kill it? > > This is not hypothetical; I'm doing it now, and it's working pretty > well, but I would like to be able to handle this run-on condition. I'm > using Windows 2000, but I want my program to be portable to linux. On linux it's pretty easy to do, just setup alarm signal. On windows it's not so trivial to the point you cannot do it using python.org distribution, you will need to poke in low level C API using win32 extensions or ctypes. AFAIK twisted package has some code to help you. Also take a look at buildbot sources that uses twisted. Buildbot has the same problem as you have, it needs to kill run away or non-responding processes. From jerry.levan at gmail.com Tue May 30 00:13:07 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 29 May 2006 21:13:07 -0700 Subject: How to use tk.call ? References: <1148944211.145450.46030@j33g2000cwa.googlegroups.com> Message-ID: <1148962387.776015.157320@j33g2000cwa.googlegroups.com> >> self.table.bind("",self.table.tk.call(self.table._w,'yview','scroll',-5,'units') >I haven't used Table, but are you sure that what you are calling >"self.table" here actually has mouse focus? >James Yup, I click on the table, and then frantically work the mouse wheel to no effect... Jerry From paddy3118 at netscape.net Sat May 13 05:39:21 2006 From: paddy3118 at netscape.net (Paddy) Date: 13 May 2006 02:39:21 -0700 Subject: Named regexp variables, an extension proposal. Message-ID: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> Proposal: Named RE variables ====================== The problem I have is that I am writing a 'good-enough' verilog tag extractor as a long regular expression (with the 'x' flag for readability), and find myself both 1) Repeating sections of the RE, and 2) Wanting to add '(?P...) ' around sections because I know what the section does but don't really want the group. If I could write: (?P/verilog_name/ [A-Za-z_][A-Za-z_0-9\$\.]* | \\\S+ ) ...and have the RE parser extract the section of RE after the second '/' and store it associated with its name that appears between the first two '/'. The RE should NOT try and match against anything between the outer '(' ')' pair at this point, just store. Then the following code appearing later in the RE: (?P=verilog_name) ...should retrieve the RE snippet named and insert it into the RE instead of the '(?P=...)' group before interpreting the RE 'as normal' Instead of writing the following to search for event declarations: vlog_extract = r'''(?smx) # Verilog event definition extraction (?: event \s+ [A-Za-z_][A-Za-z_0-9\$\.]* \s* (?: , \s* [A-Za-z_][A-Za-z_0-9\$\.]*)* ) ''' I could write the following RE, which I think is clearer: vlog_extract = r'''(?smx) # Verilog identifier definition (?P/IDENT/ [A-Za-z_][A-Za-z_0-9\$\.]* (?!\.) ) # Verilog event definition extraction (?: event \s+ (?P=IDENT) \s* (?: , \s* (?P=IDENT))* ) ''' Extension; named RE variables, with arguments =================================== In this, all group definitions in the body of the variable definition reference the literal contents of groups appearing after the variable name, (but within the variable reference), when the variable is referenced So an RE variable definition like: defs = r'(?smx) (?P/GO/ go \s for \s \1 )' Used like: rgexp = defs + r""" (?P=GO (it) ) \s+ (?P=\GO (broke) ) """ Would match the string: "go for it go for broke" As would: defs2 = r'(?smx) (?P/GO/ go \s for \s (?P=subject) )' rgexp = defs2 + r""" (?P=GO (?P it) ) \s+ (?P=\GO (?P broke) ) """ The above would allow me to factor out sections of REs and define named, re-ussable RE snippets. Please comment :-) - Paddy. From michele.petrazzo at TOGLIunipex.it Mon May 1 05:37:07 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 01 May 2006 11:37:07 +0200 Subject: OpenOffice UNO export PDF help needed In-Reply-To: References: Message-ID: <4455d6c3$0$29093$5fc30a8@news.tiscali.it> Sells, Fred wrote: > I've geen googling for 3 days now, and cannot find out how to do > this. > > I'm trying to use OpenOffice 2.0 and UNO to generate PDF documents. > I'm using windows, but will have to make it work under Linux for > production. I've been able to set the parameters and call the > exportToPdf method, but the exported file is not PDF but an .odt > document, Have you tried the ooextract.py found on: http://udk.openoffice.org/python/python-bridge.html Here work well and generate a pdf file. See also this for more info about generate pdf: http://mithrandr.moria.org/blog/447.html Michele From gisleyt at gmail.com Thu May 25 05:58:17 2006 From: gisleyt at gmail.com (gisleyt) Date: 25 May 2006 02:58:17 -0700 Subject: regex in python Message-ID: <1148551097.266423.141230@j55g2000cwa.googlegroups.com> I'm trying to compile a perfectly valid regex, but get the error message: r = re.compile(r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*') Traceback (most recent call last): File "", line 1, in ? File "/usr/lib/python2.3/sre.py", line 179, in compile return _compile(pattern, flags) File "/usr/lib/python2.3/sre.py", line 230, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat >>> What does this mean? I know that the regex ([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.* is valid because i'm able to use it in Regex Coach. But is Python's regex syntax different that an ordinary syntax? By the way, i'm using it to normalise strings like: London|country/uk/region/europe/geocoord/32.3244,42,1221244 to: London|country/uk/region/europe/geocoord/32.32,42,12 By using \1\2\4 as replace. I'm open for other suggestions to achieve this! -Gisle- From aleax at mac.com Sun May 14 18:30:37 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 14 May 2006 15:30:37 -0700 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> <7x4pzswmhe.fsf@ruckus.brouhaha.com> <1147644360.298154.220820@u72g2000cwu.googlegroups.com> Message-ID: <1hfc2ys.kcngufif3f05N%aleax@mac.com> George Sakkis wrote: > Paul Rubin wrote: > > > claird at lairds.us (Cameron Laird) writes: > > > For that matter, would it be an advantage for len() to operate > > > on iterables? > > > > print len(itertools.count()) > > > > Ouch!! > > How is this worse than list(itertools.count()) ? It's a slightly worse trap because list(x) ALWAYS iterates on x (just like "for y in x:"), while len(x) MAY OR MAY NOT iterate on x (under Cameron's proposal; it currently never does). Yes, there are other subtle traps of this ilk already in Python, such as "if y in x:" -- this, too, may or may not iterate. But the fact that a potential problem exists in some corner cases need not be a good reason to extend the problem to higher frequency;-). Alex From teethofgold at yahoo.com Fri May 12 13:38:54 2006 From: teethofgold at yahoo.com (Jeremy Winters) Date: Fri, 12 May 2006 10:38:54 -0700 (PDT) Subject: Best Mobile Devices for Python Message-ID: <20060512173854.80870.qmail@web52301.mail.yahoo.com> I have a project where I need to remote control one computer through a wireless tcp/ip connection in my home through a linksys router. I know there are versions of python that have been ported to mobile devices... but the whole arena of mobile devices is kind of intimidating... as it's hard to get to know the true usability of a device... as well as the ease of development for it... unless you actually have one. I don't need a GUI... a text based interface is fine for what I'm doing. Any suggestions for devices? Anybody ever done something similar? Thanks! Jeremy --------------------------------- New Yahoo! Messenger with Voice. Call regular phones from your PC and save big. -------------- next part -------------- An HTML attachment was scrubbed... URL: From softwindow at gmail.com Fri May 26 07:32:50 2006 From: softwindow at gmail.com (softwindow) Date: 26 May 2006 04:32:50 -0700 Subject: hi,everyone. a problem with shelve Module In-Reply-To: References: <1148628096.075581.113290@i40g2000cwc.googlegroups.com> <17526.52542.775526.203864@montanaro.dyndns.org> Message-ID: <1148643170.068802.264320@u72g2000cwu.googlegroups.com> really in which case? From rpdooling at gmail.com Wed May 17 15:13:24 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 17 May 2006 12:13:24 -0700 Subject: creating a new database with mysqldb In-Reply-To: References: Message-ID: <1147893204.503850.225770@j73g2000cwa.googlegroups.com> Type: create a new database with mysql into google and see what happens rd From invalidemail at aerojockey.com Fri May 5 00:25:32 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 4 May 2006 21:25:32 -0700 Subject: Tuple assignment and generators? In-Reply-To: <1vSdnRC7JP5K08fZRVn-rw@comcast.com> References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> Message-ID: <1146803131.996632.207770@v46g2000cwv.googlegroups.com> Larry Bates wrote: > You must be careful with this as they all point to > exactly the same object. Example: > > >>> q = r = s = t = u = v = 0 > >>> id(q) > 3301924 > >>> id(r) > 3301924 > >>> id(s) > 3301924 But: >>> q = 0 >>> r = 0 >>> s = 0 >>> id(q) 134536636 >>> id(r) 134536636 >>> id(s) 134536636 [snip] > My rule, don't do it unless you know exactly why you > want to do it. It will trip you up at some point and > be VERY hard to find. It's ok to do it with constant objects, really. Carl Banks From nobody at 127.0.0.1 Tue May 2 19:10:43 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 23:10:43 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > Edward, I know I told you so at least three times, but really, > seriously, do *yourself* a favor : take time to read about descriptors > and metaclasses - and if possible to experiment a bit - so you can get a > better understanding of Python's object model. Then I'll be happy to > continue this discussion (. Will do, if nothing else it will eliminate language barriers, which we may be running into at this point (though you've indicated otherwise). It probably won't happen for another week or two at though. I appreciate your patience and willingness to engage in this discussion. As a last ditch effort to get my point across: Compiler, interpreter, magic-codey-runny-thingy, whatever, at some point something has to translate this source code def method (self, a, b): something into a function object (or whatever you're calling the runnable code this week). Call this translator Foo. Whatever Foo is, it can insert 'self' into the parameter list for method, e.g. when it sees "def method (a,b)" it pretend like it saw "def method (self,a,b)" and proceed as usual. Once it does that, everything is exactly the same as before. I can prove that assertion too: make a simple text processor that reads Python source code and outputs the same source code with only one change: insert the string 'self" as the first parameter of every "def somemethod". Next run the output source code with the normal Python interpreter. Everything functions *exactly* as before because the code is *exactly* the same as what you would have written if you'd put the 'self's in there manually. Now make the Python interpreter invoke this text processor as the first step in processing source code. Voila, python + implicit self. No changes to the object model. No changes to dynamic binding. Same "runnable" code as before. Where is the problem in this scheme? Or (since I haven't read up on the object model yet) simply: Is there a problem? From aylwyn at cantab.net Wed May 17 10:04:51 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 07:04:51 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1352828.BsCtm2PuaN@jupiter.g2ctech> References: <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> <1147862865.142339.117610@j55g2000cwa.googlegroups.com> <1147868309.125766.112550@u72g2000cwu.googlegroups.com> <1352828.BsCtm2PuaN@jupiter.g2ctech> Message-ID: <1147874691.650993.54610@j33g2000cwa.googlegroups.com> Jorge Godoy wrote >Emacs guess what's used in the file and allows me to use tabs all the time, >doing the correct thing... That sounds like useful behaviour. Maybe this is an area where modern editors might be able to save us from ourselves. I'll admit I'm suspicious of relying on editor functionality - I'm happier if I know I can also use the old-school methods just in case.. Sometimes adding intelligence to an interface can be a usability disaster if it makes wrong assumptions about what you want. But if people are hell-bent on converting tabs to spaces, maybe it's the best way to accommodate them. From rupole at hotmail.com Mon May 8 21:49:20 2006 From: rupole at hotmail.com (Roger Upole) Date: Mon, 8 May 2006 21:49:20 -0400 Subject: get Windows file type References: <1147089470.336984.173510@u72g2000cwu.googlegroups.com> Message-ID: <1147139138_705@sp6iad.superfeed.net> If you have pywin32 installed, you can use the shell module. from win32com.shell import shell, shellcon shell.SHGetFileInfo(filename ,0, shellcon.SHGFI_TYPENAME) Roger "BartlebyScrivener" wrote in message news:1147089470.336984.173510 at u72g2000cwu.googlegroups.com... > Using Python on Windows XP, I am able to get almost all file and path > info using os.path or stat, but I don't see a way to retrieve the file > type? E.g. Microsoft Word file, HTML file, etc, the equivalent of what > is listed in the "Type" column in the Windows Explorer box. > > Thanks, > > rick > ----== 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 __peter__ at web.de Tue May 16 17:32:00 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 May 2006 23:32:00 +0200 Subject: Python and Combinatorics References: <446a0501$0$14778$4fafbaef@reader4.news.tin.it> Message-ID: Nic wrote: > In my example I've chosen the number 3. > How should I change the Python code in order to select another number > (e.g. 7)? Here is a parameterized render(). def render(w, h, suffixes="ab"): pairs = list(unique(range(1, h+1), 2)) for item in unique(pairs, w): for suffix in repeat(*[suffixes]*w): yield tuple((a, b, s) for (a, b), s in izip(item, suffix)) if __name__ == "__main__": for item in render(3, 4, "abc"): print " ".join("%s%s%s" % t for t in item) Experiment with the numbers to see the effects Peter From rschroev_nospam_ml at fastmail.fm Tue May 9 09:28:45 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Tue, 09 May 2006 13:28:45 GMT Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: OlafMeding at gmail.com schreef: > Below are 2 files. The first is a Python program that isolates the > problem within less than 1 hour (often just a few minutes). The second > is a C++ program that shows that the Win32 Sleep() function works as > expected (ran from Friday afternoon until Monday morning). > > Note, the Python programs hangs (stops responding) with hyper-threading > turned on (a BIOS setting), but works as expected with hyper-threading > turned off. > > This problem happens on Windows only (not on Linux for days). > The operating system is MS Windows XP Professional. > Could someone with a hyper-threading (or dual core or multi processor) > CPU please > confirm this bug? Doesn't lock up on my system after 6 hours. Windows XP Pro, Python 2.4.2, hyperthreading Pentium 4. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From junkytownMAKNI at gmail.com Wed May 31 09:37:08 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Wed, 31 May 2006 15:37:08 +0200 Subject: wx: PyNoAppError Message-ID: Hi! Using XP SP2, PythonWin 2.4.3, any trying to use wx 2.6.3.2 When using wx, the first time I run a script it runs fine. Second time, it rasises an error: [Script]********************************** import wx app = wx.App() win = wx.Frame(None, title="Simple Editor") win.Show() app.MainLoop() [Error]*********************************** 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:\Python24\mystuff\ool.pyw", line 3, in ? win = wx.Frame(None, title="Simple Editor") File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_windows.py", line 493, in __init__ newobj = _windows_.new_Frame(*args, **kwargs) PyNoAppError: The wx.App object must be created first! ****************************************** So this happens no matter what the script is. And it always occurs on the first line a new widget is created. This is not a problem with the script, because it does the same thing on every script I copied from the internet. It must be a wx bug, but has anyone fixed it? I googled and only found this: http://mail.python.org/pipermail/tutor/2005-September/041678.html *Not helpful http://www.dogmelon.com.au/nsforum/viewtopic.php?p=5032&sid=53d6cc27c33f96f405873e044425e64c#5032 *Says that runnig the script outside of IDLE fixes the problem. That works for me too but if there is a way to run it from IDLE that would be much easier. Any experience on this? From email at christoph-haas.de Tue May 9 08:23:04 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 9 May 2006 14:23:04 +0200 Subject: installing numpy In-Reply-To: <20060509120715.GB20063@torf.workaround.org> References: <877j4v5ukc.fsf@localhost.localdomain> <873bfj5sp5.fsf@localhost.localdomain> <20060509120715.GB20063@torf.workaround.org> Message-ID: <20060509122303.GC20063@torf.workaround.org> (Replying to my own posting... how I hate that...) On Tue, May 09, 2006 at 02:07:15PM +0200, Christoph Haas wrote: > On Tue, May 09, 2006 at 09:43:50PM +1000, Gary Wessle wrote: > > Christoph Haas writes: > > > > > On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote: > > > > I am trying to install NumPy in my debian/testing linux > > > > 2.6.15-1-686. > > > > > > > > with no numpy for debian/testing, I am left alone, since the > > > > experimental version available by debian will result in a dependency > > > > nightmares, > > > > > > What about "python-numeric"? Found through "apt-cache search numpy". > > > > is no longer maintained, notice my previous post titled "Numerical > > Python Tutorial errors" > > Are you sure? The last update of the Debian package was slightly over a > month ago (http://packages.qa.debian.org/p/python-numeric.html). Yes, you are right. "python-numeric" refers to NumPy but contains the "Numeric" version of it (24-2). It's pretty misleading. I'll ask the package maintainer about the status of python-numpy in Debian and hopefully come back with news. Kindly Christoph -- Please reply to the list - not to me personally. Personal replies are ignored. From Serge.Orlov at gmail.com Tue May 9 06:08:35 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 9 May 2006 03:08:35 -0700 Subject: Using time.sleep() in 2 threads causes lockup whenhyper-threading is enabled References: <1147128244.193773.303270@j73g2000cwa.googlegroups.com> Message-ID: <1147169315.337517.93850@i40g2000cwc.googlegroups.com> Dennis Lee Bieber wrote: > On 8 May 2006 15:44:04 -0700, "Serge Orlov" > declaimed the following in comp.lang.python: > > > > The test program in question doesn't require a dedicated machine and it > > doesn't consume a lot of CPU resources since it sleeps most of the > > time. > > > Yet... Do we have any evidence that other activity on the machine > may or may not affect the situation? There is a big difference between > leaving a machine idle for a few hours to see if it hangs, vs doing > normal activities with a process in the background (and what about > screen savers? network activity?) But what if other processes will actually help to trigger the bug? IMHO both situations (idle or busy) are equal if you don't know what's going on. From rupole at hotmail.com Wed May 24 00:24:24 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 24 May 2006 00:24:24 -0400 Subject: documentation for win32com? References: Message-ID: <1148444403_20939@sp6iad.superfeed.net> The Excel docs are your best bet. The examples they give are all MS-specific languages like VB, but most translate fairly easily to Python. You can also run makepy on the Excel typelib, which will generate a file with all the methods, events etc available thru the Excel object model. Also, searching this group and the pywin32 mailing list for "excel.application" turns up a bunch of sample code. hth Roger "John Salerno" wrote in message news:hQHcg.2153$No6.46370 at news.tufts.edu... > Is there anything better to read on how to use this module for working with Office programs? This is not very heartening to > read in the official docs: > > > ----------------------- > How do I know which objects are available? > > Good question. This is hard! You need to use the documentation with the products, or possibly a COM browser. Note however that > COM browsers typically rely on these objects registering themselves in certain ways, and many objects to not do this. You are > just expected to know. > ----------------------- > > Yeah, thanks... > > So does this mean that the code can be different each time, or is there still a pre-determined way to refer to things, such as > opening Excel, reading a spreadsheet and working with it, etc.? If so, where can I find a list of those objects and methods? > > Thanks. ----== 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 bnblazer at gmail.com Wed May 31 14:07:04 2006 From: bnblazer at gmail.com (Brian) Date: 31 May 2006 11:07:04 -0700 Subject: TSV to HTML Message-ID: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> I was wondering if anyone here on the group could point me in a direction that would expllaing how to use python to convert a tsv file to html. I have been searching for a resource but have only seen information on dealing with converting csv to tsv. Specifically I want to take the values and insert them into an html table. I have been trying to figure it out myself, and in essence, this is what I have come up with. Am I on the right track? I really have the feeling that I am re-inventing the wheel here. 1) in the code define a css 2) use a regex to extract the info between tabs 3) wrap the values in the appropriate tags and insert into table. 4) write the .html file Thanks again for your patience, Brian From onurb at xiludom.gro Tue May 30 04:27:15 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 30 May 2006 10:27:15 +0200 Subject: TIming In-Reply-To: References: Message-ID: <447c0254$0$6154$626a54ce@news.free.fr> WIdgeteye wrote: > HI, > I am trying to write a little program that will run a program on > scedule. There are usually existing programs to do so on most platforms (cron on *n*x, the Windows scheduler, etc). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bborcic at gmail.com Wed May 10 06:14:19 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 10 May 2006 12:14:19 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <87wtcyy5i0.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <87wtcyy5i0.fsf@rpi.edu> Message-ID: <4461bd09$1_6@news.bluewin.ch> Bill Atkins wrote: > > It's interesting how much people who don't have macros like to put > them down and treat them as some arcane art that are too "*insane*"ly > powerful to be used well. > > They're actually very straightforward and can often (shock of shocks!) > make your code more readable, without your efficiency taking a hit. Not even efficiency of debugging ? A real problem with macros is that run-time tracebacks etc, list macro outputs and not your macro'ed source code. And that becomes an acute problem if you leave code for somebody else to update. Or did lisp IDEs make progress on that front ? From steven.bethard at gmail.com Thu May 11 16:17:40 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 11 May 2006 14:17:40 -0600 Subject: NEWBIE: Tokenize command output In-Reply-To: References: Message-ID: Lorenzo Thurman wrote: > This is what I have so far: > > // > #!/usr/bin/python > > import os > > cmd = 'ntpq -p' > > output = os.popen(cmd).read() > // > > The output is saved in the variable 'output'. What I need to do next is > select the line from that output that starts with the '*' [snip] > From there, I need to tokenize the line using the spaces as delimiters. I use the subprocess module instead for better error reporting, but basically if you just iterate over the file object, you'll get the lines. import subprocess # open the process cmd = subprocess.Popen(['ntpq', '-p'], stdout=subprocess.PIPE) # iterate over the file object until we see a line-initial "*" line = None for line in cmd.stdout: if line.startswith('*'): break # make sure to catch the error if ntpq didn't produce any output assert line is not None # split the line into tokens (stolen from Tim Chase's answer (remote, refid, st, t, when, poll, reach, delay, offset, jitter) = line.split() If you need to do this for each line that starts with a "*" instead of just the first, move the line.split() code inside the for-loop. STeVe From codebuger at gmail.com Wed May 24 11:10:13 2006 From: codebuger at gmail.com (Evgeniy Zamriy) Date: Wed, 24 May 2006 18:10:13 +0300 Subject: python __import__ question Message-ID: <87psi3wjai.fsf@adm.dn.bus.com.ua> Hello, All: I have this code: try: empty_mod = __import__(some_empty_module) except ImportError: print "test" raise But python doesn't work with this except: ImportError: No module named .... My python version is 2.4.2 (Linux) Thanks for your replies.... From paddy3118 at netscape.net Sat May 20 02:13:02 2006 From: paddy3118 at netscape.net (Paddy) Date: 19 May 2006 23:13:02 -0700 Subject: number of different lines in a file In-Reply-To: <1148066348.761868.322570@g10g2000cwb.googlegroups.com> References: <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> <1148063935.859890.173230@u72g2000cwu.googlegroups.com> <1148066348.761868.322570@g10g2000cwb.googlegroups.com> Message-ID: <1148105582.284529.245820@i40g2000cwc.googlegroups.com> Hi Kaz, The 'Unix way' is to have lots of small utilities that do one thing well, then connect them via pipes. It could be that the optimised sort algorithm is hampered if it has to remove duplicates too, or that the maintainers want to draw a line on added functionality. Personally, 95%* of the time that I want to use uniq, I also want to sort any input. and 70% of the time, I also want to do 'wc -l' on the uniq lines found. Sort, on the other hand, I regularly use without uniq. Should I therefore want uniq to have a sort and wc functionality added? Not for me thanks. I like pipes. I agree with the targetted funtionality of the 'core' utilities like sort, and search for other solutions e.g. scripting when life gets more complex. - Pad. Unix pipes. You too can do parallel processing on that quad opteron server :-) * All peacentages shown is accrutt From thirsteh at gmail.com Tue May 23 18:49:54 2006 From: thirsteh at gmail.com (Patrick M. Nielsen) Date: Wed, 24 May 2006 00:49:54 +0200 Subject: Telnet linebreaks In-Reply-To: <28dc07920605231548w6fd48d25t463f510338044da8@mail.gmail.com> References: <28dc07920605231548w6fd48d25t463f510338044da8@mail.gmail.com> Message-ID: <28dc07920605231549g56cfdc4fi9d995a0e1fb4cf0b@mail.gmail.com> Oh, and, apologies for the "inpythonic" nature of this issue. On 5/24/06, Patrick M. Nielsen wrote: > > Hey guys. > > I have begun playing with the Simple MUD server example from the Stackless > website > ( http://www.stackless.com/Members/rmtew/code/mud.py ) > and it's all good so far, however, I've come to notice something that I > remember from back > in the days (some old mud code), but I don't remember what I did to fix > it. > > While the MUD reads lines from Telnet clients just fine, clients such as > Gmud are practically ignored, > probably because Gmud doesn't send Telnet-valid data ('\x08'?). > > However, a MUD that is not accessible to one such client or others isn't > much good, so I'd appreciate > some help in pinpointing the problem. > > These are the code blocks that need modification (I believe) > > def read(self): # TELNET > ret = self.readChannel.receive() > if self.echo: > if ret == '\x08': > self.send(ret+" ") > self.send(ret) > return ret > > def readline(self): # TELNET > buf = self.readBuffer > > while True: > if buf.find('\r\n') > -1: # MUD clients that aren't using the > telnet protocol > i = buf.index('\r\n') # need to be able to do stuff. > ret = buf[:i+2] > self.readBuffer = buf[i+2:] > while '\x08' in ret: > i = ret.index('\x08') > if i == 0: > ret = ret[1:] > else: > ret = ret[:i-1]+ret[i+1:] > return ret > > buf += self.read() > > I'm suspecting that Gmud doesn't send '\x08', since from looking at some > old DIKU code, > I see that the if '\n' || '\r' are there as well, but there is no check > for '\x08'. If this is indeed > the cause of my problem, how would I go about doing it? > > Thanks in advance. > -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhellwig at xs4all.nl Wed May 3 19:04:24 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 04 May 2006 01:04:24 +0200 Subject: This coding style bad practise? In-Reply-To: <44591be3$0$2626$636a55ce@news.free.fr> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> <44591be3$0$2626$636a55ce@news.free.fr> Message-ID: <445936fb$0$31642$e4fe514c@news.xs4all.nl> Bruno Desthuilliers wrote: > > Why not just use the call operator instead ? ie: > > >>> id = IDGenerator(...) > >>> id() > 01_20060424_151903_1 > >>> id() > 01_20060424_151905_2 > Because of: >>>> id = IDGenerator("01",99) >>>> id() > Traceback (most recent call last): > File "", line 1, in ? > id() > TypeError: 'IDGenerator' object is not callable >>>> But i do appreciate your comment, thanks! -- mph From nobody at 127.0.0.1 Wed May 3 18:29:02 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 22:29:02 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: Ben Finney wrote: > Edward Elliott writes: >> As long as we're trotting out aphorisms > > The ones I quoted were from Python. > >>> import this Yes I know where it's from. > You've misunderstood "don't repeat yourself". It advocates *one* > definition of any given thing in the code. You are advocating *zero* > definitions of 'self' in the code. It's implicitly defined by the language/runtime, so I shouldn't need to define it in my code. Doing so is duplication of effort, aka DRY. An implicit definition is not an empty definition. Where do the semantics of 'while' and 'for' come from? Same thing, it's implicit in the language. From duncan.booth at invalid.invalid Thu May 11 05:02:34 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2006 09:02:34 GMT Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> <1147333696.789718.189050@v46g2000cwv.googlegroups.com> Message-ID: yairchu at gmail.com wrote: > this is how I think it should be done with multi-line lambdas: > > def arg_range(inf, sup, f): > return lambda(arg): > if inf <= arg <= sup: > return f(arg) > else: > raise ValueError > > and instead of > @arg_range(5, 17) > def f(arg): > return arg*2 > > you do: > f = arg_range(5, 17, lambda(arg)): > return arg*2 > > One big problem with this is that with the decorator the function has a name but with a lambda you have anonymous functions so your tracebacks are really going to suck. From apavluck at gmail.com Thu May 25 12:28:37 2006 From: apavluck at gmail.com (Alex Pavluck) Date: 25 May 2006 09:28:37 -0700 Subject: script vs inneractive Message-ID: <1148574517.158866.157280@38g2000cwa.googlegroups.com> I am a little confused because I write most of my programs in a script editor but not all the code executes unless I run it from the inneractive shell. Am I doing something wrong? A good example is "return 1" in a script returns nothing where as in the inneractive shell it will return 1 or true. From nobody at 127.0.0.1 Tue May 2 15:06:52 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 19:06:52 GMT Subject: stripping References: <1146550856.291511.5780@v46g2000cwv.googlegroups.com> Message-ID: micklee74 at hotmail.com wrote: > while 1: > line = f.readline().rstrip("\n") > if line == '': > break > #if not re.findall(r'^$',line): > print line you want continue, not break there. but that gives you an infinite loop, so you need a new exit condition. you're better off scrapping the while and using a for loop or list comprehension on readline. From python.list at tim.thechases.com Thu May 4 08:11:04 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 May 2006 07:11:04 -0500 Subject: RegEx with multiple occurrences In-Reply-To: <1146744187.681812.266110@y43g2000cwc.googlegroups.com> References: <1146742939.692014.201270@e56g2000cwe.googlegroups.com> <1146744187.681812.266110@y43g2000cwc.googlegroups.com> Message-ID: <4459EF58.6060602@tim.thechases.com> > Tim - you're a legend. Thanks. A leg-end? I always knew something was a-foot. Sorry to make myself the butt of such joking. :) My pleasure...glad it seems to be working for you. -tkc (not much of a legend at all...just a regexp wonk) From deets at nospam.web.de Wed May 10 04:49:19 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 May 2006 10:49:19 +0200 Subject: New tail recursion decorator References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> Message-ID: <4cdnouF15dmjfU1@uni-berlin.de> Kay Schluehr wrote: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 Neat. Diez From steve at hastings.org Wed May 3 03:40:18 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 03 May 2006 00:40:18 -0700 Subject: request help with Pipe class in iterwrap.py References: Message-ID: On Wed, 03 May 2006 08:01:12 +0200, Marc 'BlackJack' Rintsch wrote: > Maybe one with less "magic" syntax. What about using a function that > takes the iterators and an iterable and returns an iterator of the chained > iterators:: > > new_list = pipe(grep('larch'), grep('parrot', 'v')), list)(my_list) This is a good idea. But not quite magic enough, I'm afraid. One of the features of Pipe() is that it automatically pastes in the first argument of each function call (namely, the iterator returned by the previous function call). It is able to do this because of a special __getattr__ that grabs the function reference but returns the "self" instance of the Pipe class, to allow the dot-chain to continue. Any supplied options will then be pasted in after that first argument. In your example, "grep('larch')" is going to be evaluated by Python, and immediately called. And it will then complain because its first argument is not an iterator. I cannot see any way to modify this call before it happens. If we take your basic idea, and apply just a little bit of magic, we could do this: new_list = Pipe(my_list, grep, 'larch', grep, ('parrot', 'v'), list) The rules would be: * the first argument to Pipe is always the initial iterable sequence. * each argument after that is tested to see if it is callable. If it is, it's remembered; if not, it is presumed to be an argument for the remembered callable. Multiple arguments must be packaged up into a tuple or list. Once Pipe() has a callable and an argument or sequence of arguments, Pipe() can paste in all arguments and make the call; alternatively, once Pipe() sees another callable, it can safely assume that there aren't going to be any extra arguments for the remembered callable, and paste in that one iterator argument and make the call. Now Pipe always knows when it has reached the last callable, because it will have reached the end of the supplied arguments! Then it can safely assume there aren't going to be any extra arguments, and make the call to the last remembered callable. However, I remain fond of the dot-chaining syntax. For interactively playing around with data, I think the dot-chaining syntax is more natural for most people. newlist = Pipe(mylist).sort.uniq.list() newlist = Pipe(mylist, sort, uniq, list) Hmmm. The second one really isn't bad... Also, the second one doesn't require my tricky e_eval() to work; it just lets Python figure out all the function references. Thinking about it, I realize that "list" is a very common thing with which to end a dot-chain. I think perhaps if my code would just notice that the last function reference is "list", which takes exactly one argument and thus cannot be waiting for additional arguments, it could just call list() right away. If there were a general way to know that a function reference only expects a single argument, I could generalize this idea. But it may be enough to just do the special case for list(). I think I'll keep Pipe(), hackish as it is, but I will also add a new one based on your idea. Maybe I'll call it "Chain()". newlist = Chain(mylist, sort, uniq, list) I did kind of want a way to make a "reusable pipe". If you come up with a useful chain, it might be nice if you could use it again with convenient syntax. Maybe like so: sort_u = [sort, uniq, list] newlist = Chain(mylist, sort_u) Thank you very much for making a helpful suggestion! -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From felipe.lessa at gmail.com Sun May 21 14:57:33 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sun, 21 May 2006 15:57:33 -0300 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <1148237544.579470.43420@i40g2000cwc.googlegroups.com> References: <200605211711.25043.me+python@modelnine.org> <1148237544.579470.43420@i40g2000cwc.googlegroups.com> Message-ID: <1148237853.3355.8.camel@kenshin.CASA> Em Dom, 2006-05-21 ?s 11:52 -0700, gangesmaster escreveu: > > Today you can archive the same effect (but not necessarily with the same > > performance) with: > > > > for node in (x for x in tree if x.haschildren()): > > > > true, but it has different semantic meanings > I know, that's also why I don't oppose the PEP. -- Felipe. From nephish at xit.net Tue May 23 12:24:01 2006 From: nephish at xit.net (nephish at xit.net) Date: 23 May 2006 09:24:01 -0700 Subject: problem with writing a simple module In-Reply-To: References: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> <1148390743.600334.227460@j73g2000cwa.googlegroups.com> Message-ID: <1148401441.799070.111030@j33g2000cwa.googlegroups.com> ok, what i posted above had the getOne method, the whole class has a function for getMany, update, and Insert. none of this will be used by an end user, it kinda runs in the background. But, if you have a good link to the docs on the API, i would like to see it. Still kinda new at this. thanks From akameswaran at gmail.com Thu May 18 17:50:47 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 14:50:47 -0700 Subject: python vs perl lines of code In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: <1147989047.427015.193270@j55g2000cwa.googlegroups.com> THe interest, on my part, is more academic than practical. I find data, particularly "dirty" data very fascinating, and I like trying to find ways to make useful statements when all you have is bad data. Maybe a pipe-dream, but it's still fun to try. So this little exercise would be quite enjoyable - a horribly dirty data set that nobody thinks could be useful. The good guys always fall for the bad data!! At an architectural or even development management perspective - there is always someone, somewhere who wants to evaluate "developer efficiency" or something similarly vague concept for which there aren't good tools for evaluation. Let's face it in the corp world these kind of figures are sometimes percieved to have value. SO if I were a corp programmer in python and a manager says to me my output is way behind the perl guys - I could pull this silly fact and .... well you see. My quick comment about his code being torn apart by perl advocates was mainly because his post seems to be complimentary to python - but your right both sides would tear him apart. ANd you took the flame bait so I'll respond :D Perhaps - ALL OTHER THINGS BEINGS EQUAL - should better be read as WRITTEN BY ME!! For the most part I have found it easier to maintain the shorter programs I have written and found it more time consuming to maintain longer programs. Really what's so dumb about this? Have you found, as a general trend you spend more time maintaining your shorter programs? I did say it was flame bait, and I never said the statement is useful - all other things are never equal in the real world. I am constantly amused by how we, as programmers, spend so much time quantifying everything else, react so negatively when anyone suggests quantitative analysis of code for anything except execution time. Course what interests me now - is how could we prove if my statement was in fact very very dumb or not? In all honesty I don't know, but it sure tastes good grilled. From tfb at conquest.OCF.Berkeley.EDU Sat May 6 15:02:26 2006 From: tfb at conquest.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 06 May 2006 12:02:26 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> Message-ID: [ I pruned the cross-posting down to a reasonable level ] Ken Tilton writes: > Thomas F. Burdick wrote: > > > This is second-hand, as I don't actually follow Python closely, but > > from what I've heard, they now have reasonable scoping rules (or maybe > > they're about to, I'm not sure). And you can use def as a > > Scheme-style inner define, so it's essentially a LABELS that gets the > > indentation wrong. > > Cool. And I know how much you like labels/flet. :) Well, I love LABELS but I hate inner defines with an equal passion -- so for me it's a wash :-) As much as I like nice low-level, close-to-the-machine mechanisms as labels and lambda, sometimes you just want the high-level expressiveness of tagbody/go, which Python doesn't have ... which in my opinion is quite a crime to readability and the ability to transcribe Knuth algorithms, which any engineer should find offensive to their sensibilities. > > This means they have proper closures, just not > > anonymous ones. And an egregiously misnamed lambda that should be > > fixed or thrown out. > > If Python gets proper macros it won't matter one bit that they only > > have named closures, since you can macro that away in a blink of an > > eye. > > Ah, well, there we go again. Without sexpr notation, the lexer/parser > again will be "hard", and "hardly worth it": we get even more sour > grapes, this time about macros not being such a big deal. > > One of the hardest things for a technologist to do is admit that a > neat idea has to be abandoned. Initial success creates a giddy > over-commitment to the design choice. After then all difficulties get > brushed aside or kludged. Y'never know, they could always Greenspun their way to almost-sexps. What with the way that selective pressure works, it's gonna be that or die, so it is a possibility. From aleaxit at yahoo.com Thu May 4 11:05:42 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 4 May 2006 08:05:42 -0700 Subject: stripping unwanted chars from string References: Message-ID: <1hesznb.1wdd6ed10adqfjN%aleaxit@yahoo.com> Edward Elliott wrote: > I'm looking for the "best" way to strip a large set of chars from a filename > string (my definition of best usually means succinct and readable). I > only want to allow alphanumeric chars, dashes, and periods. This is what I > would write in Perl (bless me father, for I have sinned...): > > $filename =~ tr/\w.-//cd, or equivalently > $filename =~ s/[^\w.-]// > > I could just use re.sub like the second example, but that's a bit overkill. > I'm trying to figure out if there's a good way to do the same thing with > string methods. string.translate seems to do what I want, the problem is > specifying the set of chars to remove. Obviously hardcoding them all is a > non-starter. (untested code, but, the general idea shd be correct)...: class KeepOnly(object): allchars = ''.join(chr(i) for i in xrange(256)) identity = string.maketrans('', '') def __init__(self, chars_to_keep): self.chars_to_delete = self.allchars.translate( self.identity, chars_to_keep) def __call__(self, some_string): return some_string.translate(self.identity, self.chars_to_delete) Alex From gandalf at designaproduct.biz Fri May 26 05:45:02 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 26 May 2006 11:45:02 +0200 Subject: hi,everyone. a problem with shelve Module In-Reply-To: <17526.52542.775526.203864@montanaro.dyndns.org> References: <1148628096.075581.113290@i40g2000cwc.googlegroups.com> <17526.52542.775526.203864@montanaro.dyndns.org> Message-ID: <4476CE1E.4080709@designaproduct.biz> skip at pobox.com i'rta: > >> i only write ten records like this: > > >> name sex age > > >> jim male 22 > >> tom male 23 > >> lucy female 21 > ... > > >> but i find the size of this file .oh my god , it is about 24k > > >> the file is too large ! is it normal ? > > Yes. It's the nature of packages like Berkeley DB, gdbm and dbm (the > packages mediate access to the database file under the covers) that they > trade space for time. Sometimes you add records but the size of the database does not change... :-) > The files they create are not simple text files. > They are organized to permit quick access to records by key and to permit > average time fast insertion. > > Skip > From steve at holdenweb.com Mon May 1 08:10:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 01 May 2006 13:10:17 +0100 Subject: SPE / winpdb problem In-Reply-To: <1146461726.790649.318060@u72g2000cwu.googlegroups.com> References: <1146461726.790649.318060@u72g2000cwu.googlegroups.com> Message-ID: MakaMaka wrote: > Hi All, > I'm having a problem with Stani's Python Editor (SPE) that I'm hoping > somebody has run into before. If I create a simple hello world > program: > > print "hello" > > and try and run it in winpdb via the SPE command ALT-F9, the program > does not launch and the following results (It's at the bottom): > > > Spe Warning: Spe was developped on wxPython v2.6.1.0., but v2.6.3.2. > was found. > If you experience any problems please install wxPython v2.6.1.0. > > > SPE v0.8.2.a (c)2003-2005 www.stani.be > > If spe fails to start: > - type "python SPE.py --debug > debug.txt 2>&1" at the command prompt > (or if you use tcsh: "python SPE.py --debug >& debug.txt") > - send debug.txt with some info to spe.stani.be[at]gmail.com > > > Spe Warning: Spe was developped on wxPython v2.6.1.0., but v2.6.3.2. > was found. > If you experience any problems please install wxPython v2.6.1.0. > > Blender support disabled (run SPE inside Blender to enable). > > Encrypted debugging disabled. > If you prefer encrypted debugging, install the "Python Cryptography > Toolkit" > from http://www.amk.ca/python/code/crypto > > Launching application... > Traceback (most recent call last): > File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", > line 3313, > in ? > ret = main() > File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", > line 3303, > in main > return rpdb2.main(StartClient) > File "C:\Python24\Lib\site-packages\_spe\plugins\winpdb\rpdb2.py", > line 7221, > in main > StartClient_func(_args, fAttach, fchdir, pwd, fAllowUnencrypted, > fRemote, ho > st) > File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", > line 3293, > in StartClient > app = CWinpdbApp(sm, fchdir, command_line, fAttach, > fAllowUnencrypted) > File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", > line 1528, > in __init__ > wx.App.__init__(self, redirect = False) > File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", > line 7700, i > n __init__ > self._BootstrapApp() > File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", > line 7352, i > n _BootstrapApp > return _core_.PyApp__BootstrapApp(*args, **kwargs) > File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", > line 1533, > in OnInit > self.m_settings.load_settings() > File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", > line 638, > in load_settings > d = cPickle.load(f) > EOFError > > > > Any ideas what is going on? > > Thanks! > I'd try installing wxPython v2.6.1.0 and see if that gets rid of your error. Multiple versions can coexist. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From Elric02 at rogers.com Tue May 16 11:26:01 2006 From: Elric02 at rogers.com (Elric02 at rogers.com) Date: 16 May 2006 08:26:01 -0700 Subject: Unable to extract Python source code using Windows Message-ID: <1147793161.867167.113480@g10g2000cwb.googlegroups.com> I'm currently trying to get access to the Python source code, however whenever I try to extract the files using the latest version of WinZip (version 10) I get the following error "error reading however after processing 0 entries From python.list at tim.thechases.com Mon May 8 09:15:36 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 08 May 2006 08:15:36 -0500 Subject: A better way to split up a list In-Reply-To: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> References: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> Message-ID: <445F4478.3090407@tim.thechases.com> > The code below works fine, but it is less than nice to > look at and somewhat long winded. Is there a better way > to do the docstring task? This is the first working > version, and can proabably be "compacted" a bit (list > comprehensions etc) but I am looking for a better basic > approach. Any help much appreciated :) It looks like there may be some problems with your code, such that it doesn't "work fine"...particularly in lists with 1, 2, or 3 elements. The below "chopupmoves2" function does what you describe, and is nice and short. A bunch of test-cases get generated and compared so you can see their output. The chopupmoves2() function regularly returns your described results, while things seem a bit off with the chopupmoves() HTH, -tkc from itertools import islice def chopupmoves2(movelist): size = len(movelist) / 3 return [ movelist[:size], movelist[size:size*2], movelist[size*2:]] def chopupmoves(movelist): '''creates a list of 3 lists from one list, that should all have (length of movelist)/3 length, with any remainder getting added to the third list''' outputlist = [[],[],[]] parlen = int(len(movelist)/3) if parlen < 3: parlen = 3 stoplist=[0];exit = 0 while exit < len(movelist): stoplist.append(exit+parlen) exit = exit + parlen while len(stoplist) > 4: stoplist.pop(len(stoplist)-1) stoplist[-1]=len(movelist) for x in range(len(stoplist)-1): for i in islice(movelist,stoplist[x],stoplist[x+1],1): outputlist[x].append(i) return outputlist # test them with a bunch of test-cases movelist =[] for i in xrange(1,12): movelist.append(i) print "Movelist:", movelist print "\toriginal:", chopupmoves(movelist) print "\tTim's: ", chopupmoves2(movelist) From bayerj at in.tum.de Tue May 16 06:42:07 2006 From: bayerj at in.tum.de (bayerj) Date: 16 May 2006 03:42:07 -0700 Subject: Argument Decorators Enhancement? In-Reply-To: <1147754531.481364.82940@j33g2000cwa.googlegroups.com> References: <1147754531.481364.82940@j33g2000cwa.googlegroups.com> Message-ID: <1147776127.240353.260140@j73g2000cwa.googlegroups.com> Hi, -1 because I find it extremly hard to read and not necessary in that scale. Actually, there are a lot of recipes in the Cookbook [1] on how to use decorators for type-checking. On example is: @require(int, int) def add(x,y): return x + y Which I find much more readable, easier to implement and even backwards compatible: def add(x,y): return x + y add = require(int, int)(add) g2g, Justin [1] http://aspn.activestate.com/ASPN/Cookbook/Python/ From aahz at pythoncraft.com Tue May 9 20:16:34 2006 From: aahz at pythoncraft.com (Aahz) Date: Tue, 9 May 2006 17:16:34 -0700 Subject: BayPIGgies: May 11, 7:30pm (Google) Message-ID: <20060510001634.GA15499@panix.com> The next meeting of BayPIGgies will be Thurs, May 11 at 7:30pm at Google. Note: Dennis Reinhardt is coordinating Google badges. Please send e-mail to DennisR at dair.com by 4pm Weds 5/10 to get an advance badge. Dennis Reinhardt will present a short tutorial of using ctypes with the Windows API, followed by Stephen McInerney discussing the results of the BayPIGgies member survey. BayPIGgies meetings alternate between IronPort (San Bruno, California) and Google (Mountain View, California). For more information and directions, see http://baypiggies.net/ Before the meeting, we sometimes meet at 6pm for dinner. Discussion of dinner plans is handled on the BayPIGgies mailing list. Advance notice: We can use a speaker for June. Please e-mail baypiggies at python.org if you want to suggest an agenda (or volunteer to give a presentation). -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From wesbrooks at gmail.com Mon May 1 09:05:43 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Mon, 1 May 2006 14:05:43 +0100 Subject: Python based file format cracking Message-ID: Dear Users, Is there another tool that can examine an string for undefined repeating patterns? I'm aware of and have limited experience regular expressions which finds supplied patterns within a string. Yours Faithfully, Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: From tjreedy at udel.edu Sun May 21 20:52:41 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 21 May 2006 20:52:41 -0400 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148254714.668727.298420@y43g2000cwc.googlegroups.com> Message-ID: "nikie" wrote in message news:1148254714.668727.298420 at y43g2000cwc.googlegroups.com... > Xah Lee wrote: > >> Software Needs Philosophers >> >> by Steve Yegge, 2006-04-15. >> >> Software needs philosophers. >> >> This thought has been nagging at me for a year now, and recently it's >> been growing like a tumor. One that plenty of folks on the 'net would >> love to see kill me. > > No, we all wish you a long and quiet life! Although some of us are a > little annoyed that you keep cross-posting articles wildly to > completely unrelated newsgroups... The above was written by Steve Yegge, not Xah Lee, who just reposted Steve's blog entry. To reply to Steve, go to his blog. tjr From xah at xahlee.org Wed May 31 09:08:51 2006 From: xah at xahlee.org (Xah Lee) Date: 31 May 2006 06:08:51 -0700 Subject: Software Needs Philosophers In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <1149080931.582431.95560@j55g2000cwa.googlegroups.com> The Condition of Industrial Programers Xah Lee, 2006-05 Before i stepped into the computing industry, my first industrial programing experience is at Wolfram Research Inc as a intern in 1995. (Wolfram Research is famously known for their highly successful flagship product Mathematica) I thought, that the programers at Wolfram are the world's top mathematicians, gathered together to research and decide and write a extremely advanced technology. But i realized it is not so. Not at all. In fact, we might say it's just a bunch of Ph Ds (or equivalent experience). Each person there are not unlike average white-collar Joes. Each working individually. And, fights and bouts of arguments between co-workers are not uncommon. Sometimes downright ugly. Almost nothing is as i naively imagined, as if some world's top mathematicians are gathered together there, daily to confer and solve the world's top problems as in some top secret government agency depicted in movies. Well, that was my introduction to the industry. The bulk of my surprise is due to my naiveness and inexperience of the industry, of any industry, as i was just a intern and this is my first experience seeing how the real world works. After Wolfram, after a couple of years i went into the web programing industry in 1998, using unix, Perl, Apache, Java, database technologies, in the center of world's technology the Silicon Valley. My evaluation of industrial programers and how software are written is a precipitous fall from my observations at Wolfram. In the so-called Info Tech industry, the vast majority of programers are poorly qualified. I learned this from my colleagues, and in dealing with programers from other companies, service providers, data centers, sys admins, API gateways, and duties of field tutoring. I didn't think i had very qualified expertise in what i do, but the reality i realized is that most are far lesser than me, and that is the common situation. That they have no understanding of basic mathematics such as trigonometry or calculus. Most have no interest in math whatsoever, and would be hard pressed for them to explain what is a ?algorithm?. I have always thought, that programing X software of field Y usually means that the programers are thoroughly fluent in languages, protocols, tools of X, and also being a top expert in field of Y. But to my great surprise, the fact is that that is almost never the case. In fact, most of the time the programers simply just had to learn a language, protocol, software tool, right at the moment as he is trying to implement a software for a field he never had experience in. I myself had to do jobs half of the time i've never done before. Constantly I'm learning new languages, protocols, systems, tools, APIs, other rising practices and technologies, reading semi-written or delve into non-existent docs. It is the norm in the IT industry, that most products are really produces of learning experiences. Extremely hurried grasping of new technologies in competition with deadlines. There is in fact little actual learning going on, as there are immense pressure to simply ?get it to (demonstrably) work? and ship it. Thinking back, in fact the Wolfram people are the most knowledgeable and inquisitive people i've met as colleagues, by far. What prompted me to write this essay is after reading the essay Teach Yourself Programming in Ten Years by Peter Norvig, 2001, at http://www.norvig.com/21-days.html (local copy). In which, the Lisp dignitary Peter Norvig derides the widely popular computing books in the name of Teaching Yourself X In (Fast) Days. Although i agree with his general sentiment that a language or technology takes time to master and use well, that these books is a damaging fad and subtly generate ignorance, but he fails to address the main point, that is: the cause of the popularity of such books, and how to remedy the situation. These books are the bedrock of the industry. It is not because people are impatient, or that they wish to hurry, but rather, it is the condition of the IT industry, in the same way modern society drives people to live certain live styles. No amount of patience or proselytization can right this, except that we change the industry's practice of quickly churning out bug-ridden software products to beat competitors. Companies do that due to market forces, and the market forces is a result of how people and organizations actually choose to purchase software. In my opinion, a solution to this is by installing the concept of responsible licenses, as i've detailed in the essay Responsible Software Licensing, at http://xahlee.org/UnixResource_dir/writ/responsible_license.html . ---- This post is archived at: http://xahlee.org/UnixResource_dir/writ/it_programers.html Xah xah at xahlee.org ? http://xahlee.org/ From none at no.chance Tue May 9 04:21:27 2006 From: none at no.chance (Peter Tillotson) Date: Tue, 09 May 2006 09:21:27 +0100 Subject: Memory leak in Python In-Reply-To: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> Message-ID: 1) Review your design - You say you are processing a large data set, just make sure you are not trying to store 3 versions. If you are missing a design, create a flow chart or something that is true to the code you have produced. You could probably even post the design if you are brave enough. 2) Check your implementation - make sure you manage lists, arrays etc correctly. You need to sever links (references) to objects for them to get swept up. I know it is obvious but easy to do in a hasty implementation. 3) Verify and test problem characteristics, profilers, top etc. It is hard for us to help you much without more info. Test your assumptions. Problem solving and debugging is a process, not some mystic art. Though sometime the Gremlins disappear after a pint or two :-) p diffuser78 at gmail.com wrote: > I have a python code which is running on a huge data set. After > starting the program the computer becomes unstable and gets very > diffucult to even open konsole to kill that process. What I am assuming > is that I am running out of memory. > > What should I do to make sure that my code runs fine without becoming > unstable. How should I address the memory leak problem if any ? I have > a gig of RAM. > > Every help is appreciated. > From invalidemail at aerojockey.com Thu May 11 00:00:59 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 10 May 2006 21:00:59 -0700 Subject: New tail recursion decorator In-Reply-To: <1147272325.625020.108840@y43g2000cwc.googlegroups.com> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <1147272325.625020.108840@y43g2000cwc.googlegroups.com> Message-ID: <1147320059.573918.82150@j73g2000cwa.googlegroups.com> Michele Simionato wrote: > CONTINUE = object() # sentinel value returned by iterfunc > > def tail_recursive(func): > """ > tail_recursive decorator based on Kay Schluehr's recipe > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 > """ > var = dict(in_loop=False, cont=True, argkw='will be set later') > # the dictionary is needed since Python closures are read-only > > def iterfunc(*args, **kwd): > var["cont"] = not var["cont"] > if not var["in_loop"]: # start looping > var["in_loop"] = True > while True: > res = func(*args,**kwd) > if res is CONTINUE: > args, kwd = var["argkw"] > else: > var["in_loop"] = False > return res > else: > if var["cont"]: > var["argkw"] = args, kwd > return CONTINUE > else: > return func(*args,**kwd) > return iterfunc CONTINUE could be put inside tail_recursive, couldn't it? And to squeeze a little more speed out of it, var could be a list (saves a hash lookup). Cool decorator. Carl Banks From rpdooling at gmail.com Fri May 12 22:16:06 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 12 May 2006 19:16:06 -0700 Subject: where do you run database scripts/where are DBs 'located'? References: <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> Message-ID: <1147486566.233799.62540@v46g2000cwv.googlegroups.com> John, I had nothing but trouble connecting to my Access and MySql dbs until I started using mxODBC. Search on it in this group, and you'll find the links that were given to me and that I've shared with others. It works like a charm. If you come up short, I'll send you the links. I can't dig them up right now. Back in an hour or so. rick From duncan.booth at invalid.invalid Tue May 16 06:19:33 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 10:19:33 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> Message-ID: Sybren Stuvel wrote: >> An editor should be capable of letting you create or modify files >> containing control characters without gratuitously corrupting them, >> but the keys should perform the expected operations > > I agree with that. > >> not insert the characters. > > But not with that, since it is contradicting. "Inserting the > characters" could very well be the same as "performing the expected > operations". It could be, and for some keys (q, w, e, r, t, y, etc. spring to mind) that is quite a reasonable implementation. For others 'tab', 'backspace', 'enter', 'delete', etc. it is less reasonable, but it is a quality of implementation issue. If I had an editor which entered a control character for each of these I would simply move to a better editor. Some keys will of course do both (e.g. space bar in some editors does completion and inserts a space), but I prefer editors which keep things simple. The tab key is particularly prone to excessively complicated actions, for example the editor I use has the following (not simple at all, and in fact not even an accurate description of what it does) binding for the tab key: > indent-previous command > > Indent based on the previous line. > > This command makes the current line start at the same column as the > previous non-blank line. Specifically, if you invoke this command > with point in or adjacent to a line's indentation, indent-previous > replaces that indentation with the indentation of the previous > non-blank line. If point's indentation exceeds that of the previous > non-blank line, or if you invoke this command with point outside of > the line's indentation, this command simply inserts a tab character. > > If a region is highlighted, Epsilon indents all lines in the region by > one tab stop. With a numeric prefix argument, Epsilon indents by that > amount. > (and it is even more complex when you are editing something like Python where it takes continuation lines into account working out the indentation). The problem is that behaviour like this is useful, and mostly even intuitive, but it's a long way from the definition of a tab or even the little metal clips you used to stick on the back of a manual typewriter. From meatbag666 at gmail.com Mon May 15 01:44:26 2006 From: meatbag666 at gmail.com (Zoidberg) Date: Mon, 15 May 2006 05:44:26 GMT Subject: Compile Python Message-ID: <_yU9g.163762$P01.96284@pd7tw3no> How would one compile python with Visual Studio 2005? From miki.tebeka at gmail.com Thu May 18 04:16:13 2006 From: miki.tebeka at gmail.com (Miki) Date: 18 May 2006 01:16:13 -0700 Subject: using wxPython events inside a loop In-Reply-To: <1147873572.398048.188890@g10g2000cwb.googlegroups.com> References: <1147873572.398048.188890@g10g2000cwb.googlegroups.com> Message-ID: <1147940173.592463.223460@y43g2000cwc.googlegroups.com> Hello BigSmoke, You can process one at a time in an "OnIdle" handler, this way you'll work only when the application is doing nothing. HTH, Miki, http://pythonwise.blogspot.com/ From rupole at hotmail.com Fri May 5 21:13:50 2006 From: rupole at hotmail.com (Roger Upole) Date: Fri, 5 May 2006 21:13:50 -0400 Subject: How to get the target of a Windows shortcut file References: <1146867133.873710.235790@i39g2000cwa.googlegroups.com> Message-ID: <1146877814_5563@sp6iad.superfeed.net> persist.Load('someshortcut.lnk') print sh.GetPath(shell.SLGP_RAWPATH)[0] hth Roger "Steve M" wrote in message news:1146867133.873710.235790 at i39g2000cwa.googlegroups.com... > Below is some code adapted from something I think was written by Mark > Hammond. Originally I needed to create a Windows shortcut (link), and > this code does the trick, requiring only the target filename and the > desired shortcut name. > Now, I find I need to open a shortcut and extract the target filename, > and I don't have a clue how that is achieved. To be clear, I mostly > don't understand the gory (Windows API) details of this code. So, can > anyone show how to open an existing shortcut file (given its name) and > discover the name of the file to which it is a shortcut? > > > import os > from win32com.shell import shell > import pythoncom > > # Get the shell interface. > sh = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, \ > pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) > > # Get an IPersist interface > persist = sh.QueryInterface(pythoncom.IID_IPersistFile) > > target_of_link = os.path.abspath('target.doc') > link_name = 'shortcut_to_target.doc.lnk' > > sh.SetPath(target_of_link) > persist.Save(link_name, 1) > ----== 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 brian at sweetapp.com Sun May 7 04:21:11 2006 From: brian at sweetapp.com (brian at sweetapp.com) Date: 7 May 2006 01:21:11 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <8764kive9g.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> Message-ID: <1146990071.634244.83380@i39g2000cwa.googlegroups.com> Bill Atkins wrote: > Buh? The project doesn't have to be late for Brooks's law to hold; > adding programmers, so goes Brooks reasoning, will always increase the > time required to complete the project because of various communication > issues. 1. This is not what Brooks says. Brooks was talking about late projects. Please provide a supporting quote if you wish to continue to claim that "adding programmers will always increase the time required to complete the project". 2. There has to be a mechanism where an organization can add developers - even if it is only for new projects. Python advocates would say that getting developers up to speed on Python is easy because: - it fits most programmers brains i.e. it is similar enough to languages that most programmers have experience with and the differences are usually perceived to beneficial (exception: people from a Java/C/C++ background often perceive dynamic typing as a misfeature and have to struggle with it) - the language is small and simple - "magic" is somewhat frowned upon in the Python community i.e. most code can be taken at face value without needing to learn a framework, mini-language, etc. (but I think that the Python community could do better on this point) I'm sure that smarter people can think of more points. > Fair enough. But what does Python offer above any garbage-collected > language that makes it so scalable? See above point - you can more easily bring programmers online in your organization because most programmers find Python easily learnable. And, as a bonus, it is actually a pretty flexible, powerful language. Cheers, Brian From scott.daniels at acm.org Mon May 8 18:29:48 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 15:29:48 -0700 Subject: Global utility module/package In-Reply-To: References: Message-ID: <445fc2a2$1@nntp0.pdx.net> Christoph Haas wrote: > As I know that importing packages from multiple modules always keeps it a > singleton I thought of something like this: > > Util.py: > ~~~~~~~~ > debugFlag = False > vibranceLevel = 'good' > > def function1(): > global debugFlag > print debugFlag The global line is not needed: global declarations are only required if you need to _write_ on globals w/in the function. --Scott David Daniels scott.daniels at acm.org From robin at reportlab.com Thu May 11 09:59:58 2006 From: robin at reportlab.com (Robin Becker) Date: Thu, 11 May 2006 14:59:58 +0100 Subject: _PyList_Extend advice Message-ID: <4463435E.5070704@chamonix.reportlab.co.uk> Is there some reason why list.extend is not documented in the C Api? I see an exported function called _PyList_Extend which seems to be the right thing, but is it deprecated? -- Robin Becker From kentilton at gmail.com Fri May 12 20:25:48 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 12 May 2006 20:25:48 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Everything else responded to separately, but... > I'd like to see a demonstration that using the same binding syntax for special > and lexical variables buys you something apart from bugs. Buys me something? Why do I have to sell simplicity, transparency, and clean syntax on c.l.python? kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From ursache.marius at gmail.com Sun May 7 06:07:28 2006 From: ursache.marius at gmail.com (ursache.marius at gmail.com) Date: 7 May 2006 03:07:28 -0700 Subject: md5 from python different then md5 from command line Message-ID: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> Hi I noticed that the md5 computed with md5 module from python is different then the md5 sum computed with md5sum utility (on slackware and gentoo). i.e. $echo marius|md5sum 0f0f60ac801a9eec2163083a22307deb - >>> test = md5.new("marius") >>> print test.hexdigest() 242aa1a97769109065e3b4df359bcfc9 Any idea why? and how to get the same md5 sum for both calls? Thanks From tdw at tdw.net Thu May 25 10:25:43 2006 From: tdw at tdw.net (Tim Williams) Date: Thu, 25 May 2006 15:25:43 +0100 Subject: wincerapi In-Reply-To: References: Message-ID: <9afea2ac0605250725j5b2cd53k4484e4ad153cd328@mail.gmail.com> On 25 May 2006 07:06:02 -0700, jordan.taylor2 at gmail.com wrote: > I know this isn't helpful at all, but now I'm curious. What's wincer? > Its a module which provides an interface to the win32 CE Remote API :) From webraviteja at gmail.com Wed May 10 18:35:11 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 10 May 2006 15:35:11 -0700 Subject: Calling C/C++ functions in a python script In-Reply-To: <1147299778.630583.83380@q12g2000cwa.googlegroups.com> References: <1147299778.630583.83380@q12g2000cwa.googlegroups.com> Message-ID: <1147300511.673435.72630@i39g2000cwa.googlegroups.com> If all you have are functions, the easiest is to create a simple dll/so and load it into Python with ctypes. http://starship.python.net/crew/theller/ctypes/tutorial.html For more advanced needs, take a look at some of the extending options available. http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html From g.brandl-nospam at gmx.net Fri May 26 05:48:47 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 26 May 2006 09:48:47 +0000 Subject: how to clear up a List in python? In-Reply-To: <1148636521.026385.171410@y43g2000cwc.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148636521.026385.171410@y43g2000cwc.googlegroups.com> Message-ID: vbgunz wrote: > Fredrik_Lundh = 'wah' > > I bet you enjoy stealing candy from babies and dunging on the little > guy every chance you get. You're suppose to be a role model in this > community? Your temper tantrum and unrelenting 'look at me look at me > i'm bigger and better' machismo attitude is nothing more than a decoyed > ploy set out by a deluded megalomaniac. Personally speaking, Fredrik's just sitting here beneath me, and I can assure you that he's not screaming "I'm bigger and better than you all" every few minutes. He may be screaming "I made it faster!", but that's why we're here ;) > You're promoting Python or the > fact that you're the son of Zeus and Hera? You're the worse sore losing > cry baby I've ever witnessed on the net in my ten years here... > pathetic for sure... You perhaps shouldn't become so excited. Next time, if you're not sure of the correctness of your solution, try to wait a bit before posting it, and see if someone other comes up with the same thing you would have posted. Georg From johnjsal at NOSPAMgmail.com Mon May 8 10:01:33 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 14:01:33 GMT Subject: which is better, string concatentation or substitution? In-Reply-To: References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <1147065351.819566.140900@j73g2000cwa.googlegroups.com> <445eeab3$0$3681$4d3efbfe@news.sover.net> Message-ID: <1bI7g.2054$No6.45780@news.tufts.edu> Duncan Booth wrote: > If you build a > list of lines to join then you don't have to repeat '\n' on the end of each > component line. How would that work? Wouldn't the last line in the list still need the newlines? From fredrik at pythonware.com Fri May 12 07:06:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 May 2006 13:06:55 +0200 Subject: Python memory deallocate References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com><1147347601.597292.15220@j73g2000cwa.googlegroups.com><1147353348.028544.143470@u72g2000cwu.googlegroups.com> <200605111554.58287.me+python@modelnine.org> Message-ID: Heiko Wundram wrote: > PIL isn't known to have any memory leaks, by the way (AFAICT), just to confirm > what I've written before, but the effbot should be of more help here... PIL is heavily used in 24/7 production systems, often by people who knows a lot about how to run mission critical systems, so memory and resource leaks in PIL tends to be noticed. there has been one leak fix in 1.1.6, afaik: converting a grayscale image to a palette image would (sometimes?) leak a palette structure. but that's a couple of hundred bytes, not a couple of hundred megabytes... From sjuranic at gmail.com Mon May 8 10:47:54 2006 From: sjuranic at gmail.com (Steve Juranich) Date: Mon, 08 May 2006 07:47:54 -0700 Subject: Python Graphics Library References: <1147099026.983602.148160@v46g2000cwv.googlegroups.com> Message-ID: utab wrote: > Dear all, > > Could you please recommend me a graphics library for python. I saw PYX > which has nice screenshots on the webpage. > > My first ambition is to be able to draw 2D or 3D graphs for my > mathematical results. Maybe later, I can handle other types of > graphical operations. Have you seen matplotlib? http://matplotlib.sourceforge.net -- Steve Juranich Tucson, AZ USA From gmc at serveisw3.net Sun May 21 19:43:45 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Mon, 22 May 2006 01:43:45 +0200 Subject: Python update trouble (2.3 to 2.4): x< References: <1148197232.312628.255650@i39g2000cwa.googlegroups.com> <1148209690.978989.65430@j55g2000cwa.googlegroups.com> <4470DF1D.4040109@lexicon.net> Message-ID: <4470FB31.7060302@serveisw3.net> Hi John! John Machin escribi?: >On 22/05/2006 5:22 AM, Gonzalo Monz?n wrote: > > >>Thank you for all the suggestions! :-) >> >>The C routine is almost -changing data type long for word- a copy of the >>function given by a hardware manufacturer, the same code used in their >>firmware to calc the checksum of every piece of data sent or received, >>and that data is somewhat special: it does not contain only plain ascii >>character data (only 0x01 - 0x09 as delimiters) and every data set ends >>with a 0x00 null byte so its fine to calculating checksum until "\x00" >>is reached. And I must get the same crc calculations. That C routine >>(and a very similar PHP one too) are tested for months and work smoothly. >> >>And of course I should use integer not long!!... we aren't anymore in >>the 8 bit computer era... ;-) original code from hardware manufacturer >>use words by the way. And now really don't know why I used long. I >>thought I did that way 'cause see pyrex C generated glue code always >>using PyInt_FromLong so thought would use the same type. >> >> > >Perhaps we need some amplification of "of course I should use integer >not long" :-) > >Is the transmitted checksum (which your routine must create and/or >verify) 2 bytes long or 4 bytes long??? This is the most important >thing; once that is established, then you choose the C and/or Python >types and the mask (0xFFFF or 0xFFFFFFFF) as/if necessary. In that >original specification from the manufacturer, how wide was a "word"? > > > Is only 2 bytes long (0x0 to 0xFFFF). I really don't know how wide is a "word" but I guess its 2 bytes long. >Note that in most/many C compilers at the moment, "int" and "long" >*both* mean 32 bits, to get 64 bits you need "long long" [or "_int64" or >whatever in realms under the sway of the dark tower], and "short" may >get you 16 bits if you are lucky. In a typical Python environment at the >moment, "int" uses the C "long", and thus typically will be 32 bits. >Python "long" is a variable-length data type. > >Also note that even if the "checksum" is 32 bits wide, the high-order 16 >bits are not verifiably useful, so you could use a [faster] 16-bit >version when receiving. > > > >>I changed the C function to use integer, and it is performing a little >>bit slowly than using longs (best with long: 0.614us, best with int: >>0.629us), that is maybe as I said due pyrex glueing always the return >>values with PyObject* PyInt_FromLong for all kind of short int to long >>data types? Anyway both results are fine, and the timming gap is >>insignificant (int: 1580403 loops -> 0.973 secs, long: 1601902 loops -> >>1.01 secs) as i usually never have to call more than 100,000 times when >>loading a full file data backup. >> >> > >I'm somewhat puzzled: Do you have the facility to cross-compile C to run >on the Pocket PC? If NO, why do you continue to mention fast versions >coded in C and glued with Pyrex? If YES, why did you include a Python >version in your initial question? > > That is just because I have some modules for common communication tasks with that hardware interface, and I use them in some PC applications, but now I'm coding a similar application that runs on PocketPC, so I use both versions of crc calculation in different applications: C/Pyrex on the PC -compiled with distutils/gcc- , and the Python one I was having trouble, only intended for PocketPC. I still have to setup a ms.evc compiling environment for the new PythonCE 2.4.3 release, but now haven't got the time so far, I'm in hurry to finish a first demo release for the PocketPC app, so as I had few C dependencies -modules in C/Pyrex for what I haven't got a working Python version yet like that crc calc.- I thought would be a better idea to re-code them in Python. If you are curious about, I'm glad to show some screenshots of the PocketPC app. -well, it runs fine both on the PC & PPC-. It is a sports timing "remote point" application, it connects to timing hardware, send data to main timing software via Internet and in the meanwhile gets other point data and race results so you can have that info live on every timing point while the race goes: http://serveisw3.net/temp/ppc_preview/ppc_preview.html >Cheers, > >John > > Regards, Gonzalo. From guido at python.org Tue May 2 13:47:43 2006 From: guido at python.org (Guido van Rossum) Date: Tue, 2 May 2006 10:47:43 -0700 Subject: [Python-3000] bug in modulus? In-Reply-To: <1f7befae0605021030r458a371fm54f263cfaf9c90cf@mail.gmail.com> References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> <4450928c$0$21107$626a54ce@news.free.fr> <1f7befae0605021030r458a371fm54f263cfaf9c90cf@mail.gmail.com> Message-ID: This is way above my head. :-) The only requirement *I* would like to see is that for floats that exactly represent ints (or longs for that matter) the result ought of x%y ought to have the same value as the same operation on the corresponding ints (except if the result can't be represented exactly as a float -- I don't know what's best then). We're fixing this for / in Py3k, so passing an int into an algorithm written for floats won't be harmful and won't require defensiev float() casting everywhere. It would be a shame if we *introduced* a new difference between ints and floats for %. --Guido On 5/2/06, Tim Peters wrote: > [Andrew Koenig, on the counter intuitive -1e-050 % 2.0 == 2.0 example] > >> I disagree. For any two floating-point numbers a and b, with b != 0, it > >> is always possible to represent the exact value of a mod b as a > >> floating-point number--at least on every floating-point system I have ever > >> encountered. The implementation is not even that difficult. > > [also Andrew] > > Oops... This statement is true for the Fortran definition of modulus (result > > has the sign of the dividend) but not the Python definition (result has the > > sign of the divisor). In the Python world, it's true only when the dividend > > and divisor have the same sign. > > Note that you can have it in Python too, by using math.fmod(a, b) > instead of "a % b". > > IMO, it was a mistake (and partly my fault cuz I didn't whine early) > for Python to try to define % the same way for ints and floats. The > hardware realities are too different, and so are the pragmatics. For > floats, it's actually most useful most often to have both that a % b > is exact and that 0.0 <= abs(a % b) <= abs(b/2). Then the sign of a%b > bears no relationship to the signs of a and b, but for purposes of > modular reduction it yields the result with the smallest possible > absolute value. That's often valuable for floats (e.g., think of > argument reduction feeding into a series expansion, where time to > convergence typically depends on the magnitude of the input and > couldn't care less about the input's sign), but rarely useful for > ints. > > I'd like to see this change in Python 3000. Note that IBM's proposed > standard for decimal arithmetic (which Python's "decimal" module > implements) requires two operations here, one that works like > math.fmod(a, b) (exact and sign of a), and the other as described > above (exact and |a%b| <= |b/2|). Those are really the only sane > definitions for a floating point modulo/remainder. > _______________________________________________ > Python-3000 mailing list > Python-3000 at python.org > http://mail.python.org/mailman/listinfo/python-3000 > Unsubscribe: http://mail.python.org/mailman/options/python-3000/guido%40python.org > -- --Guido van Rossum (home page: http://www.python.org/~guido/) From xuejmm at gmail.com Tue May 9 01:20:28 2006 From: xuejmm at gmail.com (heidan) Date: 8 May 2006 22:20:28 -0700 Subject: Is there any plan to port python to ACCESS Palm Linux Platform? Message-ID: <1147152028.828197.196790@j73g2000cwa.googlegroups.com> Another quick question about python and palm? As we all have known that ACCESS has planned to build Palm OS on top of Linux, is there any plan to port python to THIS future PALM OS? Regards, Phipps From scott.daniels at acm.org Mon May 22 19:12:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 22 May 2006 16:12:50 -0700 Subject: Name conflict in class hierarchy In-Reply-To: <44717552$0$10541$636a55ce@news.free.fr> References: <44717552$0$10541$636a55ce@news.free.fr> Message-ID: <44724152$1@nntp0.pdx.net> bruno at modulix wrote: > Ralf Muschall wrote: >> Jeffrey Barish wrote: >> >> [overriding of base class member functions by subclass] .... >> In Python, a function not intended to be overriden should be either >> have a name starting with an underscore > > actually with *two* underscores. The single-leading-underscore naming > scheme is the convention for 'protected' (read: 'implementation, not > API') attributes. The double-underscore is there to generate names that are unlikely to accidentally conflict. Use for anything else simply annoys those of us who may need to get access to those instances and methods. -- --Scott David Daniels scott.daniels at acm.org From frithiof.jensen at die_spammer_die.ericsson.com Wed May 17 04:33:36 2006 From: frithiof.jensen at die_spammer_die.ericsson.com (Frithiof Andreas Jensen) Date: Wed, 17 May 2006 10:33:36 +0200 Subject: Using python for a CAD program References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <1147807050.375537.297430@j73g2000cwa.googlegroups.com> Message-ID: <63q2o4i02 at sneakemail.com> wrote in message news:1147807050.375537.297430 at j73g2000cwa.googlegroups.com... > Cool. thanks for the links. I've already looked around quite a bit, > and am very hesitant to just write more shit on top of other shit. All software suck. If you think that yours will not then: a) you are a narcissist b) you are the only user c) all of the above > The > idea behind this is it's completely mine. So yes, I have a tendency to > want to reinvent a few wheels, but I think it'll give me greater > satisfaction. *I* think you bite off way too much and will waste two years and never get anything usable done. > The problem with geda, etc., is that it's taking the > unix approach -- a buncha little command line tools that somehow make a > "system", using text files as communication medium. That is because this approach actually works, it is proven in serious work, it can be tested without writing a test application of about the same complexity as the real job and it deals neatly with the users needs for automation without forcing the application to contain thick, bloated object management code for the users extensions. > I hate that, > largely because it allows the infectious spread of little files all > over your system, encourages people to write scripts from outside the > system that probably won't work for you, and exposes the user > unnecessarily to the implementation of where you keep files, > directories, blabla. Wrong on many levels: The idiot users will get into trouble no matter what you do; while the user that is smart enough to write an extension will need to deal with the implementation anyway. You, the developer, has to decide on wheather it is smarter to write your very own object manager, API's and the user/developer documentation thereoff or leave it to the operating system by simply using what is already there. > I'm more of the windows approach, where you have > one integrated environment, and any text you type is from within the > application itself, and most application-related data is hidden from > the user unless he *really* wants to get at it. I.M.O. The reason for the "integrated" windows approach is simply because that OS lacked/lacks efficient tasks, interproces communication and it does not support scripting. So each developer will end up rolling his own monolith and because all the code monkeys see this, it becomes "the way". > (disclosure: I've > never actually installed geda, but I tried icarus once and couldn't get > it to compile -- another bane of open source stuff I can't stand. The odds are great that the problem is to be found in front of the screen rather than the code. > I'm > not a CS person, so when I download something, I just want it to work, > and I don't get off trying to *make* it work...). Another reason for > doing this on my own is that I'd like a general-purpose CAD/design > framework, of which electrical/IC design is only one part. Also, I > think geda simulations are spice-based, which is batch, And this matters ... in what way exactly?? > which is sooo > your-father's buick, which I hate as much as text files... aaand > another thing is I'm very big on user-experience. "Experience" over "Functionality". I see - well, it worked for Bill. The "knowledge workers" forced to use the pretty etch-a-schetch tools are less than happy and will seek to minimise the pain by avoiding most of the alledged functionality. Last time I felt "the pain of the little used feature" was setting headers and footers in Excel - No, it does NOT work the same as in Word ("work" is perhaps a strong word). > I'd like my program > to *look* slick, like it belongs in a movie or something. I think that > means starting from scratch, since I've not seen any CAD program take > any artistic/human/psychological approach to its design. That *is* true - the problem with CAD programs are that they need the *exact* details to be entered at design time so one cannot easily schetch in them and fix the design errors later. But it does not follow that there is a need for rewriting the rendering engine or the design rules checker - you could actually achieve something by writing a tool that allow an existing CAD system to support the way designers actually work so that they use the tool up front instead of as it is now where CAD is the digitiser for a paper-based design. From cvanarsdall at mvista.com Thu May 18 11:42:56 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 18 May 2006 08:42:56 -0700 Subject: [silly] Does the python mascot have a name ? In-Reply-To: References: Message-ID: <446C9600.6000804@mvista.com> John D Salt wrote: > >> >>>> hon-list/2003-September/185612.html >>>> >>> "Odi" must be the Dutch for "Monty". >>> >> Nope. If it was Dutch it would probably be Odie >> > > Damn. > > Odi(e) was a punk. I'm gonna be a rebel without a cause and stay with Monty ;) -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From scott.daniels at acm.org Mon May 29 09:19:14 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 29 May 2006 06:19:14 -0700 Subject: deleting item from ListCtrl by pop-up menu In-Reply-To: References: Message-ID: <447af082$1@nntp0.pdx.net> sendhil kumar wrote: > hi all, > i need more information on the EVT_LIST_DELETE_ITEM() > for a list ctrl! iam not able to delete the selected > list item from the popup menu...below i have given the > part of the code ... im using popup menu... wher am i > wrong.... any suggestions wud b of great help... This is a wxPython question, not a Python question. Ask on the wxPython group. Available on gmane as gmane.comp.python.wxpython --Scott David Daniels scott.daniels at acm.org From maxm at mxm.dk Mon May 29 06:28:05 2006 From: maxm at mxm.dk (Max M) Date: Mon, 29 May 2006 12:28:05 +0200 Subject: send an email with picture/rich text format in the body In-Reply-To: References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <1148797671.937857.151250@y43g2000cwc.googlegroups.com> Message-ID: <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> Ben Finney wrote: > "anya" writes: > > >>Acctualy there is a solution: >>see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 > > > Again, sending anything but plain text as the message body ensures > that your message is unreadable to a large number of people using a > variety of software. It's your choice whether to restrict your > audience in this way, but know that that's what you're doing. 90% of users are non-technical users who use standard email readers, that can easily read html messages. In my experience the kind of user that receives emails with html and pictures often prefer it that way. So why bother with the lecture? I cannot remember when I have last received a relevant email that I could not read in text mode. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From rookswood at suburbian.com.au Fri May 19 23:53:17 2006 From: rookswood at suburbian.com.au (John Savage) Date: Sat, 20 May 2006 03:53:17 GMT Subject: deleting texts between patterns References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> Tim Chase writes: >> I wish to delete lines that are in between 'abc' and >> 'xyz' and print the rest of the lines. Which is the best >> way to do it? > > sed -n -e'1,/abc/p' -e'/xyz/,$p' file.txt > >which is pretty straight-forward. While it looks neat, it will not work when /abc/ matches line 1. Non-standard versions of sed, e.g., GNU, allow you to use 0,/abc/ to neatly step around this nuisance; but for standard sed you'll need a more complicated sed script. -- John Savage (my news address is not valid for email) From davidschein at alumni.tufts.edu Wed May 10 08:33:04 2006 From: davidschein at alumni.tufts.edu (David S.) Date: Wed, 10 May 2006 12:33:04 +0000 (UTC) Subject: distutils References: <4460A9D0.50503@sccs.swarthmore.edu> <4460AFF9.6040407@sccs.swarthmore.edu> Message-ID: Dan Crosta sccs.swarthmore.edu> writes: > I don't understand -- you can install multiple scripts with a single > setup.py. Do you want finer-grained control over which are installed by > a single invocation of setup.py? In that case, you should re-read the > distutils docs about sub-classing portions of the setup process. The > documentation for the Python 2.4.2 distribution is more complete than in > 2.3.5. Again, thank you. To clarify, I want to have a separate install for--potentially--each script. I imagined that I could put a setup.py in each folder that a script lived and somehow indicate the root of my source so that distutils could find other modules that the scripts use. Perhaps, I have not organized things appropriately--I do not know. I will try to read the doco again and see if I can infer some best practices. Peace, David S. From siona at chiark.greenend.org.uk Tue May 16 09:21:15 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 16 May 2006 14:21:15 +0100 (BST) Subject: Large Dictionaries References: <1147699064.107490@teuthos> <4cs1qgF17ee24U1@uni-berlin.de> Message-ID: Maric Michaud wrote: >I don't see a use case where a python programmer should need a >dictionnary "that will be probably big" but can't predict what keys will be >in. I've recently been working on an app with precisely this characteristic, although there were enough other bottlenecks that the cost of growing the dict as needed was irrelevant. (Read ~2m items from csv file, compare them with items in a database and populate assorted dictionaries based on the result of that comparison for subsequent processing. You can make a reasonable guess, and have a definite upper bound, on the sizes of the dictionaries cheaply right at the start, but you don't know what the keys in each are going to be until you discover them through the comparison of file and DB.) -- \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 larry.bates at websafe.com Fri May 26 18:07:00 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 26 May 2006 17:07:00 -0500 Subject: access serial port in python In-Reply-To: <1148678743.109181.259710@i40g2000cwc.googlegroups.com> References: <1148678743.109181.259710@i40g2000cwc.googlegroups.com> Message-ID: <0audnaDolMWd4erZRVn-jg@comcast.com> pyserial? http://pyserial.sourceforge.net/ -Larry vipulagarwal.in at gmail.com wrote: > hi > i hav written a code in python to send an SMS from a nokia 3310 > connected to my PC... > i wanted to receive a msg on my PC. In order to do so, the PC must know > when it has to read data frm the serial port ...thus an interrupt must > be generated when the serial port receives data frm the phone .....HOW > CAN I DO THIS IN PYTHON ?? > can anyone help me with this INTERRUPT HANDLING thing in PYTHON ??? > thanks > From NOatkinwSPAM at rpi.edu Sat May 6 21:43:03 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 21:43:03 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> Message-ID: <87wtcyy5i0.fsf@rpi.edu> aleaxit at yahoo.com (Alex Martelli) writes: > Yes, we are, because the debate about why it's better for Python (as a > language used in real-world production systems, *SCALABLE* to extremely > large-scale ones) to *NOT* be insanely extensible and mutable is a > separate one -- Python's uniformity of style allows SCALABILITY of > teams, and teams-of-teams, which is as crucial in the real world as > obviously not understood by you (the law you misquoted was about adding > personnel to a LATE project making it later -- nothing to do with how > desirable it can be to add personnel to a large and growing collection > of projects, scaling and growing in an agile, iterative way to meet > equally growing needs and market opportunities). > > This specific debate grew from your misuse of "scalable" to mean or > imply "a bazillion feechurz can [[and, implicitly, should]] be added to > a language, and therefore anything that stands in the way of feechuritis > is somehow holding the language back". That's bad enough, even though > in its contextual misuse of "scalable" it breaks new ground, and I don't > want to waste even more time re-treading *old* ground as to whether the > "*insane* extensibility" afforded by macros is a good or a bad thing in > a language to be used for real-world software production (as opposed to > prototyping and research). It's interesting how much people who don't have macros like to put them down and treat them as some arcane art that are too "*insane*"ly powerful to be used well. They're actually very straightforward and can often (shock of shocks!) make your code more readable, without your efficiency taking a hit. For example, at work I recently had to generate PDF reports in PHP. Certain sections would need to be indented, and then once they were done, I wanted to move back out to the previous level of indentation. I ended up with stuff like this (totally made up on the spot, but conveys the general idea): function out_main_text( ) { $old_indent = $pdf->indentation; $pdf->indent_to( $pdf->indentation + 4 ); out_header(); out_facts(); $pdf->set_indentation( $old_indent ); } function out_header() { $old_indent = $pdf->indentation; $pdf->indent_to( $pdf->indentation + 4 ); $pdf->write( "some text" ); $pdf->set_indentation( $old_indent ); } function out_facts() { $old_indent = $pdf->indentation; $pdf->indent_to( $pdf->indentation + 4 ); out_some_subsection(); out_another_subsection(); $pdf->set_indentation( $old_indent ); } Obviously, this is very much pseudocode. The point is that managing indentation was a hassle, because each of these subfunctions indents to a new position. This can pretty clearly get tedious, and is definitely error-prone, especially when you consider that different groups of functions are called depending upon the input and that some of the functions might return early. But why should I have to worry about any of this? Why can't I do: (with-indentation (pdf (+ (indentation pdf) 4)) (out-header) (out-facts)) and then within, say out-facts: (with-indentation (pdf (+ (indentation pdf) 4)) (write pdf "some text")) More readable, and no bookkeeping to worry about. This is great! And here's the macro: (defmacro with-indentation (pdf new-value &body body) (let ((old-indent (gensym))) `(let ((,old-indent (indentation pdf))) (unwind-protect (progn , at body) (setf (indentation pdf) ,old-indent))))) Bam, all of that bookkeeping, all of those potential errors have taken care of themselves. WITH-INDENTATION will expand into code that uses UNWIND-PROTECT to ensure that the indentation always gets returned to its previous value, even if an exception occurs or the code within calls RETURN. The WITH-INDENTATION call sets up an environment where there is a new indentation level in effect, and then cleans it up when it's done. I can nest these to my heart's content. Obviously, to someone totally unfamiliar with Lisp, the contents of that macro are pretty daunting. But you're crazy if you argue that having WITH-INDENTATION around isn't an improvement over manually ensuring that indentation gets saved and restored for every function call. I could even generalize this (as CLISP does) to this: (letf (((indentation pdf) (+ 4 (indentation pdf)))) (write "some text")) Now I can use LETF to temporarily set any value at all for as long as the code inside is running, and to restore it when it's done. Macros rock. -- This is a song that took me ten years to live and two years to write. - Bob Dylan From skip at pobox.com Fri May 26 05:41:18 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 26 May 2006 04:41:18 -0500 Subject: hi,everyone. a problem with shelve Module In-Reply-To: <1148628096.075581.113290@i40g2000cwc.googlegroups.com> References: <1148628096.075581.113290@i40g2000cwc.googlegroups.com> Message-ID: <17526.52542.775526.203864@montanaro.dyndns.org> >> i only write ten records like this: >> name sex age >> jim male 22 >> tom male 23 >> lucy female 21 ... >> but i find the size of this file .oh my god , it is about 24k >> the file is too large ! is it normal ? Yes. It's the nature of packages like Berkeley DB, gdbm and dbm (the packages mediate access to the database file under the covers) that they trade space for time. The files they create are not simple text files. They are organized to permit quick access to records by key and to permit average time fast insertion. Skip From robert.kern at gmail.com Sun May 7 23:30:17 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 May 2006 22:30:17 -0500 Subject: Image SIG ML Moderator does not respond In-Reply-To: <76fd5acf0605072022l46d331b4v413b1a4da7a7b0c8@mail.gmail.com> References: <76fd5acf0605072022l46d331b4v413b1a4da7a7b0c8@mail.gmail.com> Message-ID: Calvin Spealman wrote: > I have tried repeatedly to make a post to the Image SIG ML, and get > nothing but automated responses that I must wait for word from the > moderator to approve my posting on the list. I have gotten no reply, > positive or not, in over a month. I am assuming the Image SIG moderator > is currently MIA. What channels do I have to get my messages on the ML, > and how is responsible for installing a new moderator if that is needed? You could sign up for the list. Then your messages won't need moderator approval. http://mail.python.org/mailman/listinfo/image-sig -- 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 python.list at tim.thechases.com Sun May 14 20:19:33 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 14 May 2006 19:19:33 -0500 Subject: comparing values in two sets In-Reply-To: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> Message-ID: <4467C915.5050103@tim.thechases.com> > I'd like to compare the values in two different sets to > test if any of the positions in either set share the same > value (e.g., if the third element of each set is an 'a', > then the test fails). There's an inherant problem with this...sets by definition are unordered, much like dictionaries. To compare them my such means, you'd have to convert them to lists, sort the lists by some ordering, and then compare the results. Something like s1 = set([1,3,5,7,9]) s2 = set([1,2,3]) list1 = list(s1) list2 = list(s2) list1.sort() list2.sort() if [(x,y) for x,y in zip(list1,list2) if x == y]: print "There's an overlap" else: print "No matching elements" Just to evidence matters, on my version of python (2.3.5 on Debian), the following came back: >>> set([1,3,5,7,9]) set([1,3,9,5,7]) That's not the original order, but the definition of a set isn't hurt/changed by any ordering. Thus, asking for the "position in a set" is an undefined operation. -tkc PS: for the above was done in 2.3.5 using this line: from sets import Set as set From deets at nospam.web.de Tue May 9 07:32:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 May 2006 13:32:56 +0200 Subject: Enumerating Regular Expressions References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> <1147148644.762057.238640@v46g2000cwv.googlegroups.com> <1147155306.802976.229690@y43g2000cwc.googlegroups.com> Message-ID: <4cbcvgF153dvrU1@uni-berlin.de> > I thought that was the case, I've found a paper on the topic at least. > Maybe once I've finished some other work I'll give it a shot. It seems > like a fairly useful thing to be able to do with a regular expression > so I just guessed that somebody must have done it already. Just wandering: whatfor do you perceive it useful? I've been done quite a few things with rexes - yet never it occured to me that I'd be in need of enumeration all the gazillion of possible matches. YMMV - so what for? Regards, Diez From invalidemail at aerojockey.com Fri May 5 13:16:27 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 5 May 2006 10:16:27 -0700 Subject: Tuple assignment and generators? In-Reply-To: <1146839183.981537.216320@y43g2000cwc.googlegroups.com> References: <1146826136.746268.4060@i40g2000cwc.googlegroups.com> <445b3960$1_3@news.bluewin.ch> <1146831804.396839.316070@v46g2000cwv.googlegroups.com> <1146839183.981537.216320@y43g2000cwc.googlegroups.com> Message-ID: <1146849386.943302.103820@u72g2000cwu.googlegroups.com> vdrab wrote: > I guess the take-away lesson is to steer clear from any reliance on > object identity checks, if at all possible. BINGO! > Are there any other such > "optimizations" one should like to know about? You don't have to know about them, as long as you use the operators correctly. == tests equality. is tests identity. Use is ONLY when you are testing whether two things are the same object. Otherwise, use ==. When deciding which operator to use, ask yourself this: would the result still be true if they were different objects with the same value? If yes, then use ==. 0 == 0 should be true even if the two zeros are different objects. Corrollary: You should test for singleton objects with is. None, NotImplemented, and Ellipsis are singleton objects; this is part of the language and not an implementation detail. You can rely on it. Carl Banks From bignose+hates-spam at benfinney.id.au Tue May 2 19:49:36 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 03 May 2006 09:49:36 +1000 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: <87psiwc7hr.fsf@benfinney.id.au> Edward Elliott writes: > Compiler, interpreter, magic-codey-runny-thingy, whatever, at some point > something has to translate this source code > def method (self, a, b): something > into a function object (or whatever you're calling the runnable code this > week). Call this translator Foo. Whatever Foo is, it can insert 'self' > into the parameter list for method, e.g. when it sees "def method (a,b)" it > pretend like it saw "def method (self,a,b)" and proceed as usual. Once it > does that, everything is exactly the same as before. So now you're proposing that this be a special case when a function is declared by that particular syntax, and it should be different to when a function is created outside the class definition and added as a method to the object at run-time. Thus breaking not only "explicit is better than implicit", but also "special cases aren't special enough to break the rules". Still -1. -- \ "The cost of a thing is the amount of what I call life which is | `\ required to be exchanged for it, immediately or in the long | _o__) run." -- Henry David Thoreau | Ben Finney From sybrenUSE at YOURthirdtower.com.imagination Tue May 9 03:03:09 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 9 May 2006 09:03:09 +0200 Subject: Memory leak in Python References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> Message-ID: diffuser78 at gmail.com enlightened us with: > I have a python code which is running on a huge data set. After > starting the program the computer becomes unstable and gets very > diffucult to even open konsole to kill that process. What I am > assuming is that I am running out of memory. Before acting on your assumptions, you need to verify them. Run 'top' and hit 'M' to sort by memory usage. After that, use 'ulimit' to limit the allowed memory usage, run your program again, and see if it stops at some point due to memory problems. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From deets at nospam.web.de Wed May 3 13:48:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 May 2006 19:48:13 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> <1146644904.906523.255970@j73g2000cwa.googlegroups.com> <1146651877.687428.294320@v46g2000cwv.googlegroups.com> Message-ID: <4bs8nhF1373qmU1@uni-berlin.de> Edward Elliott wrote: > Michele Simionato wrote: >> Python solution is to rely on the intelligence of programmers. If they >> see an all caps name and then they try to change it without knowing what >> they are doing, then they are stupid. If you have stupid programmers >> there is no way the language can stop them for making disasters. > > Which doesn't apply here, one of the OP's examples further up this thread > doesn't modify any ALL CAPS vars directly: > >>>> A = []??#?let's?declare?a?"constant"?here >>>> b = A???#?and?let's?assign?the?constant?here >>>> b.append('1') # OOPS! That leads to the question of forbidding mutable methods. Which will require const-declarations on methods that in turn are only allowed to invoke const-methods themselves. Bottom line is: if one wants static typing and full control over construction of new pobjects when merely assigning, use C++ :) diez From leo at lspace.org Sun May 7 13:11:24 2006 From: leo at lspace.org (Leo Breebaart) Date: 7 May 2006 17:11:24 GMT Subject: Passing options around your program Message-ID: <4c6o1sF14hhjuU1@individual.net> I have another question where I am not so much looking for a solution but rather hoping to get some feedback on *which* solutions people here consider good Pythonic ways to approach a issue. The situation is this: I am writing fairly large console scripts in Python. They have quite a few command-line options, which lead to configuration variables that are needed all over the program (e.g. the "--verbose" option alone is used by just about every function and method). I am using optparse to handle the actual option parsing, so I have a main function that contains: opts,args = parser.parse_args() My question in a nutshell is: what is the best way to make the parsed options in 'opts' easily available to the rest of my program? - Having 'opts' trickle down by passing it as an explicit parameter is the most flexible option. It allows me to easily separate the options from the command-line parsing -- if I want to call my script interactively or from a GUI instead, I can just craft my own 'opts' object and pass that. But on the other hand, I feel that the proliferation of 'opts' parameters gets ugly, and does not do wonders for the readability of the program. - So especially for shorter scripts, a solution I've used is to define a global config class, and transfer the options to it: class Config: pass With in main(): for opt in vars(opts): setattr(Config, opt, getattr(opts, opt)) or: Config.cmd_opts = opts Now every method that needs it can just call Config.verbose or Config.cmd_opts.verbose or whatever. A variant I have also used occasionally is to derive Config from a Martelli Borg parent class with shared-state instances, so that every function or class that needs access to the config parameters can just instantiate its own 'local' Config() object. I find this works nicely if the program is spread out over more than one file. - A third option I have seen mentioned (possibly even here on c.l.p.), but have not actually tried yet, is that if you decide to have something 'global' anyway, why not just use a module instead of a class to store the options, so that every file can do "import config" and then say "config.verbose" etc. So, does anybody have any particular positive or negative opinions on any of these approaches, and/or are there perhaps possibilities I have overlooked? Many thanks in advance for your feedback. -- Leo Breebaart From fidtz at clara.co.uk Mon May 8 09:42:27 2006 From: fidtz at clara.co.uk (fidtz at clara.co.uk) Date: 8 May 2006 06:42:27 -0700 Subject: A better way to split up a list In-Reply-To: <445F469D.60007@lexicon.net> References: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> <445F469D.60007@lexicon.net> Message-ID: <1147095747.554970.173460@i40g2000cwc.googlegroups.com> Argh, embarassment on my part due to incomplete spec. movelist is used to store a list of chess moves and splitting it up in this way is so it can be printed in a space that is 3 lines high but quite wide. Thus the way the list grows as it is appended to in chopupmoves is intended. From Michael.J.Fromberger at Clothing.Dartmouth.EDU Sat May 6 21:10:51 2006 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Sat, 06 May 2006 21:10:51 -0400 Subject: Splice two lists References: <1146961724.195038.18680@u72g2000cwu.googlegroups.com> Message-ID: In article <1146961724.195038.18680 at u72g2000cwu.googlegroups.com>, "danmcleran at yahoo.com" wrote: > Is there a good way to splice two lists together without resorting to a > manual loop? Say I had 2 lists: > > l1 = [a,b,c] > l2 = [1,2,3] > > And I want a list: > > [a,1,b,2,c,3] as the result. > > I've been searching around but I can't seem to find a good example. Here's one possibility: list(reduce(lambda s, t: s + t, zip(L1, L2), ())) -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From tim.peters at gmail.com Wed May 3 17:46:38 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 3 May 2006 17:46:38 -0400 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <1146689930.600243.65340@v46g2000cwv.googlegroups.com> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> Message-ID: <1f7befae0605031446y4b337a10qfd36df01c5647645@mail.gmail.com> >> What do you mean "stop responding"? [OlafMeding at gmail.com] > Both threads print their thread numbers (either 1 or 2) approximately > every 10 seconds. However, after a while (minutes to hours) both > programs (see above) hang! Where "hang" means they stop printing. > Pressing ctrl-c (after the printing stops) causes the threads to "wake > up" from their sleep statement. And since the sleep took more than 1 > seconds the thread number and the duration of the sleep is printed to > the screen. > > Do you have a hyper-threading/dual/multi core CPU? Did you try this? I was using a 3.4 GHz Pentium 4 (single core) with hyper-threading enabled. I didn't run it for hours ;-) But supposing I do and see a hang, it's unlikely that will have anything to do with Python. On Windows, time.sleep() called from any thread other than the main thread just calls the Win32 API Sleep() function, after converting the argument to milliseconds. So it may be more fruitful to recode your test program in C (if there is a bug here, it's most likely in Microsoft's implementation of its Sleep() function). From bucodi at yahoo.fr.invalid Tue May 2 10:56:07 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Tue, 02 May 2006 16:56:07 +0200 Subject: wxPython, wxcombobox opening References: <9cL4g.4233$B42.2019@dukeread05> <7XH5g.9939$9c6.3212@dukeread11> Message-ID: That is what I was afraid for.... Thanks for answering, Rony > Hi, > > From the wxPython list: > >> Hi, >> >> Which event must I catch to be called when the user clicks on the combo >> "button" to make the drop down list to appear ? > > No, there isn't a specific event for the opening of the drop-down box. > > > Regards, > > Philippe > > > > > > Philippe Martin wrote: > >> Hi, >> >> I do not have the answer but am very interested in the issue. I tried >> this: >> >> l_ev = wx.MouseEvent(wx.wxEVT_LEFT_DOWN) >> l_ev.SetEventObject(self.GetCombo()) >> self.GetEventHandler().ProcessEvent(l_ev) >> >> Which did send the event to the combo (which is in a pannel in my case) .. >> but that is apparently not the event that triggers the dropping of the >> list. >> >> I posed elsewhere and will forward here any hint. >> >> Philippe >> >> >> >> Rony Steelandt wrote: >> >>> Hi, >>> >>> Does somebody knows a way to automaticely open the list part of a >>> wxCombobox when it gets the focus ? >>> >>> tia, >>> >>> Rony From steve at holdenweb.com Tue May 16 05:58:01 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 16 May 2006 10:58:01 +0100 Subject: Far from complete In-Reply-To: <1147758802.408740.131700@u72g2000cwu.googlegroups.com> References: <1147758802.408740.131700@u72g2000cwu.googlegroups.com> Message-ID: Kay Schluehr wrote: > Section 2.3 of the Python 2.5. tutorial > > "The following sections describe the standard types that are built into > the interpreter. Historically, Python's built-in types have differed > from user-defined types because it was not possible to use the built-in > types as the basis for object-oriented inheritance. With the 2.2 > release this situation has started to change, although the intended > unification of user-defined and built-in types is as yet far from > complete. " > > "Far from complete"? Have I missed something? > Releases 2.3 through 2.5, by the look of it :) Of course the "classic" classes still remain, and probably won't disappear until 3.0, so that could be regarded as "completion" of the change described. Then *everything* will ultimately be based on "object". regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tjreedy at udel.edu Wed May 17 14:44:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 May 2006 14:44:57 -0400 Subject: Question about exausted iterators References: <446b48e2$0$5293$626a54ce@news.free.fr> Message-ID: "Christophe" wrote in message news:446b48e2$0$5293$626a54ce at news.free.fr... > Is there a good reason why when you try to take an element from an > already exausted iterator, it throws StopIteration instead of some other > exception ? Yes. . . To distinguish the control message "I am done yielding values, as per the code specification (so don't bother calling me again)." from error messages that say "Something is wrong, I cannot yield values and give up." In other words, to distinguish expected correct behavior from unexpected incorrect behavior. This is essential for the normal and correct use of iterators. > I've lost quite some times already because I was using a lot > of iterators and I forgot that that specific function parameter was one. I think you mean 'specific function argument' for a parameter which could be any iterable. > Exemple : Example > >>> def f(i): > ... print list(i) > ... print list(i) > ... > >>> f(iter(range(2))) > [0, 1] > [] As per specification. I am guessing that you want the first list() call to terminate normally and return a list, which requires exhausted i to raise StopIteration, while you want the second list() to not terminate but raise an exception, which requires exhausted i to raise something other than StopIteration. Tough. One solution is call list(i) exactly once: def f(i): li = list(i) print li print li Another is to document f as requiring that i be a non-iterator reiterable iterable and only pass correct arguments. A third is to add a line like if iter(i) is i: raise TypeError("input appears to be iterator") This is not quite exact since it will improperly exclude self-iterator reiterables (which, I believe, no builtin is) and improperly pass non-reiterable non-iterator iterables (at least some file objects). But it might work for all your cases. Terry Jan Reedy From __peter__ at web.de Mon May 15 09:16:10 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 May 2006 15:16:10 +0200 Subject: How to install pyTrix? References: <44652d37$0$15982$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: DeepBlue wrote: > can any1 please tell me how to install pyTrix? Just putting the module into your site-packages directory might be sufficient. Peter From johnjsal at NOSPAMgmail.com Wed May 3 12:06:51 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 03 May 2006 16:06:51 GMT Subject: simultaneous assignment In-Reply-To: <445870fe$0$479$626a54ce@news.free.fr> References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <4457dadd$0$9654$636a55ce@news.free.fr> <44580e23$0$5389$c3e8da3@news.astraweb.com> <445870fe$0$479$626a54ce@news.free.fr> Message-ID: bruno at modulix wrote: > John Salerno wrote: >> Bruno Desthuilliers wrote: >> >>> But my question (sorry, it may not have been clear) was more along the >>> line of : "why do you worry about identity in the given snippet ?". >> >> Actually, I kind of thought that maybe it *didn't* matter in this >> particular example anyway, so my question was meant to be more general >> than I might have written it. It seems like the identity issue can be a >> problem in certain cases, although I can't think of a case right now! :) > > something > a = b = [] > a.append(1) > print b > > Ah ha! From first-name.last-name at gmail.com Mon May 8 01:28:27 2006 From: first-name.last-name at gmail.com (Nilton Volpato) Date: Mon, 8 May 2006 02:28:27 -0300 (BRST) Subject: ANN: progressbar 2.2 - Text mode progressbar for console applications Message-ID: Text progressbar library for python. http://cheeseshop.python.org/pypi/progressbar This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when the terminal size is changed. It's also efficient, because the text is only updated if need, with a minimum overhead in the case there is no need for updating. It was tested and works under windows, linux and macosx. And should also work in many other untested operating systems. You may get it from pypi: http://cheeseshop.python.org/pypi/progressbar Thanks, Nilton. -- Nilton Volpato email: "%s.%s at gmail.com" % ('nilton', 'volpato') From kps at sent.com Mon May 1 03:01:35 2006 From: kps at sent.com (Kevin Simmons) Date: Mon, 01 May 2006 00:01:35 -0700 Subject: stdin: processing characters In-Reply-To: <1146423801.634307.100970@g10g2000cwb.googlegroups.com> References: <2Bd4g.21380$tN3.16246@newssvr27.news.prodigy.net> <1146423801.634307.100970@g10g2000cwb.googlegroups.com> Message-ID: <4455B24F.4000501@sent.com> Serge Orlov wrote: > Cameron Laird wrote: >> In article <2Bd4g.21380$tN3.16246 at newssvr27.news.prodigy.net>, >> Edward Elliott wrote: >>> Kevin Simmons wrote: >>>> I have a python script that prompts the user for input from stdin via a >>>> menu. I want to process that input when the user types in two characters >>>> and not have to have the user press . As a comparison, in the bash >>>> shell one can use (read -n 2 -p "-->" CHOICE; case $CHOICE in...). Works >>>> great and is very >>> I did something like this a couple years ago, curses was the easiest way I >>> found to do it. It's pretty painless with the wrapper function, which >>> restores your terminal on error/exit. >>> >> Kevin, the bad news is that curses() is as good as Python gets in >> this regard. For better or worse, to the best of my knowledge, >> unextended Python caNOT implement bash's read. Here's the closest >> small approximation I know: >> >> import curses >> import os >> >> msvcrt = curses.initscr() >> msvcrt.addstr("-->") >> first = msvcrt.getch() >> second = msvcrt.getch() >> os.system("stty echo -nl") >> print "\nThe two characters are '%s' and '%s'." % (first, second) >> >> I hope someone proves me wrong. > > I'm not sure what "unextended Python" means, but on POSIX platforms > termios module can disable echo and command line option -u can disable > buffering. I think there should be a way to disable buffering after > program started. Probably fcntl module. > Thanks for your input. I found an answer that suits my needs, not curses :-), but stty settings and sys.stdin.read(n) : import os, sys while 1: os.system("stty -icanon min 1 time 0") print """ Radio computer control program. ------------------------------ Choose a function: po) Power toggle fq) Change frequency cm) Change mode vo) Change volume re) Reset qu) Quit -->""", func = sys.stdin.read(2) if func == "po": ... ... rest of menu actions ... elif func = "qu": os.system("stty cooked") sys.exit() Thanks again, Kevin From robert.kern at gmail.com Tue May 9 21:02:43 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 May 2006 20:02:43 -0500 Subject: installing numpy In-Reply-To: References: <877j4v5ukc.fsf@localhost.localdomain> <6Y%7g.11622$EC.10694@tornado.rdc-kc.rr.com> <8764kfkkhb.fsf@localhost.localdomain> Message-ID: Raymond L. Buvel wrote: > Since you are a new Linux user, you should definitely follow Robert's > advice about building as an ordinary user separately from the install. > I sometimes take a shortcut and just do the install as user root. > However, I then wind up cleaning out the build directory as user root > (not a very safe thing to do). For small, pure Python packages, that may be fine. numpy's build is complicated enough that you really, *really* want to build as a regular user. -- 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 crankycoder at gmail.com Wed May 24 21:12:05 2006 From: crankycoder at gmail.com (Victor Ng) Date: Wed, 24 May 2006 18:12:05 -0700 Subject: Web frameworks and credit cards In-Reply-To: <37FBB44B-74F0-4EC7-A55E-3335E6CBFCEC@leafe.com> References: <37FBB44B-74F0-4EC7-A55E-3335E6CBFCEC@leafe.com> Message-ID: Ed, On 5/24/06, Ed Leafe wrote: > I may have an opportunity to develop an online ordering system for a > client, and will have the ability to develop using any tool I choose. > Given the fact that there are more web frameworks in Python than > keywords ;-) , what I need to know is any experience anyone out there > has had integrating credit card processing with the various Python > web frameworks. Until now, my only practical experience is with Zope > 2.x, but I'm open to any and all alternatives, so long as it's Python! > > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Never attribute to malice that which can be adequately explained by stupidity." - Hanlon's Razor From jUrner at arcor.de Fri May 12 17:02:50 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 12 May 2006 14:02:50 -0700 Subject: Time to bundle PythonWin In-Reply-To: References: <1hf737g.1oyxbs31plch4nN%aleax@mac.com> Message-ID: <1147467770.161050.321880@i39g2000cwa.googlegroups.com> The ctypes.com package is no longer part of ctypes. It has been split by Thomas Heller into a separate package comtypes. See: http://sourceforge.net/projects/comtypes/ Still in its childhood but as easy as com can get, I guess, way easier and better than pythonWin at least. Juergen From larry.bates at websafe.com Fri May 5 17:01:55 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 05 May 2006 16:01:55 -0500 Subject: print formate In-Reply-To: <87odyctdrl.fsf@localhost.localdomain> References: <87odyctdrl.fsf@localhost.localdomain> Message-ID: <445BBD43.4050905@websafe.com> Gary Wessle wrote: > Hi > > > import string > import re > accumulator = [] > > pattern = '(\S*)\s*(\S*)\s*(\S*)' > for each text file in dir > openfile and read into text > data = re.compile(pattern, re.IGNORECASE).findall(text) > accumulator = accumulator + data > gives a list of tuples which when printed looks like > ('jack', 'bony', 'J') > ('sam', 'lee', 'S') > ... > > how can I get the output in the formate > jack bony J > sam lee S > ... > > > thank you for entry in list_of_tuples: print ' '.join(entry) -Larry Bates From fredrik at pythonware.com Wed May 31 06:14:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 31 May 2006 12:14:01 +0200 Subject: Best Python Editor References: Message-ID: "Manoj Kumar P" wrote: > Can anyone tell me a good python editor/IDE? emacs! > It would be great if you can provide the download link also. google it! From tim.peters at gmail.com Mon May 15 23:13:52 2006 From: tim.peters at gmail.com (Tim Peters) Date: Mon, 15 May 2006 23:13:52 -0400 Subject: Why does stack.inspect take so long? In-Reply-To: <1147745178.664795.326020@v46g2000cwv.googlegroups.com> References: <1147745178.664795.326020@v46g2000cwv.googlegroups.com> Message-ID: <1f7befae0605152013s59feb8d3xc00c26371060cf28@mail.gmail.com> [63q2o4i02 at sneakemail.com] > Hi, I've written a top-down recursive decent parser for SPICE circuit > descriptions. For debugging purposes, I wanted each production > rule/function to know what its own name was, so at the beginning of > each rule/function, I make a call to inspect.stack()[0][3] (I think...) > and that fetches the name from someplace. However, with a bunch of > test text input, this takes ~10 seconds to run. When I comment out the > inspect.stack() function from each production/function, the program > speeds up to 0.04s, or 250x !! I loaded up the profiler to see what > was there, and although I don't understand the output entirely, it > looks like the stack frame functions are used in disproportionately > large amounts compared to other often-used functions. This is a > *recursive* parser, so it's being called a lot even for simple things. > I'm wondering still why there is a 250x speed up when I comment it out. > Any clues? Look at the source code (inspect.py, function `stack()`). It obviously takes time proportional to the total depth of the call stack, and for a recursive-descent parser that's likely to be highly non-trivial most of the time. It should go much faster to use a function that doesn't crawl the entire call stack. For example, >>> import sys, inspect >>> def name_of_caller(): ... return inspect.getframeinfo(sys._getframe(1), context=0)[2] >>> def f(): ... print "my name is", name_of_caller() >>> f() my name is f name_of_caller() takes time independent of the call-stack depth. The "context=0" is to avoid wasting time sucking up and packaging source-code lines you don't want anyway. From python.list at tim.thechases.com Wed May 24 16:46:08 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 24 May 2006 15:46:08 -0500 Subject: Finding Upper-case characters in regexps, unicode friendly. (oh, bugger) In-Reply-To: <4474C3C8.8080204@tim.thechases.com> References: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> <4474C3C8.8080204@tim.thechases.com> Message-ID: <4474C610.9000204@tim.thechases.com> Sorry...I somehow missed the key *uppercase* bit of that, and somehow got it in my head that you just wanted unicode letters, not numbers. Please pardon the brain-blink. I can't find anything in Python's regexp docs that do what you want. Vim's regexp engine has a "uppercase characters" and "lowercase characters" atoms, but it seems there's no counterpart to them in Python. Thus, you may have to take a combined attack of regexps+isupper(). Using isupper() has some peculiar side-effects in that it only checks uppercase-able characters, so >>> "1A".isupper() True which may or may not be what you wanted. The previously shot-from-the-hip regexp stuff will help you filter out any non-alphabetic unicode characters, which can then be passed in turn to isupper() -tkc From rpdooling at gmail.com Thu May 25 21:36:02 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 25 May 2006 18:36:02 -0700 Subject: Python Programming Books? In-Reply-To: <1148599852.040381.290030@y43g2000cwc.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148599852.040381.290030@y43g2000cwc.googlegroups.com> Message-ID: <1148607362.337121.121380@j33g2000cwa.googlegroups.com> >> "Learning to Program" by Alan Gauld >> (http://www.freenetpages.co.uk/hp/alan.gauld/) The best by far, for a n00b, in my opinion. From kevin.bell at slcgov.com Fri May 26 11:47:40 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Fri, 26 May 2006 09:47:40 -0600 Subject: hide python window, cont'd Message-ID: <2387F0EED10A4545A840B231BBAAC7226083B9@slcimail1.slcgov.com> Bell, Kevin wrote: > Great! And now that it's hiding w/ .pyw, how would I kill it if I want? > Just log off, or is there a better way? > > Kevin > > >>JOE WROTE: >>Close it in the Task Manager? I don't see it in the task manager. From onurb at xiludom.gro Tue May 9 08:42:06 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 14:42:06 +0200 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <87r7359emf.fsf@voodoo.myself> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> <1147071499.135783.193610@e56g2000cwe.googlegroups.com> <87r7359emf.fsf@voodoo.myself> Message-ID: <44608e7f$0$30109$636a55ce@news.free.fr> Lawrence Oluyede wrote: > "ankyhe at gmail.com" writes: > > >>However, I wonder why L.sort() don't return the reference L, the >>performance of return L and None may be the same. > > > It's not "the same". sort() does not return anything. Yes it does : it returns the None object. > >>Why? > > I've just explained to you and so the others: by default operations on mutable > objects are in place. this is pure non-sens : class MyList(list): def sort(self): return sorted(self) This is a mutable object, and the sort() is not in place. class MyObj(object): def __init__(self, name): self.name = name def sayHello(self): return "hello from %s" self.name This is another mutable object, and I fail to see how 'in place' could sensibly have any meaning when applied to sayHello(). Also, and FWIW, the fact that a method modifies the object it's called on doesn't technically prevent it from returning the object: class MyOtherList(list): def sort(self, *args, **kw): list.sort(self, *args, **kw) return self > s = "abc" > s.upper() > > does return another string. String are immutable references. Strings are immutable *objects*. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Thu May 4 04:27:59 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 10:27:59 +0200 Subject: This coding style bad practise? In-Reply-To: <445936fb$0$31642$e4fe514c@news.xs4all.nl> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> <44591be3$0$2626$636a55ce@news.free.fr> <445936fb$0$31642$e4fe514c@news.xs4all.nl> Message-ID: <4459bb6b$0$14029$626a54ce@news.free.fr> Martin P. Hellwig wrote: > Bruno Desthuilliers wrote: > > >> >> Why not just use the call operator instead ? ie: >> >> >>> id = IDGenerator(...) >> >>> id() >> 01_20060424_151903_1 >> >>> id() >> 01_20060424_151905_2 >> > > Because of: > >>>>> id = IDGenerator("01",99) >>>>> id() >> >> Traceback (most recent call last): >> File "", line 1, in ? >> id() >> TypeError: 'IDGenerator' object is not callable >> >>>>> Of course - you have to overload the call operator for this to work. Just rename IDGenerator.__repr__ to IDGenerator.__call__, and I garantee this will work - and will be *much* more cleaner than abusing __repr__. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From digitalorganics at gmail.com Wed May 24 12:20:32 2006 From: digitalorganics at gmail.com (Cloudthunder) Date: Wed, 24 May 2006 12:20:32 -0400 Subject: Rapyd: control variables Message-ID: Okay, I'm just starting out with rapyd, so bear with me. I have one form and a label and I gave the label a controlvariable (textvariable). See: #------------------------------------------------------------------------------# # # # testme # # # #------------------------------------------------------------------------------# class testme(Frame): def __init__(self,Master=None,**kw): self.MyName = StringVar() self.MyName = str(type(ClassKernelBasic)) apply(Frame.__init__,(self,Master),kw) self.MyLabel = Label(self,text='replace me!',textvariable= self.MyName) self.MyLabel.pack(side='top') # #Start of event handler methods # # #Start of non-Rapyd user code # In the main file I imported my module (classkernelbasic) where the comment told me to and it seemed to have no problem importing. But when I run the app, nothing shows up in the label or, if something does, it's whatever I put in the label widget's "text" variable. I also tried setting the text variable to MyName, but this also failed to display anything. What's wrong? -------------- next part -------------- An HTML attachment was scrubbed... URL: From sjmachin at lexicon.net Wed May 24 22:37:46 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 May 2006 12:37:46 +1000 Subject: Unexpected extension module behaviour In-Reply-To: <1148522952.022925.229350@u72g2000cwu.googlegroups.com> References: <1148522952.022925.229350@u72g2000cwu.googlegroups.com> Message-ID: <4475187A.3030705@lexicon.net> On 25/05/2006 12:09 PM, rimmer wrote: > I'm writing an extension module in C in which I'm passing an array of > floats from C to python. The code below illustrates a simple C > function designed to output an array of floats. > > --------- > extTest.c > --------- > #include > > double *testArray(int nsamp) { > > double nums[10000]; > int i; > double cumdata = 0.0; > > printf("%d\n", nsamp); > for (i=0; i<=nsamp; i++) { > printf("%d\n", i); > nums[i] = cumdata; > cumdata += 0.5; > printf("%f\n", nums[i]); > } > return nums; Your problem is right here. The array nums is local to the function. You are returning a pointer to memory whose contents are utterly useless once you return from the function. Depending on the architecture and the compiler, the pointer may point outside the stack, maybe causing the hardware to take exception when the pointer is dereferenced, or it may be inside the stack, in which case the next few function calls are liable to trash the contents. > } > > Then I write a wrapper function to pass the data back and forth between > C and Python. Before you do that, test it with a simple C main()!!! [snip] > Here is where I'm stumped. I must be doing something wrong during the > PyList_SetItem or the Py_BuildValue. Yes, you may have problems there too, but I didn't bother reading that far :-) > > Any ideas on fixing this problem ? > > Regards, > > Rimmer > From maxerickson at gmail.com Wed May 31 11:05:38 2006 From: maxerickson at gmail.com (Max Erickson) Date: Wed, 31 May 2006 15:05:38 +0000 (UTC) Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> Message-ID: "mateus" wrote: > print "hello world" > > I have a nested loop where the outer loop iterates over key value > pairs of a dictionary and the inner loop iterates over a list > each list of which is a mapped value from the dictionary > > def showReport(self): > for dev, sessions in self.logger.items(): > for tree in session: > self.addTestItem(self, tree) > > What I don't understand is why this executes w/o any problems > when "sessions" was spelled as plural (sessionS) while later > being spelled in the singular (session). > > Is there some type of name resolution of local variables where > Python makes assumptions? > Is self.logger.items() empty? This does not raise a NameError even when 'explode' is not defined: for x in []: explode max From johnjsal at NOSPAMgmail.com Tue May 2 13:15:05 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 17:15:05 GMT Subject: simultaneous assignment In-Reply-To: <4bphvsF12acj1U1@uni-berlin.de> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > I can't imagine what you're actually after here, but assuming that you > really need this Hard to explain because I'm still trying to figure out how to do it myself. I'm trying to solve a little puzzle using Python, even though I'm sure it's not necessary. Basically W, X, Y and Z are propositions that are either true or false, and the puzzle lists a few statements such as "Exactly one of X, Y and Z is true", and I'm trying to work out a little algorithm that might test for this kind of stuff. Another thing I'm trying to do is write a function that tests to see if a list contains exactly one true item, and the rest are false (obviously this would have to be a list of boolean values, I guess). I'm sure this isn't a handy utility, but I enjoy figuring out how to implement it. From stephan.diehl at gmx.net Mon May 22 04:42:46 2006 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Mon, 22 May 2006 10:42:46 +0200 Subject: Dumb-as-rocks WSGI serving using standard library References: Message-ID: On Mon, 22 May 2006 18:18:34 +1000, Ben Finney wrote: [...] > > Everything else that I can find leads to dependencies I don't want for > flexibility I don't need: cherrypy, paste, et al. > > Any suggestions for how to serve up a simple WSGI application with > just the standard library? the easiest seems to be james: http://wsgiarea.pocoo.org/james/ or flup: http://www.saddi.com/software/flup/ (for FCGI adapter) From dkuhlman at rexx.com Fri May 19 19:08:47 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Fri, 19 May 2006 23:08:47 GMT Subject: FAQ for XML with Python Message-ID: <3esbg.19024$Lm5.1740@newssvr12.news.prodigy.com> For those who are beginners to using Python to process XML, I've recently updated my Python XML FAQ (PyXMLFaq). It has a number of code samples that may help you get started. You can find it here: http://www.rexx.com/~dkuhlman/pyxmlfaq.html Comments and suggestions will be appreciated. Dave -- http://www.rexx.com/~dkuhlman From dmercer at mn.rr.com Mon May 22 20:03:25 2006 From: dmercer at mn.rr.com (Dan Mercer) Date: Tue, 23 May 2006 00:03:25 GMT Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148254714.668727.298420@y43g2000cwc.googlegroups.com> Message-ID: "nikie" wrote in message news:1148254714.668727.298420 at y43g2000cwc.googlegroups.com... : Xah Lee wrote: : : : I wonder where you get your historical "facts" form? (Monty Python : movies?) Let's just add a few fun facts: Yes, philosophy did flourish : in ancient greece, but liberty certainly didn't. Yes, Athens was (at : least most of the time) a democracy - which by the way, most : philosophers thought was a very bad thing. But still, about 90% of the : population of Athens were slaves at that time. Not just "mentally : enslaved", no, real, physical slaves. Small quibble - while only 10% of the population were citizens, by no means were the rest all slaves. The other 90% were children, women, metoikoi (a commercial class of free men of foreign birth who paid for the right to live in Athens) and house slaves. Most Athenian slaves lived in the country. : Also, it was dangerous to have oppinions that authorities didn't like : (Socrates for example was sentenced to death because of impiety, : Anaxagoras and Aristoteles had to flee because of similar charges, : Hipposus, who _proved_ a flaw in Pythagoras' number theory was : drowned). Which should act as a warning to all who employ the Socratic Method. Sadly, it doesn't. Dan Mercer From gry at ll.mit.edu Tue May 23 14:20:38 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 23 May 2006 11:20:38 -0700 Subject: "Thinking like CS" problem I can't solve In-Reply-To: <1148402620.032735.60000@g10g2000cwb.googlegroups.com> References: <1148402620.032735.60000@g10g2000cwb.googlegroups.com> Message-ID: <1148408438.572719.324030@i40g2000cwc.googlegroups.com> Alex Pavluck wrote: > Hello. On page 124 of "Thinking like a Computer Scientist". There is > an exercise to take the following code and with the use of TRY: / > EXCEPT: handle the error. Can somone help me out? Here is the code: > > def inputNumber(n): > if n == 17: > raise 'BadNumberError: ', '17 is off limits.' > else: > print n, 'is a nice number' > return n > > inputNumber(17) Yikes! It's a very bad idea to use string literals as exceptions. Use one of the classes from the 'exceptions' module, or derive your own from one of them. E.g.: class BadNum(ValueError): pass def inputNumber(n): if n == 17: raise BadNum('17 is off limits') else: print n, 'is a nice number' try: inputNumber(17) except BadNum, x: print 'Uh Oh!', x Uh Oh! 17 is off limits See: http://docs.python.org/ref/try.html#try especially the following bit: ...the clause matches the exception if the resulting object is ``compatible'' with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception,... Note that the object identities must match, i.e. it must be the same object, not just an object with the same value. Identity of string literals is a *very* slippery thing. Don't depend on it. Anyway, python 2.5 gives a deprecation warning if a string literal is used as an exception. From me at dagsunde.com Wed May 24 05:14:50 2006 From: me at dagsunde.com (Dag Sunde) Date: 24 May 2006 11:14:50 +0200 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <4474240a$1@news.wineasy.se> "Xah Lee" skrev i melding news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... > I'm sorry to trouble everyone. But as you might know, due to my > controversial writings and style, recently John Bokma lobbied people to > complaint to my web hosting provider. After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. The solution to your problem is very simple: Stop posting your "controversial writings and style" to public newgroups, and keep them on your web-server where they belong. -- Dag. From jjl at pobox.com Fri May 5 16:29:13 2006 From: jjl at pobox.com (John J. Lee) Date: 05 May 2006 20:29:13 +0000 Subject: Tuple assignment and generators? References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> Message-ID: <878xpg1ahy.fsf@pobox.com> "vdrab" writes: [...] > In fact, I think my code contains things like "if len(arg) is 0:" and > so on, So you made a mistake. It's OK, you can forgive yourself, nobody will notice > and I feel I should be able to do so given the way python treats > (claims to treat?) constant objects, even if I don't care whether the > values actually represent the same object. (By "constant" I assume you mean immutable.) I'm afraid it sounds like your assumptions about "the way python treats (claims to treat?) constant objects" were "made up out of your own head" as Tim Peters once put it :-) Python does not make such guarantees about the identity of separately-constructed immutable objects, and that's good, careful design, in my book (you might be able to see why if you think about what "is" *means* and what it would take to ensure it *always* remains true for e.g. x is 10E9, where x == 10E9 but is assigned elsewhere, and at another time during program execution). OTOH, it's good practice in Python to use "is" to compare values with the immutable singleton None ("if x is None"). No harm comes of that, simply because there is only one None object. John From nobody at 127.0.0.1 Wed May 17 19:37:53 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 23:37:53 GMT Subject: python vs perl lines of code References: <1147900508.423650.155470@i40g2000cwc.googlegroups.com> Message-ID: achates wrote: > It probably says something about your coding style, particularly in > perl. I've found (anecdotally of course) that while perl is potentially > the more economical language, writing *legible* perl takes a lot more > space. I'm sure it does. My perl (from 5 years ago) may be considered verbose (or not, I don't know). I avoid shortcuts like $_, use strict mode, etc. Then again I frequently use short forms like "statement if/unless (blah);" when appropriate. So there's a big personal component in there. But again, the interesting thing to me isn't what could one do, it's what are people actually doing in the real world? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From william.boquist at gte.net Sat May 6 00:33:55 2006 From: william.boquist at gte.net (william.boquist at gte.net) Date: Sat, 06 May 2006 04:33:55 GMT Subject: Newbie question on code vetting References: <_%w6g.44217$C63.42016@trnddc06> Message-ID: Edward, thanks for the thoughtful comments. I would like to offer a couple of links to the kind of stuff I am talking about w.r.t. the "transparency" issue. First, some from Eclipse: http://www.eclipse.org/org/documents/Eclipse%20IP%20Policy2006_03_20.pdf http://www.eclipse.org/legal/ See especially the "committer resources" stuff at the bottom. Here are a couple more from the Apache software foundation. My understanding is that these methods/principles are applied across all projects within the ASF. http://www.apache.org/foundation/how-it-works.html http://www.apache.org/licenses/#clas My thinking is that if that kind of documentation were more widely available, the process of doing appropriate diligence on the part of the consuming organizations would be easier and more repeatable. As it is now, one is pretty much left to rummage around on project web sites trying to get a gut feel for what is going on. Asking the higher-ups at work to reach technology management decisions based on my gut feel is an uphill climb. It is difficult to erase "FUD" among managers, but if it can be done not just at my company, but widely, more people can use and examine the code, report bugs, suggest improvements, etc. Availability of documentation like the Eclipse Project and the ASF are a big step in the right direction, I think. The overall goal is to remove a barrier to more widespread use of Open Source - growing the mindshare dedicated to it and potentially shrinking the mindshare dedicated to commercially-produced software. A couple of responders to my earlier notes wrote something like "do you ask the same thing of closed source vendors?" The answer is "no, not at present", but if the Open Source movement can cause Bill Gates to show his code to the Chinese government, who knows what else it can do? I think the Open Source movement is leading, not following, commercial code producers. If there is a better way to do business, I would like to see Open Source get there first. Regards, Bill From brandon.mcginty at gmail.com Wed May 31 01:02:09 2006 From: brandon.mcginty at gmail.com (Brandon McGinty) Date: Tue, 30 May 2006 22:02:09 -0700 Subject: ideas for programs? Message-ID: <447D2351.6000002@gmail.com> Hi, I've been learning python for the past couple of months and writing misc scripts here and there, along with some web apps. I'm wondering if anyone has ideas of programs I might try my hand at making? I'd appreciate it if they don't use images, because I'm blind. Also, I'm thinking of hiring myself out as a free-lance programmer. Are there many individuals/companies which would aprove programs written in python? Most adds I've seen require the programmer have a strong grasp of c++ or java. Thanks much for all of your help. THX, Brandon McGinty From scott.daniels at acm.org Mon May 29 10:08:20 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 29 May 2006 07:08:20 -0700 Subject: Ricerca Programmatore Python In-Reply-To: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> References: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> Message-ID: <447afc06@nntp0.pdx.net> Nic wrote: > Please accept my apologies for the use of the Italian language. > ... ... To be convivial it is not enough to simply begin by acknowledging that you know the rule you are violating and then violating it. You would not like: Please accept my apologies for a commercial message. ****** Great prices on V146RA ... I understand there is an Italian-language Python group, but _here_ the language is English, even if you begin by an apology in English. The reason is not for the generally monolingual Americans, as some suspect, but for, example, the hapless native Chinese speaker who has put the work into learning enough English to get by and is confronted with yet another European language to decipher. In consideration for such people, please limit yourself to English. --Scott David Daniels scott.daniels at acm.org From me+python at modelnine.org Sun May 14 15:00:54 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 14 May 2006 21:00:54 +0200 Subject: Question regarding checksuming of a file In-Reply-To: <126ev127h04e2bb@corp.supernews.com> References: <126d1u4ke4itg7f@corp.supernews.com> <7xhd3tav56.fsf@ruckus.brouhaha.com> <126ev127h04e2bb@corp.supernews.com> Message-ID: <200605142100.56327.me+python@modelnine.org> Am Sonntag 14 Mai 2006 20:51 schrieb Andrew Robert: > def getblocks(f, blocksize=1024): > while True: > s = f.read(blocksize) > if not s: return > yield s This won't work. The following will: def getblocks(f,blocksize=1024): while True: s = f.read(blocksize) if not s: break yield s --- Heiko. From johnjsal at NOSPAMgmail.com Fri May 19 16:49:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 20:49:26 GMT Subject: altering an object as you iterate over it? In-Reply-To: References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> Message-ID: Paul McGuire wrote: > I think it is just part of the objectification trend - "f = > open('xyzzy.dat')" is sort of a functional/verb concept, so it has to return > something, and its something non-objecty like a file handle - urk! Instead, > using "f = file('xyzzy.dat')" is more of an object construction concept I see what you mean, but I think that's why I like using open, because I like having my functions be verbs instead of nouns. > Note though, the asymmetry of > "f = open('blah')" and "f.close()" - there is no "close(f)". I'm not sure that's a perfect comparison though, because the counterpart of close(f) would be open(f), and whether you use file() or open(), neither is taking f as the parameter like close() does, and you aren't calling close() on 'blah' above. From duncan.booth at invalid.invalid Wed May 10 09:00:41 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 10 May 2006 13:00:41 GMT Subject: New tail recursion decorator References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > > Diez B. Roggisch wrote: >> Kay Schluehr wrote: >> >> > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 >> >> Neat. >> >> Diez > > Hi Diez, > > for all those who already copied and pasted the original solution and > played with it I apologize for radical changes in the latest version ( > the recipe is on version 1.5 now ! ). The latest implementation is > again a lot faster than the previous one. It does not only get rid of > exceptions but also of stack-frame inspection. > > Regards, > Kay > I'm not convinced by this. You have to recognise that the function is using tail recursion, and then you have to modify the code to know that it is using tail recursion. This is not always trivial. For example, the given example is: @tail_recursion def factorial(n, acc=1): "calculate a factorial" if n == 0: return acc res = factorial(n-1, n*acc) return res but a more common way to write the function would be: @tail_recursion def factorial(n): "calculate a factorial" if n == 0: return 1 return n * factorial(n-1) which won't work because it isn't actually tail recursion, but it looks sufficiently close to tail recursion that it would probably mislead a lot of people into expecting it will work. If you are going to have to rewrite functions in a stilted manner, and they use simple tail recursion, then why not just factor out the tail recursion in the first place. My other problem with this is that the decorator is very fragile although this may be fixable. e.g. (using the published example) an exception thrown inside the function makes future calls return garbage: >>> factorial(3) 6 >>> factorial('a') Traceback (most recent call last): File "", line 1, in -toplevel- factorial('a') File "", line 12, in result tc = g(*args,**kwd) File "", line 6, in factorial res = factorial(n-1, n*acc) TypeError: unsupported operand type(s) for -: 'str' and 'int' >>> factorial(3) ('continue', (3,), {}) From ptmcg at austin.rr._bogus_.com Fri May 19 15:21:40 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 19:21:40 GMT Subject: number of different lines in a file References: <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> <1148063935.859890.173230@u72g2000cwu.googlegroups.com> <1148066348.761868.322570@g10g2000cwb.googlegroups.com> Message-ID: <8Vobg.42803$Qq.38623@tornado.texas.rr.com> "Kaz Kylheku" wrote in message news:1148066348.761868.322570 at g10g2000cwb.googlegroups.com... > Paddy wrote: > ...if you are lucky enough to have a "zero copy" > pipe implementation whcih allows data to go from the writer's buffer > directly to the reader's one without intermediate kernel buffering. > I love it when you talk dirty... :) -- Paul From nnorwitz at gmail.com Wed May 3 03:15:33 2006 From: nnorwitz at gmail.com (Neal Norwitz) Date: Wed, 3 May 2006 00:15:33 -0700 Subject: Seeking students for the Summer of Code Message-ID: There is less than a week left before students must submit a final application. There are a bunch of ideas up on the wiki: http://wiki.python.org/moin/SummerOfCode/ The wiki has instructions for how to submit a proposal. There are many different areas including: core language features, libraries, and applications. This is a great opportunity to get real coding experience. Not to mention the chance to work with a nice and fun group of people. The earlier you submit an application, the more feedback you can get to improve it and increase your liklihood of getting accepted. Feel free to contact me if you have any questions. Cheers, n From OlafMeding at gmail.com Wed May 10 17:39:04 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 10 May 2006 14:39:04 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1264k82rk3pvu26@corp.supernews.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> <1147292178.325015.172460@y43g2000cwc.googlegroups.com> <1264k82rk3pvu26@corp.supernews.com> Message-ID: <1147297144.537106.161310@j73g2000cwa.googlegroups.com> Grant > You might want to run some memory tests. We have multiple identical boxes and they all have the same problem. Olaf From miki.tebeka at gmail.com Sun May 14 09:29:46 2006 From: miki.tebeka at gmail.com (Miki) Date: 14 May 2006 06:29:46 -0700 Subject: Is there any pure python webserver that can use FCGI In-Reply-To: <1147431543.658099.106310@j73g2000cwa.googlegroups.com> References: <1147431543.658099.106310@j73g2000cwa.googlegroups.com> Message-ID: <1147613386.056072.156120@i40g2000cwc.googlegroups.com> Hello llothar, IIRC trac (http://www.edgewall.com/trac/) is pure python, have a web server and support FCGI HTH, Miki From Serge.Orlov at gmail.com Fri May 19 18:21:41 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 May 2006 15:21:41 -0700 Subject: the tostring and XML methods in ElementTree In-Reply-To: <1148052433.497179.148240@u72g2000cwu.googlegroups.com> References: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> <1147853382.250160.270530@i39g2000cwa.googlegroups.com> <446dd405$0$4512$9b4e6d93@newsread2.arcor-online.net> <1148052433.497179.148240@u72g2000cwu.googlegroups.com> Message-ID: <1148077301.029353.153310@j73g2000cwa.googlegroups.com> George Sakkis wrote: > > > I'm currently using > > > (a variation of) the workaround below instead of ET.tostring and it > > > works fine for me: > > > > > > def tostring(element, encoding=None): > > > text = element.text > > > if text: > > > if not isinstance(text, basestring): > > > text2 = str(text) > > > elif isinstance(text, str) and encoding: > > > text2 = text.decode(encoding) > > > element.text = text2 > > > s = ET.tostring(element, encoding) > > > element.text = text > > > return s > > > > > > > > > Why isn't this the standard behaviour ? > > > > > > Because it wouldn't work. What if you wanted to serialize a different encoding > > than that of the strings you put into the .text fields? How is ET supposed to > > know what encoding your strings have? And how should it know that you didn't > > happily mix various different byte encodings in your strings? > > If you're mixing different encodings, no tool can help you clean up the > mess, you're on your own. This is very different though from having > nice utf-8 strings everywhere, asking ET.tostring explicitly to print > them in utf-8 and getting back garbage. Isn't the most reasonable > assumption that the input's encoding is the same with the output, or > does this fall under the "refuse the temptation to guess" motto ? If > this is the case, ET could at least accept an optional input encoding > parameter and convert everything to unicode internally. This is an optimization. Basically you're delaying decoding. First of all have you measured the impact on your program if you delay decoding? I'm sure for many programs it doesn't matter, so what you're proposing will just pollute their source code with optimization they don't need. That doesn't mean it's a bad idea in general. I'd prefer it implemented in python core with minimal impact on such programs, decoding delayed until you try to access individual characters. The code below can be implemented without actual decoding: utf8_text_file.write("abc".decode("utf-8") + " def".decode("utf-8")) But this example will require decoding done during split method: a = ("abc".decode("utf-8") + " def".decode("utf-8")).split() > > Use unicode, that works *and* is portable. > > *and* it's not supported by all the 3rd party packages, databases, > middleware, etc. you have to or want to use. You can always call .encode method. Granted that could be a waste of CPU and memory, but it works. From johnjsal at NOSPAMgmail.com Tue May 2 15:50:35 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 19:50:35 GMT Subject: simultaneous assignment In-Reply-To: References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> Message-ID: Steve R. Hastings wrote: > We could also use "generator expressions", available only in > Python 2.4 and newer. > > A list comprehension always builds a list. A generator expression can > return values one at a time. > > [v for v in seq if v] # builds a list and returns it > (v for v in seq if v) # returns a generator object Woah, interesting. Somehow I don't think I knew that generators could exist outside of generator functions (using yield)! I was wondering why the second one above worked without brackets. :) From ptmcg at austin.rr._bogus_.com Sun May 14 15:14:39 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 14 May 2006 19:14:39 GMT Subject: Named regexp variables, an extension proposal. References: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> <1147631397.922734.167880@u72g2000cwu.googlegroups.com> Message-ID: "Paddy" wrote in message news:1147631397.922734.167880 at u72g2000cwu.googlegroups.com... > I have another use case. > If you want to match a comma separated list of words you end up writing > what constitutes a word twice, i.e: > r"\w+[,\w+]" > As what constitues a word gets longer, you have to repeat a longer RE > fragment so the fact that it is a match of a comma separated list is > lost, e.g: > r"[a-zA-Z_]\w+[,[a-zA-Z_]\w+]" > > - Paddy. > Write a short function to return a comma separated list RE. This has the added advantage of DRY, too. Adding an optional delim argument allows you to generalize to lists delimited by dots, dashes, etc. (Note - your posted re requires 2-letter words - I think you meant "[A-Za-z_]\w*", not "[A-Za-z_]\w+".) -- Paul import re def commaSeparatedList(regex, delim=","): return "%s[%s%s]*" % (regex, delim, regex) listOfWords = re.compile( commaSeparatedList(r"\w+") ) listOfIdents = re.compile( commaSeparatedList(r"[A-Za-z_]\w*") ) # might be more robust - people put whitespace in the darndest places! def whitespaceTolerantCommaSeparatedList(regex, delim=","): return r"%s[\s*%s\s*%s]*" % (regex, delim, regex) # (BTW, delimitedList in pyparsing does this too - the default delimiter is a comma, but other expressions can be used too) from pyparsing import Word, delimitedList, alphas, alphanums listOfWords = delimitedList( Word(alphas) ) listOfIdents = delimitedList( Word(alphas+"_", alphanums+"_") ) -- Paul From rupole at hotmail.com Mon May 29 23:55:22 2006 From: rupole at hotmail.com (Roger Upole) Date: Mon, 29 May 2006 23:55:22 -0400 Subject: How to calc easier the "long" filesize from nFileSizeLow and nFileSizeHigh References: Message-ID: <1148961044_33775@sp6iad.superfeed.net> Shift nFileSizeHigh by 32 and add FileSizeLow. Roger "DurumDara" wrote in message news:mailman.6311.1148917245.27775.python-list at python.org... > Hi ! > > I get the file datas with FindFilesW. > I want to calc the filesize from nFileSizeLow and nFileSizeHigh with easiest as possible, without again calling os.getsize(). > How to I do it ? I need good result ! > > Thanx for help: > dd ----== 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 123 at 321.com Sat May 13 22:07:11 2006 From: 123 at 321.com (DeepBlue) Date: Sun, 14 May 2006 10:07:11 +0800 Subject: How to install pyTrix? In-Reply-To: References: <44652d37$0$15982$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <446690d5$0$15990$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi, PyTrix can be obtained from http://www.american.edu/econ/pytrix/pytrix.htm cheers! Claudio Grondi wrote: > DeepBlue wrote: >> Hi all, >> >> can any1 please tell me how to install pyTrix? >> >> thx! > The first step should be to get it, but how can it be got? > > Claudio From kentilton at gmail.com Fri May 12 15:11:20 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 12 May 2006 15:11:20 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> Message-ID: Alexander Schmolck wrote: > jayessay writes: > > >>"Michele Simionato" writes: >> >> >>>I was interested in a proof of concept, to show that Python can >>>emulate Lisp special variables with no big effort. >> >>OK, but the sort of "proof of concept" given here is something you can >>hack up in pretty much anything. > > > Care to provide e.g. a java equivalent? I think the point is that, with the variable actually being just a string and with dedicated new explicit functions required as "accessors", well, you could hack that up in any language with dictionaries. It is the beginnings of an interpreter, not Python itself even feigning special behavior. perhaps the way to go is to take the Common Lisp: (DEFVAR *x*) *x* = special_var(v=42) ;; I made this syntax up that could make for cleaner code: *x*.v = 1 print *x*.v -> 1 (Can we hide the .v?) But there is still the problem of knowing when to revert a value to its prior binding when the scope of some WITH block is left. Of course that is what indentation is for in Python, so... is that extensible by application code? Or would this require Python internals work? kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From nobody at 127.0.0.1 Tue May 16 21:57:34 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 01:57:34 GMT Subject: do/while structure needed References: <4466bddd$0$18984$c3e8da3@news.astraweb.com><1147585422.693953.292480@u72g2000cwu.googlegroups.com> <4467786c$0$1956$c3e8da3@news.astraweb.com> <84li629bgn1cjogggr4lgc82hjna5l8tij@4ax.com> Message-ID: Dennis Lee Bieber wrote: > Would you put the condition at the top of the loop -- and confuse > those people who believe the exit condition should appear at the point > the exit activates? Confusion is not the issue. You can put the condition smack dab in the middle of the loop, as long as the location is consistent people will know where to look for it. Rejecting because "some are confused the first time since other languages do it differently" gets you nowhere: some group will always be confused by something. They learn, problem solved. I agree that do/while is unnecessary. But I'd argue against it on grounds of simplicity and readability instead of confusion. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From tundra at tundraware.com Thu May 11 18:43:50 2006 From: tundra at tundraware.com (Tim Daneliuk) Date: 11 May 2006 18:43:50 EDT Subject: [ANN] tdir 1.69 Released And Available In-Reply-To: References: <1bq9j3-q86.ln1@eskimo.tundraware.com> Message-ID: <25rcj3-5jb.ln1@eskimo.tundraware.com> Edward Elliott wrote: > Tim Daneliuk wrote: > >> 'tdir' is a reimplementation and enhancement of the old 'xdir' CP/M >> utility from Ancient Times. >> >> 'tdir' is an advanced directory display utility written in Pure Python, >> and runs on both *nix and Win32 systems.\ >> >> With 'tdir' you can display directories sorted by file "extension", > > ls -X > >> display directory trees, > > ls -R Does not do the same thing. I like my version better . YMMV > >> and separate directories from files in the output listing. > > ls -u > > color me unimpressed ;) > I - and the 200+ downloaders - are deeply hurt ... Color me indifferent. -- ------------------------------------------------------------------------------ Tim Daneliuk tundra at tundraware.com http://www.tundraware.com/PGP From bignose+hates-spam at benfinney.id.au Sat May 6 19:18:43 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 07 May 2006 09:18:43 +1000 Subject: Counterproductive goals (was Re: code vetting) References: <_%w6g.44217$C63.42016@trnddc06> Message-ID: <87d5eqspws.fsf_-_@benfinney.id.au> Edward Elliott writes: > I think both your goal and his (spreading free software at the > expense of non-free) are counterproductive. Huh? A goal is counterproductive? By what do you measure "counterproductive", if not the goal? > Organizations (and people) should look for the software that best > fits their needs. Sometimes that means highest technical quality. > Sometimes it means open standards or open source. Sometimes it > means features X, Y, and Z. Sometimes it means vendor support. > Often it's a combination. A successful project should focus on > discovering and meeting its users' needs. Again, success is measured by the goal. My goal is to increase the freedom of software users. > Spreading open source for its own sake helps no one. Increasing the freedom of software users helps all software users, except those who want that freedom restricted. -- \ "Last year I went fishing with Salvador Dali. He was using a | `\ dotted line. He caught every other fish." -- Steven Wright | _o__) | Ben Finney From xbello at gmail.com Wed May 10 03:43:16 2006 From: xbello at gmail.com (XBello) Date: 10 May 2006 00:43:16 -0700 Subject: Can Python installation be as clean as PHP? References: <1147211815.312069.135140@u72g2000cwu.googlegroups.com> <1147231092.546800.100860@j73g2000cwa.googlegroups.com> <1147234711.208138.160320@y43g2000cwc.googlegroups.com> <1147238991.889910.309190@j33g2000cwa.googlegroups.com> Message-ID: <1147246996.480879.89910@v46g2000cwv.googlegroups.com> It's possible to work with php just with these single file? Maybe I'm doing the wrong thing, because to start to program I needed to install a web server too (a large bunch of files). Also I've been looking into http://www.modpython.org/, which appears to be a modular kind of python with less than 400kb. Thanks, Xabier. From aleaxit at yahoo.com Sat May 6 20:34:31 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 17:34:31 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> Message-ID: <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> Ken Tilton wrote: ... > True but circular, because my very point is that () was a great design > choice in that it made macros possible and they made CL almost > infinitely extensible, while indentation-sensitivity was a mistaken > design choice because it makes for very clean code (I agree > wholeheartedly) but placed a ceiling on its expressiveness. Having to give functions a name places no "ceiling on expressiveness", any more than, say, having to give _macros_ a name. > As for: > > > At a syntax-sugar > > level, for example, Lisp's choice to use parentheses as delimiter means > > it's undesirable, even unfeasible, to use the single character '(' as an > > ordinary identifier in a future release of the language. > > (defun |(| (aside) (format nil "Parenthetically speaking...~a." aside)) > => |(| > (|(| "your Lisp /is/ rusty.") > => "Parenthetically speaking...your Lisp /is/ rusty.." > > :) No, seriously, is that all you can come up with? Interestingly, the SECOND lisper to prove himself unable to read the very text he's quoting. Reread carefully, *USE THE ***SINGLE*** CHARACTER* ... *AS AN ORDINARY IDENTIFIER*. What makes you read a ``PART OF'' that I had never written? You've shown how to use the characters as *PART* of an identifier [[and I believe it couldn't be the very start]], and you appear to believe that this somehow refutes my assertion? Are you ready to admit you were utterly wrong, and (while it is indeed true that my Lisp is rusty) there is nothing in this exchange to show it, as opposed to showing rustiness in your ability to understand English? Or shall we move from polite although total dissent right on to flamewars and namecalling? The point is, OF COURSE any design choice places limitations on future design choices; but some limitations are even DESIRABLE (a language where *every* single isolated character could mean anything whatsoever would not be "expressive", but rather totally unreadable) or at least utterly trivial (syntax-sugar level issues most typically are). Wilfully distorting some such limitation as meaning that one language "can scale" (when EVERY language inevitably has SOME such limitations) is not even funny, and clearly characterizes a polemist who is intent on proving a preconceived thesis, as opposed to an investigator with any real interest in ascertaining the truth of the matter. > > Oh, is that the same Graham who writes: > > So we are going to skip the point I was making about Common Lisp being > so insanely extensible? By /application/ programmers? Hell, for all we > know CL does have a BDFL, we just do not need their cooperation. Yes, we are, because the debate about why it's better for Python (as a language used in real-world production systems, *SCALABLE* to extremely large-scale ones) to *NOT* be insanely extensible and mutable is a separate one -- Python's uniformity of style allows SCALABILITY of teams, and teams-of-teams, which is as crucial in the real world as obviously not understood by you (the law you misquoted was about adding personnel to a LATE project making it later -- nothing to do with how desirable it can be to add personnel to a large and growing collection of projects, scaling and growing in an agile, iterative way to meet equally growing needs and market opportunities). This specific debate grew from your misuse of "scalable" to mean or imply "a bazillion feechurz can [[and, implicitly, should]] be added to a language, and therefore anything that stands in the way of feechuritis is somehow holding the language back". That's bad enough, even though in its contextual misuse of "scalable" it breaks new ground, and I don't want to waste even more time re-treading *old* ground as to whether the "*insane* extensibility" afforded by macros is a good or a bad thing in a language to be used for real-world software production (as opposed to prototyping and research). > > """ > > A friend of mine who knows nearly all the widely used languages uses > > Python for most of his projects. He says the main reason is that he > > likes the way source code looks. > > No argument. The little Python I wrote while porting Cells to Python was > strikingly attractive. But it was a deal with the devil, unless Python > is content to be just a scripting language. (And it should be.) It's hard to attribute feelings to a programming language, but, if you really must, I'd say Pyton aspires to be *useful* -- if all you need is "just a scripting language", it will be content to be one for you, and if your need SCALE, well then, PYTHON IS SCALABLE, and will remain a *SIMPLE, CLEAN, LITTLE AND POWERFUL LANGUAGE* (letting nobody do anything INSANE to it;-) while scaling up to whatever size of project(s) you need (including systems so large that they redefine the very concept of "large scale" -- believe me, once in a while at a conference I make the mistake of going to some talk about "large scale" this or that, and invariably stagger out once again with the realization that what's "large scale" to the world tends to be a neat toy-sized throwaway little experiment to my current employer). > OK, I propose a duel. We'll co-mentor this: > > http://www.lispnyc.org/wiki.clp?page=PyCells > > In the end Python will have a Silver Bullet, and only the syntax will > differ, because Python has a weak lambda, statements do not always > return values, it does not have macros, and I do not know if it has > special variables. > > Then we can just eyeball the code and see if the difference is > interesting. These abstract discussions do tend to loop. As a SummerOfCode mentor, I'm spoken for, and can't undertake to mentor other projects. I do agree that these discussions can be sterile, and I'll be glad to see what comes of your "pycells" project, but until then there's little we can do except agree to disagree (save that I'd like you to acknowledge my point above, regarding what exactly I had said and the fact that your alleged counterexample doesn't address at all what I had said -- but, I'll live even without such an acknowledgment). Alex From bignose+hates-spam at benfinney.id.au Mon May 22 20:48:32 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 23 May 2006 10:48:32 +1000 Subject: Too big of a list? and other problems References: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> Message-ID: <87k68d36sf.fsf@benfinney.id.au> "Brian" writes: > First off, I am sorry for cluttering this group with my inept > questions Questions aren't a problem; we all come here to learn at some point. I will ask you, though, to learn effective quoting when you respond to someone's post (i.e. quote relevant material that gives some context to your response, with your response following). > I have a function (below) that takes a list of html pages that have > images on them (not porn but boats). Not boat porn? :-) > When I looked at it while running, it appears as if my regex is > actually appending a tuple (I think) of the results it finds to the > list. Yes, that's what you asked it to do. > pics = re.compile(r"images/.*\.jpeg") > foundPics.append(pics.findall(html)) The 'findall' method of a regex object acts like the module's 'findall' function; it returns a list of the matches. The 'append' method of a list object appends a single value to a list. You're appending a list value to a list, extending it by one value (the list of matches). Perhaps you want the 'extend' method, which will append each item in the specified sequence, extend the existing list by the values from that sequence. -- \ "Yesterday I told a chicken to cross the road. It said, 'What | `\ for?'" -- Steven Wright | _o__) | Ben Finney From mike.klaas at gmail.com Tue May 16 18:29:08 2006 From: mike.klaas at gmail.com (Klaas) Date: 16 May 2006 15:29:08 -0700 Subject: Large Dictionaries In-Reply-To: <1147772420.405097@teuthos> References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> Message-ID: <1147818548.532882.94180@i39g2000cwa.googlegroups.com> >22.2s 20m25s[3] 20m to insert 1m keys? You are doing something wrong. With bdb's it is crucial to insert keys in bytestring-sorted order. Also, be sure to give it a decent amount of cache. -Mike From jstroud at ucla.edu Tue May 2 21:07:50 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 02 May 2006 18:07:50 -0700 Subject: py2app, pythoncard build problems In-Reply-To: <1146576615.234047.196110@v46g2000cwv.googlegroups.com> References: <1146576615.234047.196110@v46g2000cwv.googlegroups.com> Message-ID: loren.davie at gmail.com wrote: > Hi, > > I'm attempting to build a small app that uses pythoncard for a gui > layer. The intention is to use py2app to construct an .app bundle for > the Mac. I'm running OS 10.4 on an Intel MacBook Pro. I'm using the > default installed Python 2.3 > > The .app bundle appears to build, but when I start up it fails - > checking the console reveals that it can't find the "wx" package, as > its called from some pythoncard code. (The app launches just fine in > non-bundled form when I run it from the command line using pythonw). > > Not sure where to go with this. Any help would be greatly appreciated > - thanks. > Did you explicitly specify packages to bundle via the packages keyword? E.g.: setup( app=['%s.py' % appname], name=appname, options={'py2app' : {'strip': True, 'packages': ['helptext', 'tkHyperlinkManager', 'rst2tkinter', 'Crypto', 'SecureRandom', 'ResettableTimer'], 'iconfile': '%s.icns' % appname, 'argv_emulation' : True}} Jaems -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From kbk at shore.net Tue May 30 00:23:03 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Tue, 30 May 2006 00:23:03 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200605300423.k4U4N3tN024355@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 375 open ( -3) / 3264 closed (+26) / 3639 total (+23) Bugs : 910 open ( +3) / 5851 closed (+20) / 6761 total (+23) RFE : 217 open ( -1) / 220 closed ( +3) / 437 total ( +2) New / Reopened Patches ______________________ Minor Correction to urllib2 HOWTO (2006-05-20) CLOSED http://python.org/sf/1492147 opened by Mike Foord None missing from keyword module (2006-05-20) CLOSED http://python.org/sf/1492218 opened by ?iga Seilnacht Socket-object convenience function: getpeercred(). (2006-05-20) http://python.org/sf/1492240 opened by Heiko Wundram urllib2 HOWTO - Further (minor) Corrections (2006-05-20) CLOSED http://python.org/sf/1492255 opened by Mike Foord Windows CE support (part 1) (2006-05-21) CLOSED http://python.org/sf/1492356 opened by Luke Dunstan Windows CE support (part 2) (2006-05-27) http://python.org/sf/1495999 opened by Luke Dunstan Unification of list-comp and for syntax (2006-05-21) http://python.org/sf/1492509 opened by Heiko Wundram distinct error type from shutil.move() (2006-05-22) http://python.org/sf/1492704 opened by Zooko O'Whielacronx Improvements to ceval.c (2006-05-22) http://python.org/sf/1492828 opened by mrjbq7 Speed up gzip.readline (~40%) (2005-09-04) CLOSED http://python.org/sf/1281707 reopened by marumari Speed up gzip.readline (~40%) (2005-09-04) CLOSED http://python.org/sf/1281707 reopened by marumari Allow build without tracing (2006-05-22) CLOSED http://python.org/sf/1493102 opened by Steve Holden Performance enhancements for struct module (2006-05-23) CLOSED http://python.org/sf/1493701 opened by Bob Ippolito Documentation for new Struct object (2006-05-24) http://python.org/sf/1494140 opened by Bob Ippolito PyUnicode_Resize cannot resize shared unicode object (2006-05-25) CLOSED http://python.org/sf/1494487 opened by Hirokazu Yamamoto Numeric characters not recognized. (2006-05-24) CLOSED http://python.org/sf/1494554 opened by Anders Chrigstr?m BaseWidget.destroy updates master's childern too early (2006-05-24) http://python.org/sf/1494750 opened by Greg Couch Scalable zipfile extension (2003-09-27) CLOSED http://python.org/sf/813436 reopened by jafo Remove types.InstanceType and new.instance (2006-05-26) CLOSED http://python.org/sf/1495675 opened by Collin Winter Fix test_exceptions.py (2006-05-27) http://python.org/sf/1496135 opened by Collin Winter urllib2 HTTPPasswordMgr: default ports (2006-05-28) CLOSED http://python.org/sf/1496206 opened by John J Lee Convert Tkinter to METH_VARARGS style (2006-05-29) http://python.org/sf/1496952 opened by Georg Brandl deprecate METH_OLDARGS (2006-05-29) CLOSED http://python.org/sf/1496957 opened by Georg Brandl urllib2: ensure digest auth happens in preference to basic (2006-05-29) CLOSED http://python.org/sf/1497027 opened by John J Lee Let dicts propagate the exceptions in user __eq__ (2006-05-29) http://python.org/sf/1497053 opened by Armin Rigo Patches Closed ______________ Minor Correction to urllib2 HOWTO (2006-05-21) http://python.org/sf/1492147 closed by quiver None missing from keyword module (2006-05-20) http://python.org/sf/1492218 closed by gbrandl urllib2 HOWTO - Further (minor) Corrections (2006-05-21) http://python.org/sf/1492255 closed by quiver Windows CE support (part 1) (2006-05-21) http://python.org/sf/1492356 closed by loewis PC new-logo-based icon set (2006-05-17) http://python.org/sf/1490384 closed by loewis Cleaned up 16x16px icons for windows. (2006-05-03) http://python.org/sf/1481304 closed by loewis property to get the docstring from fget (2004-08-08) http://python.org/sf/1005461 closed by gbrandl Speed up gzip.readline (~40%) (2005-09-04) http://python.org/sf/1281707 closed by etrepum Speed up gzip.readline (~40%) (2005-09-04) http://python.org/sf/1281707 closed by etrepum Speed up gzip.readline (~40%) (2005-09-04) http://python.org/sf/1281707 closed by etrepum scary frame speed hacks (2004-01-13) http://python.org/sf/876206 closed by tim_one Allow build without tracing (2006-05-22) http://python.org/sf/1493102 closed by gbrandl MacOSX: distutils support for -arch and -isysroot flags (2006-05-13) http://python.org/sf/1488098 closed by ronaldoussoren Performance enhancements for struct module (2006-05-23) http://python.org/sf/1493701 closed by etrepum Fix for int(string, base) wrong answers (take 2) (2005-10-24) http://python.org/sf/1335972 closed by tim_one remove 4 ints from PyFrameObject (2005-10-25) http://python.org/sf/1337051 closed by tim_one PyUnicode_Resize cannot resize shared unicode object (2006-05-24) http://python.org/sf/1494487 closed by doerwalter Numeric characters not recognized. (2006-05-24) http://python.org/sf/1494554 closed by loewis PyLong_FromString optimization (2006-03-04) http://python.org/sf/1442927 closed by tim_one Remove some invariant conditions and assert in ceval (2005-02-20) http://python.org/sf/1145039 closed by tim_one Scalable zipfile extension (2003-09-27) http://python.org/sf/813436 closed by jafo Reduce number of open calls on startup (2004-03-23) http://python.org/sf/921466 closed by gbrandl Remove types.InstanceType and new.instance (2006-05-26) http://python.org/sf/1495675 closed by gvanrossum urllib2 HTTPPasswordMgr: default ports (2006-05-27) http://python.org/sf/1496206 closed by gbrandl urllib2 handler naming convention collision (2004-06-13) http://python.org/sf/972322 closed by gbrandl Rename functional to functools (2006-04-29) http://python.org/sf/1478788 closed by ncoghlan deprecate METH_OLDARGS (2006-05-29) http://python.org/sf/1496957 closed by gbrandl urllib2: ensure digest auth happens in preference to basic (2006-05-29) http://python.org/sf/1497027 closed by gbrandl New / Reopened Bugs ___________________ keyword and topic help broken in Pythonwin IDE (2006-05-15) CLOSED http://python.org/sf/1489051 reopened by gbrandl Wierd Floating Point on FreeBSD4 (2006-05-20) CLOSED http://python.org/sf/1492293 opened by David Abrahams bsddb: db never opened for writing forgets its size (2006-05-22) http://python.org/sf/1493322 opened by Steven Taschuk time.strftime() %z error (2006-05-23) CLOSED http://python.org/sf/1493676 opened by Cillian Sharkey Setting a socket timeout breaks SSL (2006-05-24) CLOSED http://python.org/sf/1493922 opened by Andrew Pollock Cannot use high-numbered sockets in 2.4.3 (2006-05-24) http://python.org/sf/1494314 opened by Michael Smith SVN longobject.c compiler warnings (2006-05-24) CLOSED http://python.org/sf/1494387 opened by Joel Konkle-Parker unchecked PyObject_SetAttrString() in PyErr_SyntaxLocation() (2006-05-24) CLOSED http://python.org/sf/1494605 opened by Brett Cannon PyOS_ascii_strtod() uses malloc() (2006-05-24) CLOSED http://python.org/sf/1494671 opened by Brett Cannon PyOS_ascii_strtod() uses malloc() directly (2006-05-25) CLOSED http://python.org/sf/1494671 reopened by gbrandl pyclbr add whitespace chars to base class name (2006-05-25) CLOSED http://python.org/sf/1494787 opened by Dmitry Vasiliev int/long assume that the buffer ends in \0 => CRASH (2006-05-25) http://python.org/sf/1495033 opened by James Y Knight sys.getfilesystemencoding (2006-05-25) CLOSED http://python.org/sf/1495089 opened by Felix Wiemann OverflowWarning still in 2.5 despite docstring (2006-05-25) CLOSED http://python.org/sf/1495175 opened by Jim Jewett Install under osx 10.4.6 breaks shell. (2006-05-25) http://python.org/sf/1495210 opened by ephantom W3C <-> Python DOM type mapping docs need updating (2006-05-25) http://python.org/sf/1495229 opened by Mike Brown make altinstall installs pydoc (2006-05-26) http://python.org/sf/1495488 opened by Tim Heaney os.listdir(): inconsistent behavior with trailing spaces (2006-05-26) CLOSED http://python.org/sf/1495754 opened by Kenneth J. Pronovici Still a problem (2006-05-26) http://python.org/sf/1495802 opened by jpsc986_hj test_float segfaults with SIGFPE on FreeBSD 6.0 / Alpha (2006-05-27) http://python.org/sf/1496032 opened by Bob Ippolito Incorrect error message related to **kwargs (2006-05-28) CLOSED http://python.org/sf/1496278 opened by Collin Winter strptime: wrong default values used to fill in missing data (2006-05-28) http://python.org/sf/1496315 opened by Markus Gritsch tarfile.py: dict order dependency (2006-05-28) http://python.org/sf/1496501 opened by Armin Rigo Modules in cwd can't be imported in interactive mode (2006-05-28) CLOSED http://python.org/sf/1496539 opened by ?iga Seilnacht Building Python 2.4.3 on Solaris 9/10 with Sun Studio 11 (2006-05-28) http://python.org/sf/1496561 opened by Andreas Bugs Closed ___________ Segmentation fault while using Tkinter (2006-05-01) http://python.org/sf/1479586 closed by loewis keyword and topic help broken in Pythonwin IDE (2006-05-15) http://python.org/sf/1489051 closed by gbrandl Wierd Floating Point on FreeBSD4 (2006-05-21) http://python.org/sf/1492293 closed by loewis time.strftime() %z error (2006-05-23) http://python.org/sf/1493676 closed by bcannon int(string, base) wrong answers (2005-10-22) http://python.org/sf/1334662 closed by tim_one Setting a socket timeout breaks SSL (2006-05-24) http://python.org/sf/1493922 closed by loewis SVN longobject.c compiler warnings (2006-05-24) http://python.org/sf/1494387 closed by tim_one unchecked PyObject_SetAttrString() in PyErr_SyntaxLocation() (2006-05-24) http://python.org/sf/1494605 closed by gbrandl PyOS_ascii_strtod() uses malloc() directly (2006-05-25) http://python.org/sf/1494671 closed by gbrandl PyOS_ascii_strtod() uses malloc() directly (2006-05-24) http://python.org/sf/1494671 closed by bcannon Erroneous \url command in python.sty (2005-09-03) http://python.org/sf/1281291 closed by fdrake pyclbr add whitespace chars to base class name (2006-05-25) http://python.org/sf/1494787 closed by gbrandl Setting socket timeout crashes SSL (2005-02-27) http://python.org/sf/1153016 closed by twouters Multiple dots in relative import statement raise SyntaxError (2006-05-15) http://python.org/sf/1488915 closed by twouters sys.getfilesystemencoding (2006-05-25) http://python.org/sf/1495089 closed by gbrandl OverflowWarning still in 2.5 despite docstring (2006-05-25) http://python.org/sf/1495175 closed by gbrandl os.listdir(): inconsistent behavior with trailing spaces (2006-05-26) http://python.org/sf/1495754 closed by gbrandl urllib2 Request.get_host and proxies (2003-03-05) http://python.org/sf/698374 closed by jjlee Incorrect error message related to **kwargs (2006-05-28) http://python.org/sf/1496278 closed by gbrandl Modules in cwd can't be imported in interactive mode (2006-05-28) http://python.org/sf/1496539 closed by gbrandl can't pickle slice objects (2006-05-12) http://python.org/sf/1487420 closed by gbrandl New / Reopened RFE __________________ Create "Performance" category? (2006-05-22) CLOSED http://python.org/sf/1492856 opened by Sean Reifschneider Integer bit operations performance improvement. (2006-05-22) http://python.org/sf/1492860 opened by Sean Reifschneider sys.getrefcount should be in gc (2006-05-24) http://python.org/sf/1494595 opened by Jim Jewett RFE Closed __________ Create "Performance" category? (2006-05-22) http://python.org/sf/1492856 closed by tim_one Create a fat build on darwin (2005-06-10) http://python.org/sf/1218333 closed by ronaldoussoren Add encoding to DocFileSuite (2004-12-08) http://python.org/sf/1080727 closed by quiver From marco.herrn at sourcepark.de Wed May 17 04:43:21 2006 From: marco.herrn at sourcepark.de (Marco Herrn) Date: 17 May 2006 08:43:21 GMT Subject: simultaneous reading and writing a textfile References: <4469f3d6$0$11070$9b4e6d93@newsread4.arcor-online.net> Message-ID: <446ae229$0$11074$9b4e6d93@newsread4.arcor-online.net> On 2006-05-16, Peter Otten <__peter__ at web.de> wrote: >> Now how can I achieve, what I want? Really exchange one line with >> another, regardless of their length. Is this possible? If this is not >> possible, then what would be the best approach to do this? > > A file is exposed as a sequence of bytes. You can only exchange a string of > bytes with the same number of (different) bytes. Inserting or removing > bytes means you have to rewrite the file from the insertion/deletion point > onwards. Usually you don't bother and just rewrite the whole file. Thanks to you both. I will use that. I do not think, that the files will be that large, that a database is useful. The main advantage of the file is, that it is directly human readible. Regards Marco From Serge.Orlov at gmail.com Tue May 23 00:25:58 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 22 May 2006 21:25:58 -0700 Subject: No math module?? References: Message-ID: <1148358358.421593.39230@j55g2000cwa.googlegroups.com> WIdgeteye wrote: > I have been trying to run a python program and I get the following > error: > Traceback (most recent call last): > Fil e "", line 39, in ? That doesn't look like a python program, File "" means it's an embedded script. When a script is embedded it is responsibility of the caller (blender application) to setup correct path to modules. > File "/home/Larry/.blender/scripts/bzflag/__init__.py", line 22, in ? > import BZfileRead > File "/home/Larry/.blender/scripts/bzflag/BZfileRead.py", line 24, in ? > import BZsceneWriter > File "/home/Larry/.blender/scripts/bzflag/BZsceneWriter.py", line 25, in ? > import BZcommon > File "/home/Larry/.blender/scripts/bzflag/BZcommon.py", line 24, in ? > import math > ImportError: No module named math > [snip] > So what's up?? :) Try to insert ============== import sys print sys.path, sys.version, sys.executable ============== right before the failing "import math". The next step is most likely to RTFM how to properly setup python embedded into blender. If everything looks as described in the manual, it's a bug in blender. From kay.schluehr at gmx.net Fri May 12 12:42:49 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 12 May 2006 09:42:49 -0700 Subject: New tail recursion decorator In-Reply-To: References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> <1147437656.779139.54840@d71g2000cwd.googlegroups.com> <1147441799.331677.88460@d71g2000cwd.googlegroups.com> Message-ID: <1147452169.797342.43740@g10g2000cwb.googlegroups.com> Duncan Booth wrote: > The decorator also fails for functions which are tail-recursive but which > contain other non-tail recursive calls within themselves. For example I > would be pretty sure you couldn't write a working implementation of > Ackermann's function using the decorator: > > def Ack(M, N): > if (not M): > return( N + 1 ) > if (not N): > return( Ack(M-1, 1) ) > return( Ack(M-1, Ack(M, N-1)) ) Definitely. The translation into a proper tail-recursive form is non-trivial but nevertheless possible as demonstrated by the following Ackermann implementation: @tail_recursion def ack(m,n,s=[0]): # use a stack-variable s as "accumulator" if m==0: if s[0] == 1: return ack(s[1]-1,n+1,s[2]) elif s[0] == 0: return n+1 elif n==0: return ack(m-1,1,s) else: return ack(m,n-1,[1,m,s]) Regards, Kay From agr at fq.uniovi.es Mon May 15 07:44:57 2006 From: agr at fq.uniovi.es (=?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?=) Date: Mon, 15 May 2006 13:44:57 +0200 Subject: List of lists of lists of lists... References: <44608890$0$18266$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: > for N: > mylist = [mylist] > Right that! > I'm afraid I don't understand. Could you forgive my stupidity and > re-explain this a bit more clearly ? > No need to. Former solution worked fine. Thanks! -- ?ngel Guti?rrez Rodr?guez - agr at fq.uniovi.es Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiation Facility - Grenoble - France Postal adress: Departamento de Qu?mica F?sica y Anal?tica Universidad de Oviedo - c/Juli?n Claver?a 8 33006 - Oviedo Asturias - Spain E-mail: agr at fq.uniovi.es Telf.: +34-985103687 From apardon at forel.vub.ac.be Wed May 10 04:54:17 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 10 May 2006 08:54:17 GMT Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> Message-ID: Op 2006-05-10, yairchu at gmail.com schreef : > multi-line lambdas, had it been added to python a long time ago, would > had reduced a lot of complexity in the language. > for example - with multi-line lambdas - decorators are unneccesary. I don't like the words neccesary or unneccesary in these discussions, because they rarely add anything. For instances decorators are unneccesary in python now, even without multi-line lambdas. There is nothing you can do with decorators that you can't do without. > just give the multi-line lambda as an argument to a function - no need > for special syntax.. There is no need for special syntax. The decorators are just syntactic sugar to do something that was already possible before. > the alternative decorators would also be simpler. > currently when you want to create a "decorator-that-accepts-additional- > arguments" you gotta make a funtion that gets those > additional-arguments and returns a function that will be the decorator. Could you give me an example. Suppose I have the following: def arg_range(inf, sup): def check(f): def call(arg): if inf <= arg <= sup: return f(arg) else: raise ValueError return call return check @arg_range(3, 12) def func(arg): return arg How would this look simpler with multi-line lambda's? -- Antoon Pardon From onurb at xiludom.gro Wed May 10 10:37:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 10 May 2006 16:37:26 +0200 Subject: problemi con POST In-Reply-To: <1147269667.987862.104680@v46g2000cwv.googlegroups.com> References: <1147208587.275024.317410@i40g2000cwc.googlegroups.com> <1147269667.987862.104680@v46g2000cwv.googlegroups.com> Message-ID: <4461fb08$0$307$626a54ce@news.free.fr> Heavy wrote: > Sorry, > you got reason, I thought I can write in my language, cause this is the > first time that I post a question in this group... usually, the comp.* usenet hierarchy is english-speaking. > My problem is that I > have to receive parameters from a POST method, i try to read them from > the socket 'rfile', but this action is blocking, it never finish to > read. Is there some existing method that can help me? Can you help me? > thanks... Could you give more precisions about the context, architecture, librairies used etc ? FWIW, if it's a web application, you should be able to retrieve the POST parameters via the web application solution you're using (CGI, mod_python, etc...), so I don't really understand why you're doing raw socket read ??? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ajr at bez_tego.aster.pl Tue May 16 07:50:08 2006 From: ajr at bez_tego.aster.pl (A. Rogowski) Date: 16 May 2006 13:50:08 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> Message-ID: aleaxit at yahoo.com (Alex Martelli) writes: > Bill Atkins wrote: > ... > > > ``allow ( as an ordinary single-character identifier'' as for the > > > unneded feature ``allow unnamed functions with all the flexibility of > > > named ones''. > > > > Not so infeasible: > > > > (let ((|bizarrely(named()symbol| 3)) > > (+ |bizarrely(named()symbol| 4)) > > > > ;; => 7 > > Read again what I wrote: I very specifically said "ordinary > *single-character* identifier" (as opposed to "one of many characters > inside a multi-character identifier"). Why do you think I said > otherwise, when you just quoted what I had written? (Even just a > _leading_ ( at the start of an identifier may be problematic -- and just > as trivial as having to give names to functions, of course, see below). bah... [1]> (setq rtbl (copy-readtable)) # [2]> (set-syntax-from-char #\{ #\() T [3]> (set-syntax-from-char #\( #\a) T [4]> {defun ( {a) {1+ a)) ( [5]> {( 1) 2 [6]> {( 4) 5 [7]> {setq *readtable* rtbl) # [8]> (1+ 1) 2 With readtable and reader macros you can change the syntax as you wish. ajr. From deets at nospam.web.de Thu May 11 11:25:52 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 May 2006 17:25:52 +0200 Subject: Python memory deallocate References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <-yy*V4mgr@news.chiark.greenend.org.uk> <1147355266.189030.131420@y43g2000cwc.googlegroups.com> <4463462a$0$297$626a54ce@news.free.fr> <1147358549.473182.89950@i40g2000cwc.googlegroups.com> Message-ID: <4ch3crF15qv23U1@uni-berlin.de> mardif wrote: > In python 2.5 this was resolved, ok, but i can't use any python version > then 2.3.5. > This project was initializated with this version, and now it can be > dangerous change version, even because I use McMillan installer for > compile e build an executable. > > So, my initial window is a "menu window", when i can choose, for > example, upload foto for print, or create an object as PhotoAlbum. > > If i'will choose PhotoAlbum, it will allocate 200Mb. well! if i decide > to abort this work, i will return to initial window. and if i will > click in PhotoAlbum ago, the memory will increase to 350-400Mb. > > It's that!!! I don't understand why!!! when i abort the work the first > time, i call > > app.Destroy() > del app > > Why Python ( or GarbageCollector, or.... ) don't deallocate memory?? > If it's not possibile, why python don't reuse the memory "cached"? Because you might have kept references somewhere. And nobody knows where without you showing code. Lots of long-running memory intensive apps such as ZODB are written in python - so I doubt that it is a problem of python itself, but instead of your program. Try and reproduce the behavior with a self-contained script - if that still exposes the problem we can look at it maybe fixpython if needed. Besides: _if_ it was a python error, you'd have to move to a knew python version anyway, won't you? And just because you McMillan Installer won't work doesn't mean that YOU can't try python2.4 or even 2.5, and see if it works better. Diez From manstey at csu.edu.au Wed May 24 19:44:28 2006 From: manstey at csu.edu.au (manstey) Date: 24 May 2006 16:44:28 -0700 Subject: NEWB: how to convert a string to dict (dictionary) In-Reply-To: References: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> Message-ID: <1148514268.491292.276670@38g2000cwa.googlegroups.com> Thanks. I didn't know eval could do that. But why do many posts say they want a solution that doesn't use eval? From bitsandbytes88 at hotmail.com Thu May 25 13:40:16 2006 From: bitsandbytes88 at hotmail.com (Dan) Date: Thu, 25 May 2006 13:40:16 -0400 Subject: sybase open client 15_0 Message-ID: I have compiled and installed sybase-.037 , the module to add sybase to python. However, when I try to use it I get Import error: /usr/local/lib/python2.3/site-packages/sybasect.so undefined symbol: cs_dt_info I've seen some posts on the internet with other people having this issue. But nothing they've suggested has resolved this issue. Maybe python just needs to be installed again or upgraded to support sybase Open Client. Thanks, ~DjK From ask at me Thu May 11 08:10:16 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 08:10:16 -0400 Subject: redirecting print to a a file In-Reply-To: References: <7JudnYwllewrrv7ZRVn-vA@comcast.com> Message-ID: Sybren Stuvel wrote: >>I have a large program and would like to avoid touching hundreds of >>print's. > > > I can suggest using the logging module instead of print. It's much > more flexible than prints, and well suited for large programs. > Thx for the hint. I will look into that. A. From john at castleamber.com Wed May 24 23:11:24 2006 From: john at castleamber.com (John Bokma) Date: 25 May 2006 03:11:24 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <1hfv0or.1krs4uf1704ou8N%wrf3@stablecross.com> Message-ID: wrf3 at stablecross.com (Bob Felts) wrote: > Count me among the clueless, then. I just wrote to DreamHost and asked > that they reverse their decision to terminate his account. I am sure that DreamHost has quite a nice /dev/null for clueless idiots like you and your sock puppets :-D. -- 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 elventear at gmail.com Fri May 19 13:38:07 2006 From: elventear at gmail.com (elventear) Date: 19 May 2006 10:38:07 -0700 Subject: Decimal and Exponentiation Message-ID: <1148060287.088387.41150@j55g2000cwa.googlegroups.com> Hi, I am the in the need to do some numerical calculations that involve real numbers that are larger than what the native float can handle. I've tried to use Decimal, but I've found one main obstacle that I don't know how to sort. I need to do exponentiation with real exponents, but it seems that Decimal does not support non integer exponents. I would appreciate if anyone could recommend a solution for this problem. Thank you. From stijndesaeger at gmail.com Fri May 5 23:22:33 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 20:22:33 -0700 Subject: how to construct a binary-tree using python? In-Reply-To: <1146879397.871842.183790@u72g2000cwu.googlegroups.com> References: <1146879397.871842.183790@u72g2000cwu.googlegroups.com> Message-ID: <1146885753.256714.73790@j73g2000cwa.googlegroups.com> Depending on what concrete use you have for binary trees, you may want to consider tuples. What's cool about them is that you get pattern matching on your tree for free. >>> x = ((2,4),(5,6)) >>> y, _ = x >>> y (2, 4) >>> (_,y), _ = x >>> y 4 >>> Or you could code your own binary tree class subclassing tuple. ... just a thought. v. From deets at nospam.web.de Fri May 5 06:08:32 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 12:08:32 +0200 Subject: Tuple assignment and generators? References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> Message-ID: <4c0mi2F13miioU1@uni-berlin.de> > > I was just at a point when I thought I learned something but got > confused again after trying the following and unfortunately didn't > find an answer in the docs. > >>>> a = 10 >>>> b = 10 >>>> id(a) > 134536516 >>>> id(b) > 134536516 > > So the two memory addesses are the same, but > >>>> a = 10000 >>>> b = 10000 >>>> id(a) > 134604216 >>>> id(b) > 134604252 > > and they are not the same (I restarted the interpreter between the two > cases). So how is this now? Sorry if it's too trivial, but I simply > don't get it. It's an optimization scheme that will cache number objects up to a certain value for optimized reuse. However this is impractical for larger numbers - you only hold a table of lets say 1000 or so objects. Then the look up of one of those objects is extremely fast, whereas the construction of arbitrary numbers is somewhat more expensive. And as "is" is the operator for testing if objects are identical and _not_ the operator for testing of equality (which is ==), the above can happen. And is totally irrelevant from a practical POV (coding-wise that is - it _is_ a relevant optimization). Diez From fredrik at pythonware.com Mon May 29 15:50:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 May 2006 21:50:03 +0200 Subject: Is anybody knows about a linkable, quick MD5/SHA1 calculator library ? In-Reply-To: <447B2810.20402@gmail.com> References: <447B2810.20402@gmail.com> Message-ID: DurumDara wrote: > I use the Python standard modules, but I think that it can be faster if > I use C, or other module for it. Python's MD5 and SHA-1 code is written in C, and is quite fast: python -m timeit -s "import sha; s = sha.new(); S = '*'*1000000" "s.update(S)" 100 loops, best of 3: 12.2 msec per loop python -m timeit -s "import md5; s = md5.new(); S = '*'*1000000" "s.update(S)" 100 loops, best of 3: 6.45 msec per loop are you sure it's really a CPU-bound problem? From scott.daniels at acm.org Mon May 29 09:33:52 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 29 May 2006 06:33:52 -0700 Subject: send an email with picture/rich text format in the body In-Reply-To: <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <1148797671.937857.151250@y43g2000cwc.googlegroups.com> <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> Message-ID: <447af3f0$1@nntp0.pdx.net> Max M wrote: > 90% of users are non-technical users who use standard email readers, > that can easily read html messages. > > In my experience the kind of user that receives emails with html and > pictures often prefer it that way. > > So why bother with the lecture? I cannot remember when I have last > received a relevant email that I could not read in text mode. Because (A) This _is_ a technical newsgroup with mores you are violating. (B) Some of us "technical users" avoid such email/news readers precisely because they can cause tracking across the web. -- --Scott David Daniels scott.daniels at acm.org From DustanGroups at gmail.com Wed May 31 21:12:51 2006 From: DustanGroups at gmail.com (Dustan) Date: 31 May 2006 18:12:51 -0700 Subject: Downloading and Displaying an Image from the Internet in Tkinter Message-ID: <1149124371.337732.3650@f6g2000cwb.googlegroups.com> The title pretty much says it all. What is the easiest way in Tkinter to display an image from the internet given the URL? From roy at panix.com Wed May 24 08:57:33 2006 From: roy at panix.com (Roy Smith) Date: Wed, 24 May 2006 08:57:33 -0400 Subject: Python keywords vs. English grammar Message-ID: I noticed something interesting today. In C++, you write: try { throw foo; } catch { } and all three keywords are verbs, so when you describe the code, you can use the same English words as in the program source, "You try to execute some code, but it throws a foo, which is caught by the handler". In Python, you write: try: raise foo except: and now you've got a mix of verbs and (I think), a preposition. You can't say, "You try to execute some code, but it raises a foo, which is excepted by the handler". It just doesn't work grammatically. Sigh. From Serge.Orlov at gmail.com Wed May 10 05:20:03 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 10 May 2006 02:20:03 -0700 Subject: Memory leak in Python References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> Message-ID: <1147252803.325579.151510@j33g2000cwa.googlegroups.com> diffuser78 at gmail.com wrote: > I am using Ubuntu Linux. > > My program is a simulation program with four classes and it mimics bit > torrent file sharing systems on 2000 nodes. Now, each node has lot of > attributes and my program kinds of tries to keep tab of everything. As > I mentioned its a simulation program, it starts at time T=0 and goes on > untill all nodes have recieved all parts of the file(BitTorrent > concept). The ending time goes to thousands of seconds. In each sec I > process all the 2000 nodes. Most likely you keep references to objects you don't need, so python garbage collector cannot remove those objects. If you cannot figure it out looking at the source code, you can gather some statistics to help you, for example use module gc to iterate over all objects in your program (gc.get_objects()) and find out objects of which type are growing with each iteration. From michele.simionato at gmail.com Mon May 8 05:14:02 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 8 May 2006 02:14:02 -0700 Subject: Is this a good use of __metaclass__? In-Reply-To: References: Message-ID: <1147079642.732317.210890@i40g2000cwc.googlegroups.com> Answering to the title of your post, no, this is not a good use of metaclasses. Your problem seems a textbook example of multiple dispatch, so I suggest you to look at PEAK with has an implementation of multimethods/generic functions. Notice that Guido seems to be intentioned to add support for generic functions in future versions of Python, so that solution would likely have the blessing of the BDFL ;) The problem you have with your metaclass version, is the infamous metaclass conflict. It can be solved by hand or automatically (http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/204197) but it is best to avoid it altogether. Just use PEAK or an hand made dispatcher, like for instance this one: class SimpleDispatcher(object): # this is on purpose not object oriented """A dispatcher is a callable object that looks in a "namespace" for callable objects and calls them with the signature ``(, , <*args>, <**kw>)`` The "namespace" can be a module, a class, a dictionary, or anything that responds to ``getattr`` or (alternatively) to ``__getitem__``. Here is an example of usage: >>> call = SimpleDispatcher(globals()) >>> def manager_showpage(): ... return 'Manager' >>> def member_showpage(): ... return 'Member' >>> def anonymous_showpage(): ... return 'Anonymous' >>> call('showpage', 'anonymous') 'Anonymous' >>> call('showpage', 'manager') 'Manager' >>> call('showpage', 'member') 'Member' """ def __init__(self, ns): self._ns = ns def __call__(self, funcname, classname, *args, **kw): try: func = getattr(self._ns, '%s_%s' % (classname, funcname)) except AttributeError: func = self._ns['%s_%s' % (classname, funcname)] return func(*args, **kw) if __name__ == "__main__": import doctest; doctest.testmod() BTW, the usual advice holds here: if you can find an workable solution not involving metaclasses and decorators, don't use them. Michele Simionato From kkylheku at gmail.com Fri May 19 12:54:21 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 19 May 2006 09:54:21 -0700 Subject: number of different lines in a file In-Reply-To: <1147991237.732146.29350@j55g2000cwa.googlegroups.com> References: <1147991237.732146.29350@j55g2000cwa.googlegroups.com> Message-ID: <1148057661.180369.140190@j33g2000cwa.googlegroups.com> Bill Pursell wrote: > Have you tried > cat file | sort | uniq | wc -l ? The standard input file descriptor of sort can be attached directly to a file. You don't need a file catenating process in order to feed it: sort < file | uniq | wc -l Sort has the uniq functionality built in: sort -u < file | wc -l > sort might choke on the large file, and this isn't python, but it > might work. Solid implementations of sort can use external storage for large files, and perform a poly-phase type sort, rather than doing the entire sort in memory. I seem to recall that GNU sort does something like this, using temporary files. Naively written Python code is a lot more likely to choke on a large data set. > You might try breaking the file into > smaller peices, maybe based on the first character, and then > process them seperately. No, the way this is done is simply to read the file and insert the data into an ordered data structure until memory fills up. After that, you keep reading the file and inseting, but each time you insert, you remove the smallest element and write it out to the segment file. You keep doing it until it's no longer possible to extract a smallest element which is greater than all that have been already written to the file. When that happens, you start a new file. That does not happen until you have filled memory at least twice. So for instance with half a gig of RAM, you can produce merge segments on the order of a gig. From yalexfan at gmail.com Tue May 30 23:26:38 2006 From: yalexfan at gmail.com (Zhang Fan) Date: Wed, 31 May 2006 11:26:38 +0800 Subject: shuffling elements of a list In-Reply-To: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <9c61c48d0605302026t549c784dgfb5577114d6b5bec@mail.gmail.com> On 30 May 2006 20:18:19 -0700, greenflame wrote: > Second of all, I would like to have > other methods of shuffling, prefererably riffle shuffling and just > plain randomly arranging the elements of the list. The random module has a `shuffle' method. It "Shuffle the sequence x in place". It may be help for you From duncan.booth at invalid.invalid Fri May 5 07:55:27 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 May 2006 11:55:27 GMT Subject: (question) How to use python get access to google search without query quota limit References: <1146829024.301402.282540@e56g2000cwe.googlegroups.com> Message-ID: Heiko Wundram wrote: > Am Freitag 05 Mai 2006 13:37 schrieb Per: >> I think google's rich retrieval information and query-segment might >> be of help, I downloaded google api, but there is query >> limit(1000/day), How can I write python code to simulate the >> browser-like-activity to submit more than 10k queries in one day? > > How about asking them for a "license" which doesn't have this > restriction before taking the trouble to work around a limit they > don't impose for nothing? Anything else might be considered > text-/email-grabbing, and can get you into serious trouble... > Google's FAQ says they don't currently offer licenses for more than 100 searches per day. The OP should accept this and try living within these limits. From bjourne at gmail.com Fri May 26 19:51:57 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sat, 27 May 2006 01:51:57 +0200 Subject: stupid perl question In-Reply-To: <44778C05.9020701@grads.ece.mcmaster.ca> References: <44778C05.9020701@grads.ece.mcmaster.ca> Message-ID: <740c3aec0605261651h7c4c249o6a4cc186ca74b6db@mail.gmail.com> > how can i split a string that contains white spaces and '_' > > any clue? If the white spaces and the '_' should be applied equivalently on the input and you can enumerate all white space characters, you could do like this: def split_helper(list, delims): if not delims: return list ch = delims[0] lst = [] for item in list: lst += split_helper(item.split(ch), delims[1:]) return lst def split(str, delims): return split_helper([str], delims) >>> split("foo_bar eh", "_ ") ['foo', 'bar', 'eh'] Though I bet someone will post a one-line solution in the next 30 minutes. :) -- mvh Bj?rn From robert.differentone at gmail.com Tue May 9 13:05:48 2006 From: robert.differentone at gmail.com (robert.differentone at gmail.com) Date: 9 May 2006 10:05:48 -0700 Subject: Calling python functions from C Message-ID: <1147194348.285669.218280@g10g2000cwb.googlegroups.com> I am a newbie to Python. I want to call python functions from C. I looked for examples but I couldn't get any simple one. Lets say my python code is : def add(a,b) return (a+b) I want to call add from C. Could anybody please help me? Thanks in advance. R. From mumia.w.18.spam+fbi.gov at earthlink.net Wed May 24 13:00:46 2006 From: mumia.w.18.spam+fbi.gov at earthlink.net (Mumia W.) Date: Wed, 24 May 2006 17:00:46 GMT Subject: John Bokma harassment In-Reply-To: <1148479202.486847.243280@g10g2000cwb.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <1148478219.803585.158850@g10g2000cwb.googlegroups.com> <1148479202.486847.243280@g10g2000cwb.googlegroups.com> Message-ID: <2j0dg.26$u4.7@newsread1.news.pas.earthlink.net> SamFeltus wrote: > I was considering opening an account with Dreamhost. Can't say I agree > with all of Xah's writings, but they often raise important points. > Dreamhost is a company I will never spend money with. Usenet is full > of narrow minded group thinking that needs to be questioned. > Write abuse at dreamhost and tell them why you're not going to patronize them. Explain to them that what they are doing to Xah you're not going to support. Who knows? Maybe Dreamhost isn't all that bad. Perhaps the worst thing about Dreamhost is that John Bokma can harass Xah through them. The idea that an ISP allows itself to be used like that is pretty bad, but Xah hasn't lost his account yet. Write something to the abuse address at Dreamhost in support of Xah. It's not about whether Xah is correct on every issue; it's about peoples' freedom to communicate on the Internet. Otherwise, you could say something controversial, and John Bokma writes your ISP/hosting service, and you get TOSSed. From NOatkinwSPAM at rpi.edu Sat May 6 21:19:58 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 21:19:58 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> Message-ID: <87bquaskap.fsf@rpi.edu> aleaxit at yahoo.com (Alex Martelli) writes: > Bill Atkins wrote: > ... >> > >> > Read again what I wrote: I very specifically said "ordinary >> > *single-character* identifier" (as opposed to "one of many characters >> > inside a multi-character identifier"). Why do you think I said >> > otherwise, when you just quoted what I had written? (Even just a >> > _leading_ ( at the start of an identifier may be problematic -- and just >> > as trivial as having to give names to functions, of course, see below). >> >> Well, the same technique can obviously be used for: >> >> (let ((|(| 3))) >> (+ |(| 4))) >> ;; => 7 >> >> The length of the identifier is irrelevant... > > But it cannot be a SINGLE CHARACTER, *just* the openparenthesis. > > Wow, it's incredible to me that you STILL can't read, parse and > understand what I have so clearly expressed and repeated! Read my other post. It's incredible that you STILL haven't considered the possibility that you're just wrong. > >> Common Lisp does not support unnamed macros (how would these be >> useful?), but nothing stops me from adding these. What use case do >> you envision for anonymous macros? > > None, just like there is none for anonymous functions -- there is > nothing useful I can do with anonymous functions that I cannot do with > named ones. Sure there are. Does Python have any support for closures? If so, ignore this point. But if not, what about examples like this: (defun make-window (window observer) ;; initialization code here (add-handler window 'close (lambda (event) (notify observer event))) ;; more code) Being able to keep pass around state with functions is useful. There are also cases where a function is so trivial that the simplest way to describe it is with its source code, where giving it a name and putting it at the beginning of a function is just distracting and time-consuming. E.g.: (remove-if (lambda (name) (find #\- name :test #'char=)) list-of-names) What's the sense of giving that function its own name? It's much clearer to simply write it in place. Yes, it's _possible_ to use named functions, but in this case its functionality is so simple that it's clearer to simply type it in place. Why is this expressiveness a bad thing, aside from its power to wreck an indentation-significant language? > >> > Anyway, I repeat: *any* design choice (in a language, or for that matter >> > any other artefact) has consequences. As Paul Graham quotes and >> > supports his unnamed friend as saying, Python lets you easily write code >> > that *looks* good, and, as Graham argues, that's an important issue -- >> > and, please note, a crucial consequence of using significant >> > indentation. Alien whitespace eating nanoviruses are no more of a worry >> > than alien parentheses eating nanoviruses, after all. >> >> It *is* an important issue, but it's also a subjective issue. I find >> Lisp to be far prettier than any syntax-based language, so it's far >> from an objective truth that Python code often looks good - or even at >> all. > > The undeniable truth, the objective fact, is that *to most programmers* > (including ones deeply enamored of Lisp, such as Graham, Tilton, Norvig, > ...) Python code looks good; the Lisp code that looks good to YOU (and, > no doubt them), and palatable to me (I have spoken of "eerie beauty"), > just doesn't to most prospective readers. If you program on your own, > or just with a few people who share your tastes, then only your taste > matters; if you want to operate in the real world, maybe, as I've > already pointed out, to build up a successful firm faster than had ever > previously happened, this *DOESN'T SCALE*. Essentially the same issue > I'm explaining on the parallel subthread with Tilton, except that he > fully agrees with my aesthetic sense (quoting Tilton, "No argument. The > little Python I wrote while porting Cells to Python was strikingly > attractive") so this facet of the jewel needed no further belaboring > there. And I'm sure Kelly Clarkson sounds better *to most listeners* but that doesn't mean she's a better musician than Hendrix. The fact that most people are used to ALGOL-like languages does not mean that ALGOL-like languages are more aesthetically pleasing on their own merits. >> >> Plus, I can easily write code that looks good without using a language >> that enforces indentation rules. Lisp's regular syntax lets Emacs do >> it for me with a simple C-M-a C-M-q. What could be easier? > > If you need to edit and reformat other people's code with Emacs to find > it "looks good", you've made my point: code exists to be read, far more > than it's written, and Python's design choice to keep punctuation scarce > and unobtrusive obviates the need to edit and reformat code that way. That's not what I'm saying at all. My point is that I can write a function, counting on Emacs to keep it indented for me, and then after making a series of changes to it, a mere C-M-a C-M-q takes them into account and bam, no-fuss indenting. > > Alex > -- This is a song that took me ten years to live and two years to write. - Bob Dylan From spohle at gmail.com Fri May 26 13:50:51 2006 From: spohle at gmail.com (spohle) Date: 26 May 2006 10:50:51 -0700 Subject: sort a dictionary by keys in specific order In-Reply-To: References: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> Message-ID: <1148665851.182749.101720@g10g2000cwb.googlegroups.com> how do i get the result back into the dictionary ? From kkylheku at gmail.com Wed May 10 13:51:59 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 10 May 2006 10:51:59 -0700 Subject: Multi-line lambda proposal. In-Reply-To: References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> Message-ID: <1147283519.066005.134470@i40g2000cwc.googlegroups.com> Antoon Pardon wrote: > Could you give me an example. Suppose I have the following: > > def arg_range(inf, sup): > > def check(f): > > def call(arg): > if inf <= arg <= sup: > return f(arg) > else: > raise ValueError > > return call > > return check def arg_range(inf, sup) return lambda(f): return lambda(arg): if inf <= arg <= sup: return f(arg) else raise ValueError Nice; now I can see what this does: returns a function that, for a given function f, returns a function which passes its argument arg to f if the argument is in the [inf, sup] range, but otherwise raises a ValueError. The English description pops out from the nested lambda. The names in the inner-function version only serve to confuse. The function check doesn't check anything; it takes a function f and returns a validating function wrapped around f. In fact, an excellent name for the outer-most inner function is that of the outer function itself: def range_checked_function_maker(inf, sup): def range_checked_function_maker(f): def checked_call_of_f(arg): if inf <= arg <= sup: return f(arg) else: raise ValueError return checked_call_of_f return range_checked_function_maker This alone makes a good case for using an anonymous function: when you have a function which does nothing but return an object, and that function has some noun as its name, it's clear that the name applies to the returned value. This: def forty_two(): return 42 is not in any way made clearer by: def forty_two(): forty_two = 42 return forty_two :) From jweida at gmail.com Wed May 24 14:00:34 2006 From: jweida at gmail.com (Jerry) Date: 24 May 2006 11:00:34 -0700 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> <1148483986.822220.287590@i39g2000cwa.googlegroups.com> <1148488038.055267.174810@j33g2000cwa.googlegroups.com> Message-ID: <1148493634.352935.26280@j55g2000cwa.googlegroups.com> I think that Beginning Python: From Novice to Professional is a great book for beginners. It's probably a bit too simplistic for someone who already understands the language or who has a decent background in development. I just borrowed it from my brother and while I consider myself a pretty good developer (I know PHP, Perl, Shell Scripting, VBScript, Visual Basic, and some C), I found that some of the things that other books presented where more advanced and that they left me missing some of the more basic concepts in Python (i.e. list comprehension made simple). After Beginning Python, a good book to go to would be Dive Into Python which you can get free at http://www.diveintopython.org. The book covers much of the same material that Beginning Python does, but has many more full fleged examples to help solidify what you are doing. I've also heard really good things about Learning Python, but these other two books seem to cover all of the same material. After these, I plan on reading Game Programming with Python and the Python Cookbook to round out my library. I'll have to check out Python Essential Reference and I'll probably get Mastering Regular Expressions (which I think is a must have for any language even though it focuses on Perl). -- Jerry From Depcnb1 at aol.com Wed May 24 14:02:33 2006 From: Depcnb1 at aol.com (Depcnb1 at aol.com) Date: Wed, 24 May 2006 14:02:33 EDT Subject: perl to python Message-ID: <435.20e3a3e.31a5f9b9@aol.com> I'm looking for Steve Rumbalski -------------- next part -------------- An HTML attachment was scrubbed... URL: From marcoacarvalho at gmail.com Sat May 27 15:03:34 2006 From: marcoacarvalho at gmail.com (Marco Carvalho) Date: Sat, 27 May 2006 16:03:34 -0300 Subject: Python - Web Display Technology In-Reply-To: <87odxp3cvc.fsf@benfinney.id.au> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <87odxp3cvc.fsf@benfinney.id.au> Message-ID: <9c9ec91c0605271203v73fe3b59r21ca71020dfa5a75@mail.gmail.com> We don't need any proprietary junk to make a nice-look website: http://www.csszengarden.com You can navigate in this site with any kind of browser, even graphical or text-based, like lynx. From vbgunz at gmail.com Wed May 24 20:53:16 2006 From: vbgunz at gmail.com (vbgunz) Date: 24 May 2006 17:53:16 -0700 Subject: IronPython 1.0 Beta 7 Released In-Reply-To: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> Message-ID: <1148518396.856710.173810@g10g2000cwb.googlegroups.com> maybe I am a bit ignorant and love living in the bliss of it and maybe I am a bit tired on the subject but may I ask you a question? if i decided to use IronPython for strict cPython work, is this possible? probably dumb when I can use cPython but is it still possible in case maybe sometime down the road I wanted to use the .NET libaries? In other words, IronPython is Python but with the extra capability of working in .NET correct? Do you have some introductory information on it? I am very interested on some news that explains what IronPython is. What would you recommend I check out for a great intro on IronPython? From aleax at mac.com Tue May 9 01:44:56 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 8 May 2006 22:44:56 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> Message-ID: <1hf1hlk.uf6b5hc60js1N%aleax@mac.com> Patrick May wrote: > aleax at mac.com (Alex Martelli) writes: > > ...an alleged reply to me, which in fact quotes (and responds to) > > only to statements by Brian, without mentioning Brian... > > > > Mr May, it seems that you're badly confused regarding Usenet's > > quoting conventions. > > It seems that someone pisses in your cornflakes nearly every > morning. > > For the record, I was attempting to respond to your post which I > only saw quoted in another message. Please excuse any accidental > misquoting. Your message was an immediate followup to mine, but all the text you quoted in it was by Brian (w/o mentioning him) -- you quoted no text written by me. > > Your "pragmatic benefits", if such they were, would also apply to the > > issue of "magic numbers", > > That claim is, frankly, silly. A function is far more > understandable without a name than a value like 1.19 in isolation. > The situations aren't remotely comparable. I think the comparability is definitely there. Somebody asked me about translating a bunch of Lisp he'd written (he later admitted he had misunderstood the power of python's def, and that it lets one do all he's using unnamed functions for); well, each of those HOF's returns an unnamed function *with a nice short comment explaining WHAT it does*. The code would be of far worse quality without the nice short comments, but it would be much better if the comments were turned into *NAMES* (allowing easier inspection in interactive development, debugging including examination of tracebacks, etc). What's the *POINT* of coding (python syntax): def blank(*a): " return a blank picture " return lambda *ignore_args: [] rather than: def blank(*a): def blank_picture(*ignore_args): return [] return blank_picture and so forth? The former is obscure (ok, it's an anonymous function taking and ignoring arbitrary args and returning an empty list, but WHY, WHAT DOES IT MEAN?!), except for the explanatory comment; the latter clearly defines the purpose of the returned-function by its name. The situation is exactly parallel to "magic numbers", as in: total *= 1.19 is entirely mysterious (OK, total, is being multiplied by 1.19, but WHY, WHAT DOES IT MEAN?!), better is # augment total by VAT total *= 1.19 and better still VAT_MULTIPLIER = 1.19 total *= VAT_MULTIPLIER A comment is better than nothing (given that the 1.19 constant, or the function ignoring its arguments and returning empty list, are mysterious in their purpose), a name is better still. > > cost: I like languages that are and stay SMALL and SIMPLE. > > Like Scheme? Didn't want to trigger some flamewar;-), but, yes, if that was my only choice, I'd much rather use small, simple Scheme than huge, complicated, rich, powerful Common Lisp. ((But in this case I'm biased by early experiences, since when I learned and used Lisp-ish languages there WAS no Common Lisp, while Scheme was already there, although not quite the same language level as today, I'm sure;-)). Alex From mariano.difelice at gmail.com Thu May 11 09:47:46 2006 From: mariano.difelice at gmail.com (mariano.difelice at gmail.com) Date: 11 May 2006 06:47:46 -0700 Subject: Python memory deallocate In-Reply-To: <-yy*V4mgr@news.chiark.greenend.org.uk> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <-yy*V4mgr@news.chiark.greenend.org.uk> Message-ID: <1147355266.189030.131420@y43g2000cwc.googlegroups.com> Ok, this is true. Well, you consider that my app has a first windows, where I choose, for example, the application 1. The application 1 will be started, and it will allocate 200Mb total. Now I want to abort this operation, and i will return to main initial window. The memory usage remain to 200Mb, even if I've destroyed the application 1 object with app1.Destroy() and del app1. When from initial windows i re-choose application1, the memory usage don't stay to 200Mb, but will increase to 360-380Mb memory, and I think this is not good!!! If I will repeat this procedure for 5-6 times, the application will crash... And it's not good!!! From fredrik at pythonware.com Wed May 31 02:49:06 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 31 May 2006 08:49:06 +0200 Subject: genexp performance problem? In-Reply-To: References: Message-ID: Giovanni Bajo wrote: > > I found this strange: > > > > python -mtimeit "sum(int(L) for L in xrange(3000))" > > 100 loops, best of 3: 5.04 msec per loop > > > > python -mtimeit "import itertools; sum(itertools.imap(int, xrange(3000)))" > > 100 loops, best of 3: 3.6 msec per loop > > > > I thought the two constructs could achieve the same speed. hint: how many times do the interpreter have to look up the names "int" and "L" in the two examples ? From http Sun May 7 14:56:47 2006 From: http (Paul Rubin) Date: 07 May 2006 11:56:47 -0700 Subject: md5 from python different then md5 from command line References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> <445e3a3b$0$22630$c3e8da3@news.astraweb.com> Message-ID: <7xd5epek9c.fsf@ruckus.brouhaha.com> John Salerno writes: > Just a quick md5-related follow-up question: I was experimenting with > it and making md5 sums for strings, but how do you use the md5 module > to create a sum for an actual file, such as an .exe file? m = md5.new() f = file('foo.exe', 'b') # open in binary mode while True: t = f.read(1024) if len(t) == 0: break # end of file m.update(t) print m.hexdigest() From python-url at phaseit.net Mon May 1 19:08:18 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 01 May 2006 23:08:18 GMT Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 1) Message-ID: QOTW: "I have a certain fondness for the first over-100-lines module I wrote for Python" - Alex Martelli "Programmers should be paid by the amount of code that they avoid writing." - Michael P. Soulier If you know Python basics but managed to get along without creating your own classes, have a look at Jay Parlar's contribution to the Unofficial Python Tutorial Wiki: http://pytut.infogami.com/node11-baseline.html There's a reason you cannot set attributes on object [the baseclass of all new-style classes] instances: http://groups.google.com/group/comp.lang.python/msg/8086116fa893c283 Jason Huggins plays with dot notation for domain-specific languages: http://www.jrandolph.com/blog/?p=29 The competitors for non-web based templating systems are many: http://groups.google.com/group/comp.lang.python/browse_frm/thread/51d5694377a5d1a6/df98a68c5718deec?tvc=1 While web frameworks written in Python abound, WSGI as a low-level interface between web servers and web applications gets BDFL blessing and a reference implementation may make it into Python 2.5: http://www.artima.com/weblogs/viewpost.jsp?thread=158191 For still more breaking news on Web frameworks, see: http://radar.oreilly.com/archives/2005/12/ruby_book_sales_surpass_python.html http://pylonshq.com/ You may have to look into a man page to learn more about the details of format strings: http://groups.google.com/group/comp.lang.python/browse_frm/thread/323c70d603946f84/7afd45a984b88ae5?tvc=1 'Want an "open source graphical design environment" for Tkinter? Rapyd-Tk bills itself that way: http://home.cogeco.ca/~rapyd Kevin Simmons finds a way to read two characters from stdin without resorting to curses: http://groups.google.com/group/comp.lang.python/msg/faa76bb532195fd8?hl=en Steve Holden releases his PyCon 2006 tutorials "Using Databases in Python" and "An Introduction to wxPython" under a Creative Commons license: http://groups.google.com/group/comp.lang.python/msg/b3fb85114fcd1f32 ======================================================================== 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, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python 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!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From nobody at 127.0.0.1 Fri May 12 02:33:18 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 06:33:18 GMT Subject: Threads References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> Message-ID: Dennis Lee Bieber wrote: > On 11 May 2006 17:02:51 -0700, "placid" declaimed the > following in comp.lang.python: >> do is, when the queue is empty, i want the thread to pause (or more >> technical, i want the thread to block) until the queue gets populated >> again. Is this possible ? >> > Did you read the documentation for Queue methods? > > x = q.get(true) #blocks until data is available Like a good lawyer, Dennis knows the answer before he asks the question. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From redefined.horizons at gmail.com Tue May 23 09:41:28 2006 From: redefined.horizons at gmail.com (Redefined Horizons) Date: Tue, 23 May 2006 06:41:28 -0700 Subject: Using python for a CAD program In-Reply-To: <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <446C8950.3070107@anansispaceworks.com> <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> Message-ID: This is a very interesting discussion. :] I regularly use CAD and GIS programs at work, and have dabbled in traditional RDBMS design. I ran into a problem with an open source GIS program I work with, that reads all features in a shapefile into memory. This limits the use of the program, given the size of many geospatial data sets. I decided we needed to implement a system for storage of features and geometries that would overcome this memory limitation. I looked at existing RDBMS and Object-Oriented Databases and decided it would be better to start from scratch. I am designing an object oriented-database that will work with CAD and GIS systems. The first implementation will be in Java, but I hope to create an implementation in Python as well. It will have features like undo/redo (transactions) and mulit-user access. I am no expert programmer, so I'm not sure how great this will work, but I know it will be better than the system we have now. Scott Huey On 5/22/06, baalbek wrote: > > David Cuthbert wrote: > > > This does not mean the design itself should be stored as an RDBMS. As > > I've stated previously, CAD data (both electrical and, it appears, > > mechanical) does not lend itself to RDBMS relationship modeling. > > I simply do not agree with this. > > A CAD program (like Autocad) is nothing > but an advanced database editor: the program loads data from a binary > file and creates its object (in memory) from the tables that it reads > from the file on the disk. > > The point is that this could as well have been stored on tables in a > RDBMS; the process of loading the object once the data has been fetched > (either from a binary file, or a RDBMS) the process is similar. > > The advantage of having the data stored in a RDBMS is many, amongst them > the ability to check-out just the data one needs, better administration > of the drawings (consistent plotting, dimensioning styles, fonts, etc) > and a much better tool for gathering statistics of the project (sums of > areas, rooms, doors, etc etc). > > What happens in the CAD program (once loaded in memory) is simply > irrelevant to how the data are stored. > > Regards, > Baalbek > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: From tomasz.zielonka at gmail.com Sat May 6 07:04:56 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Sat, 6 May 2006 11:04:56 +0000 (UTC) Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> Message-ID: Bill Atkins wrote: > OK, my real question is: what features of Python make it "scalable"? Let me guess: Python makes it easier to scale the application on the "features" axis, and the approach to large-scale computation taken by google makes Python's poor raw performance not so big an issue, so it doesn't prevent the application from scaling on the "load" and "amount of data" axes. I also guess that python is often used to control simple, fast C/C++ programs, or even to generate such programs. Best regards Tomasz From johnjsal at NOSPAMgmail.com Wed May 10 10:02:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 14:02:31 GMT Subject: MySQLdb trouble In-Reply-To: References: Message-ID: Nicolay A. Vasiliev wrote: > def loc_connect_db(): > """ > The DB connection subroutine > """ > db = MySQLdb.connect(host = "localhost", > user = "root", > passwd="mysql", > db="some_db") > return db Hi. Sorry I can't help, but I'm interested in learning about mysqldb and I was wondering why you chose to wrap the 'connect' function inside your own function. Does this accomplish something that I'm not seeing? Couldn't you just use the body of the loc_connect_db() function as your actual code in order to get 'db'? Thanks. From cito at online.de Sun May 7 04:09:14 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 07 May 2006 10:09:14 +0200 Subject: Integrate docs of site-packages with Python doc index? Message-ID: I just thought it would be nice to have a standardized place to put the accompanying documentation for Python site packages, and something like a hook to register documentation so that all installed site packages can install links to their documentation in the Python Documentation Index. Are there already any thoughts or standards on how to integrate/append documentation of later installed site packages to the standard Python documentation index, in order to get a complete hypertext documentation of all the installed Python modules? -- Christoph From apavluck at gmail.com Tue May 23 12:43:40 2006 From: apavluck at gmail.com (Alex Pavluck) Date: 23 May 2006 09:43:40 -0700 Subject: "Thinking like CS" problem I can't solve Message-ID: <1148402620.032735.60000@g10g2000cwb.googlegroups.com> Hello. On page 124 of "Thinking like a Computer Scientist". There is an exercise to take the following code and with the use of TRY: / EXCEPT: handle the error. Can somone help me out? Here is the code: def inputNumber(n): if n == 17: raise 'BadNumberError: ', '17 is off limits.' else: print n, 'is a nice number' return n inputNumber(17) From bdesth.quelquechose at free.quelquepart.fr Tue May 2 21:47:55 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 03:47:55 +0200 Subject: search file for tabs In-Reply-To: References: <1146606666.249084.12810@j73g2000cwa.googlegroups.com> Message-ID: <4457dd19$0$9654$636a55ce@news.free.fr> Tim Chase a ?crit : (snip) > If you were using strip() to get rid of the newlines, you can easily > enough do that with > > text = text[:-1] Which is a very bad idea IMHO. > Or, depending on what your needs are, rstrip() may do the trick for you. ... eventually with it's optional param: text = text.rstrip('\n') From jiangchanghao at hotmail.com Fri May 19 22:27:31 2006 From: jiangchanghao at hotmail.com (Changhao) Date: Fri, 19 May 2006 21:27:31 -0500 Subject: performance problem of streaming data over TCP Message-ID: Hi, friends, I am implementing a protocol on top of 'asyncore.dispatcher' to send streaming multimedia data over TCP socket. However, I found that the throughput of my current implementation is surprisingly low. Below is a snippet of my code with a note that: the packet sent over the socket is of variable length, of which the first a couple bytes indicates the length of the packet. I implemented a 'var_str_to_int' function to get the 'length' and the offset of the payload. ############################################### def handle_read(self): self.socket.setblocking(1) while (True) : data = self.assemble_msg() if (not data) : self.socket.setblocking(0) return (length,index) = var_str_to_int(data) self._dispatch_cmd(data[index:]) if (not self.recv_buffer) : break self.socket.setblocking(0) def assemble_msg(self) : if (self.recv_buffer) : data = self.recv_buffer else : data = self.socket.recv(self.BUFFER_SIZE) if (len(data) == 0) : return None length,index = var_str_to_int(data) while (length +index > len(data)) : data += self.socket.recv(self.BUFFER_SIZE) if (length + index == len(data)) : self.recv_buffer = '' else : self.recv_buffer = data[length+index:] data = data[:length+index] return data ############################################### I found it took around 7 seconds to receive a packet of 40KB sent from localhost. The throughput is even not enough to support any streaming multimedia file for live playback in a LAN. I read some threads in the group. It sounds like the problem might have to do with the TCP option, setting TCP_NODELAY probably could solve the problem. But I tried the following on both a Linux and a windows XP machine. Neither of them worked: ############################################## self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) ############################################## Any comments or suggests is highly appreciated. Thanks, Changhao From bignose+hates-spam at benfinney.id.au Sat May 6 19:31:53 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 07 May 2006 09:31:53 +1000 Subject: the print statement References: <1146950481.610645.39710@j33g2000cwa.googlegroups.com> Message-ID: <871wv6spau.fsf@benfinney.id.au> mirandacascade at yahoo.com writes: > My questions are: Mostly answered in the language reference: -- \ "Facts are meaningless. You could use facts to prove anything | `\ that's even remotely true!" -- Homer, _The Simpsons_ | _o__) | Ben Finney From michele.simionato at gmail.com Wed May 3 05:00:38 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 3 May 2006 02:00:38 -0700 Subject: Zope Guru... In-Reply-To: References: Message-ID: <1146646838.604997.215290@v46g2000cwv.googlegroups.com> The guys here are Zope and workflow guru's I have worked with and I have been very happy with them: http://www.reflab.com/ Michele Simionato From paul at eval.ca Wed May 24 15:50:07 2006 From: paul at eval.ca (Paul Osman) Date: Wed, 24 May 2006 15:50:07 -0400 Subject: simple print is not working.. In-Reply-To: <1148499666.824598.313720@i40g2000cwc.googlegroups.com> References: <1148499666.824598.313720@i40g2000cwc.googlegroups.com> Message-ID: On 24-May-06, at 3:41 PM, lahirister at gmail.com wrote: > What is wrong with this script? > > #!/usr/bin/python > fsfile = open('/tmp/fs_info.al', 'r') > for line in fsfiles.readlines(): > print line > fsfile.close() > > > #./get_fs_info.py > File "./get_fs_info.py", line 4 > print line > ^ > SyntaxError: invalid syntax > > > Any ideas? > > Thanks > AL Well first, you have to indent properly :) Assuming you did that and the copy & paste just removed it, you're also creating a variable called fsfile, then trying to call the readlines() method on an object called fsfiles... that'll cause a problem. Cheers, -- Paul Osman http://www.eval.ca From mahs at telcopartners.com Wed May 17 17:25:11 2006 From: mahs at telcopartners.com (Michael Spencer) Date: Wed, 17 May 2006 14:25:11 -0700 Subject: How to add columns to python arrays In-Reply-To: References: <1147882432.166728.207820@j55g2000cwa.googlegroups.com> Message-ID: Terry Reedy wrote: > "Michael Spencer" wrote in message > news:e4ft0l$356$1 at sea.gmane.org... >> If you're just looking for a multi-dimensional array type, and don't need >> maximum speed or the vast range of array-processing that numpy offers, >> then >> *pyarray* provides a pure-python single module solution. >> >> the latest pyarray is available with tests and documentation at: >> http://svn.brownspencer.com/pyarray/trunk/ > > Nice. I downloaded and expect to give it a try sometime. I suggest > putting the url in the module file itself to make it easier to search for > updated versions ;-) > > tjr > > > Thanks for the suggestion, Terry. I've added a static link in each source file to the repository at: http://svn.brownspencer.com/pyarray/ and also added an email address. If you do try it, I'd be interested to hear your feedback. Michael From onurb at xiludom.gro Wed May 24 04:20:36 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 24 May 2006 10:20:36 +0200 Subject: dict literals vs dict(**kwds) In-Reply-To: <1148424591.982669.225430@i39g2000cwa.googlegroups.com> References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> Message-ID: <447417c1$0$22094$626a54ce@news.free.fr> George Sakkis wrote: > Bruno Desthuilliers wrote: > > >>George Sakkis a ?crit : >> >>>Although I consider dict(**kwds) as one of the few unfortunate design >>>choices in python since it prevents the future addition of useful >>>keyword arguments (e.g a default value or an orderby function), I've >>>been finding myself lately using it sometimes instead of dict literals, >>>for no particular reason. Is there any coding style consensus on when >>>should dict literals be preferred over dict(**kwds) and vice versa ? >> >>using dict literals means that you'll always have a builtin dict - you >>cannot dynamically select another dict-like class. OTHO, you can only >>use valid python identifiers as keys with dict(**kw). > > > This is all good but doesn't answer my original question: I thought it did - at least partly. > under which > circumstances (if any) would {'name':'Mike, 'age':23} be preferred > over dict(name='Mike', age=23) When you're sure you want a builtin dict (not any other dictlike) and/or some keys are invalid Python identifiers. > and vice versa, When all your keys are valid Python identifiers, and you may want to use another dict-like instead of the builtin dict. It's easy to replace the dict() factory in a function, class, or whole module : class MyDict(...): # dict-like class dict = MyDict then all following calls to dict(**kw) in this namespace will use MyDict instead of the builtin's one. Can't do that with dict litterals. > or if it's just a matter > of taste, Partly also, but... > similar to using single vs double quote for string literals > (when both are valid of course). Nope, this is not so similar, cf above. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From dadapapa at googlemail.com Thu May 4 07:50:18 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 4 May 2006 04:50:18 -0700 Subject: __getattr__ for global namespace? Message-ID: <1146743418.248566.241890@e56g2000cwe.googlegroups.com> Hi, I am writing an application that initializes the global namespace, and afterwards, leaves the user with the python prompt. Now, I want to catch NameErrors in user input like e.g. >>> some_name Traceback (most recent call last): File "", line 1, in ? NameError: name 'some_name' is not defined For classes, there are the __getattr__ and __getattribute__ functions. I wonder if there is some related function for (failed) global attribute lookup that is invoked with name as its argument instead. I consulted the docs, but could not find anything. Any ideas? - harold - From rory.brandybuck at gmail.com Mon May 15 08:52:47 2006 From: rory.brandybuck at gmail.com (rory.brandybuck at gmail.com) Date: 15 May 2006 05:52:47 -0700 Subject: please help me is sms with python In-Reply-To: <1147694913.198080.183750@i39g2000cwa.googlegroups.com> References: <4cr6deF17i9mpU1@uni-berlin.de> <1147694913.198080.183750@i39g2000cwa.googlegroups.com> Message-ID: <1147697567.718667.141590@j55g2000cwa.googlegroups.com> Yet another option: Use Python high level API for Symbian (http://opensource.nokia.com/projects/pythonfors60/) to write simple server which listen to desktop client (both in Python). Server (phone side): accept requests, send SMS using mobile phone capability Client (desktop): send requests, specify phone number, message to send. Use any suitable connection between the phone and computer. From dadapapa at googlemail.com Thu May 11 08:56:11 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 11 May 2006 05:56:11 -0700 Subject: redirecting print to a a file In-Reply-To: <7JudnYwllewrrv7ZRVn-vA@comcast.com> References: <7JudnYwllewrrv7ZRVn-vA@comcast.com> Message-ID: <1147352171.658508.187490@y43g2000cwc.googlegroups.com> >>> import sys >>> sys.stdout = file("output","w") >>> print "here you go" From david.murmann at rwth-aachen.de Fri May 12 21:40:27 2006 From: david.murmann at rwth-aachen.de (David Murmann) Date: Sat, 13 May 2006 03:40:27 +0200 Subject: getting rid of pass Message-ID: <4ckrmbF16kr2bU1@news.dfncis.de> Hi all! i just had this crazy idea: instead of while cond(): pass write while cond(). or try: import xyz except ImportError: pass compared to try: import xyz except ImportError. i don't know whether this is syntactically unambiguous or replaces all uses of pass, but i find it quite nice to read. also if something like this has been proposed before and rejected, i apologize for this late-in-the-night idea. what do you people think? have a nice day, David. From manstey at csu.edu.au Tue May 16 22:19:59 2006 From: manstey at csu.edu.au (manstey) Date: 16 May 2006 19:19:59 -0700 Subject: A Unicode problem -HELP References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> Message-ID: <1147832399.383507.155800@j55g2000cwa.googlegroups.com> Hi Martin, HEre is how I write: input_file = open(input_file_loc, 'r') output_file = open(output_file_loc, 'w') for line in input_file: output_file.write(str(word_info + parse + gloss)) # = three functions that return tuples (u'F', u'\u0254') are two of the many unicode tuple elements returned by the three functions. What am I doing wrong? From onurb at xiludom.gro Mon May 22 04:17:58 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 22 May 2006 10:17:58 +0200 Subject: altering an object as you iterate over it? In-Reply-To: References: <1Mobg.2139$No6.46432@news.tufts.edu> <446e1def$0$6919$626a54ce@news.free.fr> <446e573a$0$4960$626a54ce@news.free.fr> Message-ID: <44717421$0$10541$636a55ce@news.free.fr> Paul McGuire wrote: > "Bruno Desthuilliers" wrote in > message news:446e573a$0$4960$626a54ce at news.free.fr... > >>bruno at modulix a ?crit : >>(snip) >> >>(responding to myself) >>(but under another identity - now that's a bit schizophrenic, isn't it ?-) >> > > > Do you ever flame yourself? class Myself(Developper, Schizophrenic): def _flame(self): """ implementation left as an exercice to the reader... Note that this is *not* part of the public API !-) """ pass -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From OlafMeding at gmail.com Wed May 10 16:16:18 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 10 May 2006 13:16:18 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1147292178.325015.172460@y43g2000cwc.googlegroups.com> This is an update on what we found so far: We located one other PC that was not identical to the PC with the problem. So we installed Windows XP on it and ran the Python test program. It ran fine all night w/o locking up. Here is what winmsd reports for this PC: winmsd: OS Name: Microsoft Windows XP Professional Version: 5.1.2600 Service Pack 2 Build 2600 Processor: x86 Family 15 Model 4 Stepping 3 GenuineIntel ~3600Mhz Processor: x86 Family 15 Model 4 Stepping 3 GenuineIntel ~3600Mhz Okay so this together with what others reported on in this newsgroup leads to the conclusion that the problem is with the specific software or hardware configuration of our PC. So to make sure that no other software is involved we took the PC with the problem, reset the BIOS to its defaults (which also enables hyper-threading) and installed Windows XP Professional (SP2) on it (but no further driver software, etc). We accepted all defaults during the installation. Once Windows XP was running we installed Python downloaded from (and accepted all defaults during the installation): http://www.python.org/ftp/python/2.4.3/python-2.4.3.msi And we then ran our Python test program and it hung after less than 15 minutes! We are now contacting the company that puts that PC together for further advice. Olaf From usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo Wed May 24 07:33:02 2006 From: usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo (KW) Date: Wed, 24 May 2006 13:33:02 +0200 Subject: PHP's openssl_sign() using M2Crypto? References: <1148319025.745324.171890@i40g2000cwc.googlegroups.com> <1148407334.274505.314250@i39g2000cwa.googlegroups.com> Message-ID: On 2006-05-23, heikki at osafoundation.org wrote: > That is really strange, because PKey has had sign_init method since > 2004. That code works for me (just tested). What version of M2Crypto > are you using? I'd advice you upgrade to 0.15 if possible. See > > http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto Great! I was using 0.13.1 from both Debian en Ubuntu and I thought no further development was done on it.. It would be nice to get this version into Debian. Best regards, -- Konrad From johnjsal at NOSPAMgmail.com Sun May 7 19:54:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 07 May 2006 19:54:56 -0400 Subject: utility functions within a class? Message-ID: <445e8992$0$9427$c3e8da3@news.astraweb.com> I might be missing something obvious here, but I decided to experiment with writing a program that involves a class, so I'm somewhat new to this in Python. Anyway, what is the best way to create a function (A) within a class that another function (B) can use? Function A is not something that an instance will ever call, so I figure it's a choice between static or class methods, but I don't know which one, or if this is even the right approach. Specifically, I am writing a class that defines methods that wrap string arguments inside HTML elements, and ultimately creates and HTML page. I know there are probably a ton of programs like this already, but this is just to give me something to do with Python. So I have a generate() method that will create the final HTML file once you are done creating elements. First it will create a string with the proper DTD, then it will append the element and the element, wrapped in the element. Rather than have the generate() function do all the work, I thought I could write two utility functions to generate the head and body elements. These would simply wrap the element names around some pre-defined text (for the head) and around all the other elements (for the body). So I'm wondering, how would I define these two functions? They would be called from the generate method solely for the purpose of creating the head and body blocks. Thanks! From Bulkan at gmail.com Thu May 11 20:02:51 2006 From: Bulkan at gmail.com (placid) Date: 11 May 2006 17:02:51 -0700 Subject: Threads In-Reply-To: References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> Message-ID: <1147392171.914234.48260@q12g2000cwa.googlegroups.com> Carl J. Van Arsdall wrote: > placid wrote: > > Hi all, > > > > In Python, Threads cannot be paused, i remember reading this somewhere, > > so is there a way around this ? > > > > When you say paused do you mean paused by an external source or paused > by a call internal to the thread? There are plenty of synchronization > constructs for making threads wait: Check out Events and Conditions I have a thread that has a job Queue, it continuosly polls this queue to see if there are any jobs for it, what i really wont to be able to do is, when the queue is empty, i want the thread to pause (or more technical, i want the thread to block) until the queue gets populated again. Is this possible ? > > -carl > > > > -- > > Carl J. Van Arsdall > cvanarsdall at mvista.com > Build and Release > MontaVista Software From robert.kern at gmail.com Mon May 22 10:51:31 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 May 2006 09:51:31 -0500 Subject: XP64 64 Bit Linux and Programming Best Practice Guide In-Reply-To: References: Message-ID: Wesley Brooks wrote: > Dear Users, > > Is there a version of python that will make full use of the 64 bit > processing capabilities on XP64 or a 64 bit version of linux? The coming Python 2.5 has loosened some 32-bit restrictions. http://www.python.org/dev/peps/pep-0353/ > Is there a particular version of linux best suited to coding in python > and c++? Ubuntu is a very Python-friendly distribution. -- 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 micklee74 at hotmail.com Mon May 8 06:19:03 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 8 May 2006 03:19:03 -0700 Subject: printing out elements in list In-Reply-To: <1147078414.615247.165010@j73g2000cwa.googlegroups.com> References: <1147074279.391832.158350@y43g2000cwc.googlegroups.com> <1147075890.042861.250650@i40g2000cwc.googlegroups.com> <1147078414.615247.165010@j73g2000cwa.googlegroups.com> Message-ID: <1147083543.776548.284020@i39g2000cwa.googlegroups.com> thanks for the detailed explaination... i know about basic lists slicing..just havn't seen one with "steps" yet.. thanks again...clp rocks. From johnjsal at NOSPAMgmail.com Mon May 8 09:40:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 13:40:04 GMT Subject: utility functions within a class? In-Reply-To: <1147062228.849272.225110@j73g2000cwa.googlegroups.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> Message-ID: blair.bethwaite at gmail.com wrote: > John Salerno wrote: >> What I originally meant was that they would not be called from an >> instance *outside* the class itself, i.e. they won't be used when >> writing another script, they are only used by the class itself. > > Yep, so you want to encapsulate the functionality that those methods > provide, which is the whole point of building them in a class in the > first place. And you want them to be private to the class so that they > do not form part of the classes public/external interface. But it's right that they should still be regular instance methods? So from within the class I still call them as self._generate_head(), etc.? From timr at probo.com Wed May 3 02:41:44 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 03 May 2006 06:41:44 GMT Subject: detect video length in seconds References: <1146613626.090047.186390@j33g2000cwa.googlegroups.com> Message-ID: "garylinux at gmail.com" wrote: > >Is there a way to get the length of a video clip (divix/xvid) in >seconds? This is non-trivial. MPEG files do not have an index, so the only way to figure this out is to scan from the front of the file until you find a timestamp, then scan backwards from the end of the file until you find a timestamp, and subtract. You can also try to extract the bitrate from an early header and use arithmetic to get a good estimate. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From http Mon May 15 03:09:00 2006 From: http (Paul Rubin) Date: 15 May 2006 00:09:00 -0700 Subject: comparing values in two sets References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> <7xslncdsvk.fsf@ruckus.brouhaha.com> Message-ID: <7xhd3r4veb.fsf@ruckus.brouhaha.com> Peter Otten <__peter__ at web.de> writes: > Here's a variant that does performs only the necessary tests: > > >>> from itertools import izip > >>> True not in (a == b for a, b in izip(range(3), range(3))) Cute! From bj_666 at gmx.net Wed May 3 16:57:23 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 03 May 2006 22:57:23 +0200 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: In , Edward Elliott wrote: > I can prove that assertion too: make a simple text processor that reads > Python source code and outputs the same source code with only one change: > insert the string 'self" as the first parameter of every "def somemethod". > Next run the output source code with the normal Python interpreter. > Everything functions *exactly* as before because the code is *exactly* the > same as what you would have written if you'd put the 'self's in there > manually. Now make the Python interpreter invoke this text processor as > the first step in processing source code. Voila, python + implicit self. Okay, let's start with writing a simple text processor for this little mess:: def b(c): def d(r, *s, **t): print '***' c(r, *s, **t) return d class A: @b def a(x, y, z): print y, z x.e(23) def e(u, v): print u, v class B: def e(v, w): print 'spam', v, w A.e = e x = A() x.a('answer', 42) e('eric', 'viking') A.a(x, 'ham', 'eggs') Ciao, Marc 'BlackJack' Rintsch From george.sakkis at gmail.com Sun May 14 00:27:40 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 May 2006 21:27:40 -0700 Subject: retain values between fun calls References: <87d5ehh6z6.fsf@localhost.localdomain> Message-ID: <1147580860.582605.108450@j33g2000cwa.googlegroups.com> Gary Wessle wrote: > Hi > > the second argument in the functions below suppose to retain its value > between function calls, the first does, the second does not and I > would like to know why it doesn't? and how to make it so it does? > > thanks > > # it does > def f(a, L=[]): > L.append(a) > return L > print f('a') > print f('b') > > > # it does not > def f(a, b=1): > b = a + b > return b > print f(1) > print f(2) It's a FAQ: http://www.python.org/doc/faq/general/#why-are-default-values-shared-between-objects. Whenever you want to control one or more objects beyond the lifetime of a single function call, your first thought should be to use a class to couple behaviour with state: class SomeFancyClassName(object): def __init__(self, b=1): self.b = b def f(self, a): self.b += a return self.b x = SomeFancyClassName() print x.f(1) print x.f(2) HTH, George From Serge.Orlov at gmail.com Mon May 1 22:57:58 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 May 2006 19:57:58 -0700 Subject: Can Python kill a child process that keeps on running? References: <1146532884.872505.154370@i40g2000cwc.googlegroups.com> Message-ID: <1146538678.842231.232010@j33g2000cwa.googlegroups.com> I. Myself wrote: > Serge Orlov wrote: > > I. Myself wrote: > > > >> Suppose we spawn a child process with Popen. I'm thinking of an > >> executable file, like a compiled C program. > >> Suppose it is supposed to run for one minute, but it just keeps going > >> and going. Does Python have any way to kill it? > >> > >> This is not hypothetical; I'm doing it now, and it's working pretty > >> well, but I would like to be able to handle this run-on condition. I'm > >> using Windows 2000, but I want my program to be portable to linux. > >> > > > > On linux it's pretty easy to do, just setup alarm signal. On windows > > it's not so trivial to the point you cannot do it using python.org > > distribution, you will need to poke in low level C API using win32 > > extensions or ctypes. AFAIK twisted package > > has some code to help you. Also take a look at buildbot sources > > that uses twisted. Buildbot has the same > > problem as you have, it needs to kill run away or non-responding > > processes. > > > That is bad news. Thanks anyway; bad news is better than no news. The good news is that I think you can work around it using only stock 2.4 modules. The idea is that you launch a separate watchdog process and communicate with it using portable asynchronous channel (file system or socket). Here is totally untested (not even passed the compilation) code just to show the idea how to communicate asynchronously over filesystem: ======= watchdog.py ========= import os, sys timeout = int(sys.argv[1]) commdir = sys.argv[2] worker_pid = int(sys.argv[3]) heart_beat = os.path.join(commdir, "heartbeat") work_is_done = os.path.join(commdir, "done") while True: if os.path.exists(work_is_done): break if os.path.exists(heartbeat): os.kill(worker_pid) break file(heart_beat, "w").close() time.sleep(timeout) =========================== ======= work_consumer.py ======== # launch worker process # launch watchdog def heart_beat(): try: os.remove(heart_beat) except OSError: pass def done(): file(heart_beat, "w").close() try: while True: data = worker.read() heart_beat() # process data if done: break finally: done() ============================= If you don't like so much file system activity, you can implement asynchronous communications over local socket. It is also portable. From sRuEmMrOnVoEt at hotmail.com Wed May 24 14:11:02 2006 From: sRuEmMrOnVoEt at hotmail.com (Geoffrey Summerhayes) Date: Wed, 24 May 2006 14:11:02 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <1148485967.164221.304310@y43g2000cwc.googlegroups.com> <87y7wre6yr.fsf@rpi.edu> Message-ID: <1l1dg.1627$%Z2.224933@news20.bellglobal.com> "Bill Atkins" wrote in message news:87y7wre6yr.fsf at rpi.edu... > John Bokma writes: > > [snip] > >> -- >> John MexIT: http://johnbokma.com/mexit/ >> personal page: http://johnbokma.com/ >> Experienced programmer available: http://castleamber.com/ >> Happy Customers: http://castleamber.com/testimonials.html > > Interesting. Doesn't your signature contain advertisements for your > website? Aren't you posting to five different groups? Shh! Pointing out ironic hypocrisy never works. -- Geoff P.S. You forgot that it's also off-topic for all groups. P.P.S. Mea culpa From ptmcg at austin.rr._bogus_.com Mon May 8 12:20:48 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 08 May 2006 16:20:48 GMT Subject: regular expressions, substituting and adding in one step? References: Message-ID: "John Salerno" wrote in message news:yEI7g.2056$No6.45379 at news.tufts.edu... > Ok, this might look familiar. I'd like to use regular expressions to > change this line: > > self.source += '

' + paragraph + '

\n\n' > > to read: > > self.source += '

%s

\n\n' % paragraph > John - You've been asking for re-based responses, so I apologize in advance for this digression. Pyparsing is an add-on Python module that can provide a number of features beyond just text matching and parsing. Pyparsing allows you to define callbacks (or "parse actions") that get invoked during the parsing process, and these callbacks can modify the matched text. Since your re approach seems to be on a fairly convergent path, I felt I needed to come up with more demanding examples to justify a pyparsing solution. So I contrived these additional cases: self.source += '

' + paragraph + '

\n\n' listItem1 = '
  • ' + someText + '
  • ' listItem2 = '
  • ' + someMoreText + '
  • ' self.source += '
      ' + listItem1 + '\n' + listItem2 + '\n' + '
    \n\n' The following code processes these expressions. Admittedly, it is not as terse as your re-based code samples have been, but it may give you another data point in your pursuite of a solution. (The pyparsing home wiki is at http://pyparsing.wikispaces.com.) The purpose of the intermediate classes is to convert the individual terms of the string expresssion into a list of string terms, either variable references or quoted literals. This conversion is done in the term-specific parse actions created by makeTermParseAction. Then the overall string expression gets its own parse action, which processes the list of term objects, and creates the modified string expression. Two different string expression conversion functions are shown, one generating string interpolation expressions, and one generating "".join() expressions. Hope this helps, or is at least mildly entertaining, -- Paul ================ from pyparsing import * testLines = r""" self.source += '

    ' + paragraph + '

    \n\n' listItem1 = '
  • ' + someText + '
  • ' listItem2 = '
  • ' + someMoreText + '
  • ' self.source += '
      ' + listItem1 + '\n' + listItem2 + '\n' + '
    \n\n' """ # define some classes to use during parsing class StringExprTerm(object): def __init__(self,content): self.content = content class VarRef(StringExprTerm): pass class QuotedLit(StringExprTerm): pass def makeTermParseAction(cls): def parseAction(s,l,tokens): return cls(tokens[0]) return parseAction # define parts we want to recognize as terms in a string expression varName = Word(alphas+"_", alphanums+"_") varName.setParseAction( makeTermParseAction( VarRef ) ) quotedString.setParseAction( removeQuotes, makeTermParseAction( QuotedLit ) ) stringTerm = varName | quotedString # define a string expression in terms of term expressions PLUS = Suppress("+") EQUALS = Suppress("=") stringExpr = EQUALS + stringTerm + ZeroOrMore( PLUS + stringTerm ) # define a parse action, to be invoked every time a string expression is found def interpolateTerms(originalString,locn,tokens): out = [] refs = [] terms = tokens for term in terms: if isinstance(term,QuotedLit): out.append( term.content ) elif isinstance(term,VarRef): out.append( "%s" ) refs.append( term.content ) else: print "hey! this is impossible!" # generate string to be interpolated, and interp operator outstr = "'" + "".join(out) + "' % " # generate interpolation argument tuple if len(refs) > 1: outstr += "(" + ",".join(refs) + ")" else: outstr += ",".join(refs) # return generated string (don't forget leading = sign) return "= " + outstr stringExpr.setParseAction( interpolateTerms ) print "Original:", print testLines print print "Modified:", print stringExpr.transformString( testLines ) # define slightly different parse action, to use list join instead of string interp def createListJoin(originalString,locn,tokens): out = [] terms = tokens for term in terms: if isinstance(term,QuotedLit): out.append( "'" + term.content + "'" ) elif isinstance(term,VarRef): out.append( term.content ) else: print "hey! this is impossible!" # generate string to be interpolated, and interp operator outstr = "[" + ",".join(out) + "]" # return generated string (don't forget leading = sign) return "= ''.join(" + outstr + ")" del stringExpr.parseAction[:] stringExpr.setParseAction( createListJoin ) print print "Modified (2):", print stringExpr.transformString( testLines ) ================ Prints out: Original: self.source += '

    ' + paragraph + '

    \n\n' listItem1 = '
  • ' + someText + '
  • ' listItem2 = '
  • ' + someMoreText + '
  • ' self.source += '
      ' + listItem1 + '\n' + listItem2 + '\n' + '
    \n\n' Modified: self.source += '

    %s

    \n\n' % paragraph listItem1 = '
  • %s
  • ' % someText listItem2 = '
  • %s
  • ' % someMoreText self.source += '
      %s\n%s\n
    \n\n' % (listItem1,listItem2) Modified (2): self.source += ''.join(['

    ',paragraph,'

    \n\n']) listItem1 = ''.join(['
  • ',someText,'
  • ']) listItem2 = ''.join(['
  • ',someMoreText,'
  • ']) self.source += ''.join(['
      ',listItem1,'\n',listItem2,'\n','
    \n\n']) ================ From johnjsal at NOSPAMgmail.com Sun May 7 23:14:23 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 07 May 2006 23:14:23 -0400 Subject: utility functions within a class? In-Reply-To: <1147055211.899384.323190@v46g2000cwv.googlegroups.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> Message-ID: <445eb889$0$13297$c3e8da3@news.astraweb.com> jeffshannon at gmail.com wrote: > Even if you don't end up referring to self or any instance > attributes within the method, it's simpler to keep it as a normal > method. Thanks, that makes sense to me! So basically just create them as methods, and if I want a little 'privacy' I can lead with an underscore? Somehow that sounds like the right idea... :) From Symantec_Mail_Security_for_SMTP at hu.edu.jo Tue May 9 02:09:30 2006 From: Symantec_Mail_Security_for_SMTP at hu.edu.jo (Symantec_Mail_Security_for_SMTP at hu.edu.jo) Date: Tue, 9 May 2006 08:09:30 +0200 (CEST) Subject: =?utf-8?B?RGVsaXZlcnkgZmFpbHVyZSBub3RpZmljYXRpb25=?= Message-ID: <20060509060930.391271E400C@bag.python.org> Your message with Subject: could not be delivered to the following recipients: john at ait.ac.th Please do not resend your original message. Delivery attempts will continue to be made for 5 day(s). From george.sakkis at gmail.com Sat May 20 18:39:07 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 20 May 2006 15:39:07 -0700 Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <1148073990.938267.320410@38g2000cwa.googlegroups.com> Message-ID: <1148164747.641393.68350@g10g2000cwb.googlegroups.com> Edward Elliott wrote: > John Bokma wrote: > > > Edward Elliott wrote: > > > >> A little out-of-order execution seems useful here. ;) > > > > No, not interested in a pissing contest. Your statement that the Perl > > community encourages importing is *encouraged* (over using OO without > > importing) is false. > > The cookbook says otherwise. So it depends how you define community. > > You lecturing people on pissing contests, that's rich. Nice way to duck the > issue and sound like a winner. Wake me when you decide to address the > substance of my arguments. > > -- > Edward Elliott > UC Berkeley School of Law (Boalt Hall) > complangpython at eddeye dot net Not trying to be as ass, but can you take this offline or at least in a perl newsgroup ? Arguing on a particular fact or speculation about the perl community is rather unproductive and offtopic for a python newsgroup. Thanks, George From ursache.marius at gmail.com Sun May 7 06:53:07 2006 From: ursache.marius at gmail.com (Marius Ursache) Date: 7 May 2006 03:53:07 -0700 Subject: md5 from python different then md5 from command line References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> Message-ID: <1146999187.874299.40390@j33g2000cwa.googlegroups.com> > echo adds a newline: > > >>> import md5 > >>> test = md5.new("marius\n") > >>> print test.hexdigest() > 0f0f60ac801a9eec2163083a22307deb > > Just Thanks, that was it ;) From rschroev_nospam_ml at fastmail.fm Sun May 21 17:41:05 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Sun, 21 May 2006 21:41:05 GMT Subject: Python - Web Display Technology In-Reply-To: <1148223307.073050.33710@y43g2000cwc.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> Message-ID: SamFeltus schreef: > Here is a visual argument, I would love to see a list of AJAX and SVG > sites that display excellent graphics. > http://bacardimojito.com/main.swf > http://tokyoplastic.com/LF.swf > http://coolbreathpower.com/ > http://www.peterjoel.com/flash8previews/candleFlame.html > http://shiroganeya.co.jp/main_en.html > http://samfeltus.com/swf/contact_globes.swf > http://justforthefofit.com/ > http://mochiland.com/ > http://obleek.com/iraq/index.html > http://www.flashbum.com/v4/ > http://spaceinvaders.de/ (example of antiquated graphics simply handled > by Flash) In my humble opinion, those sites are an argument _against_ the use of Flash on websites. They may look pretty (I don't think they do, but I can imagine there are people out there who like the looks of those sites), but they fail as websites: long load times and especially such horrible navigation is a big no-no. I guess there is a place for Flash, but it's certainly not appropriate as an alternative for websites. I admit that they _can_ be useful as objects on a pages, for example the games on the last site you mention. But please don't use Flash to design the website itself. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From http Fri May 26 18:37:18 2006 From: http (Paul Rubin) Date: 26 May 2006 15:37:18 -0700 Subject: Thread vs. generator problem Message-ID: <7xodxkmmzl.fsf_-_@ruckus.brouhaha.com> As I understand it, generators are supposed to run til they hit a yield statement: import time def f(): print 1 time.sleep(3) for i in range(2,5): yield i for k in f(): print k prints "1" immediately, sleeps for 3 seconds, then prints 2, 3, and 4 without pausing, as expected. When I try to do it in a separate thread: import time, itertools def remote_iterate(iterator, cachesize=5): # run iterator in a separate thread and yield its values q = Queue.Queue(cachesize) def f(): print 'thread started' for x in iterator: q.put(x) threading.Thread(target=f).start() while True: yield q.get() g = remote_iterate(itertools.count) print 'zzz...' time.sleep(3) print 'hi' for i in range(5): print g.next() I'd expect to see 'thread started' immediately, then 'zzz...', then a 3 second pause, then 'hi', then the numbers 0..4. Instead, the thread doesn't start until the 3 second pause has ended. When I move the yield statement out of remote_iterate's body and instead have return a generator made in a new internal function, it does what I expect: import time, itertools def remote_iterate(iterator, cachesize=5): # run iterator in a separate thread and yield its values q = Queue.Queue(cachesize) def f(): print 'thread started' for x in iterator: q.put(x) threading.Thread(target=f).start() def g(): while True: yield q.get() return g() Any idea what's up? Is there some race condition, where the yield statement freezes the generator before the new thread has started? Or am I just overlooking something obvious? Thanks. From david.bear at asu.edu Thu May 11 16:51:27 2006 From: david.bear at asu.edu (David Bear) Date: Thu, 11 May 2006 13:51:27 -0700 Subject: calling perl modules from python Message-ID: <1690502.fNiZoSDNhf@teancum> I have a hash function written by another organization that I need to use. It is implemented in perl. I've been attempting to decode what they are doing in their hash function and it is taking way too long. I've identified two functions in a perl module that I would like to 'call' from a python program. I found the following: http://www.annocpan.org/~GAAS/pyperl-1.0/perlmodule.pod and wondered if anyone had any comments. This thing implements a perl interpreter inside python. That seems like overkill to me. I wonder what wisdom this group can offer. -- David Bear -- let me buy your intellectual property, I want to own your thoughts -- From perlefar at gmail.com Wed May 24 18:52:57 2006 From: perlefar at gmail.com (Zameer) Date: 24 May 2006 15:52:57 -0700 Subject: Best way to handle exceptions with try/finally In-Reply-To: References: <1148481073.976420.316970@j55g2000cwa.googlegroups.com> Message-ID: <1148511177.319796.228280@g10g2000cwb.googlegroups.com> > I tend to put "return" > statements at the end of functions to make an attempt at being clean. I > realize that a lot of the time functions will just return but I was > hoping by explicitly stating my function returns that another person > reading my code would more easily see any exit points in my code. Turns > out that it came to bite me later. You can put the return statement at the end. try: stuff() finally: cleanup() return The return statement is not necessary in this case, but it's not in the finally part either. If you like it, keep it. Just don't make it part of finally if you want exceptions to propagate. I can see where you are going by making the return statement part of finally, and I actually expected it to work the same as if it was not part of finally. Turns out it doesn't. Can somebody please comment on how this works in other languages? I know that finally is not a part of standard C++ but Borland and Microsoft compilers allow use of the keyword __finally. Delphi also has finally and I seem to recall that returning from the finally part does not prevent the exception from propagating, but memory may not serve me right. Thank you for "raising" this quite interesting question. From fredrik at pythonware.com Wed May 3 09:07:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 15:07:41 +0200 Subject: Sorting a list of dictionaries by dictionary key References: <4458A61F.3010004@gmail.com> Message-ID: Nico Grubert wrote: > I am looking for a way to sort a list containing dictionaries. > > This is my example list: > [{'Title': 'ABC', 'from_datetime': DateTime('2006/04/25 12:45:00 > GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 > 12:45:00 GMT+2')}, {'Title': 'GHI', 'from_datetime': > DateTime('2006/03/10 12:45:00 GMT+2')}] > > I want to sort the list by dictionary's key 'from_datetime' so the > sorted list should be: > > [{'Title': 'GHI', 'from_datetime': DateTime('2006/03/10 12:45:00 > GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 > 12:45:00 GMT+2')}, {'Title': 'ABC', 'from_datetime': > DateTime('2006/04/25 12:45:00 GMT+2')}] > > Any idea how I can sort this list? assuming that DateTime returns something that compares correctly, you can do something like: def sortkey(item): return item.get("from_datetime") data.sort(key=sortkey) (assuming Python 2.4 or later) From siona at chiark.greenend.org.uk Thu May 11 09:14:39 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 May 2006 14:14:39 +0100 (BST) Subject: Python memory deallocate References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> Message-ID: <-yy*V4mgr@news.chiark.greenend.org.uk> wrote: >If I write: > >a = range(500*1024) > >I see that python process allocate approximately 80Mb of memory. >What can i do for DEALLOCATE this memory, or good part of this? > [ ... ] >I've tried with Destroy, del command, but the memory don't show down. It won't (much). When an object gets garbage collected Python will keep hold of the memory and reuse it. Note how much memory your process is using after assigning a above, then: >>> del a Of course, you've seen this doesn't release back to the OS all the memory being that was being used. But now do: >>> a = range(500*1024) and you'll see that you're using no more memory than you were after the first assignment. If your memory usage keeps on growing then either (a) your program needs that much memory for the data, and you'll just have to stick more in your box or deal with swapping if this is causing you a problem or (b) you've got some stray references left over to objects you think you've deleted. -- \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 vinay_sajip at yahoo.co.uk Wed May 31 18:05:13 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 31 May 2006 15:05:13 -0700 Subject: logging In-Reply-To: References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> Message-ID: <1149113113.083677.235570@i39g2000cwa.googlegroups.com> ibr at radix50.net wrote: > Hello Vinay, > > Hmm, log1 decides once whether to print an event, and after that it gets > printed in log1 and all its ancestors, regardless of their level? I find > this quite counter-intuitive. I'd instead expect that each logger > decides whether to print an event according to its own level. Could you > give an example why one would want the python behavior? Loggers are hierarchical for a reason - not just randomly named channels. Just as it is generally useful to develop a system by modularising it into subsystems, packages, modules, etc. so it is useful when logging to follow a parallel hierarchy. The audiences for the logging events are orthogonal to the events themselves, and the way the logging module is organised reflects good practice as determined by practical experience over a period of time. The approach you're questioning is not specific to Python - log4j (which inspired Python's logging), and the logging built into Java 1.4, also work this way. Practically, this makes configuration a lot simpler; if I want to log everything to console, I just attach a handler to the root logger, and I never have to worry about attaching to every single logger. (Logger names are generally not cast in stone - I might break down a module's logic into smaller pieces and thus introduce new logger names to describe events in the refactored module. I certainly don't want to change my logging configuration every time I refactor my code.) May I suggest you review the log4j documentation to get a better exposition of the principles which govern the design of such logging systems. From jdhunter at ace.bsd.uchicago.edu Tue May 9 11:46:43 2006 From: jdhunter at ace.bsd.uchicago.edu (John Hunter) Date: Tue, 09 May 2006 10:46:43 -0500 Subject: two of pylab.py References: <87bqu75zrb.fsf@localhost.localdomain> <4cb5jmF15873jU1@uni-berlin.de> Message-ID: <873bfji4kc.fsf@peds-pc311.bsd.uchicago.edu> >>>>> "Diez" == Diez B Roggisch writes: >> I use debian/testing linux Linux debian/testing 2.6.15-1-686 >> >> I found some duplicate files in my system, I don't if the are >> both needed, should I delete one of the groups below and which >> one? site-packages/pylab.py is just there for convenience to import matplotlib.pylab, since it is easier to type >>> import pylab rather than >>> import matplotlib.pylab You should leave all of the file as is, because code will assume both are there. JDH From luismgz at gmail.com Wed May 24 13:09:22 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 24 May 2006 10:09:22 -0700 Subject: IronPython 1.0 Beta 7 Released Message-ID: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> Check it out: http://www.gotdotnet.com/workspaces/workspace.aspx?id=ad7acff7-ab1e-4bcb-99c0-57ac5a3a9742 From s.steffann at computel.nl Fri May 26 09:30:53 2006 From: s.steffann at computel.nl (Sander Steffann) Date: Fri, 26 May 2006 15:30:53 +0200 Subject: John Bokma harassment In-Reply-To: Message-ID: <2B1A983EDCEC3447B22632B64F72646014EA29@bill.office.computel.nl> From: John Bokma > dreamhost has made a decission, a right one IMO. And now you > ask people to harass them more? > > You really are just a pathetic little shit now aren't you? > Not even the balls nor the guts to fix the issue that you are. Using language like this clearly shows who has a communication problem... Please use decent language or shut up - Sander From satishkumar.gourabathina at gmail.com Fri May 26 01:32:34 2006 From: satishkumar.gourabathina at gmail.com (satish) Date: 25 May 2006 22:32:34 -0700 Subject: Can any body help me Message-ID: <1148621554.184942.155430@38g2000cwa.googlegroups.com> how to write script for these 1.Given a test file containing lines of words such as (abc, abb, abd,abb, etc), write a script that prints, in order of frequency, how many times each word appears in the file. 2. Write a script running in an endless loop that pings an IP (specified on the command line) periodically. If the IP goes down n times in a row send one email message (to an address specified on the command line) that it's down (n is specified on the command line). Once it's available again n times in a row send an email that it's back up. When a specific signal is sent to the script it sends and email saying that it is shutting down and then exits thanx satish From dan.gass at gmail.com Thu May 18 09:09:40 2006 From: dan.gass at gmail.com (dan.gass at gmail.com) Date: 18 May 2006 06:09:40 -0700 Subject: Which is More Efficient? In-Reply-To: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> Message-ID: <1147957780.445241.6090@38g2000cwa.googlegroups.com> Measure it and find out. Sounds like a little investment in your time learning how to measure performance may pay dividends for you. From nobody at 127.0.0.1 Thu May 11 18:41:54 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 11 May 2006 22:41:54 GMT Subject: Reg Ex help References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> <4463a7be$0$290$626a54ce@news.free.fr> Message-ID: Bruno Desthuilliers wrote: > don a ?crit : >> Also if there is a better way than using regex, please let me know. > > s ="/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT > from /main/parallel_branch_1/release_branch_1.0/4" > parts = s.replace(' ', '/').strip('/').split('/') > branch = parts[parts.index('CHECKEDOUT') - 1] I wouldn't call these better (or worse) than regexes, but a slight variation on the above: marker = s.index('/CHECKEDOUT') branch = s [s.rindex('/', 0, marker) + 1 : marker] This version will throw exceptions when the marker isn't found, which may or may not be preferable under the circumstances. From onurb at xiludom.gro Tue May 9 04:51:25 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 10:51:25 +0200 Subject: utility functions within a class? In-Reply-To: <445ec3d4$0$1965$c3e8da3@news.astraweb.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> Message-ID: <4460586d$0$11335$636a55ce@news.free.fr> John Salerno wrote: > blair.bethwaite at gmail.com wrote: > >> I'm having trouble deciphering what this bit means - "but these >> functions will be called from another method in the class, not from the >> instance itself", I don't think it makes sense. > > > Yeah, I'm starting to see that as I tried to implement it. Here's what I > came up with, which works: > > def generate(self, filename): > self.head = self.generate_head() > self.body = self.generate_body() > > So the two generate_* methods are called from within another class > method, here, generate() is *not* a class method, it's an instance method (which is the default). > and it seemed necessary to still call them from an instance. > What I originally meant was that they would not be called from an > instance *outside* the class itself, i.e. they won't be used when > writing another script, they are only used by the class itself. Yeps, that's pretty common in any OO language. In most mainstream OOPLs, these methods would have the 'protected' access restriction modifier. In Python, we rely on the convention that an attribute whose name is prefixed with a single underscore is an implementation detail - not part of the API - and should not be called by client code. Just renaming these two methods is enough to warn users of your code that they're on their own if they start messing with them. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sybrenUSE at YOURthirdtower.com.imagination Thu May 18 11:18:23 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 18 May 2006 17:18:23 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <1147961355.652526.230610@i39g2000cwa.googlegroups.com> Message-ID: SamFeltus enlightened us with: > I guess there isn't much to understand. If you are satisfied with a > text based, static image web, that is light on artistic > possabilities, all that HTML stuff is acceptable. You don't need Flash to be artistic. > Perhaps the HTML/JS group will even get off their rear ends and > bring some decent cross platform graphics capabilities to the web > one decade? Perhaps you can get Mickeysoft to get SVG support in their browser. > WC3 at Work - Beware Falling Luddites MSIE doesn't even properly support PNG files (at least last time I looked), so you should start blaming the people that actually don't implement all the goodies that are already there. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From john at castleamber.com Mon May 29 15:37:29 2006 From: john at castleamber.com (John Bokma) Date: 29 May 2006 19:37:29 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> Message-ID: ilitzroth at gmail.com wrote: >>"There is so much noise we can't hear each other, but I will defend >>to the death a chance to get heard for whatever you might have to say >>that's intelligent (while not necessarily from your own mouth)". > > You write a much cooler quote! > >>Besides, it is not clear that Voltaire really said that. > > No? well I guess it's alright to harrass Xah then. Your first question should be: Is it alright that Xah harasses 5 newsgroups? Or maybe work on your spelling, harass is with one r, but maybe you didn't read the subject, which wouldn't amaze me, since you sound like you should be spending time on MySpace OMG!. -- 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 rdh at new.rr.com Fri May 26 14:52:21 2006 From: rdh at new.rr.com (DataSmash) Date: 26 May 2006 11:52:21 -0700 Subject: Linking onClick event to other controls on the Frame Message-ID: <1148669541.274757.136760@i40g2000cwc.googlegroups.com> Hello, I've created a simple form with 2 radio boxes, 2 text boxes and a button. When I click the button, I'd like to write each "choice" to a text file. I can't figure out how to "link" the onClick event to the other 4 controls. Any help would be much appreciated! R.D. Harles import wx, sys class Form1(wx.Panel): def __init__(self, parent, id): wx.Panel.__init__(self, parent, id) # Create button self.button =wx.Button(self, 50, "GO!", wx.Point(20, 200)) wx.EVT_BUTTON(self, 50, self.OnClick) ## First name # Edit control self.lblname = wx.StaticText(self, -1, "First Name :",wx.Point(20,50)) self.editname = wx.TextCtrl(self, 10, "", wx.Point(90, 50), wx.Size(100,-1)) wx.EVT_TEXT(self, 10, self.EvtText) ## Last Name # Edit control self.lblname = wx.StaticText(self, -1, "Last Name :",wx.Point(20,75)) self.editname = wx.TextCtrl(self, 20, "", wx.Point(90, 75), wx.Size(100,-1)) wx.EVT_TEXT(self, 20, self.EvtText) # Radio Boxes self.radioList = ['Employed', 'Unemployed'] rb = wx.RadioBox(self, 30, "Status:", wx.Point(20, 100), wx.DefaultSize, self.radioList, 2, wx.RA_SPECIFY_COLS) wx.EVT_RADIOBOX(self, 30, self.EvtRadioBox) # Radio Boxes self.radioList = ['Married', 'Single'] rb = wx.RadioBox(self, 40, "Status:", wx.Point(20, 150), wx.DefaultSize, self.radioList, 2, wx.RA_SPECIFY_COLS) wx.EVT_RADIOBOX(self, 40, self.EvtRadioBox) # Text event def EvtText(self, event): print event.GetString() # RadioBox event def EvtRadioBox(self, event): print event.GetId() # Button event def OnClick(self,event): print "Writing job.cfg..." file = open("job.cfg", "w") file.write("") app = wx.PySimpleApp() frame = wx.Frame(None, -1, " Questions") Form1(frame,-1) frame.Show(1) app.MainLoop() From robert.kern at gmail.com Thu May 18 20:35:26 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 May 2006 19:35:26 -0500 Subject: WTF? Printing unicode strings In-Reply-To: References: <1147992722.970761.220840@j73g2000cwa.googlegroups.com> Message-ID: Ron Garret wrote: > In article , > Robert Kern wrote: > >>Ron Garret wrote: >> >>>I'm using an OS X terminal to ssh to a Linux machine. >> >>Click on the "Terminal" menu, then "Window Settings...". Choose "Display" >>from >>the combobox. At the bottom you will see a combobox title "Character Set >>Encoding". Choose "Unicode (UTF-8)". > > It was already set to UTF-8. Then take a look at your LANG environment variable on your Linux machine. For example, I have LANG=en_US.UTF-8 on my Linux machine, and I can ssh into it from a UTF-8-configured Terminal.app and print unicode strings just fine. -- 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 May 18 18:59:01 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 May 2006 00:59:01 +0200 Subject: newb: comapring two strings In-Reply-To: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> Message-ID: <4d4chmF185ohoU1@uni-berlin.de> > Is there a clever way to see if two strings of the same length vary by > only one character, and what the character is in both strings. > > E.g. str1=yaqtil str2=yaqtel > > they differ at str1[4] and the difference is ('i','e') > > But if there was str1=yiqtol and str2=yaqtel, I am not interested. > > can anyone suggest a simple way to do this? Use the levenshtein distance. http://en.wikisource.org/wiki/Levenshtein_distance > My next problem is, I have a list of 300,000+ words and I want to find > every pair of such strings. I thought I would first sort on length of > string, but how do I iterate through the following: > > str1 > str2 > str3 > str4 > str5 > > so that I compare str1 & str2, str1 & str3, str 1 & str4, str1 & str5, > str2 & str3, str3 & str4, str3 & str5, str4 & str5. decorate-sort-undecorate is the idion for this l = l = [(len(w), w) for w in l] l.sort() l = [w for _, w in l] Diez From deets at nospam.web.de Tue May 2 13:25:18 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 May 2006 19:25:18 +0200 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> Message-ID: <4bpj08F12b91rU1@uni-berlin.de> John Salerno wrote: > Diez B. Roggisch wrote: > >> I can't imagine what you're actually after here, but assuming that you >> really need this > > Hard to explain because I'm still trying to figure out how to do it > myself. I'm trying to solve a little puzzle using Python, even though > I'm sure it's not necessary. Basically W, X, Y and Z are propositions > that are either true or false, and the puzzle lists a few statements > such as "Exactly one of X, Y and Z is true", and I'm trying to work out > a little algorithm that might test for this kind of stuff. Then use a Proposition-class that holds the actual value. > Another thing I'm trying to do is write a function that tests to see if > a list contains exactly one true item, and the rest are false (obviously > this would have to be a list of boolean values, I guess). No - you can for example override the comparison-semantics on the Proposition-class to be comparable with True/False with the proper semantics: class Proposition(object): def __init__(self, v): self._v = v def __eq__(self, o): return self._v == o TrueProposition = Proposition(True) FalseProposition = Proposition(False) print True == TrueProposition print False == TrueProposition print False == FalseProposition Diez From bnblazer at gmail.com Mon May 22 21:06:13 2006 From: bnblazer at gmail.com (Brian) Date: 22 May 2006 18:06:13 -0700 Subject: Too big of a list? and other problems References: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> Message-ID: <1148346373.860105.101860@j55g2000cwa.googlegroups.com> Thank you for your insight. It appears that using .extend rather than .append solved the problem. Brian From chris.cavalaria at free.fr Thu May 18 10:05:17 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 16:05:17 +0200 Subject: Question about exausted iterators In-Reply-To: References: <446b48e2$0$5293$626a54ce@news.free.fr> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> Message-ID: <446c7f44$0$7128$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > Christophe wrote: > >> Because I'm still waiting for a valid answer to my question. The >> answer "Because it has been coded like that" or is not a valid one. > > > it's been coded like that because that's what the specification says: > > http://www.python.org/dev/peps/pep-0234/ I didn't though I had to mention that "Because the spec has been writen like that" wasn't a valid answer either. From george.sakkis at gmail.com Fri May 26 13:01:36 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 26 May 2006 10:01:36 -0700 Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> <1148650269.190130.209840@i39g2000cwa.googlegroups.com> <44772b4c$0$312$626a54ce@news.free.fr> Message-ID: <1148662896.693077.213140@u72g2000cwu.googlegroups.com> Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > The thing is there are four (at least?) ways to get a dict instance: > > > > In [1]: d1={'name':'mike', 'age':23} > > > > In [2]: d2=dict(d1) > > > > In [3]: d3=dict(**d1) > > > > In [4]: d4=dict(d1.items()) > > > > In [5]: d1==d2==d3==d4 > > Out[5]: True > > > > Talk about "there should be one and preferably one obvious way to do > > it". > > > > This actually makes 2 (two) ways of creating a dict: > - the default call to type (ie : dict(...) > - the syntactic sugar dict-litteral syntax. > > The fact that dict() takes either a sequence of pairs and/or keyword > args (yes, you can use both at once) doesn't make for 2 distinct ways. > And the second syntax (litteral) is nothing else than syntaxic sugar - > read : a special case. So if we are to get rid of one or the other, it's > the dict-litteral syntax that should go away. > > > > >>>Perhaps it's something that should be reconsidered for Py3K > >> > >>Hopefully not. The fact that you fail to understand why a given feature > >>exists and how it can be useful is not a reason to ask for arbitrary > >>restrictions on the language. > > > > > > Perhaps you fail to understand that the given feature is > > 1) redundant (see above). > > see above for an answer on this. FWIW, there are a *lot* of other > syntactic-sugar redundancy in Python. Most of which you're probably not > even aware of. Even without the syntactic-sugar form, I fail to see why you seem to think that dict(items), dict(otherdict) and dict(**kwds) are all one thing. > > 2) restricting in a more serious sense: the future addition of optional > > keyword arguments that affect the dict's behaviour. > > This has already been discussed, and IIRC no-one managed to make a > *serious* point about it. The actual signature of dict() is perfectly > sensible for 99% of uses case, and I *never* had a need for "keyword > arguments that affect the dict's behaviour" in 6+ years of Python > programming. > > If you want another behaviour, feel free to subclass dict or implement > your own dict-like - FWIW, that's what I do when the need arises. Me too, but I'd gladly toss them if one day dicts were extended to accept, say a default value or ordering. Plus, adding new functionality by subclassing often leads to combinatorial explosion (think of "class OrderedDefaultPrettifiedDict(defaultdict, odict, prettydict)"). George From greg.kujawa at gmail.com Mon May 15 14:01:50 2006 From: greg.kujawa at gmail.com (gregarican) Date: 15 May 2006 11:01:50 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147716110.595988.283140@j73g2000cwa.googlegroups.com> Peter Decker wrote: > Funny, I was going to say that the problem is when the author prefers > a font with a differntly-sized space. Some of us got rid of editing in > fixed-width fonts when we left Fortran. Don't know what all of the hub-bub here is regarding tab/space indentation. My punched cards break down such matters as in quite fine fashion :-/ From drevil_53711 at yahoo.com Mon May 22 14:39:34 2006 From: drevil_53711 at yahoo.com (Steve Young) Date: Mon, 22 May 2006 11:39:34 -0700 (PDT) Subject: manual http request Message-ID: <20060522183934.80428.qmail@web36507.mail.mud.yahoo.com> Hi, I was wondering if there's a way to mimic a web pages' form and just manually send the http request and get the html response without having to go through a browser. For example, lets say i wanted to make a search on google of the key word "cars" but i want to be able to get the results of the search without having to go to google and typing it in and submiting it. Thanks. -Steve --------------------------------- Sneak preview the all-new Yahoo.com. It's not radically different. Just radically better. -------------- next part -------------- An HTML attachment was scrubbed... URL: From gavinpaterson at yahoo.com Tue May 9 04:39:40 2006 From: gavinpaterson at yahoo.com (gavinpaterson) Date: Tue, 09 May 2006 08:39:40 -0000 Subject: Embedding Python Message-ID: Dear Pythoners, I am writing as I am having trouble embedding a Python program into a Win XP C++ console application. I have written a script file for importing and I am trying to use the example for "Pure Embedding" found in the product documentation. The program fails to successfully execute past the line: if (pFunc && PyCallable_Check(pFunc)) I have checked the pFunc pointer at runtime and it is not null so I assume that the PyCallable_Check fails. If I define my function in python in file "multiply.py" as: def multiply(a,b): print "Will compute", a, "times", b c = 0 for i in range(0, a): c = c + b return c Then in VC++ I call the program with arguments: multiply multiply 23 3 Then I'd expect a successful result, the file seems to be getting parsed if multiply.pyc is available, but the function multiply does not seem to be callable - where am I going wrong? From gslindstrom at gmail.com Mon May 8 09:58:49 2006 From: gslindstrom at gmail.com (Greg Lindstrom) Date: Mon, 8 May 2006 08:58:49 -0500 Subject: Scaled Vector Graphics Message-ID: <57aa55060605080658p48c6ddd0g71bc88201909e867@mail.gmail.com> I have been asked to write a routine to merge documents in pfd and svg formats into a single file (preferably pfd format). Currently we send the pdf image to the printer followed by the svg image (a scan of a health care claim) but this is not a satisfactory solution. We have as many as 3000 document pairs daily (another project in development will send all the information to out clients electronically via EDI X12 format). Does Python offer support for working with svg files? I've looked at the PIL and Reportlab packages and Googled around but have not found anything. My other option is to snag one of the routines I've found that claim to convert scg to pdf and then merge them as pdf files. Any help or suggestions you may supply will be greatly appreciated, Greg Lindstrom NovaSys Health Little Rock, Arkansas (USA) -------------- next part -------------- An HTML attachment was scrubbed... URL: From timr at probo.com Thu May 11 01:58:34 2006 From: timr at probo.com (Tim Roberts) Date: Thu, 11 May 2006 05:58:34 GMT Subject: python rounding problem. References: Message-ID: "chun ping wang" wrote: > >Hey i have a stupid question. > >How do i get python to print the result in only three decimal place... > >Example>>> round (2.995423333545555, 3) >2.9950000000000001 > >but i want to get rid of all trailing 0's..how would i do that? Your "problem" is not a problem in real programs -- it's only a problem because of the way the interactive interpreter works: C:\WINDOWS>python Python 2.4.1 (#65, Mar 30 2005, 09:13:57) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> round(2.99543322,3) 2.9950000000000001 >>> print round(2.99543322,3) 2.995 >>> -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From vbgunz at gmail.com Mon May 8 09:09:38 2006 From: vbgunz at gmail.com (vbgunz) Date: 8 May 2006 06:09:38 -0700 Subject: Python CHM Doc Contains Broken Links on Linux in xCHM. In-Reply-To: <1147079616.383506.257220@j73g2000cwa.googlegroups.com> References: <1147025957.253391.125240@i40g2000cwc.googlegroups.com> <1147079616.383506.257220@j73g2000cwa.googlegroups.com> Message-ID: <1147093778.214292.181910@i39g2000cwa.googlegroups.com> Thank you Razvan. You're right. I downloaded the 1.7.1 source and built it and the links do work just fine. Thank you for pointing that out! From No.Spam at Spam.none Wed May 10 01:06:49 2006 From: No.Spam at Spam.none (I. Myself) Date: Wed, 10 May 2006 05:06:49 GMT Subject: SciPy - I need an example of use of linalg.lstsq() Message-ID: And it has to run on Windows, so it can't use xplt. I would prefer that it use the simplest multi-dimensional model, z = k + a*x1 + b*x2 + c*x3 + d*x4 Anyone have such a thing? Thanks, Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From phddas at yahoo.com Tue May 9 07:03:31 2006 From: phddas at yahoo.com (Gary Wessle) Date: 09 May 2006 21:03:31 +1000 Subject: installing numpy Message-ID: <877j4v5ukc.fsf@localhost.localdomain> Hi I am trying to install NumPy in my debian/testing linux 2.6.15-1-686. with no numpy for debian/testing, I am left alone, since the experimental version available by debian will result in a dependency nightmares, so after unpacking the downloaded file "numpy-0.9.6.tar.gz" which crated a directory in my home directory called numpy-0.9.6 with **************************************************************** -rw-r--r-- 1 fred fred 1537 2006-01-21 19:12 LICENSE.txt -rw-r--r-- 1 fred fred 246 2006-01-22 12:44 MANIFEST.in drwxr-xr-x 11 fred fred 4096 2006-05-08 20:06 numpy -rw-r--r-- 1 fred fred 1472 2006-03-14 19:27 PKG-INFO -rw-r--r-- 1 fred fred 476 2006-01-07 08:29 README.txt -rw-r--r-- 1 fred fred 1164 2006-05-08 20:06 semantic.cache -rwxr-xr-x 1 fred fred 2516 2006-03-13 18:02 setup.py **************************************************************** **************************************************************** $cat README.txt ... To install: python setup.py install The setup.py script will take advantage of fast BLAS on your system if it can find it. You can help the process with a site.cfg file. If fast BLAS and LAPACK cannot be found, then a slower default version is used. ... **************************************************************** do I issue the command above "python setup.py install" from the unpacked directory numpy-0.9.6, would it put the packages in the correct places in my system, I was under the impression that a numpy.py is unpacked and then I place it the sys.path but this is not the case here. thanks From deets at nospam.web.de Thu May 4 08:35:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 May 2006 14:35:25 +0200 Subject: Python function returns: References: Message-ID: <4buap6F12pcheU2@uni-berlin.de> Michael Yanowitz wrote: > I am still new to Python but have used it for the last 2+ months. > One thing I'm still not used to is that functions parameters can't > change as expected. For example in C, I can have > status = get_network_info (strIpAddress, &strHostname, &nPortNumber) > where this fictitious function returns a status, but also returns > modified > values for a hostname and a port number. > In Python, there does not seem to be an easy way to have functions > return > multiple values except it can return a list such as: > strHostname, nPortNumber, status = get_network_info (strIpAddress, > strHostname, > nPortNumber) > Am I missing something obvious? Is there a better, or more standard way > to return values from functions? No, that exactly is the way to go. But usually one uses tuples and the possibility of sequence-unpacking together to reach a solution tha at least to my eye looks more favorable: def foo(a, b): return a*b, a+c a = 10 b = 20 a, b = foo(a, b) Diez From onurb at xiludom.gro Wed May 10 11:25:54 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 10 May 2006 17:25:54 +0200 Subject: Memory leak in Python In-Reply-To: <1147225282.478996.134910@i39g2000cwa.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <44605dd1$0$2056$626a54ce@news.free.fr> <1147225282.478996.134910@i39g2000cwa.googlegroups.com> Message-ID: <44620664$0$11339$636a55ce@news.free.fr> diffuser78 at gmail.com wrote: (top-post corrected) > > bruno at modulix wrote: > >>diffuser78 at gmail.com wrote: >> >>>I have a python code which is running on a huge data set. After >>>starting the program the computer becomes unstable and gets very >>>diffucult to even open konsole to kill that process. What I am assuming >>>is that I am running out of memory. >>> >>>What should I do to make sure that my code runs fine without becoming >>>unstable. How should I address the memory leak problem if any ? I have >>>a gig of RAM. >>> >>>Every help is appreciated. >> >>Just a hint : if you're trying to load your whole "huge data set" in >>memory, you're in for trouble whatever the language - for an example, >>doing a 'buf = openedFile.read()' on a 100 gig file may not be a good >>idea... >> > > The amount of data I read in is actually small. So the problem is probably elsewhere... Sorry, since you were talking about huge dataset, the good old "read-whole-file-in-memory" antipattern seemed an obvious guess. > If you see my algorithm above it deals with 2000 nodes and each node > has ot of attributes. > > When I close the program my computer becomes stable and performs as > usual. I check the performance in Performance monitor and using "top" > and the total memory is being used and on top of that around half a gig > swap memory is also being used. > > Please give some helpful pointers to overcome such memory errors. A real memory leak would cause the memory usage to keep increasing as long as your program is running. If this is not the case, it's not a "memory error", but a design/program error. FWIW, apps like Zope can end up using a whole lot of memory, but there's no known memory-leak problem AFAIK. And believe me, a Zope app can end up managing a *really huge lot* of objects (>= many thousands). > I revisited my code to find nothing so obvious which would let this > leak happen. How to kill cross references in the program. Using weakref and/or gc might help. FWIW, the default memory management in Python is based on reference-counting. As long as anything keeps a reference to an object, this object will stay alive. If you have lot of cross-references and 2000+ big objects, you may effectively end up eating all the ram and more. The gc module can detect and manage some cyclic references (obj A has a ref on obj B which has a ref on obj A). The weakref module uses 'proxy' references that let reference-counting do it's job (I guess the doc will be much more explicit than me). Another possible improvement could be to use the flyweight design pattern to share memory for some attributes : - a general (while somewhat Java-oriented) explanation: http://www.exciton.cs.rice.edu/JavaResources/DesignPatterns/FlyweightPattern.htm - two Python exemples (the second being based on the first) http://www.suttoncourtenay.org.uk/duncan/accu/pythonpatterns.html#flyweight http://push.cx/2006/python-flyweights HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bdesth.quelquechose at free.quelquepart.fr Thu May 4 18:08:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 May 2006 00:08:10 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <1146634135.469447.54670@j73g2000cwa.googlegroups.com> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> Message-ID: <445a4c8a$0$30092$636a55ce@news.free.fr> tsaar2003 at yahoo.com a ?crit : > Bruno Desthuilliers wrote: > >>tsaar2003 at yahoo.com a ?crit : >> >>>Hi Pythonians, >>> >>>To begin with I'd like to apologize that I am not very experienced >>>Python programmer so please forgive me if the following text does not >>>make any sense. >>> >>>I have been missing constants in Python language. >> >>Why so ? >> >>I guess you're talking about named (symbolic) constants ? If so, just >>follow the convention : a name in ALL_UPPERCASE is a constant (or at >>least will be treated as such by anyone not wanting to mess with your >>package's implementation). No need to add extra syntax here IMHO. > > > Hi Bruno, > > For example: > > >>>>A = [] # let's declare a "constant" here Uh ? That's the strangest idea I've ever seen - I mean, using an empty list as a constant... If you need your constant to be a sequence (while I can't imagine any reason to do so), use a tuple. (snip) > As you can see, the "constant" A can be modified this easily. But if > there were an intuitive mechanism to declare a symbol to be immutable, Don't worry about the symbol, use an immutable type !-) From rvtol+news at isolution.nl Sun May 7 05:20:02 2006 From: rvtol+news at isolution.nl (Dr.Ruud) Date: Sun, 7 May 2006 11:20:02 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> <445c8812$0$31639$e4fe514c@news.xs4all.nl> <7xhd43qkxq.fsf@ruckus.brouhaha.com> <7xd5erqk70.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin schreef: > a cryptographic PRNG seeded with good entropy is supposed to be > computationally indistinguishable from physical randomness Doesn't your "good entropy" include "physical randomness"? -- Affijn, Ruud "Gewoon is een tijger." From nikolai.hlubek at mailbox.tu-dresden.de Thu May 11 07:21:12 2006 From: nikolai.hlubek at mailbox.tu-dresden.de (Nikolai Hlubek) Date: Thu, 11 May 2006 13:21:12 +0200 Subject: Python editor recommendation. In-Reply-To: References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <44631E28.80405@mailbox.tu-dresden.de> Thomas Guettler wrote: > Am Tue, 09 May 2006 14:37:53 +0100 schrieb Dale Strickland-Clark: > > >>Vim. >>Everything else is Notepad. > > > Vi or vim are good for editing config files over ssh. For programming > I use XEmacs. Smelling napalm here. If you don't want to use vim you should give eric3 a try. Cheers, Nikolai -- "1984" is not a howto! From grante at visi.com Thu May 25 09:54:56 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 25 May 2006 13:54:56 -0000 Subject: how to use matplotlib contour()? References: <1279j0o8va1fq12@corp.supernews.com> Message-ID: <127bdpg9ar2rh8a@corp.supernews.com> On 2006-05-24, Robert Kern wrote: > Yes, unfortunately, much of the documentation was written by people who were > very familiar with the Matlab interfaces that these functions are emulating. Since I've never used matlab, I'm a bit clueless. >> For example one parameter is specied as "an array". No clue as >> to how many dimensions or what the axis are. >> >> In another place it says "the X,Y parameters specify the (x,y) >> coordinates of a surface". _How_ do they specify the surface? >> Are they just equal length lists of x and y coordinates that >> specify len(X) points. Or do they specify a len(X) x len(Y) >> grid of points? > >> Why would my Z values be a 2D array? > > contour() only does contouring on gridded data. That's what I was beginning to suspect. What confused me was that if it required gridded data, I expected the input parameters to specify a grid (e.g. for a 5x7 grid, the X parameter would be a vector of 5 values, and the Y parameter would be a vector of 7 values) rather than just lie on a grid. > If you want to handle scattered datapoints, you will have to > do some interpolation. > > http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data Thanks, that looks like exactly what I need. My next step was actually going to be to use the Delaunay triangulation module to interpolate the data onto a much finer grid. > So X, Y, and Z are all 2-D arrays laid out corresponding to > the grid that you have sampled. I thought the contour_demo.py > example was reasonably clear on this, but if you didn't get it > to run, then I can see why you wouldn't have read it. I did delete some code that was attempting to label the graph, and then it ran. The examples do use gridded data, but when I changed them to non-gridded data, it seemed to run fine. > Talking about this on matplotlib-users will probably get these > problems fixed faster: > > https://lists.sourceforge.net/lists/listinfo/matplotlib-users After I got the demos to run, it became apparent that the contour functions don't do what I want anyway, so it's all moot at this point. -- Grant Edwards grante Yow! YOW!! Now I at understand advanced visi.com MICROBIOLOGY and th' new TAX REFORM laws!! From jstroud at ucla.edu Mon May 29 22:35:01 2006 From: jstroud at ucla.edu (James Stroud) Date: Mon, 29 May 2006 19:35:01 -0700 Subject: How to use tk.call ? In-Reply-To: <1148944211.145450.46030@j33g2000cwa.googlegroups.com> References: <1148944211.145450.46030@j33g2000cwa.googlegroups.com> Message-ID: jerry.levan at gmail.com wrote: > > I can't find how too use tk.call, can anyone give me a clue as to how > to > solve my problem? py> from Tkinter import * py> tk = Tk() py> tk.tk py> tk.tk.call Also, any widget should have a tk (which has a call): py> b = Button(tk, text='button') py> b.tk py> b.tk.call > I have tried the following: > > self.table.bind("",self.table.tk.call(self.table._w,'yview','scroll',-5,'units') I haven't used Table, but are you sure that what you are calling "self.table" here actually has mouse focus? James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From fb at frank-buss.de Sun May 7 04:58:17 2006 From: fb at frank-buss.de (Frank Buss) Date: Sun, 7 May 2006 10:58:17 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> Message-ID: <1vspxcmldcqa5.t1b4abyraqom.dlg@40tude.net> Alex Martelli wrote: > I cannot conceive of one. Wherever within a statement I could write the > expression > lambda : body > I can *ALWAYS* obtain the identical effect by picking an otherwise > locally unused identifier X, writing the statement > def X(): body > and using, as the expression, identifier X instead of the lambda. This is true, but with lambda it is easier to read: http://www.frank-buss.de/lisp/functional.html http://www.frank-buss.de/lisp/texture.html Would be interesting to see how this would look like in Python or some of the other languages to which this troll thread was posted :-) -- Frank Buss, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From raghavan.viswanathan at wipro.com Thu May 18 02:28:15 2006 From: raghavan.viswanathan at wipro.com (raghu) Date: 17 May 2006 23:28:15 -0700 Subject: Reference Counts Message-ID: <1147933695.752344.195350@u72g2000cwu.googlegroups.com> Hi All, I am a new user of Python and am having a bit of problem understanding the Reference counting and memory leakage issues. Requesting help from experienced users.... I wrote the following simple program. #!/usr/bin/python import sys global a print "Total Reference count at the start =",sys.gettotalrefcount() a=1 print "a ref count =",sys.getrefcount(a) b=a print "a ref count =",sys.getrefcount(a) del a del b print "Total Reference count at the end =",sys.gettotalrefcount() I executed it. I am seeing the following. Total Reference count at the start = 16538 a ref count = 49 a ref count = 50 Total Reference count at the end = 16540 [6416 refs] There are a few questions that I am having on this. (1) Why should 'a' reference count be 49 before I even made an assignment ? (2) The Total Reference count at the end has increased by 2 . Why ? Am I leaking memory ? (3) I have read somewhere that an increase in sys.gettotalrefcount() is indicative of a memory leak ? Aint that correct ? Thanks for the help. Bye, raghavan V From xah at xahlee.org Sun May 7 06:14:26 2006 From: xah at xahlee.org (Xah Lee) Date: 7 May 2006 03:14:26 -0700 Subject: algorithmic mathematical art Message-ID: <1146996866.280944.313050@y43g2000cwc.googlegroups.com> i've long time been interested in algorithmic mathematical art. That is, mathematical or algorithmic visual art works that are generated by computer such that the program's source code reflects the algorithmic essence of the visual quality in the art work. (for detail, see Algorithmic Mathematical Art at http://xahlee.org/Periodic_dosage_dir/t1/20040113_cmaci_larcu.html ) Mathematica programers, especially Michael Trott, have been doing algorithmic mathematical art since the early 1990s. I started my programing career with Mathematica in 1995, and since late 1990s i've been searching for such work outside of Mathematica, but it is almost non-existent. (maybe less than 10 cases that i know of, and most their code do not capture the algorithmic nature of the rendered art.) The one most prominent mention of it is in chapter 2 of the book Structure and Interpretation of Computer Programs by Hal Abelson et al. anyway, today i ran into this page by Frank Bu? http://www.frank-buss.de/lisp/functional.html which used the idea in the book to render a traditional Escher's tiling piece. I hope this will help the spread of algorithmic mathematical art. If you find other algorithmic mathematical art, please let me know! Xah xah at xahlee.org ? http://xahlee.org/ From OlafMeding at gmail.com Wed May 3 17:17:26 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 14:17:26 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <1146690671.421084.56450@i40g2000cwc.googlegroups.com> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <1146690671.421084.56450@i40g2000cwc.googlegroups.com> Message-ID: <1146691046.361342.210370@u72g2000cwu.googlegroups.com> Serge > I got bored and tried to stop it with ctrl-c ... Yes, you have to use the ctrl-break key to stop the first program. And neither program every hangs on a single core CPU. It also does not hang on a hyper-threading CPU if hyper-threading is turned off in the BIOS. Olaf From alikakakhel at yahoo.com Wed May 31 00:10:06 2006 From: alikakakhel at yahoo.com (greenflame) Date: 30 May 2006 21:10:06 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <1149048606.100581.119980@y43g2000cwc.googlegroups.com> Zhang Fan wrote: > On 30 May 2006 20:18:19 -0700, greenflame wrote: > > Second of all, I would like to have > > other methods of shuffling, prefererably riffle shuffling and just > > plain randomly arranging the elements of the list. > > The random module has a `shuffle' method. It "Shuffle the sequence x > in place". > It may be help for you I am sorry but this does not help much. In my version of python (2.3) this method does not seem to exist. Also from the documentation, it seems that this method would give a random number. From http Mon May 15 14:32:47 2006 From: http (Paul Rubin) Date: 15 May 2006 11:32:47 -0700 Subject: Decrypt DES by password References: Message-ID: <7xlkt3dtps.fsf@ruckus.brouhaha.com> Thomas Dybdahl Ahle writes: > byte[] array2 = bytes1.CryptDeriveKey("DES", "MD5", 0, array1); > > Anybody know how to do this in python? I'm not aware of a standard that says how CryptDeriveKey is supposed to work. Or rather, there are multiple possible standard ways to do it. If you can find an exact specification, or C# source code that does it, it will probably be straightforward to reimplement in Python. If you want to just do something generic and don't need to interoperate with a C# application that uses CryptDeriveKey, the following should be ok: import hmac password = 'the big sekrit password goes here' key1 = hmac.HMAC(password, '1').digest()[:8] # get 8 bytes And if you need additional keys, such as for triple DES: key2 = hmac.HMAC(password, '2').digest()[:8] # get 8 bytes key3 = hmac.HMAC(password, '3').digest()[:8] # get 8 bytes If you want to be fancier you could try PKCS5 KDF2: http://www.rsasecurity.com/rsalabs/node.asp?id=2127 CryptDeriveKey may in fact be doing something like this. From deets at nospam.web.de Tue May 30 05:25:02 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 May 2006 11:25:02 +0200 Subject: os.time() References: Message-ID: <4e2helF1cvdleU1@uni-berlin.de> Anthony wrote: > i have a problem with the os.times() command, on different Python > versions, i get different printout: > and on the 3 servers, the linux command: $date > returns the same value..... > > any suggestions??? > what is the command that gives me the actual time? time.time(), not os.times(). The latter is for process-times. No idea why it can become _negative, though. Diez From gisleyt at gmail.com Mon May 22 03:33:45 2006 From: gisleyt at gmail.com (gisleyt) Date: 22 May 2006 00:33:45 -0700 Subject: Index counting from the last char Message-ID: <1148283224.962829.116120@g10g2000cwb.googlegroups.com> I'd like to use the index-function to retrieve a certain char in a string, but i need it to start counting from the last char. E.g. in the string. Foo-bar, foo foo-bar I want the latter hyphen to be returned when i do a index for '-'. Is there any built in function for this, I don't want to reverse every string just to do this. -Gisle- From sam at nuevageorgia.com Wed May 24 10:00:02 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 24 May 2006 07:00:02 -0700 Subject: John Bokma harassment In-Reply-To: <1148478219.803585.158850@g10g2000cwb.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <1148478219.803585.158850@g10g2000cwb.googlegroups.com> Message-ID: <1148479202.486847.243280@g10g2000cwb.googlegroups.com> I was considering opening an account with Dreamhost. Can't say I agree with all of Xah's writings, but they often raise important points. Dreamhost is a company I will never spend money with. Usenet is full of narrow minded group thinking that needs to be questioned. From scobloke2 at infotop.co.uk Wed May 24 06:29:07 2006 From: scobloke2 at infotop.co.uk (Ian Wilson) Date: Wed, 24 May 2006 11:29:07 +0100 Subject: John Bokma harassment In-Reply-To: <1148463588.566212.36300@i39g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> Message-ID: <44-dnSw6EOzlqOnZRVny3g@bt.com> ilitzroth at gmail.com wrote: > Xah Lee schreef: > >> Which reminds me of http://www.catb.org/~esr/faqs/smart-questions.html#not_losing > We seem to have strayed a long way from Voltaire's > "I do not agree with what you say, but I will defend to the death your > right to say it.", I don't think we have. Surely Voltaire didn't support speaking in inappropriate fora? He didn't support causing a public nuisance? Would you lay down *your* life to defend Xah's "right" to wallpaper your street, your church, your school with printed essays about his personal obsessions? In societies with a right to free speech, there are limits on where and how you may exercise that right. For example, you don't have a right to force any newspaper or TV station to publish your speech. Xah's ISP can decide whether their terms of service provide Xah with a "right" to publish anything he wishes through their facilities regardless of established standards of appropriateness. From siona at chiark.greenend.org.uk Thu May 11 07:08:03 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 11 May 2006 12:08:03 +0100 (BST) Subject: releasing interpreter lock in custom code? References: <1147340518.685734@blaat.sara.nl> Message-ID: Bram Stolk wrote: >I've implemented, in C, a function that does a lot of I/O, and thus >can block for a long time. > >If I execute this function in my Python script, it does not >relinquish the global interpreter lock, like Python's native >blocking functions do, like I/O funcs, and time.sleep() func. > >How can I have my func release the lock? http://docs.python.org/api/threads.html is the first hit on searching docs.python.org for "global interpreter lock". It says: """ This is so common that a pair of macros exists to simplify it: Py_BEGIN_ALLOW_THREADS ...Do some blocking I/O operation... Py_END_ALLOW_THREADS """ -- \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 bdesth.quelquechose at free.quelquepart.fr Sat May 13 07:50:38 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 May 2006 13:50:38 +0200 Subject: getting rid of pass In-Reply-To: <4ckrmbF16kr2bU1@news.dfncis.de> References: <4ckrmbF16kr2bU1@news.dfncis.de> Message-ID: <44659910$0$5314$626a54ce@news.free.fr> David Murmann a ?crit : > Hi all! > > i just had this crazy idea: > > instead of > > while cond(): > pass > > write > > while cond(). Yuck > or > > try: > import xyz > except ImportError: > pass > > compared to > > try: > import xyz > except ImportError. Yuck again > i don't know whether this is syntactically unambiguous or replaces all > uses of pass, but i find it quite nice to read. I don't. I find it highly unreadable. I really find the pass statement to be a great idea, and to highly improve readability. > also if something like this has been proposed before and rejected, i > apologize for this late-in-the-night idea. > > what do you people think? Please don't feel offended, but I think it would be a very bad thing to do. From chris.cavalaria at free.fr Fri May 19 10:34:33 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 19 May 2006 16:34:33 +0200 Subject: open file with whitespaces In-Reply-To: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> References: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> Message-ID: <446dd79c$0$8021$636a55ce@news.free.fr> mardif a ?crit : > Hi guys. > I've a very big big big problem: > > I've in my windows computer a file named cicciobello.html, located in > c:\documents and settings\username\desktop\cicciobello.html. > > Now, I MUST open this file with os.spawn(os.P_WAIT ...., because I must > wait the user cancel the explorer window, ok? > And so, I write: > > import os > os.spawnl(os.P_WAIT, "c:\programmi\internet explorer\iexplorer.exe", > "c:\documents and settings\username\desktop\cicciobello.html") > > the python process don't fail, but explorer don't visualize correctly > the file opened: i receive an "not found" error message. > > I've found that the whitespaces in file path are the problem. > If you see to explorer address bar, you will find the address > completely wrong... > > I've found no solution! > Can you help me, please?? > > thx very very very much!!! > And I thought the problem where the incorrectly used \ :) Try that first : os.spawnl(os.P_WAIT, r"c:\programmi\internet explorer\iexplorer.exe", r"c:\documents and settings\username\desktop\cicciobello.html") From sumrnot at NhOoStPmAaMil.com Thu May 25 22:11:31 2006 From: sumrnot at NhOoStPmAaMil.com (Geoffrey Summerhayes) Date: Thu, 25 May 2006 22:11:31 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <87ejyjv40w.fsf@rpi.edu> Message-ID: "John Bokma" wrote in message news:Xns97CE8E1B64A6Bcastleamber at 130.133.1.4... > "Geoffrey Summerhayes" wrote: > >> After you kill Navarth, will it be nothing but gruff and deedle >> with a little wobbly to fill in the chinks? > > Comparing Navarth with Xah is a huge insult to Jack Vance. You should be > ashamed of yourself for even thinking about it, let alone write it down. Mr. Vance is too intelligent to be insulted by this. OTOH, Mad Navarth is free to be as insulted as much as his fictional soul will allow. :) -- Geoff From chris.cavalaria at free.fr Thu May 18 04:18:10 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 10:18:10 +0200 Subject: Question about exausted iterators In-Reply-To: References: <446b48e2$0$5293$626a54ce@news.free.fr> Message-ID: <446c2dea$0$5306$626a54ce@news.free.fr> Terry Reedy a ?crit : > "Christophe" wrote in message > news:446b48e2$0$5293$626a54ce at news.free.fr... > >>Is there a good reason why when you try to take an element from an >>already exausted iterator, it throws StopIteration instead of some other >>exception ? > > > Yes. > . > . > To distinguish the control message "I am done yielding values, as per the > code specification (so don't bother calling me again)." from error messages > that say "Something is wrong, I cannot yield values and give up." In other > words, to distinguish expected correct behavior from unexpected incorrect > behavior. This is essential for the normal and correct use of iterators. You talk about expected behaviour and my expected behaviour is that an iterator should not be usable once it has raised StopIteration once. >>>>>def f(i): >> >>... print list(i) >>... print list(i) >>... >> >>>>>f(iter(range(2))) >> >>[0, 1] >>[] > > > As per specification. Specifications sometimes have "bugs" too. > I am guessing that you want the first list() call to terminate normally and > return a list, which requires exhausted i to raise StopIteration, while you > want the second list() to not terminate but raise an exception, which > requires exhausted i to raise something other than StopIteration. Tough. Exactly. This would be a sane way to handle it. > One solution is call list(i) exactly once: > > def f(i): > li = list(i) > print li > print li Ok, call me stupid if you want but I know perfectly well the "solution" to that problem ! Come on, I was showing example code of an horrible gotcha on using iterators. Instead of saying that all works as intended could you be a little helpful and tell me why it was intended in such an obviously broken way instead ? From nobody Thu May 25 20:15:46 2006 From: nobody (Erik Johnson) Date: Thu, 25 May 2006 18:15:46 -0600 Subject: __getattr__ and functions that don't exist References: <44762cf8$1@nntp.zianet.com> <1148596303.833301.15190@g10g2000cwb.googlegroups.com> Message-ID: <447648ab$1@nntp.zianet.com> Thanks for your reply, Nick. My first thought was "Ahhh, now I see. That's slick!", but after playing with this a bit... >>> class Foo: ... def __getattr__(self, attr): ... def intercepted(*args): ... print "%s%s" % (attr, args) ... return intercepted ... >>> f = Foo() >>> f __repr__() Traceback (most recent call last): File "", line 1, in ? TypeError: __repr__ returned non-string (type NoneType) my thought is "Oooooh... that is some nasty voodoo there!" Especially if one wants to also preserve the basic functionality of __getattr__ so that it still works to just get an attribute where no arguments were given. I was thinking it would be clean to maintain an interface where you could call things like f.set_Spam('ham') and implement that as self.Spam = 'ham' without actually having to define all the set_XXX methods for all the different things I would want to set on my object (as opposed to just making an attribute assignment), but I am starting to think that is probably an idea I should just simply abandon. I guess I don't quite follow the error above though. Can you explain exactly what happens with just the evaluation of f? Thanks, -ej "Nick Smallbone" wrote in message news:1148596303.833301.15190 at g10g2000cwb.googlegroups.com... > Erik Johnson wrote: > > Maybe I just don't know the right special function, but what I am wanting to > > do is write something akin to a __getattr__ function so that when you try to > > call an object method that doesn't exist, it get's intercepted *along with > > it's argument*, in the same manner as __getattr__ intercepts attributes > > references for attributes that don't exist. > > > > > > This doesn't quite work: > > > > >>> class Foo: > > ... def __getattr__(self, att_name, *args): > > ... print "%s%s" % (att_name, str(tuple(*args))) > > ... > > >>> f = Foo() > > The problem is that the call to f.bar happens in two stages: the > interpreter calls getattr(f, "foo") to get a function, and then it > calls that function. When __getattr__ is called, you can't tell what > the parameters of the function call will be, or even if it'll be called > at all - someone could have run "print f.bar". > > Instead, you can make __getattr__ return a function. Then *that* > function will be called as f.bar, and you can print out its arguments > there: > > class Foo: > def __getattr__(self, attr): > def intercepted(*args): > print "%s%s" % (attr, args) > return intercepted > From buzzard at urubu.freeserve.co.uk Wed May 24 09:26:58 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Wed, 24 May 2006 14:26:58 +0100 Subject: Python keywords vs. English grammar In-Reply-To: References: Message-ID: <44746136.0@entanet> Roy Smith wrote: > I noticed something interesting today. In C++, you write: > > try { > throw foo; > } catch { > } > > and all three keywords are verbs, so when you describe the code, you can > use the same English words as in the program source, "You try to execute > some code, but it throws a foo, which is caught by the handler". > > In Python, you write: > > try: > raise foo > except: > > and now you've got a mix of verbs and (I think), a preposition. You can't > say, "You try to execute some code, but it raises a foo, which is excepted > by the handler". It just doesn't work grammatically. > > Sigh. It does, but it's maybe not 'plain English'. http://dictionary.reference.com/search?q=except Duncan From johnjsal at NOSPAMgmail.com Wed May 10 15:37:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 19:37:46 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: References: <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> Message-ID: John Salerno wrote: > mpeters42 at gmail.com wrote: > >>>>> string = 'abababababababab' >>>>> pat = 'aba' >>>>> [pat for s in re.compile('(?='+pat+')').findall(string)] >> ['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba'] > > Wow, I have no idea how to read that RE. First off, what does it match? > Should something come before the parentheses, and that will be what > matches? Also, what are the '+'s doing? Are they literal +s or still > being used as RE syntax? Nevermind, I get it! The point is that you *aren'* matching anything (except the empty string), and this only to see how many times it occurs, then you are replacing those occurrences with the pattern string. So this is basically like a counter? From robin.meier at gmail.com Wed May 31 05:59:43 2006 From: robin.meier at gmail.com (robin) Date: 31 May 2006 02:59:43 -0700 Subject: summarize text In-Reply-To: <1148914353.156936.309040@g10g2000cwb.googlegroups.com> References: <1148903386.095226.249270@38g2000cwa.googlegroups.com> <1148914353.156936.309040@g10g2000cwb.googlegroups.com> Message-ID: <1149069583.186438.312820@c74g2000cwc.googlegroups.com> thanks for all your replies. lemur looks pretty interesting! robin gene tani wrote: > robin wrote: > > hello list, > > > > does anyone know of a library which permits to summarise text? i've > > been looking at nltk but haven't found anything yet. any help would be > > unclear what you're asking, maybe look at: > http://www.cs.waikato.ac.nz/~ml/weka/index.html > > http://www.kdnuggets.com/software/suites.html > http://www.ailab.si/orange > > http://mallet.cs.umass.edu/index.php/Main_Page > http://minorthird.sourceforge.net/ > http://www.dia.uniroma3.it/db/roadRunner/ > > http://www.lemurproject.org/ From jstroud at ucla.edu Tue May 23 20:02:57 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 23 May 2006 17:02:57 -0700 Subject: Guide to using python for bash-style scripting In-Reply-To: <1148405239.840908.120910@j33g2000cwa.googlegroups.com> References: <1148405239.840908.120910@j33g2000cwa.googlegroups.com> Message-ID: 4zumanga wrote: > I have a bunch of really horrible hacked-up bash scripts which I would > really like to convert to python, so I can extend and neaten them. > However, I'm having some trouble mapping some constructs easily, and > was wondering if anyone know of a guide to mapping simple uses of > command line programs to python. > > For an example, the kind of thing I am thinking of are things like > (yes, this is horrible code). > > # These are a run of a program I have written > ./proggy -test1 > out1 > ./proggy -test2 > out2 > > #Do some simple manipulation of the output. > grep Node out1 > new_out1 > grep Node out2 > new_out2 > diff out1 out2 > Chapter 2 of Mark Lutz's "Programming Python" (2nd Edition) will make you adept at using Python as a (***VASTLY SUPERIOR***) alternative to shell scripting. Chapters 3-5 will get you pretty close to master level at shell/system scripting. Note: This is not an intro to python. You should already be able to do simple programming in python for Lutz's book to be useful. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From kar1107 at gmail.com Tue May 9 23:06:43 2006 From: kar1107 at gmail.com (Karthik Gurusamy) Date: 9 May 2006 20:06:43 -0700 Subject: Memory leak in Python In-Reply-To: <1147225282.478996.134910@i39g2000cwa.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <44605dd1$0$2056$626a54ce@news.free.fr> <1147225282.478996.134910@i39g2000cwa.googlegroups.com> Message-ID: <1147230403.415674.72580@e56g2000cwe.googlegroups.com> diffuser78 at gmail.com wrote: > The amount of data I read in is actually small. > > If you see my algorithm above it deals with 2000 nodes and each node > has ot of attributes. > > When I close the program my computer becomes stable and performs as > usual. I check the performance in Performance monitor and using "top" > and the total memory is being used and on top of that around half a gig > swap memory is also being used. > > Please give some helpful pointers to overcome such memory errors. > > I revisited my code to find nothing so obvious which would let this > leak happen. How to kill cross references in the program. I am kinda > newbie and not completely aware of the finetuning such programming > process. > I suspect you are trying to store each node's attributes in every other node. Basically you have a O(N^2) algorithm (in space and probably more in time). For N=2000, N^2 is pretty big and you see memory issues. Try not to store O(N^2) information and see if you can just scale memory requirements linearly in N. That is, see if you can store attributes of a node at only one place per node. I'm just guessing your implementation; but from what you say (peer-to-peer), I feel there is a O(N^2) requirements. Also try experimenting with small N (100 nodes say). Thanks, Karthik > Thanks > > > bruno at modulix wrote: > > diffuser78 at gmail.com wrote: > > > I have a python code which is running on a huge data set. After > > > starting the program the computer becomes unstable and gets very > > > diffucult to even open konsole to kill that process. What I am assuming > > > is that I am running out of memory. > > > > > > What should I do to make sure that my code runs fine without becoming > > > unstable. How should I address the memory leak problem if any ? I have > > > a gig of RAM. > > > > > > Every help is appreciated. > > > > Just a hint : if you're trying to load your whole "huge data set" in > > memory, you're in for trouble whatever the language - for an example, > > doing a 'buf = openedFile.read()' on a 100 gig file may not be a good > > idea... > > > > > > > > -- > > bruno desthuilliers > > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > > p in 'onurb at xiludom.gro'.split('@')])" From jstroud at ucla.edu Wed May 3 16:52:20 2006 From: jstroud at ucla.edu (James Stroud) Date: Wed, 03 May 2006 13:52:20 -0700 Subject: Python & SSL In-Reply-To: References: Message-ID: John J. Lee wrote: > James Stroud writes: > > >>I have been trying to make an https client with python, but it seems > > > What exactly do you mean by "make an https client"? Something that can communicate with an https server. Fetch web pages, send POST and GET information securely. >>that, to do this, one needs to have the socket module compiled with ssl. >>This is not the default. So I have a couple of questions. >> >> 1. Where do I specify to compile socket with ssl? I found no >> obvious option in configure or setup.py or several other >> files I checked. > > > What OS are you on? Linux FC 4 with my self-compiled versions of just about everything. > >> 2. Is there a way to do this without re-compiling all of python? > > > Are you sure it's NOT compiled in? But, if it's not compiled, it's > not compiled. Its not compiled by default. I think I read this somewhere. I was thinking of compiling just the socket module rather than installing over my old version. > >>Also, I have done numerous combinations of searches with ssl, https, & >>python as terms, but I haven't found a page outlining the steps to make >>a certificate and key that python understands. Has anyone been >>successful at this? Did you use openssl? I want to make sure I am doing >>this part correctly. > > > Since you say "make a certificate", and mention "https client", it > sounds like you want to authenticate yourself to an HTTP server using > an SSL certificate? If so, I don't believe the issue Benji raised is > relevant (that issue is relevant for fetching HTTPS URLs rather than > authenticating yourself to a server using an SSL certificate, I > think). > > urllib claims to have support for this in the form of the key_file and > cert_file arguments to Urlopener constructor (UNTESTED): > > import urllib > opener = urllib.URLopener(key_file="/path/to/my_key_file", > cert_file="/path/to/my_cert_file") > response = opener.open(url) At this point, authenticating is not an issue, though it would be nice to know how to do. Mainly, I want to establish a secure connection for 2-way communication via https. At any rate, I was able to make M2Crypto do what I wanted last night, so I think I'll bypass the standard library route for now. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From skip at pobox.com Wed May 17 12:06:03 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 May 2006 11:06:03 -0500 Subject: CFLAGS are not taken into account properly In-Reply-To: <446B1972.4090107@fft.be> References: <446ad377$0$438$6c56d894@reader0.news.be.easynet.net> <446B1972.4090107@fft.be> Message-ID: <17515.18923.565106.85789@montanaro.dyndns.org> Toon> But some other (but 'similar') functionality is broken. Now I Toon> succeeded in compiling python. But when using distutils (e.g. when Toon> installing numarray using the setup.py), python will compile the Toon> files using the '-xarch=v9' option but drops this option when Toon> linking dynamic libraries (although I defined LDFLAGS="-xarch=v9" Toon> before configuring python). Additionally python adds the option Toon> '-xcode=pic32' to the compile-command which will compile my Toon> numarray in 32bit instead of 64bit (while python itself is in Toon> 64bit) That seems like a bug in distutils. Can you submit a help ticket? Skip From johnjsal at NOSPAMgmail.com Tue May 9 10:13:27 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 14:13:27 GMT Subject: i don't understand this RE example from the documentation In-Reply-To: <1147129892.758708.207620@y43g2000cwc.googlegroups.com> References: <1147129892.758708.207620@y43g2000cwc.googlegroups.com> Message-ID: Ben Cartwright wrote: > The groups *are* 0-based. The 0th group is the whole match, e.g.: Ah, I see! But I also read that if a group number starts with 0, it is treated as octal. Did I read that wrong, or maybe it doesn't matter since 0 is 0 in any base system? From NOatkinwSPAM at rpi.edu Sun May 7 06:39:40 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 06:39:40 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1146990071.634244.83380@i39g2000cwa.googlegroups.com> <871wv6b3y0.fsf@rpi.edu> <1146996240.867564.139490@u72g2000cwu.googlegroups.com> Message-ID: <87vesi5dar.fsf@rpi.edu> brian at sweetapp.com writes: > Bill Atkins wrote: >> brian at sweetapp.com writes: >> >>> Bill Atkins wrote: >>>> Buh? The project doesn't have to be late for Brooks's law to hold; >>>> adding programmers, so goes Brooks reasoning, will always increase the >>>> time required to complete the project because of various communication >>>> issues. >>> 1. This is not what Brooks says. Brooks was talking about late >>> projects. Please provide a supporting quote if you wish to continue >>> to claim that "adding programmers will always increase the time >>> required to complete the project". >> >> The "always" in my claim should not be there, I admit. Brooks didn't >> claim that. >> >> I refer you to pages 17 - 18 of The Mythical Man-Month: >> >> Since software construction is inherently a systems effort - an >> exercise in complex interrelationships - communication effort is >> great...Adding more men then lengthens, not shortens, the schedule. >> >> It is totally absurd to assume that, simply because a project has not >> yet passed its deadline, it will somehow become immune to the kinds of >> things Brooks is talking about. > > Right. But only when a project is late does Brooks say that adding > programmers will always make it later (the claim that you made). In > other cases he says "Add manpower, ..., this may or may not help". That > seems intuitively obvious to me. If the programmers being added require > extensive training [1] by the team to become productive, and their > contribution to the project will be smaller than that amount (e.g. it > is a small or nearly completed project) then their net impact on the > project will be negative. If, OTOH, the new programmers are able to > quickly understand the project/organization/technologies and almost > immediately make useful contributions, then they are likely to have a > net positive impact. There is another essay in TMM-M that discusses the difference between essential complexity and accidental complexity. You might think Python is really swell, and I might think Common Lisp is really swell, but at the heart of it there is still what Brooks calls "essential complexity" - the difficulty of mapping a complicated real-world situation into a model a computer can handle. So I think using Python or Lisp will help get rid of a lot of the accidental complexity that would arise from using C or C++, but it can only do so much; there is still a lot of complexity involved even in projects that are written in very high-level languages. IMHO. >>> 2. There has to be a mechanism where an organization can add >>> developers - even if it is only for new projects. Python advocates >> >> Obviously. > > It's good that you agree. I think that the ability to add new > productive developers to a project/team/organization is at least part > of what Alex means by "scaleability". I'm sure that he will correct me > if I am wrong. > >>> [list of proposed Python advantages snipped] >> These are not things I look for in a programming language. > > Fair enough. That doesn't mean that these advantages aren't important > to others or, in some situations, objectively important in the survival > of a project/organization. Sure, agreed. > For example, imagine that Google had used language X instead of Python > to develop their tools (assume they started with 10 expert X > programmers). Expert X programmers are Y percent more productive than > expert Python programmers. Now Google wants to grow aggressively and > needs 100 times more developer productivity (and expects to need even > more productivity in the future). If it is harder to find/hire/create > experts in language X than Python, then Y will have to be large to make > language X a better choice than Python. Also, if non-expert Python > programmers can be more productive than non-expert X programmers, then > Python also has an advantage. Eric Raymond claims that Python has very > high initial productivity and that becoming an expert is fairly easy. > > BTW, I'm not saying that Common Lisp fits X in this example. > > Cheers, > Brian > > [1] I'm considering introducing bugs or misdesigns that have to be > fixed > as part of training for the purposes of this discussion. Also the > time needed to learn to coordinate with the rest of the team. > -- This is a song that took me ten years to live and two years to write. - Bob Dylan From Serge.Orlov at gmail.com Mon May 8 21:07:15 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 8 May 2006 18:07:15 -0700 Subject: ascii to latin1 References: <445fdc6c$0$15793$14726298@news.sunsite.dk> Message-ID: <1147136835.481913.323510@v46g2000cwv.googlegroups.com> Luis P. Mendes wrote: > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Hi, > > I'm developing a django based intranet web server that has a search page. > > Data contained in the database is mixed. Some of the words are > accented, some are not but they should be. This is because the > collection of data began a long time ago when ascii was the only way to go. > > The problem is users have to search more than once for some word, > because the searched word can be or not be accented. If we consider > that some expressions can have several letters that can be accented, the > search effort is too much. > > I've searched the net for some kind of solution but couldn't find. I've > just found for the opposite. > > example: > if the word searched is 'televis?o', I want that a search by either > 'televisao', 'televis?o' or even 't?l?visao' (this last one doesn't > exist in Portuguese) is successful. > > So, instead of only one search, there will be several used. > > Is there anything already coded, or will I have to try to do it all by > myself? You need to covert from latin1 to ascii not from ascii to latin1. The function below does that. Then you need to build database index not on latin1 text but on ascii text. After that convert user input to ascii and search. import unicodedata def search_key(s): de_str = unicodedata.normalize("NFD", s) return ''.join(cp for cp in de_str if not unicodedata.category(cp).startswith('M')) print search_key(u"televis?o") print search_key(u"t?l?visao") ===== Result: televisao televisao From robin at NOSPAMreportlab.com Mon May 1 11:02:07 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Mon, 01 May 2006 15:02:07 +0000 Subject: self modifying code In-Reply-To: <1146492266.605324.282670@u72g2000cwu.googlegroups.com> References: <445399A1.9020506@jessikat.plus.net> <44548536.7060409@jessikat.plus.net> <1146469385.334797.128930@i39g2000cwa.googlegroups.com> <4455D863.6070906@jessikat.plus.net> <1146492266.605324.282670@u72g2000cwu.googlegroups.com> Message-ID: <445622EF.6050708@jessikat.plus.net> taleinat at gmail.com wrote: > Yes, my implementation was less efficient because of the extra function > call. > >> class Weird(object): >> @staticmethod >> def __call__(arg): >> data = 42 >> def func(arg): >> return arg+data >> Weird.__call__ = staticmethod(func) >> return func(arg) >> c = Weird() > ugh indeed > Ugh... you've used a class just like a function. You can't have two > different objects of this class, since you are overriding a static > method of the class! And you've hard-coded the data into the class > definition. Yes, it works, but I would never, ever trust such code to > someone else to maintain. > > And you'll have to manually define such a class for every such > function. That's not very Pythonic. no arguments here > > Here's a reusable function that will define such a class for you, as > well as hide most of the ugliness (in fact, it supports -exactly- the > same interface as my previous implementation): > > def InitializingFunction(func): > class temp: > @staticmethod > def __call__(*args, **kw): > temp.__call__ = staticmethod(func()) > return temp.__call__(*args, **kw) > return temp() > > @InitializingFunction > def func(): > data = somethingcomplexandcostly() > def foo(a): > return simple(data, a) > return foo > I already tried this kind of factory function, but in fact I think the original global test version outperforms even the statically coded Weird class. ie data = None def d(arg): global data if data is None: data = 42 return arg+data @InitializingFunction def e(): data = 43 def foo(a): return data+a return foo are both better than any except the global function replacement nonsense C:\Tmp>\Python\lib\timeit.py -s"from dingo import d;d(0)" d(1) 1000000 loops, best of 3: 0.556 usec per loop C:\Tmp>\Python\lib\timeit.py -s"from dingo import e;e(0)" e(1) 1000000 loops, best of 3: 1.09 usec per loop but the structured approach is still twice as slow as the simplistic one :( -- Robin Becker From malvert at telenet.be Fri May 19 05:21:39 2006 From: malvert at telenet.be (malv) Date: 19 May 2006 02:21:39 -0700 Subject: Programming language productivity In-Reply-To: References: Message-ID: <1148030499.484778.8260@j33g2000cwa.googlegroups.com> John Bokma wrote: > Connelly Barnes wrote: > > > http://barnesc.blogspot.com/2006/05/programming-language-productivity.h > > tml > > C: 3 hours to write the program, 5 hours to track down the memory leaks > Java: 4 hours to write the program, 6 hours to get all the exception > handling right > C++ 5 hours to write the program after reading Stroustrup for 6 hours > > Just kidding, of course. > > Also note that Python programmers write more lines/hour which they need to > finish in the same time as Perl programmers :-D. > > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html I am not shure whether your criterion is very valid. OK if you have to write only one compact piece of code like in your example. Sometimes I think that most python users fall within this category. Once you get involved in larger projects, the dynamic nature of the programming tool becomes much more important. I mean by this, the ability to stop running code, modify or add to it and continue without having to re-establish the state of the program. This may sound trivial to many, but in major applications setting up the state again can take a considerable processing time. Such feature should be available from within the debugging tools. In fact, languages like Smalltalk, Lisp and even VB offer this possibility. Ruby coming up strongly these days also has this dynamic reload capability. To sum up, I like Python very much but I don't understand how come this basic flaw has not been taken care of. It is sufficient to search for "reload" to see how many people have struggled with it over the years. I hate the idea of having to take up Ruby to really find out how it could serve me better in this most critical productivity area. From skip at pobox.com Tue May 16 10:40:16 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 May 2006 09:40:16 -0500 Subject: Using python for a CAD program In-Reply-To: References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Message-ID: <17513.58448.475801.436161@montanaro.dyndns.org> Someone in hiding wrote: > Hi, I'm interested in using python to start writing a CAD program for > electrical design. Google for PythonCAD. Skip From aleax at mac.com Tue May 9 23:12:29 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 9 May 2006 20:12:29 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <7xmzdrdky8.fsf@ruckus.brouhaha.com> Message-ID: <1hf346g.1uppwsa11k1uggN%aleax@mac.com> Paul Rubin wrote: > aleax at mac.com (Alex Martelli) writes: > > I think it's reasonable to make a name a part of functions, classes and > > modules because they may often be involved in tracebacks (in case of > > uncaught errors): to me, it makes sense to let an error-diagnosing > > tracebacks display packages, modules, classes and functions/methods > > involved in the chain of calls leading to the point of error _by name_. > > But it would be even nicer if the traceback could point back to the > exact location in the source code where the function definition > occurred, and that wouldn't need any name for the function. I believe a name is a useful "summary" or "conceptual handle" for a thing, saving us from having to describe/analyze/recognize it in more detail each and every time. "Need" may be too strong a word, but I maintain there's _usefulness_ (and reasonableness, and good common sense) in the naming. Alex From aahz at pythoncraft.com Wed May 17 16:56:15 2006 From: aahz at pythoncraft.com (Aahz) Date: 17 May 2006 13:56:15 -0700 Subject: python vs perl lines of code References: Message-ID: In article , Edward Elliott wrote: > >Fair enough, but advocacy isn't at all what I'm after. Anecdotes are fine, >after all what is data but a collection of anecdotes? :) "The plural of anecdote is not data." -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From luis_lupe2XXX at netvisaoXXX.pt Wed May 10 07:56:54 2006 From: luis_lupe2XXX at netvisaoXXX.pt (Luis P. Mendes) Date: Wed, 10 May 2006 12:56:54 +0100 Subject: ascii to latin1 In-Reply-To: <1147254139.954024.273040@j33g2000cwa.googlegroups.com> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <4460831e$0$15794$14726298@news.sunsite.dk> <1147180014.685659.325830@i39g2000cwa.googlegroups.com> <4460dec2$0$15791$14726298@news.sunsite.dk> <1147254139.954024.273040@j33g2000cwa.googlegroups.com> Message-ID: <4461d4c9$0$15781$14726298@news.sunsite.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 > > With regards to ?, Richie already gave you food for thoughts, if you > want "1 DE MO" to match "1? DE MO" remove that symbol from the key > (linha_key = linha_key.translate({u"?": None}), if you don't want such > a fuzzy matching, keep it. > Thank you all for your help. That was what I did. That symbol '?' is not needded for the field. It's working fine, now. Luis P. Mendes -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEYdUGHn4UHCY8rB8RAhWgAKCNqUaknEmiNlA050u5G+p4cTPGHwCgs7fu 7/5HMYDDo+sOP2QDexIELn8= =XiPL -----END PGP SIGNATURE----- From phddas at yahoo.com Tue May 9 05:11:20 2006 From: phddas at yahoo.com (Gary Wessle) Date: 09 May 2006 19:11:20 +1000 Subject: two of pylab.py Message-ID: <87bqu75zrb.fsf@localhost.localdomain> Hi I use debian/testing linux Linux debian/testing 2.6.15-1-686 I found some duplicate files in my system, I don't if the are both needed, should I delete one of the groups below and which one? -rw-r--r-- 1 root root 80375 2006-01-24 00:28 /usr/lib/python2.3/site-packages/matplotlib/pylab.py -rw-r--r-- 1 root root 96202 2006-05-07 13:44 /usr/lib/python2.3/site-packages/matplotlib/pylab.pyc -rw-r--r-- 1 root root 96202 2006-05-07 13:45 /usr/lib/python2.3/site-packages/matplotlib/pylab.pyo -rw-r--r-- 1 root root 31 2004-12-10 03:05 /usr/lib/python2.3/site-packages/pylab.py -rw-r--r-- 1 root root 160 2006-05-07 13:44 /usr/lib/python2.3/site-packages/pylab.pyc -rw-r--r-- 1 root root 160 2006-05-07 13:45 /usr/lib/python2.3/site-packages/pylab.pyo my sys.path shows that /usr/lib/python2.3/site-packages/ is present. **************************************************************** $cat /usr/lib/python2.3/site-packages/pylab.py from matplotlib.pylab import * **************************************************************** This imports all names except those beginning with an underscore (_). thanks From bborcic at gmail.com Tue May 9 09:11:29 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 09 May 2006 15:11:29 +0200 Subject: Enumerating Regular Expressions In-Reply-To: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> Message-ID: <44609516$1_4@news.bluewin.ch> blair.bethwaite at gmail.com wrote: > Hi all, > > Does anybody know of a module that allows you to enumerate all the > strings a particular regular expression describes? > > Cheers, > -Blair > By hand write down a generator that will solve the simplest case of '.*' as a regexp, and filter the output of that by the given regexp ? - seriously, that's an interesting question, thanks for asking it ;) From bignose+hates-spam at benfinney.id.au Wed May 17 22:19:47 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 12:19:47 +1000 Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> Message-ID: <87k68km5vg.fsf@benfinney.id.au> Edward Elliott writes: > Ben Finney wrote: > > > I responded to a post that seemed to claim that anecdotes about events > > can be treated as data about events. They can't; that's what I'm > > arguing. > > And conveniently ignoring the key part of my post. Here it is again for > those who missed it: > > "Before the days of cheap video, lots of scientific data was gathered by > lone observers recording unrepeatable events.??You?build?statistics?by > accumulating a vast number of such observations over time." > > Sounds like anecdotes can become data to me. Note the transformation though. You're not collecting data *about the unrepeatable events*, you're collecting data *about the reports*. Thus my assertion: anecdotes about events cannot be treated as data about those events. At best, they are data about *reports* of events. > It's a stupid argument anyway. Anecdotes *are* data. They're a different kind of data though. Anecdotes about UFO sightings says *nothing* for or against the existence of UFOs, only about the incidence of people reporting sightings of UFOs. Treating an anecdote about X as though it were a data point about X is a fallacy. Treating an aggregate of anecdotes about X as though it were data about X is a very common practice, but is equally a fallacy. -- \ "The reward of energy, enterprise and thrift is taxes." -- | `\ William Feather | _o__) | Ben Finney From bencvt at gmail.com Thu May 25 21:24:03 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 25 May 2006 18:24:03 -0700 Subject: Speed up this code? In-Reply-To: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> Message-ID: <1148606643.363075.129630@j73g2000cwa.googlegroups.com> aomighty at gmail.com wrote: > I'm creating a program to calculate all primes numbers in a range of 0 > to n, where n is whatever the user wants it to be. I've worked out the > algorithm and it works perfectly and is pretty fast, but the one thing > seriously slowing down the program is the following code: > > def rmlist(original, deletions): > return [i for i in original if i not in deletions] > > original will be a list of odd numbers and deletions will be numbers > that are not prime, thus this code will return all items in original > that are not in deletions. For n > 100,000 or so, the program takes a > very long time to run, whereas it's fine for numbers up to 10,000. > > Does anybody know a faster way to do this? (finding the difference all > items in list a that are not in list b)? The "in" operator is expensive for lists because Python has to check, on average, half the items in the list. Use a better data structure... in this case, a set will do nicely. See the docs: http://docs.python.org/lib/types-set.html http://docs.python.org/tut/node7.html#SECTION007400000000000000000 Oh, and you didn't ask for it, but I'm sure you're going to get a dozen pet implementations of prime generators from other c.l.py'ers. So here's mine. :-) def primes(): """Generate prime numbers using the sieve of Eratosthenes.""" yield 2 marks = {} cur = 3 while True: skip = marks.pop(cur, None) if skip is None: # unmarked number must be prime yield cur # mark ahead marks[cur*cur] = 2*cur else: n = cur + skip while n in marks: # x already marked as multiple of another prime n += skip # first unmarked multiple of this prime marks[n] = skip cur += 2 --Ben From onurb at xiludom.gro Tue May 16 12:26:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 16 May 2006 18:26:21 +0200 Subject: Unable to extract Python source code using Windows In-Reply-To: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> Message-ID: <4469fd93$0$7028$636a55ce@news.free.fr> Elric02 at rogers.com wrote: > I'm currently trying to get access to the Python source code, however > whenever I try to extract the files from what ? > using the latest version of WinZip > (version 10) I get the following error "error reading header after > processing 0 entries" > I was under the impression that I could (from reading the various posts > on this group) that I could simply extract the tar ball, using WinZip. I don't know if winzip handles tarballs... > If this is not the case does anybody know how I can actually get source > code on Windows platform. You can get Python sources from python.org HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From bignose+hates-spam at benfinney.id.au Sat May 20 01:53:34 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 May 2006 15:53:34 +1000 Subject: file() and open() separate in Python 2.5 (was: Re: DO NOT USE file()) References: <1Mobg.2139$No6.46432@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <446e8a54$0$5326$c3e8da3@news.astraweb.com> <1f7befae0605192133m1760cb91wfb8dee9e4936c2ad@mail.gmail.com> Message-ID: <87sln5i6n5.fsf_-_@benfinney.id.au> "Tim Peters" writes: > [John Salerno, on the difference between `open` and `file`] > > Interesting. What is the difference between them now? > > In 2.5 `file` is unchanged but `open` becomes a function: > > >>> file > > >>> open > In that case I'll happily use 'file()', since it meshes nicely with creating a new instance of any built-in type. -- \ "None can love freedom heartily, but good men; the rest love | `\ not freedom, but license." -- John Milton | _o__) | Ben Finney From OlafMeding at gmail.com Wed May 3 21:52:47 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 18:52:47 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> Message-ID: <1146707567.506771.327490@i40g2000cwc.googlegroups.com> Tim > I didn't run it for hours ;-) Please try. The sleep statement does not return! And this should not happen. The code above does nothing special or unusual. The problem only occurs if 2 threads use the sleep statement and hyper-threading is enabled. We discovered this bug perhaps a year ago. The only solution was to tell our customers to disable hyper-threading (you can imagine they did not like our "solution" very much). It then took many days of hard work to isolate the problem down to the code I posted above. > Where "hang" means they stop printing. Our Python code just stops running (locking up the entire application). We use Qt for our GUI. We have over a hundred .py files. We use a total of 4 threads (they get created once and stay running). One thread uses sockets. Once the application locks up (getting stuck in a sleep statement) all comes back to live if I pull the network cable out. So perhaps the socket thread returns from the sleep statement and other threads return to live because they were waiting for the socket thread. Our software runs on both Windows and Linux. We are not sure if the problem also happens on Linux. In any case, if someone else can confirm the bug then this is a serious problem meriting further investigation. We have searched the Internet far and wide and were not able to find any information that indicates that someone else has reported a similar problem (neither Python nor Windows Sleep related). Thank you for your help. Olaf From onurb at xiludom.gro Tue May 30 13:01:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 30 May 2006 19:01:21 +0200 Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional In-Reply-To: <1148980889.507643.52440@u72g2000cwu.googlegroups.com> References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> <1148980889.507643.52440@u72g2000cwu.googlegroups.com> Message-ID: <447c7ad3$0$31649$636a55ce@news.free.fr> Moneyhere wrote: > Good :) > Can someone provide this ebook? . > I'm looking forwards it. > http://www.amazon.com/gp/product/0130410659/002-1715230-0496030?v=glance&n=283155 -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From utabintarbo at gmail.com Tue May 23 08:43:39 2006 From: utabintarbo at gmail.com (utabintarbo) Date: 23 May 2006 05:43:39 -0700 Subject: freeze tool like perl2exe? In-Reply-To: References: <1148329713.916486.68410@i40g2000cwc.googlegroups.com> Message-ID: <1148388219.214377.170980@i39g2000cwa.googlegroups.com> CX_Freeze? http://starship.python.net/crew/atuining/cx_Freeze/ From Serge.Orlov at gmail.com Thu May 18 21:21:48 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 18 May 2006 18:21:48 -0700 Subject: WTF? Printing unicode strings In-Reply-To: References: <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <1147998139.268318.315250@y43g2000cwc.googlegroups.com> Message-ID: <1148001708.183506.296240@g10g2000cwb.googlegroups.com> Ron Garret wrote: > > > I'm using an OS X terminal to ssh to a Linux machine. > > > > In theory it should work out of the box. OS X terminal should set > > enviromental variable LANG=en_US.utf-8, then ssh should transfer this > > variable to Linux and python will know that your terminal is utf-8. > > Unfortunately AFAIK OS X terminal doesn't set that variable and most > > (all?) ssh clients don't transfer it between machines. As a workaround > > you can set that variable on linux yourself . This should work in the > > command line right away: > > > > LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > Or put the following line in ~/.bashrc and logout/login > > > > export LANG=en_US.utf-8 > > No joy. > > ron at www01:~$ LANG=en_US.utf-8 python -c "print unichr(0xbd)" > Traceback (most recent call last): > File "", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > position 0: ordinal not in range(128) > ron at www01:~$ What version of python and what shell do you run? What the following commands print: python -V echo $SHELL $SHELL --version From nvasiliev at whiteriversoft.com Wed May 10 04:23:30 2006 From: nvasiliev at whiteriversoft.com (Nicolay A. Vasiliev) Date: Wed, 10 May 2006 12:23:30 +0400 Subject: MySQLdb trouble Message-ID: <4461A302.9070203@whiteriversoft.com> Hello there! I got some trouble trying to insert data into the database with MySQLdb module. I have such code: from MySQLdb import * def loc_connect_db(): """ The DB connection subroutine """ db = MySQLdb.connect(host = "localhost", user = "root", passwd="mysql", db="some_db") return db db = loc_connect_db() cursor = db.cursor() query = """insert ignore into categories (cat_id, cat_name, parent) values (%d, "%s", %d)""" % (int(CatId), CatName.capitalize(), int(parent)) print query cursor.execute(query) Queries are formed in the loop, they look fine. No errors, but no effect, records are not inserted into the table. There is my possible mistake? Any suggestions are very appreciated - Thanks in advance. Best regards, Nicolay From bdesth.quelquechose at free.quelquepart.fr Tue May 23 21:58:29 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 May 2006 03:58:29 +0200 Subject: Running script in __main__ shows no output in IDLE In-Reply-To: <1148367832.691286.320790@j33g2000cwa.googlegroups.com> References: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> <44724be3$1@nntp0.pdx.net> <1148367832.691286.320790@j33g2000cwa.googlegroups.com> Message-ID: <44738e7e$0$2554$636a55ce@news.free.fr> heidi.hunter at fantasy-interactive.com a ?crit : > Shouldn't Idle have shown an error when trying to > read the string constant if it's not interpretable as a normal string, > then? Yes. In my python shell, it raised an error. I don't know for sure why this did not appear in IDLE, but there are far better tools anyway. From joncle at googlemail.com Mon May 29 01:53:31 2006 From: joncle at googlemail.com (Jon Clements) Date: 28 May 2006 22:53:31 -0700 Subject: generating random passwords ... for a csv file with user details References: <1148802192.793574.209720@i40g2000cwc.googlegroups.com> <1148871652.481927.235200@j55g2000cwa.googlegroups.com> Message-ID: <1148882011.181979.163250@38g2000cwa.googlegroups.com> Something like: import csv in_csv=csv.reader( file('your INPUT filenamehere.csv') ) out_csv=csv.writer( file('your OUPUT filenamehere.csv','wb') ) ## If you have a header record on your input file, then out_csv.writerow( in_csv.next() ) ## Iterate over your input file for row in in_csv: # Row will be a list where row[0]=userid and row[3]=passwd password=some_function_as_advised_by_rest_of_group() # Assuming you want to write password as new field then out_csv.writerow( row + [password] ) # Assuming you want to over-write password field then row[3] = password out_csv.writerow(row) All the best, Jon. k.i.n.g. wrote: > Hi ALL, > > I am sorry for not mentioning that I am new to python and scripting. > How can I add the above script to handle csv file. I want the script to > generate passwords in the passwords column/row in a csv file. > > userid,realname,dateofB,passwd > > The script should read the userid and genrate the password for each > user id (there are thousands of userids) > > Kanthi From cito at online.de Fri May 12 07:41:12 2006 From: cito at online.de (Christoph Zwerschke) Date: Fri, 12 May 2006 13:41:12 +0200 Subject: State of the "Vaults of Parnassus" Message-ID: Does anybody know what happened to the "Vaults of Parnassus" site at http://www.vex.net/~x/parnassus/? "Dr Dobb's weekly Python news" still claims that it "ambitiously collects references to all sorts of Python resources." But I have the impression that it does not do this any more since April 2005, probably because we have the Cheese Shop now. It's strange that the site does not mention that it is not maintained any more, and it is still possible to submit and update entries, but these changes seem to be discarded. That's not very nice. Also, I found no contact address on the whole website. Who is in charge of it? -- Christoph From NA at NA.com Tue May 9 02:46:21 2006 From: NA at NA.com (N/A) Date: Tue, 09 May 2006 14:46:21 +0800 Subject: Import data from Excel In-Reply-To: <1147155787.055054.52150@i40g2000cwc.googlegroups.com> References: <1147155787.055054.52150@i40g2000cwc.googlegroups.com> Message-ID: sorry, can you say it more clearly? In Matlab, I can easily import data from Excel just simply use 'xlsread' command. How to do that in Python environment? thank u! Paddy wrote: > The CSV module? > From junkytownMAKNI at gmail.com Mon May 29 12:17:07 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Mon, 29 May 2006 18:17:07 +0200 Subject: omniorbpy: problems sending float values In-Reply-To: <1148914432.514658.216050@38g2000cwa.googlegroups.com> References: <1148914432.514658.216050@38g2000cwa.googlegroups.com> Message-ID: Juergen wrote: > hi, > > I've got a problem sending floating point values to an corba server. > With other datatyes like short or string it works fine. > > > So having this idl file : > > module Example{ > interface User{ > void setV( in float x ); > }; > interface Target{ > void getV( out short x); > }; > }; > > I just receive zero ( -2.58265845332e-05) by sending an float to > another client with the above interface. > the client : > ********************************************************** > import sys > from omniORB import CORBA > import _omnipy > import Example, CosNaming > > orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) > > > > ior = sys.argv[1] > obj = orb.string_to_object(ior) > > us = obj._narrow( Example.User ) > > if us is None: > print "blabla" > sys.exit(1) > > us.setV( 5.0 ) > ********************************************************** > > the server : > ********************************************************** > import sys > from omniORB import CORBA, PortableServer > import CosNaming, Example, Example__POA > > class User_i( Example__POA.User ): > def setV( self, x ): > print x > print type(x) > y = float(x) > print y > print type(y) > > > class Target_i( Example__POA.Target ): > def getV( self ): > return 5 > > orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) > poa = orb.resolve_initial_references("RootPOA") > > > us = User_i() > tg = Target_i() > > uo = us._this() > to = tg._this() > print orb.object_to_string(uo) > print > print orb.object_to_string(to) > > > poaManager = poa._get_the_POAManager() > poaManager.activate() > > orb.run() > ********************************************************** > > does anyone have an answer to that kind of problem? > I mean, it just like sending short values, or strings. > I never used omniorb and have no clue were's the problem, but if you don't find a solution just convert float into a string on one side and back on the other hehe =B) From joel.hedlund at gmail.com Wed May 3 16:59:45 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 03 May 2006 22:59:45 +0200 Subject: Possibly dumb question about dicts and __hash__() In-Reply-To: <1146688748.486494.111430@j33g2000cwa.googlegroups.com> References: <1146686634.117498.313470@j73g2000cwa.googlegroups.com> <1146688748.486494.111430@j33g2000cwa.googlegroups.com> Message-ID: Beautiful! But how come my attempt didn't work? I've seen docs that explain how __hash__() methods are used to put objects in dict buckets: http://docs.python.org/ref/customization.html#l2h-195 But if it's really hash(str(o)) that's used for dict keys, what good are __hash__() methods? Or am I reading the docs wrong? /Joel From penneys at bigfoot.com Wed May 10 03:01:16 2006 From: penneys at bigfoot.com (MrBlueSky) Date: 10 May 2006 00:01:16 -0700 Subject: Redirecting unittest output to a Text widget Message-ID: <1147244476.396761.36600@i40g2000cwc.googlegroups.com> Morning! I'm writing my first Python program, so please have patience! I'd like to redirect the output from my application's unit tests ("import unittest") to a Tkinter Text object. I found the magic to redirect stdout and stderr: sys.stdout = myTextWindow sys.stderr = myTextWindow where myTextWindow inherits from Text and implements write() and writelines(). But the output from my UT still appears in the command window, not the Text box. My own "print" statements *do* appear in the Text box. Can anyone suggest a way forward here? John From raghavan.viswanathan at wipro.com Wed May 24 05:40:46 2006 From: raghavan.viswanathan at wipro.com (raghu) Date: 24 May 2006 02:40:46 -0700 Subject: referrers Message-ID: <1148463646.603330.275000@i40g2000cwc.googlegroups.com> Hi All, The sys.getrefcount() is very useful to get the number of references on a particular object. Is there any companion function to get "who" the referrers are ? for e.g. global x global y global z x0=24012 y=x0 z=x0 print "ref count ",sys.getrefcount(x0) This prints a ref count of 5. Basically, I need to know which are the 5 entities who are referring to x0 ? Is there any way of doing it ? Thanks. Bye, raghavan V From akameswaran at gmail.com Tue May 30 13:22:54 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 30 May 2006 10:22:54 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> Message-ID: <1149009774.346691.294680@r44g2000cwb.googlegroups.com> Well thanks for the mathematical restatement of my problem. I had forgotten the proper terms. Searching on those terms generates some interesting results. However, none of the algo's I have checked will work with generated sequences, or iterable classes, as posited in my first post. While appropriate to the current domain, ie dice. What if you want combinations of extrememely large lists, say 3 sets of 10 mil items. In such a case, I really do want my sets to be generators rather than lists or set objects. This is what had me stumped before, and still has me stumped. From manstey at csu.edu.au Thu May 18 18:53:12 2006 From: manstey at csu.edu.au (manstey) Date: 18 May 2006 15:53:12 -0700 Subject: newb: comapring two strings Message-ID: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> Hi, Is there a clever way to see if two strings of the same length vary by only one character, and what the character is in both strings. E.g. str1=yaqtil str2=yaqtel they differ at str1[4] and the difference is ('i','e') But if there was str1=yiqtol and str2=yaqtel, I am not interested. can anyone suggest a simple way to do this? My next problem is, I have a list of 300,000+ words and I want to find every pair of such strings. I thought I would first sort on length of string, but how do I iterate through the following: str1 str2 str3 str4 str5 so that I compare str1 & str2, str1 & str3, str 1 & str4, str1 & str5, str2 & str3, str3 & str4, str3 & str5, str4 & str5. Thanks in advance, Matthew From larry.bates at websafe.com Mon May 22 10:19:40 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 22 May 2006 09:19:40 -0500 Subject: problem with writing a simple module In-Reply-To: <1148307297.076724.128310@j33g2000cwa.googlegroups.com> References: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> <4471C4D9.8020806@websafe.com> <1148307297.076724.128310@j33g2000cwa.googlegroups.com> Message-ID: <_s2dnXJvyY7vVezZnZ2dneKdnZydnZ2d@comcast.com> nephish at xit.net wrote: > ok, cool, and thanks very much. That worked. > thanks for the info too. > i am still new at the OO thing, just tired of doing a copy and paste > over and over again. > > thanks again > Glad that helped. The OO "stuff" does require a new set of understanding, but once you get it you can write reusable classes and productivity really begins to take off. If you haven't yet picked one up, get a copy of the Python Cookbook (really good) and if you do Windows get a copy of Python Programming on Win32. -Larry From Bulkan at gmail.com Thu May 11 20:24:01 2006 From: Bulkan at gmail.com (placid) Date: 11 May 2006 17:24:01 -0700 Subject: Threads In-Reply-To: References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> Message-ID: <1147393441.055782.126380@i40g2000cwc.googlegroups.com> David Reed wrote: > On May 11, 2006, at 8:02 PM, placid wrote: > > > > > Carl J. Van Arsdall wrote: > >> placid wrote: > >>> Hi all, > >>> > >>> In Python, Threads cannot be paused, i remember reading this > >>> somewhere, > >>> so is there a way around this ? > >>> > >> > >> When you say paused do you mean paused by an external source or > >> paused > >> by a call internal to the thread? There are plenty of > >> synchronization > >> constructs for making threads wait: Check out Events and Conditions > > > > I have a thread that has a job Queue, it continuosly polls this queue > > to see if there are any jobs for it, what i really wont to be able to > > do is, when the queue is empty, i want the thread to pause (or more > > technical, i want the thread to block) until the queue gets populated > > again. Is this possible ? > > > > > > > The previous poster answered your question - you want to use a > condition variable. > > http://docs.python.org/lib/condition-objects.html thanks, this is what i was after > > Dave From russell_turpin at hotmail.com Fri May 26 12:08:01 2006 From: russell_turpin at hotmail.com (Russell) Date: 26 May 2006 09:08:01 -0700 Subject: How does a generator object refer to itself? In-Reply-To: <1148542937.078674.223580@i40g2000cwc.googlegroups.com> References: <1148311069.417177.254550@y43g2000cwc.googlegroups.com> <1148542937.078674.223580@i40g2000cwc.googlegroups.com> Message-ID: <1148659680.977207.198690@38g2000cwa.googlegroups.com> > Why don't you use a class ? Because we use this pattern for thousands of functions, and don't want thousands of new classes. Right now we use a single class that creates an instance for each such generator. I was hoping to find a way to get even more lightweight than that. :-) From aylwyn at cantab.net Wed May 17 15:39:50 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 12:39:50 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) References: <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <446B6AD1.4080104@mvista.com> Message-ID: <1147894790.768592.219760@u72g2000cwu.googlegroups.com> Dave Hansen wrote: >However, to twist an observation I've read about C++, while it's >clearly possible to use TABs in a sensible manner like this, it seems >that no one does. I think it's evident from this thread that quite a few people do that, judging by the fact that my previous post explaining this was doubly redundant by the time I got round to sending it. Also we should remember that in Python, alignment only applies to continuation lines and comments. Logical lines (the vast majority of lines in a source file) can't be arbitraily aligned. From sybrenUSE at YOURthirdtower.com.imagination Fri May 19 04:27:07 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 19 May 2006 10:27:07 +0200 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: Duncan Booth enlightened us with: > Can you point at any significant body of publically visible Python > code which uses tabs exclusively? Everything Python at http://www.stuvel.eu/software > Also, in the open source universe you are quite likely to pull in > bits of code from other projects, and you don't want to either have > to reformat it or to switch your editor settings for some files. If I grab a module, I just leave the module as is. If I grab a code snippet, I always reformat it to my own style. That's very easy using VIM's "retab" command. > Do you know of any open-source projects which actually try to enforce a > 'tab only' convention for Python? My software is, although I'm still the only one working on them ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From grante at visi.com Thu May 4 09:38:55 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 04 May 2006 13:38:55 -0000 Subject: Because of multithreading semantics, this is not reliable. References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <1146691613.911363.242620@e56g2000cwe.googlegroups.com> <4459c03b$0$2633$636a55ce@news.free.fr> <4459f1dd$1_2@newspeer2.tds.net> Message-ID: <125k0vfpqr93bcc@corp.supernews.com> On 2006-05-04, Olaf Meding wrote: >> return result before that line, some other thread added a value ! > > Sure, but that is the nature of using threads and a mutex. Yes. > I hope you are you not saying that every function that uses a > mutex should have a comment saying this is not "reliable"? My point exactly. -- Grant Edwards grante Yow! My pants just went to at high school in the Carlsbad visi.com Caverns!!! From ivoras at __yahoo__.com_ Fri May 12 18:53:32 2006 From: ivoras at __yahoo__.com_ (Ivan Voras) Date: Sat, 13 May 2006 00:53:32 +0200 Subject: Slow network reading? In-Reply-To: References: Message-ID: Andrew MacIntyre wrote: > Comparative CPU & memory utilisation statistics, not to mention platform > and version of Python, would be useful hints... During benchmarking, all versions cause all CPU to be used, but Python version has ~1.5x more CPU time allocated to it than PHP. Python is 2.4.1 > Note that the file-like object returned by makefile() has significant > portions of heavy lifting code in Python rather than C which can be a > drag on ultimate performance... If on a Unix platform, it may be worth > experimenting with os.fdopen() on the socket's fileno() to see whether > the core Python file object (implemented in C) can be used in place of > the lookalike returned from the makefile method. That's only because I need the .readline() function. In C, I'm using fgets() (with the expectation that iostream will buffer data). > Even without that, you are specifying a buffer size smaller than the > default (8k - see Lib/socket.py). 16k might be even better. The benchmark is such that all of data is < 200 bytes. I estimate that in production almost all protocol data will be < 4KB. > Although they're only micro-optimisations, I'd be interested in the > relative performance of the query method re-written as: The change (for the better) is minor (3-5%). From kentilton at gmail.com Thu May 11 00:20:46 2006 From: kentilton at gmail.com (Ken Tilton) Date: Thu, 11 May 2006 00:20:46 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hf26zk.1uqniari93h7fN%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> <87ac9r1tem.fsf@snobis.de> <1hf26zk.1uqniari93h7fN%aleax@mac.com> Message-ID: Alex Martelli wrote: > Stefan Nobis wrote: > > >>aleax at mac.com (Alex Martelli) writes: >> >> >>>if anonymous functions are available, they're used in even more >>>cases where naming would help >> >>Yes, you're right. But don't stop here. What about expressions? Many >>people write very complex expression, that are hard to understand. A >>good language should forbid these abuse and don't allow expressions >>with more than 2 or maybe 3 operators! > > > That would _complicate_ the language (by adding a rule). I repeat what > I've already stated repeatedly: a good criterion for deciding which good > practices a language should enforce and which ones it should just > facilitate is _language simplicity_. If the enforcement is done by > adding rules or constructs it's probably not worth it; if the > "enforcements" is done by NOT adding extra constructs it's a double win > (keep the language simpler AND push good practices). Gosh, that looks like fancy footwork. But maybe I misunderstand, so I will just ask you to clarify. In the case of (all syntax imaginary and not meant ot be Python): if whatever = 42 dothis do that do something else else go ahead make my day You do not have a problem with unnamed series of statements. But in the case of: treeTravers( myTree, lambda (node): if xxx(node) print "wow" return 1 else print "yawn" return 0) ...no, no good, you want a named yawnOrWow function? And though they look similar, the justification above was that IF-ELSE was lucky enough to get multiline branches In the Beginning, so banning it now would be "adding a rule", whereas lambda did not get multiline In the Beginning, so allowing it would mean "adding a construct". So by positing "adding a rule or construct" as always bad (even if they enforce a good practice such as naming an IF branch they are bad since one is /adding/ to the language), the inconsistency becomes a consistency in that keeping IF powerful and denying lambda the same power each avoids a change? In other words, we are no longer discussing whether unnamed multi-line statements are a problem. The question is, would adding them to lambda mean a change? Oh, yeah, it would. :) hth, kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From yinglcs at gmail.com Wed May 31 21:52:41 2006 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 31 May 2006 18:52:41 -0700 Subject: Save data to a file thru a http connection In-Reply-To: <447e0221$1@nntp0.pdx.net> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> <447e0221$1@nntp0.pdx.net> Message-ID: <1149126761.726836.73360@y43g2000cwc.googlegroups.com> Scott, Can you please tell me which chapter of the tutorial that you are referring to http://docs.python.org/tut/tut.html? The only chapter that I find about http is chapter 10.7, but it does not have the example that you are referring to Scott David Daniels wrote: > yinglcs at gmail.com wrote: > > I am new to python. I read an example here about how to fetch data thru > > a HTTP connection: > > http://diveintopython.org/http_web_services/review.html, > > > > My question is how can i save the data to a file after reading it from > > a http connection. > > Do the tutorial and this and many other things will become clear. > > Instead of just "print sometext", do something like: > ... > f = open('filename', 'w') > ... > print >>f, sometext > ... (possibly more prints like the above). > f.close() > > --Scott David Daniels > scott.daniels at acm.org From duncanm255 at hotmail.com Mon May 8 10:36:19 2006 From: duncanm255 at hotmail.com (D) Date: 8 May 2006 07:36:19 -0700 Subject: Active Directory Authentication In-Reply-To: References: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> Message-ID: <1147098979.335452.137330@g10g2000cwb.googlegroups.com> Thanks to everyone for your help..I'm not familiar with the packages mentioned, so this will definitely be a learning experience! From scott.daniels at acm.org Wed May 31 12:30:10 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 31 May 2006 09:30:10 -0700 Subject: wx: PyNoAppError In-Reply-To: References: Message-ID: <447dc033$1@nntp0.pdx.net> SuperHik wrote: (1) A wxPython question. Better to ask on the wxPython newsgroup (listed as comp.python.wxpython on gmane). > Using XP SP2, PythonWin 2.4.3, any trying to use wx 2.6.3.2 > When using wx, the first time I run a script it runs fine. > Second time, it rasises an error: .... Up here you should have mentioned you are doing this in IDLE, that is your problem. Later in your message you say: > ... *Says that runnig the script outside of IDLE fixes the problem. > That works for me too but if there is a way to run it from IDLE > that would be much easier. This is the inevitable result of running a pair of GUIs simultaneously: They both want control of the main program to run their idle loop, and only can win. --Scott David Daniels scott.daniels at acm.org From martin at v.loewis.de Sat May 27 08:06:34 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sat, 27 May 2006 14:06:34 +0200 Subject: how to clear up a List in python? In-Reply-To: <44773ba7.0@entanet> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148653059.381151.113360@j73g2000cwa.googlegroups.com> <44772de5.0@entanet> <1148662012.600336.113660@j33g2000cwa.googlegroups.com> <44773ba7.0@entanet> Message-ID: <447840CA.6030106@v.loewis.de> Duncan Smith wrote: > chris brat wrote: >> Doesnt this do what the original poster is try accomplish? >> > > Not what the OP asked for, no. Clearing a list implies that list1 > should still be bound to the same list (which might be important if > there are other names bound to the same list). If it wasn't important > that it be bound to the same list then I would probably go with > linnorm's approach (which isn't really 'clearing' the list). Sure. However, the OP still might have been happy with just discarding the old list and creating a new one. Although he explicitly said "clear the list", he might have meant "make it so that the variable refers to an empty list", to which clearing the list is only one possible solution. Regards, Martin From robert.kern at gmail.com Mon May 29 01:33:39 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 29 May 2006 00:33:39 -0500 Subject: dynamically loaded libraries In-Reply-To: References: Message-ID: mhearne808 wrote: > I have a question about how dynamically loaded C++ modules work, which > I will phrase as a hypothetical scenario involving the Numeric module. > Please understand that I don't really care about Numeric per se, it's > just a useful example of a module that defines a generally useful data > type. > > Let's say I want to create a C++ Python extension module that has > methods accepting the Numeric array type as input, and also create > these arrays as output. > > In order to make this work, do I have to statically link against the > Numeric source, or do I only have to include the headers, under the > assumption (??) that the Numeric functionality will be available > because the Python executable has dynamically loaded it? Here's how Numeric/numarray/numpy do it (I'll discuss numpy since it is the currently developed one): Pointers to each of the API items that we want to export, types and functions mostly, are packed into a void** array, PyArray_API. A common header file is used by the numpy extension module that provides the API (multiarraymodule.so) and each of the modules that use the API. We use #ifdefs to determine whether to use real prototypes (for multiarray) or #defines that index into PyArray_API and cast the function pointer there to the appopriate prototype (for everybody else). In initmultiarray(), we actually pack PyArray_API with the appropriate pointers and create a PyCObject that points to the beginning of the array. The CObject is assigned to multiarray._ARRAY_API . We define a function import_array() for the API-users that will import multiarray, get the object _ARRAY_API and assign pointer to the beginning of the array to void **PyArray_API. import_array() is supposed to be called in the initialization function of the other extension modules. That will make sure that multiarray is imported and the function pointers are available for dereferencing. -- 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 roy at panix.com Mon May 8 09:28:40 2006 From: roy at panix.com (Roy Smith) Date: Mon, 08 May 2006 09:28:40 -0400 Subject: which is better, string concatentation or substitution? References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> Message-ID: In article <445ec45e$0$1965$c3e8da3 at news.astraweb.com>, John Salerno wrote: > My initial feeling is that concatenation might take longer than > substitution, but that it is also easier to read: > > > def p(self, paragraph): > self.source += '

    ' + paragraph + '

    \n\n' > > vs. > > def p(self, paragraph): > self.source += '

    %s

    \n\n' % paragraph > > > > Is there a preference between these two ways? One may be marginally faster, but they both require copying the source string, and are thus both O(n). If you're just doing one or a small fixed number of these, it really doesn't matter. Pick whichever one you think is easier to read. On the other hand, if you're doing a lot of them (i.e. in a loop), the entire loop will now be O(n^2), which is a killer. If that's the case, what you want to do is accumulate the individual substrings in a list, then join the list elements all at once: parts = [] for paragraph in foo: parts.append ('

    ') parts.append (paragraph) parts.append ('

    \n\n') # or maybe instead of that ... # parts += ['

    ', paragraph, '

    \n\n'] self.source = "".join (parts) This only requires a single copy, and thus you're back to being O(n), which beats the heck out of O(n^2). From bencvt at gmail.com Sat May 6 21:38:40 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 6 May 2006 18:38:40 -0700 Subject: Splice two lists References: <1146961724.195038.18680@u72g2000cwu.googlegroups.com> Message-ID: <1146965920.842441.168920@i40g2000cwc.googlegroups.com> danmcleran at yahoo.com wrote: > Is there a good way to splice two lists together without resorting to a > manual loop? Say I had 2 lists: > > l1 = [a,b,c] > l2 = [1,2,3] > > And I want a list: > > [a,1,b,2,c,3] as the result. Our good friend itertools can help us out here: >>> from itertools import chain, izip >>> x = ['a', 'b', 'c'] >>> y = [1, 2, 3] >>> list(chain(*izip(x, y))) ['a', 1, 'b', 2, 'c', 3] >>> # You can splice more than two iterables at once too: >>> z = ['x', 'y', 'z'] >>> list(chain(*izip(x, y, z))) ['a', 1, 'x', 'b', 2, 'y', 'c', 3, 'z'] >>> # Cleaner to define it as a function: >>> def splice(*its): return list(chain(*izip(*its))) >>> splice(x, y) ['a', 1, 'b', 2, 'c', 3] >>> splice(x, y, z) ['a', 1, 'x', 'b', 2, 'y', 'c', 3, 'z'] --Ben From rpdooling at gmail.com Sun May 7 19:14:46 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 7 May 2006 16:14:46 -0700 Subject: why _import__ only works from interactive interpreter? References: <1147041996.232232.165820@i39g2000cwa.googlegroups.com> Message-ID: <1147043686.558715.124540@j73g2000cwa.googlegroups.com> I'm on Windows, but I think you need the shebang thing at the top of your script, right? Then, put whatever you want to import in a script or module called testmod.py. Then you should be able to import either into a script or at the command line using simply: import testmod If it doesn't work then you need to make sure the script is in your PythonPath. It looks like you are using the built-in function version of import. http://docs.python.org/dev/lib/built-in-funcs.html Is there a reason? Otherwise, do it the easy way: rick From tjreedy at udel.edu Sat May 6 21:37:41 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 May 2006 21:37:41 -0400 Subject: the print statement References: <1146950481.610645.39710@j33g2000cwa.googlegroups.com> <1146960978.564533.59730@j73g2000cwa.googlegroups.com> Message-ID: wrote in message news:1146960978.564533.59730 at j73g2000cwa.googlegroups.com... > bit of an understanding of the \xhh pattern. It's still unclear to me, > however, how one can go from the \x92 pattern and arrive at the > apostrophe character. Is \x92 the apostrophe character in another > character set? If so, which character set? What you see with "print '\x92'" and indeed any value above '\x7F' is situation-dependent. On my WinXP system, typing that in the Python command window gives the AE ligature (ie, the two letters joined together). Doing the same in the IDLE shell window gives an accent mark similar to ` but slanting the other way. An apostrophe ' in the same window is vertical, so they are different characters. Terry Jan Reedy From mhellwig at xs4all.nl Sat May 6 07:27:02 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 06 May 2006 13:27:02 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <87mzdvo2nm.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> Message-ID: <445c8812$0$31639$e4fe514c@news.xs4all.nl> Bill Atkins wrote: > "Martin P. Hellwig" writes: > >> Bill Atkins wrote: >> >>> How do you define scalability? >>> >> http://www.google.com/search?hl=en&q=define%3Ascalability&btnG=Google+Search >> >> ;-) >> >> -- >> mph > > OK, my real question is: what features of Python make it "scalable"? > Well I'm no expert, but I guess the ease of creating network services and clients make it quite scalable. For example, I'm creating a xmlrpcserver that returns a randomized cardlist, but I because of fail-over I needed some form of scalability , my solution was to first randomize the deck then marshal it and dump the file on a ZFS partition, giving back the client a ticket number, the client can then connect with the ticket number to receive the cardlist (read the file - unmarshal it). While this is overkill for 1 server, I needed multiple because of fail-over and load-balancing, in this case I have 3 'crypto' boxes (with hardware crypto engines using OpenBSD) doing only the randomizing and 4 solaris machines doing the zfs and distribution of the list. By using xmlrpc and DNS round-robin, I can just add boxes and it scales without any problem, The ZFS boxes are the front-end listening to the name 'shuffle' and are connecting to a private network to my crypto boxes listening to the name 'crypto'. So as long as I make DNS aliases (I have a little script that hearbeats the boxes and when not responding within 10 seconds removes it alias) and install the right scripts on the box I can scale till I'm round the earth. Of course when the machine amount gets over a certain degree I have to add some management functionality. Now I don't say that I handle this situation well and that its the right solution, but it worked for me and it was easy and fun to do with python, but I guess that any language in this sence should be 'scalable' and perhaps other languages have even better built-in networking libraries but I'm not a professional programmer and until I learn other languages (and are comfortable enough to use it) I'll keep on using python for my projects. For me python is easy, scalable, fun and by this the 'best' but that is personal and I simply don't know whether my opinion will change in the future or not. -- mph From tbrkic at yahoo.com Thu May 18 03:04:00 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 00:04:00 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <446bb897$1@nntp0.pdx.net> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <446bb897$1@nntp0.pdx.net> Message-ID: <1147935840.210400.216590@38g2000cwa.googlegroups.com> Actually we did start of with YAML, but realised that we need to have the power of a programming language aswell. But I wanted to come up with something that looked very clos to YAML since I find it quite readable. I have implemented the syntax, but as a preprocessor for python and it works quite nice. Cheers, T From bdesth.quelquechose at free.quelquepart.fr Mon May 15 20:58:30 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 May 2006 02:58:30 +0200 Subject: regular expression error ? In-Reply-To: <4468e354$0$61167$ae4e5890@news.nationwide.net> References: <4468e354$0$61167$ae4e5890@news.nationwide.net> Message-ID: <4468f4a8$0$5147$626a54ce@news.free.fr> Lance Hoffmeyer a ?crit : > why isn't re.search recognizing "file"? I can print the contents of "file". > > > import win32com.client > import re > > D=MSWord.Documents.Open('C:/test/Test.doc') > file=D.Content > print file > > match = re.search('(Table ?)', file) > if match: > print "Table Number is: ", match.group(1) > > > Traceback (most recent call last): > File "test.py", line 21, in ? > match = re.search('(Table ?)', file) > File "C:\Python24\Lib\sre.py", line 134, in search > return _compile(pattern, flags).search(string) > TypeError: expected string or buffer The fact that you can print 'file' doesn't mean it's a string. You may want to try this: (...) # let's see what it really is: print type(D.Content), repr(D.Content) # and try to make it usable for re: file = str(D.Content) (...) NB : not tested, I don't have Word on my Linix box !-) From NOatkinwSPAM at rpi.edu Sun May 7 03:02:17 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 03:02:17 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> Message-ID: <87psiq48sm.fsf@rpi.edu> "Serge Orlov" writes: > Ken Tilton wrote: >> It is vastly more disappointing that an alleged tech genius would sniff >> at the chance to take undeserved credit for PyCells, something probably >> better than a similar project on which Adobe (your superiors at >> software, right?) has bet the ranch. This is the Grail, dude, Brooks's >> long lost Silver Bullet. And you want to pass????? >> >> C'mon, Alex, I just want you as co-mentor for your star quality. Of >> course you won't have to do a thing, just identify for me a True Python >> Geek and she and I will take it from there. >> >> Here's the link in case you lost it: >> >> http://www.lispnyc.org/wiki.clp?page=PyCells >> >> :) >> >> peace, kenny >> >> ps. flaming aside, PyCells really would be amazingly good for Python. >> And so Google. (Now your job is on the line. ) k > > Perhaps I'm missing something but what's the big deal about PyCells? > Here is 22-lines barebones implementation of spreadsheet in Python, > later I create 2 cells "a" and "b", "b" depends on a and evaluate all > the cells. The output is > > a = negate(sin(pi/2)+one) = -2.0 > b = negate(a)*10 = 20.0 > > =================== spreadsheet.py ================== > class Spreadsheet(dict): > def __init__(self, **kwd): > self.namespace = kwd > def __getitem__(self, cell_name): > item = self.namespace[cell_name] > if hasattr(item, "formula"): > return item() > return item > def evaluate(self, formula): > return eval(formula, self) > def cell(self, cell_name, formula): > "Create a cell defined by formula" > def evaluate_cell(): > return self.evaluate(formula) > evaluate_cell.formula = formula > self.namespace[cell_name] = evaluate_cell > def cells(self): > "Yield all cells of the spreadsheet along with current values > and formulas" > for cell_name, value in self.namespace.items(): > if not hasattr(value, "formula"): > continue > yield cell_name, self[cell_name], value.formula > > import math > def negate(x): > return -x > sheet1 = Spreadsheet(one=1, sin=math.sin, pi=math.pi, negate=negate) > sheet1.cell("a", "negate(sin(pi/2)+one)") > sheet1.cell("b", "negate(a)*10") > for name, value, formula in sheet1.cells(): > print name, "=", formula, "=", value > I hope Ken doesn't mind me answering for him, but Cells is not a spreadsheet (where did you get that idea?). It does apply the basic idea of a spreadsheet to software - that is, instead of updating value when some event occurs, you specify in advance how that value can be computed and then you stop worrying about keeping it updated. Incidentally, is this supposed to be an example of Python's supposed "aesthetic pleasantness"? I find it a little hideous, even giving you the benefit of the doubt and pretending there are newlines between each function. There's nothing like a word wrapped in pairs of underscores to totally ruin an aesthetic experience. P.S. Is this really a spreadsheet? It looks like it's a flat hashtable... -- This is a song that took me ten years to live and two years to write. - Bob Dylan From jeff_barish at earthlink.net Sat May 20 16:47:42 2006 From: jeff_barish at earthlink.net (Jeffrey Barish) Date: Sat, 20 May 2006 14:47:42 -0600 Subject: Name conflict in class hierarchy Message-ID: I believe that the answer to my question is no, but I want to be sure that I understand this issue correctly: Suppose that there are two classes defined as follows: class A(object): def f1(self): print 'In A.f1, calling func' self.func() def func(self): print 'In A.func' class B(A): def func(self): print 'In B.func, calling A.f1' A.f1(self) Class A was defined by someone else or it comes from a library, so I have no prior information about what is in it. I subclass A to add some new functionality, and I call the new function "func". The function B.func uses A.f1, but unbeknownst to me, A.f1 uses A.func. Unfortunately, class B overrides func, so the call in A.f1 to self.func actually invokes B.func, resulting in this case in an infinite loop. Is there a way from B to specify that A should use its own version of func and ignore the version in B? I know that I could rename A.func to avoid the name clash, but since A is actually in a library, I will lose that change when I upgrade the library. I could rename B.func, but there is already a bunch of code that calls it so I would have to update all the calls. That seems like the correct solution, though. The other possibility is to use composition rather than subclassing: class B: def func(self): print 'In B.func, calling A.f1' a = A() a.f1() but then B does not inherit other functions of A that I would like to use. It struck me that this must be a common problem in OOP, so I'm wondering whether there is a simple solution that I am missing. -- Jeffrey Barish From elventear at gmail.com Fri May 19 22:56:20 2006 From: elventear at gmail.com (elventear) Date: Sat, 20 May 2006 02:56:20 GMT Subject: Question about Python on Mac References: <1148073591.308980.289300@u72g2000cwu.googlegroups.com> Message-ID: <2006051921555775249-elventear@gmailcom> On 2006-05-19 16:19:51 -0500, "elventear" said: > The weird thing is that just for kicks I tried building with Python > that comes with MacOSX (py2.3) and it works. It builds and it loads > fine. Anybody have an idea why this would happen? Any ideas how to > solve this? In the worse case scenario, can I use the binary (gmpy.so) > built with against Python 2.3 with Python 2.4.3 (It seems to load > correctly but I don't know if I should expect any meltdowns later on) First of all I have to correct myself and say that the latest version offered in Fink is 2.4.2. I decided to try with binary build of MacPython 2.4.3 available on Python.org and it also works. Weird. Could this be related to some bug in Python 2.4.2? Thanks. From akameswaran at gmail.com Thu May 18 17:52:23 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 14:52:23 -0700 Subject: python vs perl lines of code In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: <1147989143.575737.285300@y43g2000cwc.googlegroups.com> >Until we get the code to examine independently, all we have is an >anecdote. Thus the comparison to UFO sightings. touche! Ed post the code, please - it'll be fun. We won't hurt you. From gene.tani at gmail.com Mon May 1 10:08:02 2006 From: gene.tani at gmail.com (gene tani) Date: 1 May 2006 07:08:02 -0700 Subject: Measure memory usage in Python In-Reply-To: <1146490276.060838.63870@i40g2000cwc.googlegroups.com> References: <1146431890.904603.98620@i39g2000cwa.googlegroups.com> <1146455362.984926.216240@g10g2000cwb.googlegroups.com> <1146490276.060838.63870@i40g2000cwc.googlegroups.com> Message-ID: <1146492482.691896.58230@e56g2000cwe.googlegroups.com> Rune Strand wrote: > gene tani wrote: > > Rune Strand wrote: > > > Is there a way to measure how much memory a data structure use? For > > > instance, what is the footprint of a particular list object like > > > [0,1,2,3,4,5,6,7,8,9]? > > > > i have a note to try this, but haven't got around to it, if you want to > > blog/post > > > > http://pysizer.8325.org/ > > Thank you! That seems to be what I was looking for. ok, my notes are disorganized: http://guppy-pe.sourceforge.net/#Heapy http://www.softwareverify.com/ From gregory.petrosyan at gmail.com Mon May 22 10:37:35 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 22 May 2006 07:37:35 -0700 Subject: enumerate() question In-Reply-To: References: <1148308146.493287.323770@38g2000cwa.googlegroups.com> Message-ID: <1148308655.816148.13620@i39g2000cwa.googlegroups.com> Thanks a lot. From bdesth.quelquechose at free.quelquepart.fr Thu May 11 20:06:54 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 May 2006 02:06:54 +0200 Subject: 2 books for me In-Reply-To: <1147375933.114803.40870@q12g2000cwa.googlegroups.com> References: <87lkt9ytxx.fsf@localhost.localdomain> <4462f24d$0$311$636a55ce@news.free.fr> <1147375933.114803.40870@q12g2000cwa.googlegroups.com> Message-ID: <4463a2aa$0$297$636a55ce@news.free.fr> Robert Hicks a ?crit : > Wouldn't portability go with Tkinter since that is installed with every > Python? Tkinter ? What's that ?-) From phddas at yahoo.com Sat May 6 16:22:38 2006 From: phddas at yahoo.com (Gary Wessle) Date: 07 May 2006 06:22:38 +1000 Subject: sort a list of files Message-ID: <877j4ysy29.fsf@localhost.localdomain> Hi I am trying to print out the contents of a directory, sorted. **************** the code **************** 1 import os, sys 2 3 if len(sys.argv) < 2: 4 sys.exit("please enter a suitable directory.") 5 6 print os.listdir(sys.argv[1]).sort() **************************************************************** if I remove ".sort()" at the end of line 6 I get an unsorted list of files, if I leave it I get None. who do I fix this? thank you From sam at nuevageorgia.com Mon May 22 12:04:59 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 22 May 2006 09:04:59 -0700 Subject: Python - Web Display Technology In-Reply-To: <1148313166.202814.55680@j73g2000cwa.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> Message-ID: <1148313899.527530.58390@i40g2000cwc.googlegroups.com> Perhaps the my question should be this, and don't get me wrong, I REALLY like Python. Perhaps Python is not a great language to focus on for someone with a strong interest in Flash and little interest in HTML? From skn at skn.com Fri May 5 03:28:21 2006 From: skn at skn.com (Shankar) Date: Fri, 5 May 2006 12:58:21 +0530 Subject: Embedding Python: How to run compiled(*.pyc/*.pyo) files using Python C API? Message-ID: Hello, I am trying to run compiled Python files (*.pyc and *.pyo) using Python C API. I am using the method PyRun_FileFlags() for this purpose. The code snippet is as follows:- PyCompilerFlags myFlags; myFlags.cf_flags=1; // I tried all values 0, 1 and 2 PyRun_FileFlags(script, file, Py_file_input, globals, locals, &myFlags); But unfortunately I get the following exception:- "DeprecationWarning: Non-ASCII character '\xf2' in file E:\test.pyc on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details" When I run the .py file, then things work fine. The .py file contains only one statement, print "Hello World" Which Python C API should I use to run compiled Python files(*.pyc and *.pyo) in the scenario where the source file (*.py) is not present. Thanks in advance, Regards, Shankar From __peter__ at web.de Thu May 25 02:25:08 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 25 May 2006 08:25:08 +0200 Subject: Conversion of perl based regex to python method References: <127923enb2dbh21@corp.supernews.com> <127998j378v4n3d@corp.supernews.com> Message-ID: Andrew Robert wrote: Wanted: > perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge'??somefile.txt Got: > # Evaluate captured character as hex > def ret_hex(ch): > return?chr((ord(ch)?+?1)?%?) Make it compile at least before posting :-) > # Evaluate the value of whatever was matched > def eval_match(match): > return?ret_hex(match.group(0)) > > # open file > file = open(r'm:\mq\mq\scripts\testme.txt','r') > > # Read each line, pass any matches on line to function > for line in file.readlines(): > re.sub('[^\w\s]',eval_match,?line) for line in file: ... without readlines() is better because it doesn't read the whole file into memory first. If you want to read data from files passed as commandline args or from stdin you can use fileinput.input(): import re import sys import fileinput def replace(match): return "%%%2X" % ord(match.group(0)) for line in fileinput.input(): sys.stdout.write(re.sub("[^\w\s]", replace, line)) Peter From nobody at 127.0.0.1 Mon May 29 15:43:22 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 29 May 2006 19:43:22 GMT Subject: Ricerca Programmatore Python References: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> <447afc06@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > I understand there is an Italian-language Python group, but _here_ > the language is English, even if you begin by an apology in English. > ... In consideration for such people, please limit yourself to English. I doubt he'll ever see your reprimand, looks like a hit-and-run job. Too bad we can't force non-English posts through Babelfish first. At the very least, we'll get a good laugh out of it: Blank to all, I write in order to inform you of one proposed of collaboration. I am trying a programmatore for the realization of a minium-software useful in order to analyze and to represent multigrafi. An optimal competence is demanded in uses of Python with the relati to you packages of mathematical rappresentazione (es. matplotlib). For the notion of grafo it is referred to the following pages: http://it.wikipedia.org/wiki/Teoria_dei_grafi (Italian). http://en.wikipedia.org/wiki/Graph_theory (English). The residence in province of Milan, sight of a possible encounter is preferibile. Draft of one retribuita external collaboration. The interested ones can directly contact to the present deliveries in tail to the email, sending the relative resume to me. I hope of to have made what appreciate postando this announcement. In contrary case, I make excuses myself for the disturbance. Salutes, Giandomenico Sica -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From qrczak at knm.org.pl Sat May 13 07:44:01 2006 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sat, 13 May 2006 13:44:01 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: <87fyjejgji.fsf@qrnik.zagroda> Alexander Schmolck writes: > I'd like to see a demonstration that using the same binding syntax > for special and lexical variables buys you something apart from bugs. There are 3 fundamental operations related to plain mutable variables: A1. Making a new mutable variable with an initial value. A2. Getting the current value. A3. Setting the new value. and 4 operations related to dynamically scoped variables: B1. Making a new dynamic variable with an initial value. B2. Getting the current value. B3. Setting the new value. B4. Local rebinding with a new initial value. If you don't ever use B4, dynamic variables behave exactly like plain variables. For this reason I see no point in distinguishing A2 from B2, or A3 from B3. Dynamic variables are a pure extension of plain variables by providing an additional operation. Distinguishing the syntax of A1 and B1 is natural: somehow it must be indicated what kind of variable is created. Mutability is orthogonal to dynamic scoping. It makes sense to have a variable which is like a plain variable but without A3, and a variable which is like a dynamic variable but without B3, although it doesn't provide anything new, only allows to express more constraints with a potential for optimization. I won't consider them here. Common Lisp does something weird: it uses the same syntax for A1 and B4, where the meaning is distinguished by a special declaration. Here is its syntax: Directly named plain variables: A1. (let ((name value)) body) and other forms A2. name A3. (setq name value), (setf name value) First-class dynamic variables: B1. (gensym) B2. (symbol-value variable) B3. (set variable value), (setf (symbol-value variable) value) B4. (progv `(variable) `(value) body) Directly named dynamic variables: B1. (defvar name value), (defparameter name value) B2. name B3. (setq name value), (setf name value) B4. (let ((name value)) body) and other forms Dynamic variables in Lisp come in two flavors: first-class variables and directly named variables. Directly named variables are always global. You can convert a direct name to a first-class variable by (quote name). Plain variables have only the directly named flavor and they are always local. You can emulate the first-class flavor by wrapping a variable in a pair of closures or a closure with dual getting/setting interface (needs a helper macro in order to be convenient). You can emulate a global plain variable by wrapping a dynamic variable in a symbol macro, ignoring its potential for local rebinding. You can emulate creation of a new first-class variable by using a dynamic variable and ignoring its potential for local rebinding, but this can't be used to refer to an existing directly named plain variable. In order to create a plain variable, you must be sure that its name is not already used by a dynamic variable in the same scope. So any essential functionality is possible to obtain, but the syntax is very irregular. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From loren.davie at gmail.com Tue May 2 09:30:15 2006 From: loren.davie at gmail.com (loren.davie at gmail.com) Date: 2 May 2006 06:30:15 -0700 Subject: py2app, pythoncard build problems Message-ID: <1146576615.234047.196110@v46g2000cwv.googlegroups.com> Hi, I'm attempting to build a small app that uses pythoncard for a gui layer. The intention is to use py2app to construct an .app bundle for the Mac. I'm running OS 10.4 on an Intel MacBook Pro. I'm using the default installed Python 2.3 The .app bundle appears to build, but when I start up it fails - checking the console reveals that it can't find the "wx" package, as its called from some pythoncard code. (The app launches just fine in non-bundled form when I run it from the command line using pythonw). Not sure where to go with this. Any help would be greatly appreciated - thanks. From danmcleran at yahoo.com Fri May 26 15:29:34 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 26 May 2006 12:29:34 -0700 Subject: PIL problem with biprocessor hardware In-Reply-To: <1148670754.148116.23950@y43g2000cwc.googlegroups.com> References: <1148661656.407762.147020@j73g2000cwa.googlegroups.com> <1148663531.254814.301790@i40g2000cwc.googlegroups.com> <1148665221.735821.211520@y43g2000cwc.googlegroups.com> <1148670754.148116.23950@y43g2000cwc.googlegroups.com> Message-ID: <1148671774.185653.234650@j55g2000cwa.googlegroups.com> oops. lost my train of thought. I was gonna say, I wonder if some of these image manipulation routines are using multiple threads? From hancock at anansispaceworks.com Fri May 19 10:15:49 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 19 May 2006 14:15:49 +0000 Subject: python vs perl lines of code In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> Message-ID: <446DD315.5010704@anansispaceworks.com> Edward Elliott wrote: >For inquiries into real-world code, it's enough to >believe that I'm not lying > Yeah, well, this is the internet -- I've gotten emails trying to sell me ex-soviet rocket-launchers and child porn.* So I don't make assumptions about people without some kind of evidence. There *are* plenty of "bad guys" out there, so one learns both to have a thick skin and to rely on that which is reasonably proven, rather than making casual assumptions of good will. That'd be like leaving your car in downtown LA overnight with the doors unlocked. Cheers, Terry *In the same email, no less. This is of course an extreme example, but there are *loads* of merely irritating behaviors like trolling. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From tim.leeuwvander at nl.unisys.com Wed May 17 08:40:18 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 17 May 2006 05:40:18 -0700 Subject: Option parser question - reading options from file as well as command line In-Reply-To: <126m3ru1ql02m72@corp.supernews.com> References: <126k3273j7kb28f@corp.supernews.com> <1147851955.954641.180880@38g2000cwa.googlegroups.com> <126m3ru1ql02m72@corp.supernews.com> Message-ID: <1147869618.724199.313820@38g2000cwa.googlegroups.com> Andrew Robert wrote: > Tim N. van der Leeuw wrote: > > Andrew Robert wrote: [...] > Hi Tim, > > I am using the pymqi module which is freely available at > http://pymqi.sourceforge.net/ . > > Documentation on the module can be found at > http://pymqi.sourceforge.net/pymqidoc.html . > > I have a few python examples on my web site located at > http://home.townisp.com/~arobert/ > > There are also a lot of good examples at > http://www.koders.com/info.aspx?c=ProjectInfo&pid=TVM5FGBZMY4E5ZH7GC9AX54PAC > . > > If you come up with anything, I would be glad to see what you have. > > Thanks a lot for these examples! I have some Java tools that send MQ messages (reading, in fact, a ton of command-line arguments from a file) and I need better tools. If I could use some Python for rewriting this, it might speed me up a lot. > Back to the original issue: > > I'm not sure exactly what you mean about the readfile option and format. > > Could you send me a code snippet so I can get a better feel for it? > > > Thanks, > Andy Here's the file I used: ===cut here=== x=4 w=6 what=7 zoo=9 ===cut here=== Here's some snippets of code: >>> from optparse import OptionParser >>> op = OptionParser() >>> op.add_option('-x', dest='x') >>> op.add_option('--what', '-w', dest='what') >>> v=op.parse_args()[0] >>> v.read_file('options-test.txt') >>> v As you can see, I'm parsing an empty command-line but I could parse a full command-line as well before loading options from file. After parsing the command-line, I get an instance of a 'Values' object, and on this object I call a method 'read_file' with a filename. (I could also call 'read_module', and it will add the __doc__ string). I didn't test what happens with a more advanced useage of OptionParser options. Cheers, --Tim From mumia.w.18.spam+fbi.gov at earthlink.net Fri May 26 12:17:18 2006 From: mumia.w.18.spam+fbi.gov at earthlink.net (Mumia W.) Date: Fri, 26 May 2006 16:17:18 GMT Subject: John Bokma harassment In-Reply-To: <4476e478$0$4510$9b4e6d93@newsread2.arcor-online.net> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <447479A1.8050809@hotORgooMAIL.invalid> <447485B6.4070507@hotORgooMAIL.invalid> <44748E79.9010208@hotORgooMAIL.invalid> <4476e478$0$4510$9b4e6d93@newsread2.arcor-online.net> Message-ID: Robert Sedlacek wrote: > In comp.lang.perl.misc Mitch wrote > >> All that I snipped is your opinion, which is yours to do with as you >> please. "I like it just the way it is." is *MY* opinion, so please >> don't try to change it. I think I know my opinion best. > > Wrong. You don't like it how it is. Because as it is now, if someone > acts irresponsible for his own actions, his ISP might get an abuse > message and might act on that. [...] To suggest that Xah's *on-topic* posts to *five* newsgroups is irresponsible is ludicrous. In this newsgroup, there's a message crossposted to about a dozen newsgroups with a subject of "teen sister peeing outside." This message contains a trojan. *That*'s an example of an irresponsible message. Xah's posts are not. From timr at probo.com Mon May 1 00:51:24 2006 From: timr at probo.com (Tim Roberts) Date: Mon, 01 May 2006 04:51:24 GMT Subject: wxpython - new line in radiobutton's label? References: <1146364858.814329.49900@v46g2000cwv.googlegroups.com> Message-ID: nuffnough at gmail.com wrote: > >I am creating a small gui using wxGlade and wxPython. I am using a >radio button, and the text next to the options needs to be over two >lines. I tried using a \n character, but it seems to get ignored. > >Looking around in the various wikis and the example code also didn't >turn up anything. The native Windows radio button cannot do multiline labels. You'll have to do the first line in the radio button, and the second line as a wx.StaticText. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From apardon at forel.vub.ac.be Mon May 29 06:08:02 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 29 May 2006 10:08:02 GMT Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148612582.510390.48040@i39g2000cwa.googlegroups.com> Message-ID: Op 2006-05-26, Steve Holden schreef : > vbgunz wrote: >>>I guess Fredrik's message was more along the lines of ``don't try to >>>"help" others after a week or two toying with the language because you >>>might be offering disservice, despite your good intentions; leave this >>>to more experienced users``. The words might have been a bit harsher >>>but that's just his style; you'll get used to it if you hang around >>>here often. >> >> >> I much rather stand corrected than to silently remain ignorant. I take >> revision of my solution for all it's worth but to be belittled without >> correction is arrogant and unnecessary. I've been working with Python >> for several months now and I feel I know plenty *but* I am still >> learning. >> >> I personally never had to clear a list. I never thought of Roberts >> answer and my reasoning is in Roberts message. In the end I stood >> correct because Robert was nice enough to answer two birds with one >> stone. Fredrik on the other hand had nothing positive to add and his >> message seemed gestapo. >> >> Where I come from and how I grew up is quite simple. A wrong answer is >> better than no answer and a worthless remark is worth garbage. Why? >> Because no right answer is gospel and no answer no matter how dumb is >> cause for discourtesy. I tried and thats the bottom line. >> > Frankly I can't agree that a wrong answer is better than no answer, > despite my frequent strategy of opining that something is impossible > just so the cleverer denizens of c.l.py will prove me wrong. A wrong > answer requires correction by people who know the "right" answer, so you > end up consuming group bandwidth and mindshare unnecessarily. > > I am assuming the part of Fredrik's post that "seemed gestapo" to you > is """if you don't know how to do things, you don't need to post.""" But if we all wait until we are perfectly sure that the answer we will provide is correct, then no-one will need to answer. I have even seen Fredrik post an answer that IMO was at least outdated. > Please read this carefully, as Fredrik's use of language is precise: he > doesn't say you *shouldn't* post, he says you don't *need to*. This is > good advice, because posting a lame solution too quickly, while > reflecting an earnest and praiseworthy desire to help, can often lead to > trouble with some of the less patient members of our community. Maybe those less patient members should take the same advise: They don't need to react. -- Antoon Pardon From nobody at 127.0.0.1 Thu May 11 17:07:15 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 11 May 2006 21:07:15 GMT Subject: Nested loops confusion References: <1147375547.892792.186830@g10g2000cwb.googlegroups.com> Message-ID: <7IN8g.85773$dW3.17495@newssvr21.news.prodigy.com> conor.robinson at gmail.com wrote: > Call me crazy, but be careful when programming python in different text > editors and in general, ie cutting and pasting, tabing and spacing. > Loops can look fine and not work (try moving around test print > statements for iterators), in this case try re-tabing your indents so > that everything is uniform in the editor you are using. the -tt flag is a good way to catch/avoid such problems: #!/usr/bin/python -tt From duncan.booth at invalid.invalid Mon May 8 04:04:38 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 May 2006 08:04:38 GMT Subject: which is better, string concatentation or substitution? References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <1147065351.819566.140900@j73g2000cwa.googlegroups.com> <445eeab3$0$3681$4d3efbfe@news.sover.net> Message-ID: Leif K-Brooks wrote: > fuzzylollipop wrote: >> niether .join() is the fastest > > Please quote what you're replying to. > > No, it's the slowest: > > leif at ubuntu:~$ python -m timeit "'

    %s

    \n\n' % 'foobar'" > 1000000 loops, best of 3: 0.607 usec per loop > leif at ubuntu:~$ python -m timeit "'

    ' + 'foobar' + '

    \n\n'" > 1000000 loops, best of 3: 0.38 usec per loop > leif at ubuntu:~$ python -m timeit "''.join(['

    ', 'foobar', '

    \n\n'])" > 1000000 loops, best of 3: 0.817 usec per loop > If you are only concatenating a few strings together, then straight concatenation will be faster, but when joining many strings together concatenating strings can be much slower compared to join. In the OP's original example: def p(self, paragraph): self.source += '

    ' + paragraph + '

    \n\n' it is the concatenation to self.source which is could become the bottleneck, it doesn't really matter how the text of the paragraph assembled. For most purposes use what looks clearest at the time: it isn't worth the hassle of obfuscating your code until you've identified a real cpu hog. On the other hand, the str.join idiom is sufficiently common in Python that sometimes it wins on clarity and simplicity as well. e.g. If you build a list of lines to join then you don't have to repeat '\n' on the end of each component line. BTW, be careful using timeit. I nearly got caught out running your tests: C:\Python25>python -m timeit "''.join(['

    ', 'foobar', '

    \n\n'])" 1000000 loops, best of 3: 0.872 usec per loop C:\Python25>python -m timeit "'

    ' + 'foobar' + '

    \n\n'" 10000000 loops, best of 3: 0.049 usec per loop C:\Python25>python -m timeit "'

    %s

    \n\n' % 'foobar'" 10000000 loops, best of 3: 0.0495 usec per loop C:\Python25>cd \python24 C:\Python24>python -m timeit "''.join(['

    ', 'foobar', '

    \n\n'])" 1000000 loops, best of 3: 1.05 usec per loop C:\Python24>python -m timeit "'

    ' + 'foobar' + '

    \n\n'" 1000000 loops, best of 3: 0.359 usec per loop Spot the really fast concatenations in Python 2.5 which is now detecting the constant strings and concatenating them once only. It also does that for the string formatting which only leaves poor old join to actually do any work in these tests. From blair.bethwaite at gmail.com Tue May 9 01:03:27 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 8 May 2006 22:03:27 -0700 Subject: Enumerating Regular Expressions In-Reply-To: References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> <1147148644.762057.238640@v46g2000cwv.googlegroups.com> Message-ID: <1147151007.157938.185270@u72g2000cwu.googlegroups.com> James Stroud wrote: > You see the difficulty don't you? How will the computer know in advance > that the regex matches only a finite set of possible strings? Well sure it might be a little difficult to figure _that_ out, although probably not all that hard if you converted to an FSA or something. I imagine detecting looping would be as simple as applying the right graph algorithm. But that's not the point, you don't strictly need to know in advance whether the regex represents a finite or infinite language. I just want to enumerate it, if it's going to take longer than the life of the universe and a stack size to match to do it, then so be it. It's surely up to the user to be careful about how they form their expressions. One way to get around it would be to disallow the * operator in enumerations. Cheers, -Blair From mhodkin at comcast.net Tue May 16 22:09:28 2006 From: mhodkin at comcast.net (mhodkin at comcast.net) Date: 16 May 2006 19:09:28 -0700 Subject: constucting a lookup table In-Reply-To: <9aCdnR10Sej7bPTZnZ2dnUVZ_sidnZ2d@comcast.com> References: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> <9aCdnR10Sej7bPTZnZ2dnUVZ_sidnZ2d@comcast.com> Message-ID: <1147831768.783996.10630@j33g2000cwa.googlegroups.com> Larry Bates wrote: > mhodkin at comcast.net wrote: > > I'm new to Python and want to contruct a "lookup table" which would be > > similar to a spreadsheet in that a value is read along the first > > column, then along the top row, and the intersection of the two gives a > > value that is hard-coded, i.e. not mathmatically related. An example > > would be a table with HEIGHT in the first column, WEIGHT in the first > > row, and estimated SUITSIZE with the body of the table. > > > > Which Python type would be most appropriate and/or efficient? > > > > thanks > > > I would not worry about being "efficient" at this point. There are not > enough combinations of height/weight to make even a linear search through > a list be a performance problem. One way would be to set up a dictionary > that is keyed on height/weight and have it return suit size. To work > properly you would need to express height in inches and weight in pounds > (in US measurements). Something like: > > hwdict={(60, 80): , > (61, 80): , > (62, 80): , > . > . > . > (88, 400): } > > This would be fast because lookup would consist of only (not tested): > > try: suitsize=hwdict[(heightininches, weightinpounds)] > except IndexError: > print "height/weight combination not found in lookup table" > > > -Larry Bates thanks...much appreciated From johnjsal at NOSPAMgmail.com Tue May 23 13:56:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 17:56:31 GMT Subject: how to work with tab-delimited files? Message-ID: When you're using tabs to separate values in a text file, what do you do in the case where pressing the tab key doesn't really advance the cursor a full tab space (but instead just one or two spaces) because that's where the next tab stop is? Example: Joe Smith John Salerno So the second entry has a full tab space between the names, but the first doesn't, despite the fact that the tab key was pressed. So in this situation, when the file is being read, is that single space still determined to be a tab, or do you have to press tab twice to put a full tab between the names? Thanks. From mystilleef at gmail.com Mon May 15 03:56:29 2006 From: mystilleef at gmail.com (mystilleef) Date: 15 May 2006 00:56:29 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147679789.649913.202440@i39g2000cwa.googlegroups.com> I agree, use tabs. From aylwyn at cantab.net Wed May 17 06:47:45 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 03:47:45 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147858647.488974.92230@j73g2000cwa.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> Message-ID: <1147862865.142339.117610@j55g2000cwa.googlegroups.com> Iain King wrote: >python -tt Indeed. I reckon the consensus here (to the extent that there is any!) is that it would be better if this was Python's default behaviour. The argument (not advanced by Iain but by others in this thread) that: novices will mix tabs and spaces => we should all use spaces only is clearly false by symmetry. An alternative solution to this issue would be to write an editor plugin which converted between space-indented and tab-indented Python source files on opening *and back again* on writing or closing. Then we would have: Case 1: you send me a space-indented file. My editor opens the file, finds that it is space-indented, calculates the indentation level of each line and converts it to the corresponding number of tabs, and then writes that to a temporary file which it then displays for editing. On writing, it converts indentation back to spaces and writes to the original file. Case 2: I send you a tab-indented file. As Case 1 with s/tab/space/; s/My/Your/ Case 3: You send me a file with mixed tab/space indentation Everything borks, as it should. It's horrible but at least it would insulate me from the greater hideousness of having to hit the spacebar like a madman at the start of every line of code. I can even see how to get it to work in vi at least. Just trying to be constructive! Not that it's relevant, but I've never actually encountered anyone who mixed tabs and spaces.. I've lived a sheltered life I guess. From duncanm255 at hotmail.com Thu May 18 10:30:09 2006 From: duncanm255 at hotmail.com (D) Date: 18 May 2006 07:30:09 -0700 Subject: Python Install Message-ID: <1147962608.945821.226220@i40g2000cwc.googlegroups.com> I'm sure this is an easy question for most here, but it's throwing me for a loop at the moment - I need to upgrade RHEL 3 with the latest version of Python. I downloaded the source and installed, but we're still having problems (i.e. some Python apps don't work, Add/Remove Applications console errors out and doesn't open, etc.). My guess is that it's using old libraries or otherwise conflicting with the old Python version, but I'm not sure how to remove the original version. Any help would be greatly appreciated! From webraviteja at gmail.com Tue May 2 03:00:44 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 2 May 2006 00:00:44 -0700 Subject: string.find first before location In-Reply-To: <87hd49m0xc.fsf@localhost.localdomain> References: <87hd49m0xc.fsf@localhost.localdomain> Message-ID: <1146553244.226608.138400@y43g2000cwc.googlegroups.com> text[:text.find('Here')].rfind('abc') From deets at nospam.web.de Fri May 26 11:42:28 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 26 May 2006 17:42:28 +0200 Subject: Running Python scripts under a different user In-Reply-To: References: Message-ID: <4dolv4F1b8m87U1@uni-berlin.de> Bernard Lebel schrieb: > Hello, > > I would like to know if there is a way to run a Python file under a > different user account than the one logged in. Allow me to explain. > > There are a bunch of people here, they are "basic user", with limited > permissions. Basically there are locations on the network where they > can only read and execute files, but no way to write. > > Now, if these users want to write or modify files and directories, > they would have to use my tools, which would control the permissions > and allow the operations under parameters that I have defined. > > Currently I see two ways of accomplishing this: > > 1- the script changes the permissions of the locations the user is > writing to, allowing the "basic user" to write to this location, and > then restore the original permissions. What I don't like about this > one, is that if the script stops, the locations may retain the writing > permissions for the basic user. > > 2- the script itself runs under a account with writing privileges (the > power user), and network location permissions are not changed. If the > script crashes, well, nothing to worry about as far as I can see. > > > I could find in the Python library a way to do #1 easily (the os > module), but failed to find anything for #2. You didn't find anything there for a few reasons - mainly because if there was anything that made a program decide for itself which rights it wanted to run with, the whole concept of restrictive access would be kind of useless... And as you refrain form telling us which OS you are running under one can only be very vague on what to suggest - UNIXish OSes have for example the setguid-bit, sudo springs to mind and under certain desktops there are ways to acquire root-settings (but you need a password then I guess) Windows I don't know so much - but there exist the possibility to make a program run under a different user-account. Diez From aylwyn at cantab.net Tue May 16 13:22:55 2006 From: aylwyn at cantab.net (achates) Date: 16 May 2006 10:22:55 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> Message-ID: <1147800175.234540.279960@i40g2000cwc.googlegroups.com> Duncan Booth wrote: >but I prefer editors which keep things >simple. The tab key is particularly prone to excessively complicated >actions, for example the editor I use has the following (not simple at >all, and in fact not even an accurate description of what it does) binding >for the tab key: I'm not familiar with your editor, but if that's its default behaviour when you hit tab then it sounds neither simple nor intuitive. You haven't explained why you think there's a problem with having a character which, in an unambiguous and non-implementation-specific way, means 'one level of indentation'. In Python, of all languages, it makes sense to have such a character because 'one level of indentation' is a syntactical token processed by the interpreter. But consider this: like all real men, I normally program in hex. Here's an example of some recent code: 0x66 0x6f 0x72 0x20 0x69 0x74 0x65 0x6d 0x20 0x69 0x6e 0x20 0x6d 0x65 0x6e 0x75 0x3a 0x0d 0x0a 0x09 0x70 0x72 0x69 0x6e 0x74 0x20 0x27 0x73 0x70 0x61 0x6d 0x27 0x0d 0x0a 0x70 0x72 0x69 0x6e 0x74 0x20 0x27 0x6c 0x6f 0x76 0x65 0x6c 0x79 0x20 0x73 0x70 0x61 0x6d 0x27 If I wanted to be girly about it I could use an editor, and it would probably look like this: for item in menu: print 'spam' print 'lovely spam' But then if I wanted, I could write my own editor, and make it display tabs as 'negative indents' from column 40, so that it looks like this: for item in menu: print 'spam' print 'lovely spam' Guess what: the python interpreter wouldn't know about my strange editor habits! It would read my file and run just fine. What's more you can view it with *your preferred indentation display methodology* and we can both live in harmony! With spaces for indentation, this just isn't possible, because I have to conform to your viewing preferences, and that makes me unhappy. Why would you want to make me unhappy? From sjmachin at lexicon.net Sun May 21 03:54:25 2006 From: sjmachin at lexicon.net (John Machin) Date: 21 May 2006 00:54:25 -0700 Subject: Feature request: sorting a list slice In-Reply-To: References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> Message-ID: <1148198065.724613.253490@j55g2000cwa.googlegroups.com> Context? The whole message asked for a new feature. Please tell me what context I should have supplied. From onurb at xiludom.gro Fri May 12 08:55:28 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 14:55:28 +0200 Subject: design a Condition class In-Reply-To: <1147297217.372888.167960@v46g2000cwv.googlegroups.com> References: <1147297217.372888.167960@v46g2000cwv.googlegroups.com> Message-ID: <44648624$0$7613$636a55ce@news.free.fr> joh12005 at yahoo.fr wrote: > Hello, > > i posted for suggestions a little idea even if it still needs further > thoughts but as i'm sure you could help :) > > if would like to implement some kind of Condition class which i coud > use to build bricks of more complex condition, conditions are based on > fields by using regexp > > class Condition: Do yourself a favor and use newstyle classes: class Condition(object): > def __init__(self, field0, field1, field2): > self.field0 = field0 > self.field1 = field1 > self.field2 = field2 > def match(self, against): > w, t, l = against > f0 = False > if self.field0 is None: > f0 = True > else: > f0 = self.field0.search(w) > if self.field1 is None: > f1 = True > else: > f1 = self.field1.search(t) > if self.field2 is None: > f2 = True > else: > f2 = self.field2.search(l) > return f0 and f1 and f2 > c0 = Condition(re.compile("something"), None, > re.compile("somethingelse")) > c1 = Condition(re.compile("another"), None, None) > > i can use > > if c0.search(myitem) Have you actually tested this ?-) (hint : the method name is 'match', not 'search') > > but i would like to be able to have composition such as : > > c2 = c0 | c1 > > which should be understood as defining a new c2 which is able to match > (c0 or c1) from c0 and c1 already defined. > > actually i can imagine a > > def OR(c0, c1): > # here => missing None support 'a or None' is 'a' > return Condition(re.compile("|".join((c0.field0.pattern, > c1.field0.pattern)), > re.compile("|".join((c0.field1.pattern, > c1.field1.pattern)), > re.compile("|".join((c0.field2.pattern, > c1.field2.pattern)) > > the idea is to build c2 = Condition(re.compile("something|another"), > None, re.compile("somethingelse")) > c2 = OR(c0, c1) > > but maybe have you clever suggestions ? use the __or__(self, other) special method. http://www.python.org/doc/2.4.2/ref/numeric-types.html Here is a somewhat rewritten, hopefully more pythonic version - will need some more works, specially wrt/ error handling : class Condition(object): def __init__(self, *exps): self._exps = exps def match(self, *targets): # don't know how you want to handle this case assert len(targets) == len(self._exps), \ "expected %d args, got %d" % (len(self._exps), len(targets)) for exp, target in zip(self._exps, targets): # takes care of None in the expression list if not (exp is None or exp.search(target)): return False return True def __or__(self, other): """ cf http://www.python.org/doc/2.4.2/ref/numeric-types.html """ # I let you take care of all error handling... # take care of what happens if # len(other._exps) != len(self._exps) # NB : itertools might be of some help here exps = [re.compile("(%s)|(%s)" % (e1.pattern, e2.pattern)) \ for e1, e2 in zip(self._exps, other._exps)] return self.__class__(*exps) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From blair.bethwaite at gmail.com Sun May 7 22:50:28 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 7 May 2006 19:50:28 -0700 Subject: Getting HTTP responses - a python linkchecking script. Message-ID: <1147056628.354150.116120@y43g2000cwc.googlegroups.com> Hi Folks, I'm thinking about writing a script that can be run over a whole site and produce a report about broken links etc... I've been playing with the urllib2 and httplib modules as a starting point and have found that with urllib2 it doesn't seem possible to get HTTP status codes. I've had more success with httplib... Firstly I create a new HTTPConnection object with a given hostname and port then I try connecting to the host and catch any socket errors which I can assume mean the server is either down or doesn't exist at this place anymore. If the connection was successful I try requesting the resource in question, I then get the response and check the status code. So, I've got the tools I need to do the job sufficiently. Just wondering whether anybody can recommend any alternatives. Cheers, -Blair From telesphore4 at gmail.com Sun May 21 10:10:11 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 21 May 2006 07:10:11 -0700 Subject: Using metaclasses to inherit class variables References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> Message-ID: <1148220610.980985.31780@j33g2000cwa.googlegroups.com> If some one ever wants to build on this in the future, the current form and use is: import copy class ClassVars(type): classVars = dict(fields=[], longest=0) # <<<< adjust this >>>> def __init__(cls, name, bases, dict): for name, value in ClassVars.classVars.iteritems(): if name not in dict: setattr(cls, name, copy.copy(value)) class Table(object): __metaclass__ = ClassVars # Rest of class follows... I use these class varaibles in 2 places and attempted, breifly, to abstract them into a module. But I ran into a chicken and egg situation were I wanted to use fresh copies of class variables to define the abstracted class. Given that I'd onlly save (2*3) 6 lines of code in my application, I figured that move on for now. From johnzenger at gmail.com Thu May 18 23:25:01 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 18 May 2006 20:25:01 -0700 Subject: newb: comapring two strings In-Reply-To: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> Message-ID: <1148009101.543684.190220@u72g2000cwu.googlegroups.com> manstey wrote: > Hi, > > Is there a clever way to see if two strings of the same length vary by > only one character, and what the character is in both strings. You want zip. def diffbyonlyone(string1, string2): diffcount = 0 for c1, c2 in zip(string1, string2): if c1 != c2: diffcount += 1 if diffcount > 1: return False return diffcount == 1 print diffbyonlyone("yaqtil","yaqtel") # True print diffbyonlyone("yiqtol","yaqtel") # False If your strings are long, it might be faster/more memory efficient to use itertools.izip instead. > My next problem is, I have a list of 300,000+ words and I want to find > every pair of such strings. I thought I would first sort on length of > string, but how do I iterate through the following: > > str1 > str2 > str3 > str4 > str5 > > so that I compare str1 & str2, str1 & str3, str 1 & str4, str1 & str5, > str2 & str3, str3 & str4, str3 & str5, str4 & str5. for index1 in xrange(len(words)): for index2 in xrange(index1+1,len(words)): if diffbyonlyone(words[index1], words[index2]): print words[index1] + " -- " + words[index2] ...but by all means run that only on sets of words that you have already identified, pursuant to some criteria like word length, to be likely matches. Do the math; that's a lot of comparisons! From spamspam at spam.eggs Wed May 10 09:09:35 2006 From: spamspam at spam.eggs (Ben C) Date: 10 May 2006 13:09:35 GMT Subject: clear memory? how? References: <4cb49uF15811rU1@uni-berlin.de> <2p-dnQQrLYq8QPzZRVnyjg@scarlet.biz> Message-ID: On 2006-05-10, Gr?goire Dooms wrote: > Ben C wrote: >> On 2006-05-09, Ben C wrote: >>> def clearall(): >>> all = [var for var in globals() if "__" not in (var[:2], var[-2:])] >>> for var in all: >>> del globals()[var] >>> >>> since I think magic things always start and end with __. >> >> Oops, got that wrong anyway: >> >> should be: >> >> all = [var for var in globals() if (var[:2], var[-2:]) != ("__", "__")] > > You can also add > and var != "clearall" > >:-) Good point :) I've heard of "write once run anywhere", but this is "run once". From martin at v.loewis.de Wed May 17 01:08:54 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 17 May 2006 07:08:54 +0200 Subject: A Unicode problem -HELP In-Reply-To: <1147832399.383507.155800@j55g2000cwa.googlegroups.com> References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> Message-ID: <446AAFE6.4080008@v.loewis.de> manstey wrote: > input_file = open(input_file_loc, 'r') > output_file = open(output_file_loc, 'w') > for line in input_file: > output_file.write(str(word_info + parse + gloss)) # = three > functions that return tuples > > (u'F', u'\u0254') are two of the many unicode tuple elements returned > by the three functions. > > What am I doing wrong? Well, the primary problem is that you don't tell us what you are really doing. For example, it is very hard to believe that this is the actual code that you are running: If word_info, parse, and gloss are functions, the code should read input_file = open(input_file_loc, 'r') output_file = open(output_file_loc, 'w') for line in input_file: output_file.write(str(word_info() + parse() + gloss())) I.e. you need to call the functions for this code to make any sense. You have probably chosen to edit the code in order to not show us your real code. Unfortunately, since you are a newbie in Python, you make errors in doing so, and omit important details. That makes it very difficult to help you. Regards, Martin From john at castleamber.com Fri May 19 00:21:32 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 04:21:32 GMT Subject: Script to make Windows XP-readable ZIP file References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> <1148011001.613000.294750@g10g2000cwb.googlegroups.com> Message-ID: "softwindow" wrote: > aha > we want to do it with python > don't use ant :-D I want to do a lot with Perl, but sometimes it's better to use the right tool for the job. And I think that Ant is better at for what I use it compared to a home brew tool I could make. Be careful with "Not Invented Here". -- 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 brochu121 at gmail.com Wed May 3 10:37:38 2006 From: brochu121 at gmail.com (brochu121 at gmail.com) Date: 3 May 2006 07:37:38 -0700 Subject: Customize IE to make a toolbar visible Message-ID: <1146667058.286119.27920@j33g2000cwa.googlegroups.com> Does anyone know of a way to make a toolbar visible in IE through automation? I am not speaking about the InternetExplorer.ToolBar that I have run into on MSDN, but rather want to make a toolbar such as Yahoo's visibilbe through running my script. How would I do this. Thanks, Dave From aleaxit at yahoo.com Sun May 7 14:57:57 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 11:57:57 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hextts.o0uihlttzk47N%aleaxit@yahoo.com> Message-ID: <1heyshp.jarlp675qfwN%aleaxit@yahoo.com> Tomasz Zielonka wrote: > Alex Martelli wrote: > > Tomasz Zielonka wrote: > > > >> Alex Martelli wrote: > >> > Having to give functions a name places no "ceiling on expressiveness", > >> > any more than, say, having to give _macros_ a name. > >> > >> And what about having to give numbers a name? > > > > Excellent style, in most cases; I believe most sensible coding guides > > recommend it for most numbers -- cfr > > , section > > "magic numbers in code". > > I was a bit unclear. I didn't mean constants (I agree with you on > magic numbers), but results of computations, for example Ah, good that we agree on _some_thing;-) > > (x * 2) + (y * 3) > > Here (x * 2), (y * 3) and (x * 2) + 3 are anonymous numbers ;-) > > Would you like if you were forced to write it this way: > > a = x * 2 > b = y * 3 > c = a * b > > ? > > Thanks for your answers to my questions. I do not think there would be added value in having to name every intermediate result (as opposed to the starting "constants", about which we agree); it just "spreads things out". Fortunately, Python imposes no such constraints on any type -- once you've written out the starting "constants" (be they functions, numbers, classes, whatever), which may require naming (either language-enforced, or just by good style), instances of each type can be treated in perfectly analogous ways (e.g., calling callables that operate on them and return other instances) with no need to name the intermediate results. The Function type, by design choice, does not support any overloaded operators, so the analogy of your example above (if x and y were functions) would be using named higher-order-functions (or other callables, of course), e.g.: add_funcs( times_num(x, 2), times_num(y, 3) ) whatever HOF's add and times were doing, e.g. def add_funcs(*fs): def result(*a): return sum(f(*a) for f in fs) return result def times_num(f, k): def result(*a): return k * f(*a) return result or, add polymorphism to taste, if you want to be able to use (e.g.) the same named HOF to add a mix of functions and constants -- a side issue that's quite separate from having or not having a name, but rather connected with how wise it is to overload a single name for many purposes (PEAK implements generic-functions and multimethods, and it or something like it is scheduled for addition to Python 3.0; Python 2.* has no built-in way to add such arbitrary overloads, and multi-dispatch in particular, so you need to add a framework such as PEAK for that). Alex From spohle at gmail.com Fri May 26 14:26:22 2006 From: spohle at gmail.com (spohle) Date: 26 May 2006 11:26:22 -0700 Subject: sort a dictionary by keys in specific order In-Reply-To: References: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> <1148665851.182749.101720@g10g2000cwb.googlegroups.com> Message-ID: <1148667982.894239.257080@j55g2000cwa.googlegroups.com> i write the dict out to a file, not with file methods but rather with an inhouse python code. unfortunatly the order plays a big role for that. From juergen.eckel at gmx.net Mon May 29 10:53:52 2006 From: juergen.eckel at gmx.net (Juergen) Date: 29 May 2006 07:53:52 -0700 Subject: omniorbpy: problems sending float values Message-ID: <1148914432.514658.216050@38g2000cwa.googlegroups.com> hi, I've got a problem sending floating point values to an corba server. With other datatyes like short or string it works fine. So having this idl file : module Example{ interface User{ void setV( in float x ); }; interface Target{ void getV( out short x); }; }; I just receive zero ( -2.58265845332e-05) by sending an float to another client with the above interface. the client : ********************************************************** import sys from omniORB import CORBA import _omnipy import Example, CosNaming orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) ior = sys.argv[1] obj = orb.string_to_object(ior) us = obj._narrow( Example.User ) if us is None: print "blabla" sys.exit(1) us.setV( 5.0 ) ********************************************************** the server : ********************************************************** import sys from omniORB import CORBA, PortableServer import CosNaming, Example, Example__POA class User_i( Example__POA.User ): def setV( self, x ): print x print type(x) y = float(x) print y print type(y) class Target_i( Example__POA.Target ): def getV( self ): return 5 orb = CORBA.ORB_init(sys.argv, CORBA.ORB_ID) poa = orb.resolve_initial_references("RootPOA") us = User_i() tg = Target_i() uo = us._this() to = tg._this() print orb.object_to_string(uo) print print orb.object_to_string(to) poaManager = poa._get_the_POAManager() poaManager.activate() orb.run() ********************************************************** does anyone have an answer to that kind of problem? I mean, it just like sending short values, or strings. From fredrik at pythonware.com Thu May 4 16:15:32 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 22:15:32 +0200 Subject: Python 2.4.2 to 2.4.3 transition issue References: <1146772876.641098.166110@g10g2000cwb.googlegroups.com> Message-ID: Panos Laganakos wrote: > OS: Windows XP + SP1 > > On this particular box, I hadn't moved to 2.4.3 yet. > So, earlier today, I uninstalled Python2.4.2 and installed 2.4.3 using > the .msi installer. > > It seems though everything looked great, that when I invoke 'python' > from the command line, I get Python2.4.2 (as the header states), > instead of 2.4.3. > > I looked at the registry and at the PATH variables of both system and > current user, but they are just stating 'C:\Python24\'. > > When I explicitly call C:\Python24\python.exe though, 2.4.3 comes up. > > Any ideas what seems to be the problem here? in your python 2.4.2 interpreter, what does >>> import sys >>> sys.executable say ? if you do a global search for "python24.dll", how many instances do you find ? From larry.bates at websafe.com Sat May 20 18:30:12 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 20 May 2006 17:30:12 -0500 Subject: Name conflict in class hierarchy In-Reply-To: References: Message-ID: <1fKdnaFchMr5BfLZRVn-gg@comcast.com> Jeffrey Barish wrote: > I believe that the answer to my question is no, but I want to be sure that I > understand this issue correctly: Suppose that there are two classes > defined as follows: > > class A(object): > def f1(self): > print 'In A.f1, calling func' > self.func() > > def func(self): > print 'In A.func' > > class B(A): > def func(self): > print 'In B.func, calling A.f1' > A.f1(self) > > Class A was defined by someone else or it comes from a library, so I have no > prior information about what is in it. I subclass A to add some new > functionality, and I call the new function "func". The function B.func > uses A.f1, but unbeknownst to me, A.f1 uses A.func. Unfortunately, class B > overrides func, so the call in A.f1 to self.func actually invokes B.func, > resulting in this case in an infinite loop. Is there a way from B to > specify that A should use its own version of func and ignore the version in > B? I know that I could rename A.func to avoid the name clash, but since A > is actually in a library, I will lose that change when I upgrade the > library. I could rename B.func, but there is already a bunch of code that > calls it so I would have to update all the calls. That seems like the > correct solution, though. The other possibility is to use composition > rather than subclassing: > > class B: > def func(self): > print 'In B.func, calling A.f1' > a = A() > a.f1() > > but then B does not inherit other functions of A that I would like to use. > It struck me that this must be a common problem in OOP, so I'm wondering > whether there is a simple solution that I am missing. When you subclass an object it is your responsibility to check to make sure you don't override existing methods in that class unintentionally. Of course you may want to intentionally override the methods so as to replace them with your own methods. You are correct, renaming A.func wouldn't be a good idea. A good editor should make changing all the calls to B.func not be all that hard. You can easily get information about the methods by doing an import and dir(). Example: >>> import ConfigParser >>> dir(ConfigParser) ['ConfigParser', 'DEFAULTSECT', 'DuplicateSectionError', 'Error', 'InterpolationDepthError', 'InterpolationError', 'InterpolationMissingOptionError', 'InterpolationSyntaxError', 'MAX_INTERPOLATION_DEPTH', 'MissingSectionHeaderError', 'NoOptionError', 'NoSectionError', 'ParsingError', 'RawConfigParser', 'SafeConfigParser', '__all__', '__builtins__', '__doc__', '__file__', '__name__', 're'] Depending on the author, you may also be able to get extensive help on all the methods with help(). >>> help(ConfigParser) Help on module ConfigParser: NAME ConfigParser - Configuration file parser. FILE c:\python24\lib\configparser.py DESCRIPTION A setup file consists of sections, lead by a "[section]" header, and followed by "name: value" entries, with continuations and such in the style of RFC 822. -Larry Bates From bucodi at yahoo.fr.invalid Thu May 4 10:56:08 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 04 May 2006 16:56:08 +0200 Subject: Unicode code has no method float() ? Message-ID: How can I get the value of a Unicode object ? When I do myobject.float() I get the error message that it doesn't have a float() attribute tia R_ -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From http Sun May 14 19:22:27 2006 From: http (Paul Rubin) Date: 14 May 2006 16:22:27 -0700 Subject: count items in generator References: Message-ID: <7xk68o42fg.fsf@ruckus.brouhaha.com> "Delaney, Timothy (Tim)" writes: > > Actually len(itertools.count()) would as well - when a couple of long > > instances used up everything available - but it would take a *lot* > > longer. > > Actually, this would depend on whether len(iterable) used a C integral > variable to accumulate the length (which would roll over and never end) > or a Python long (which would eventually use up all memory). That's only because itertools.count itself uses a C int instead of a long. IMO, that's a bug (maybe fixed in 2.5): Python 2.3.4 (#1, Feb 2 2005, 12:11:53) [GCC 3.4.2 20041017 (Red Hat 3.4.2-6.fc3)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import sys,itertools >>> a=sys.maxint - 3 >>> a 2147483644 >>> b = itertools.count(a) >>> [b.next() for i in range(8)] [2147483644, 2147483645, 2147483646, 2147483647, -2147483648, -2147483647, -2147483646, -2147483645] >>> From wim.verhavert at gmail.com Sat May 6 16:39:06 2006 From: wim.verhavert at gmail.com (Aengys) Date: 6 May 2006 13:39:06 -0700 Subject: GladeGen and initializing widgets at startup Message-ID: <1146947945.953256.164400@j33g2000cwa.googlegroups.com> Hi all, Being struck by article 7421 of the linux journal (http://www.linuxjournal.com/article/7421), I'll tried to give it a go. Mainly because I have done some experiments with Glade and found that it is really easy to create good looking GUIs. On the other end, there is the GladeGen tool which helps you in building a skeleton in Python such that you only have to code the events. But being a newbie with Python as well as Glade I'm heavily dependent on documentation (mainly online a big part being usenet). There I found that almost nobody seems to use it, or they don't have any problems with it. In this group there is only thread that has a reference to it! So my questions: Does anybody use GladeGen? If not, why? For those that do use it, where do I write the code which has to be executed when a window loads? The thing is pretty basic here. I have a window with a treeview, and I simply want that treeview filled up when opening the window. Hoping for some echos... Aengys From j23212 at hotmail.com Mon May 8 00:24:46 2006 From: j23212 at hotmail.com (Jon Van DeVries) Date: Mon, 08 May 2006 04:24:46 GMT Subject: dial-up from python script Message-ID: I want to create a simple script that dials my modem to whatever number I specify. Any tips on modules to be used? google didn't help much this time. Platform: SuSE 10.1 Linux 2.6.x (but since it will be done in Python, I'm assuming it doesn't matter what platform I'm using right?) thanks in advance, --------------= Posted using GrabIt =---------------- ------= Binary Usenet downloading made easy =--------- -= Get GrabIt for free from http://www.shemes.com/ =- From no-spam at no-spam-no-spam.com Fri May 5 04:59:13 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Fri, 05 May 2006 10:59:13 +0200 Subject: enriching return values / symetric call&return in P3K ? - Re: Tuple assignment and generators? In-Reply-To: References: Message-ID: Tim Chase wrote: > Just as a pedantic exercise to try and understand Python a bit better, I > decided to try to make a generator or class that would allow me to > unpack an arbitrary number of calculatible values. In this case, just > zeros (though I just to prove whatever ends up working, having a > counting generator would be nice). The target syntax would be something > like > > >>> a,b,c = zeros() > >>> q,r,s,t,u,v = zeros() > > where "zeros()" returns an appropriately sized tuple/list of zeros. > > I've tried a bit of googling, but all my attempts have just ended up > pointing to pages that blithly describe tuple assignment, not the > details of what methods are called on an object in the process. > > My first thought was to get it to use a generator: > > def zeros(): > while 1: yield 0 > > However, I get back a "ValueError: too many values to unpack" result. > > As a second attempt, I tried a couple of attempts at classes (I started > with the following example class, only derived from "object" rather than > "list", but it didn't have any better luck): > > >>> class zeros(list): > ... def __getitem__(self,i): > ... return 0 > ... > >>> z = zeros() > >>> a,b,c = z > Traceback (most recent call last): > File "", line 1, in ? > ValueError: need more than 0 values to unpack > > > It looks like I need to have a pre-defined length, but I'm having > trouble figuring out what sorts of things need to be overridden. It > seems like I sorta need a > > def __len__(self): > return INFINITY > > so it doesn't choke on it. However, how to dupe the interpreter into > really believing that the object has the desired elements is escaping > me. Alternatively if there was a "doYouHaveThisManyElements" > pseudo-function that was called, I could lie and always return true. > > Any hints on what I'm missing? Think the use case, you present, is (pythonically) ill as such. if you want to fill literal variable's do it like: a=b=c=...=0. Otherwise you'd handle variable lists zeros(7) Yet there is a real freqent need for adding transparent extra/decorating return values in cases, where you don't want to break the simple return scheme (in maybe big existing code). For such use cases check out this "RICHVALUE" approach with _named_ extra values - no puzzles about non-matching tuple assignments: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496676 : ... def f(): return RICHVALUE(7, extra='hello') ret=f() print ret, ret+1, ret.extra ... As I have this need very very often I'd like to see an even more natural builtin method for enriching return values (both positional and by name) in Python3000 - maybe by making calling and returning almost symetric! Yet, this ideas maybe strange ? ... def f_P3K(*args,**kwargs): xreturn((7,8), 3, extra=5, *args, **kwargs) # first is main v = f_P3K() # (7,8) v,x = f_P3K() # (7,8),3 v,x,*pret,**kwret= f_P3K() extra=kwret.get('extra',-1) -robert From laurent.pointal at limsi.fr Thu May 11 09:28:01 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Thu, 11 May 2006 15:28:01 +0200 Subject: Python editor recommendation. In-Reply-To: References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: Dale Strickland-Clark a ?crit : > Vim. > > Everything else is Notepad. ++, yes Notepad++ !!! (windows only) See http://notepad-plus.sourceforge.net/uk/site.htm :-) > > DeepBlue wrote: > >> Hi all, >> >> Can any one please recommend me an editor for coding Python. Thank u. >> I have Komodo (www.activestate.com) in my mind. Is the editor any good? >> >> regards. > From eric_brunel at despammed.com Tue May 30 03:25:11 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 30 May 2006 09:25:11 +0200 Subject: How to use tk.call ? References: <1148944211.145450.46030@j33g2000cwa.googlegroups.com> <1148962387.776015.157320@j33g2000cwa.googlegroups.com> Message-ID: On 29 May 2006 21:13:07 -0700, wrote: >>> self.table.bind("",self.table.tk.call(self.table._w,'yview','scroll',-5,'units') > >> I haven't used Table, but are you sure that what you are calling >> "self.table" here actually has mouse focus? > >> James > > Yup, I click on the table, and then frantically work the mouse wheel to > no > effect... ... which is quite normal, since you actually didn't define any binding. What you did is: - *Call* self.table.tk.call(self.table._w,'yview','scroll',-5,'units'), which did the scroll; - Pass the *result* of this call (which is probably None or the empty string) as the second parameter of self.table.bind. So no binding was defined. One solution is to define the binding via a lambda, like this (untested): self.table.bind("", lambda e, t=self.table: t.tk.call(t._w, 'yview', 'scroll', -5, 'units')) For more information on lambda, see here: http://docs.python.org/tut/node6.html#SECTION006750000000000000000 HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From tjreedy at udel.edu Fri May 12 16:02:36 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 May 2006 16:02:36 -0400 Subject: New tail recursion decorator References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com><4cdnouF15dmjfU1@uni-berlin.de><1147253776.042505.34430@j73g2000cwa.googlegroups.com><1147436852.364490.99440@u72g2000cwu.googlegroups.com><1147437656.779139.54840@d71g2000cwd.googlegroups.com><1147441799.331677.88460@d71g2000cwd.googlegroups.com> Message-ID: "Alexander Schmolck" wrote in message news:yfsy7x7tb9q.fsf at oc.ex.ac.uk... > Duncan Booth writes: >> Tail recursion is when a function calls itself and then immediately >> returns >> the result of that call as its own result. Which means that the value returned by the base case is returned unchanged to the original caller through the stack of returns. Which means that the return stack can potentially be compressed to just one return. > I think the definition is broader than that so that these two functions > would > also be tail-recursive (i.e. the tail call doesn't have to be a self-tail > call; I might be mistaken, don't have a good reference at hand; however > "properly tail recursive" certainly refers to being able to do the below > without exhausting the stack even for large n, not just transforming > self-tail > calls to a loop, which is sort of limited usefulness anyway): > > def even(n): > return n == 0 or not odd(n-1) > > def odd(n): > return n == 1 or not even(n-1) No, these are not even mutually tail-recursive, assuming that that would make sense. You are calling the not operator function on the results of the recursive calls before returning them. The following *is* tail-recursive: def even(n): assert n >= 0 if n >=2: return even(n-2) return bool(n) The recursive call is effectively a goto back to the top of the function, with n reduced by 2. This looping continues until n < 2. So in Python, we would usually write def even(n): assert n >= 0 while n >= 2: n -=2 return bool(n) Terry Jan Reedy From thomas at localhost.localdomain Tue May 16 02:00:04 2006 From: thomas at localhost.localdomain (Thomas Dybdahl Ahle) Date: Tue, 16 May 2006 08:00:04 +0200 Subject: Decrypt DES by password References: <7xlkt3dtps.fsf@ruckus.brouhaha.com> Message-ID: Den Mon, 15 May 2006 11:32:47 -0700. skrev Paul Rubin: > Thomas Dybdahl Ahle writes: >> byte[] array2 = bytes1.CryptDeriveKey("DES", "MD5", 0, array1); >> > Anybody know how to do this in python? > > I'm not aware of a standard that says how CryptDeriveKey is supposed > to work. Or rather, there are multiple possible standard ways to do > it. If you can find an exact specification, or C# source code that > does it, it will probably be straightforward to reimplement in Python. I tried to find out how the monofolks did it, but also they didn't know the algorithms. Maybe I should find a windows computer with .net, create the key and base64 encode it, so that I could take it to the python program... But thanks for the excample anyways. Maybe I can use it, if I need to encrypt something myself, another time. -- Programmers should realize their critical importance and responsibility in a world gone digital. They are in many ways similar to the priests and monks of Europe's Dark Ages; they are the only ones with the training and insight to read and interpret the "scripture" of this age. From ilitzroth at gmail.com Mon May 29 08:46:18 2006 From: ilitzroth at gmail.com (ilitzroth at gmail.com) Date: 29 May 2006 05:46:18 -0700 Subject: John Bokma harassment In-Reply-To: <447ae549$1_5@news.bluewin.ch> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> Message-ID: <1148906778.530827.317000@g10g2000cwb.googlegroups.com> >"There is so much noise we can't hear each other, but I will defend >to the death a chance to get heard for whatever you might have to say that's >intelligent (while not necessarily from your own mouth)". You write a much cooler quote! >Besides, it is not clear that Voltaire really said that. No? well I guess it's alright to harrass Xah then. Immanuel Litzroth From mblume at socha.net Fri May 12 13:45:17 2006 From: mblume at socha.net (Martin Blume) Date: Fri, 12 May 2006 19:45:17 +0200 Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> <44644a76$0$290$626a54ce@news.free.fr> <4464959f$1$13578$5402220f@news.sunrise.ch> <4464b6ad$0$6828$636a55ce@news.free.fr> Message-ID: <4464c90b$1$13570$5402220f@news.sunrise.ch> "bruno at modulix" schrieb > > [snip] > > The use case for @decorator is for wrapping functions > or method *in the module/class itself*. That was the question. What's the use of doing it like that in the module *itself* (I mean, you change directly the original function)? > It's not for module client code (but this of > course doesn't prevent client code to dynamically > add other wrappers...) > How do the clients it? The "oldfashioned" deco(doSillyWalk) way? Martin From luismgz at gmail.com Mon May 29 21:29:02 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 29 May 2006 18:29:02 -0700 Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> Message-ID: <1148952542.615043.94410@g10g2000cwb.googlegroups.com> I didn't know it wasn't a free ebook. I realized it once I downloaded it. But it's such a good book that I decided to buy a hard copy. This way I will support its author, while getting a very good book on Python. Luis From jjl at pobox.com Sat May 27 10:58:46 2006 From: jjl at pobox.com (John J Lee) Date: Sat, 27 May 2006 14:58:46 +0000 (UTC) Subject: HTTPS client certificates (was Re: Twill question) (fwd) In-Reply-To: References: Message-ID: Oops, spot the deliberate misteka ;-) should have been: opener = urllib.FancyURLopener(key_file=KEY_FILE, cert_file=CERT_FILE, ) r = opener.open() print r.read() ... which *does* work for me. Sorry for the noise everybody. John On Sat, 27 May 2006, John J Lee wrote: > Just forwarding this in case anybody here can shed light on this -- urllib's > support for SSL client certificates didn't work for me, and I'm wondering if > it works for anybody else... > > > John > > ---------- Forwarded message ---------- > Date: Sat, 27 May 2006 14:33:03 +0000 (UTC) > From: John J Lee > To: Wayne Wang , twill at lists.idyll.org > Subject: HTTPS client certificates (was Re: Twill question) > > On Fri, 26 May 2006, Wayne Wang wrote: > [...wants https client auth...] > > OK, I added the necessary boilerplate to mechanize (haven't committed yet), > but the basic support for this that comes with Python didn't work for me on a > local test server I set up, so I couldn't get it working with mechanize > either. > > Wayne, and anybody else who uses client certificates and is inclined to help > out: could you try running this script, after replacing HTTPS_URL with a URL > on the secure site you're trying to access, and KEY_FILE and CERT_FILE with > the full filenames where you keep those? > > I'm afraid you have to convert the p12 file into separate PEM-format key and > cert files using e.g. OpenSSL: > > openssl pkcs12 -clcerts -nokeys -in cert.p12 -out cert.pem > openssl pkcs12 -nocerts -in cert.p12 -out key.pem > > > HTTPS_URL = "https://example.com:443/restricted/foo.html" > KEY_FILE = r"c:\blah\blah\key.pem" > CERT_FILE = r"c:\blah\blah\cert.pem" > > import urllib > urllib.URLopener(key_file=KEY_FILE, > cert_file=CERT_FILE, > ) > r = urllib.urlopen() > print r.read() > > > John > From mwilson-to at sympatico.ca Fri May 26 08:29:16 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 26 May 2006 08:29:16 -0400 Subject: genexp surprise (wart?) In-Reply-To: <7xac95jekv.fsf@ruckus.brouhaha.com> References: <7xpsi14drb.fsf@ruckus.brouhaha.com> <1148622671.835989.217780@i39g2000cwa.googlegroups.com> <7xac95jekv.fsf@ruckus.brouhaha.com> Message-ID: Paul Rubin wrote: > "Paul Du Bois" writes: >> The second is that you don't like the late-binding behavior of >> generator expressions. PEP 289 has this to say: >> >>> After much discussion, it was decided that the first (outermost) >>> for-expression should be evaluated immediately and that the remaining >>> expressions be evaluated when the generator is executed. > > Thanks. That PEP is informative. It shows that I stumbled into > something that other people found confusing too, and that alternatives > were considered that turned out not to be better. The net effect of the bad version seems to be that you're not getting a new generator from stream = (q for q in stream if q%p != 0) (* disassembly shown below.) Disassembly seems to show the program getting a pre-compiled generator expression code block, and binding the new value of p to it, then getting iter(stream), which is stream. As Paul Du Bois says, the outer loop is fixed, but the subsequent if-expression is liable to change. So 3 passes because 3%2 != 0 4 passes because 4%3 != 0 5 passes because 5%4 != 0 and so on. Interesting. * Disassembly of stream = ...: 6 47 LOAD_CLOSURE 0 (p) 50 LOAD_CONST 2 ( at 009D65E0, file "try_eratos.py", line 6>) 53 MAKE_CLOSURE 0 56 LOAD_FAST 1 (stream) 59 GET_ITER 60 CALL_FUNCTION 1 63 STORE_FAST 1 (stream) From grahn+nntp at snipabacken.dyndns.org Tue May 30 15:55:22 2006 From: grahn+nntp at snipabacken.dyndns.org (Jorgen Grahn) Date: 30 May 2006 19:55:22 GMT Subject: stupid perl question References: <44778C05.9020701@grads.ece.mcmaster.ca> <4477A74C.6080605@lexicon.net> Message-ID: On Sat, 27 May 2006 11:11:40 +1000, John Machin wrote: ... > Yes, you could write out the whitespace characters for the 8-bit > encoding of your choice, or you could find them using Python (and get > some possibly surprising answers): > > >>> mkws = lambda enc, sz=256: "".join([chr(i) for i in range(sz) if > chr(i).decode(enc, 'ignore').isspace()]) ... > >>> mkws('latin1') > '\t\n\x0b\x0c\r\x1c\x1d\x1e\x1f \x85\xa0' ^^^^ That surprised me, at least. Should NO-BREAK SPACE really count as whitespace? I thought that the whole purpose with it was to have a blank character which programs automatically treated as non-whitespace, for line-breaking, word-counting and similar purposes. /Jorgen -- // Jorgen Grahn R'lyeh wgah'nagl fhtagn! From buzzard at urubu.freeserve.co.uk Fri May 26 12:24:50 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 26 May 2006 17:24:50 +0100 Subject: how to clear up a List in python? In-Reply-To: <1148653059.381151.113360@j73g2000cwa.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148653059.381151.113360@j73g2000cwa.googlegroups.com> Message-ID: <44772de5.0@entanet> linnorm at gmail.com wrote: > The original post only mentions deleting the values in the list, not > the list itself. Given that you want to keep the list and just ditch > the values it contains I'd go with: > > list1 = [] > > -Linnorm > Which rebinds list1 to a new (empty) list. It doesn't clear the original list (which appears to be what the OP wants). >>> list2 = [0,1,2,3,4,5] >>> list1 = list2 >>> list1 = [] >>> list2 [0, 1, 2, 3, 4, 5] >>> Duncan From grante at visi.com Tue May 2 17:13:48 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 02 May 2006 21:13:48 -0000 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <4457b2fe$1_7@news.bluewin.ch> <125fecqqoro46e6@corp.supernews.com> <4457bee2$1_6@news.bluewin.ch> Message-ID: <125fisc9sq8ir29@corp.supernews.com> On 2006-05-02, Boris Borcic wrote: > Grant Edwards wrote: >> On 2006-05-02, Boris Borcic wrote: >>> Grant Edwards wrote: >>>> Python knows how to count. :) >>>> >>>> def countFalse(seq): >>>> return len([v for v in seq if not v]) >>>> >>>> def countTrue(seq): >>>> return len([v for v in seq if v]) >>>> >>>> def truth_test(seq): >>>> return countTrue(seq) == 1 >>>> >>> I'd suggest the more direct >>> >>> def countFalse(seq) : >>> return sum(1 for v in seq if not v) >> >> I guess I don't see how that is more direct. >> >> If you want to know how many items are in a seqneuce, you call >> len(). > > sum doesn't construct a sequence Doh! I missed the fact that you used a generator rather than a list comprehension. >> Converting that list to a list of 1's > > that's not what my suggestion is doing I see that now. -- Grant Edwards grante Yow! Hey, waiter! I want at a NEW SHIRT and a PONY TAIL visi.com with lemon sauce! From tbrkic at yahoo.com Thu May 18 03:00:44 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 00:00:44 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <1147935644.838452.8260@i39g2000cwa.googlegroups.com> But you cant mix python code in there when creating the nodes. That is when it gets quite ugly an unreadable according to me. But I also relly do think that this: # build a tree structure root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): *=*text = "Page Title" *!*body("body"): *=*bgcolor = "#ffffff" *=*text = "Hello, World!" Especially if you start having deeper hierachies like. But the big other plus is that you can have any python code in beetween. From steve at hastings.org Tue May 2 14:46:42 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 02 May 2006 11:46:42 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> Message-ID: On Tue, 02 May 2006 17:15:05 +0000, John Salerno wrote: > Basically W, X, Y and Z are propositions > that are either true or false, and the puzzle lists a few statements > such as "Exactly one of X, Y and Z is true", and I'm trying to work out > a little algorithm that might test for this kind of stuff. Okay. You don't need to worry about the "is" tests at all. Python always represents the value "True" with a reference to a True object, and likewise "False" is a reference to a False object. To save memory, Python has just one of each object, so: a = False b = False a is b # this will always be true As some other posters showed by example, but didn't really explain, Python will *sometimes* but not always reuse integer objects. For common integer values such as 0 and 1, Python will reuse the objects; for uncommon (larger) values, Python usually won't. So: a = 12345 b = 12345 a is b # probably not true a = 0 b = 0 a is b # always true A key point is that you never really "assign a value to a variable". What you really do is "bind an object reference to a name". The long, simultaneous assignment form binds the same object reference to multiple variables: a = b = c = d = 12345 a is b # always true But as soon as you reassign any of the variables you will rebind the name to some other object reference: a += 1 a is b # definitely false a = 12345 a is b # probably false Python *could* notice that it already has an integer object with the value 12345, and rebind the name a with a reference to it. But in practice Python will probably just create a new integer object with value 12345, since the Python interpreter doesn't spend large amounts of time looking through its collection of objects to find ones that can be reused. Python also has exactly one "None" object, and always uses references to it whenever you reference None in your code. This is why it is preferred Python style to test for None with an "is" test: a is None Anyway, the major point I want you to take away from all this: it doesn't matter whether the "is" test succeeds or fails, if all you care about is the *value* of a variable. Python reuses object references to save memory, because this doesn't affect expressions that only care about the *value*. Your logic tests only care about True vs. False; they don't care about the underlying implementation of how True and False are expressed. > Another thing I'm trying to do is write a function that tests to see if > a list contains exactly one true item, and the rest are false (obviously > this would have to be a list of boolean values, I guess). I'm sure this > isn't a handy utility, but I enjoy figuring out how to implement it. This is a simple problem. I suggest you loop over the list and simply count how many values are false, and how many are true. I just wrote and tested this function in about a minute. The list doesn't have to be a list of booleans, actually. Python has a set of rules for evaluating other values as booleans: if 0: pass # never executed; 0 always false if "": pass # never executed; 0-length string always false if []: pass # never executed; 0-length list always false So, don't test to see if something is equal to True or False: if 0 == False: pass # never executed; False and 0 do not directly compare You *could* do this, but I don't really recommend it: if bool(0) == False: pass # always executed Do this: if not 0: pass # always executed if 1: pass # always executed To convert a random value into a boolean value, you could use either "bool()" or you could use "not not": a = not not 0 b = bool(0) "not not" will work on older versions of Python that didn't have an explicit boolean type; "not 0" would return 1 in that case. "bool()" will work in Python 2.2 and newer. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From fredrik at pythonware.com Thu May 4 07:08:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 13:08:52 +0200 Subject: Swaying A Coder Away From Python References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> Message-ID: Tim Williams wrote: > By David A. Utter who's this, and why does he think that sampling some random comments by some random bloggers should mean anything to anyone ? (and why do you seem to think that this matters, btw ?) (and yes, I recognize the names of some of the bloggers he quotes. they're not exactly known for their ability to get things done... but sure, if you cannot fix yourself, you can always try another language (speaking of which, has any- one seen Brandon lately? ;-)) instead of wasting time on clueless windbags, I'd recommend Pythoneers to read something written by someone with a working brain instead: http://www2.jeffcroft.com/2006/may/02/django-non-programmers/ (which can be summarized as "I hate programming, but that didn't stop me from building a really cool web application in Python"). From belred at gmail.com Thu May 4 00:01:51 2006 From: belred at gmail.com (Bryan) Date: Wed, 03 May 2006 21:01:51 -0700 Subject: python strings In-Reply-To: <445908D1.7040008@ghaering.de> References: <1146684876.311829.297280@i39g2000cwa.googlegroups.com> <445908D1.7040008@ghaering.de> Message-ID: Gerhard H?ring wrote: > Python 2.4.2 (#2, Sep 30 2005, 21:19:01) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> s = "\x000" >>>> s[0] == chr(0) > True > > - -- Gerhard this works too :) >>> s = '\x001' >>> s[0] == chr(0) True >>> s = '\x00abc' >>> s[0] == chr(0) True i think it would be more clear not to use 3 digits for this example since \x only uses the next two numbers, not 3. >>> s = '\x00' >>> s[0] == chr(0) True bryan From r.pellegrini at gmail.com Mon May 29 10:44:37 2006 From: r.pellegrini at gmail.com (Rocco) Date: 29 May 2006 07:44:37 -0700 Subject: why not in python 2.4.3 In-Reply-To: <1148906849.894298.323790@g10g2000cwb.googlegroups.com> References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> <1148851375.148311.320780@g10g2000cwb.googlegroups.com> <1148870627.058561.12800@y43g2000cwc.googlegroups.com> <1148897123.135779.91870@j33g2000cwa.googlegroups.com> <1148906849.894298.323790@g10g2000cwb.googlegroups.com> Message-ID: <1148913877.508686.266060@g10g2000cwb.googlegroups.com> Thanks Serge. It's a gzip string. So the code is >>> import urllib2 >>> def takefeed(url): request=urllib2.Request(url) request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5;Windows NT') opener = urllib2.build_opener() data=opener.open(request).read() return data >>> url='http://news.google.it/?output=rss' >>> d=takefeed(url) >>> from StringIO import StringIO >>> zipdata=StringIO(d) >>> import gzip >>> gz=gzip.GzipFile(fileobj=zipdata) >>> rss=gz.read() >>> len(rss) 102529 >>> print rss[0:100] NFE/1.0>> From webraviteja at gmail.com Fri May 5 23:39:38 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 5 May 2006 20:39:38 -0700 Subject: cross platform libraries In-Reply-To: <1146835883.634415.55510@i39g2000cwa.googlegroups.com> References: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> <1146802366.107685.299870@i40g2000cwc.googlegroups.com> <1146835883.634415.55510@i39g2000cwa.googlegroups.com> Message-ID: <1146886778.075376.307850@e56g2000cwe.googlegroups.com> Not much to it. Just follow the SimpleXMLRPCServer example from Python docs and register your shutdown function. Call it using xmlrpclib remotely. Actually, I prefer the telnet method below. Simple and straight forward. From durumdara at gmail.com Mon May 29 12:57:52 2006 From: durumdara at gmail.com (DurumDara) Date: Mon, 29 May 2006 18:57:52 +0200 Subject: Is anybody knows about a linkable, quick MD5/SHA1 calculator library ? Message-ID: <447B2810.20402@gmail.com> Hi ! I need to speedup my MD5/SHA1 calculator app that working on filesystem's files. I use the Python standard modules, but I think that it can be faster if I use C, or other module for it. I use FSUM before, but I got problems, because I "move" into "DOS area", and the parameterizing of outer process maked me very angry (not working). You will see this in this place: http://mail.python.org/pipermail/python-win32/2006-May/004697.html So: I must handle unicode filenames. I think that if I find a library that can working with py's unicode chars, and I can load and use it to hash files, the code be better, and faster. Anybody knows about same code ? Py2.4, Windows, Py2Exe, wxPy... That was the specification. Thanx for help: dd From rpw3 at rpw3.org Tue May 9 05:11:45 2006 From: rpw3 at rpw3.org (Rob Warnock) Date: Tue, 09 May 2006 04:11:45 -0500 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <1147156556.952331.29450@i39g2000cwa.googlegroups.com> <1147165494.822938.27590@e56g2000cwe.googlegroups.com> Message-ID: Pisin Bootvong wrote: +--------------- | Rob Warnock wrote: | > | No matter how scalable your language is, you cannot make a | > | 100MHz/128MB server serve 100,000 client a second over the internet. | > +--------------- | > | > Sure you can! That's ~1000 CPU cycles/request, which [assuming at least | > a 100BASE-TX NIC] is plenty to service 100K *small* requests/s... ;-} | | Well, I was really asking for a service that really service something | complicate and useful though :-D +--------------- If "only" being useful is enough, 100 cycles is enough for a DNS server, or an NTP server, or even a stub HTTP server that delivers some small piece of real-time data, like a few realtime environmental sensors [temperature, voltages, etc.]. +--------------- | > Of course, you might have to write it in assembler on bare metal, | > but the good news is that with only a 1000 cycle budget, at least | > the code won't be very large! ;-} | | And donot forget to account for OS CPU time (well may be you can write | your own OS for it too :-D ) +--------------- Uh... What I meant by "bare metal" is *no* "O/S" per se, only a simple poll loop servicing the attention flags[1] of the various I/O devices -- a common style in lightweight embedded systems. -Rob [1] a.k.a. "interrupt request" bits, except with interrupts not enabled. ----- Rob Warnock 627 26th Avenue San Mateo, CA 94403 (650)572-2607 From fredrik at pythonware.com Wed May 10 14:15:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 May 2006 20:15:31 +0200 Subject: python sqlite3 api question References: <1147282942.425241.214990@g10g2000cwb.googlegroups.com> Message-ID: lolmcbride at googlemail.com wrote: > is it possible to pass args through the api which are the same as the > args you can use on the sqlite3 command line? > What I'm talking about is the .mode or .output commands which you can > enter via the sqlite3 cli so I can dynamically change were the output > goes. sqlite/sqlite3 is an application built on top of the sqlite database engine, while Python's pysqlite/sqlite3 library is a binding to the same database engine. the database never prints anything to anywhere, and neither does Python's binding. if you want to print things, you have to print them yourself. From fredrik at pythonware.com Thu May 18 09:50:53 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 15:50:53 +0200 Subject: Conversion of perl unpack code to python - something odd In-Reply-To: <126ou0iapdasl8d@corp.supernews.com> References: <126ou0iapdasl8d@corp.supernews.com> Message-ID: Andrew Robert wrote: > # From the language declarations in manual, the following format was derived > > format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' that's 10 specifiers. > d1,d2=struct.unpack(format,data) that's two variables. > print d1 > sys.exit(0) > > When I run it, it says there are too many values to unpack. > > Traceback ( most recent call last) > File "m:\mq\mq\scripts\format.py", line 32, in ? > d1, d2 = struct.unpack(format,data) > ValueError: too many values to unpack > Error starting triggered application > > I checked the manual on the structure used to pack the code and it > appears correct. try printing the return value from struct.unpack, and see if you can figure out what's wrong with your code: print struct.unpack(format,data) From http Fri May 12 16:41:12 2006 From: http (Paul Rubin) Date: 12 May 2006 13:41:12 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: <7xy7x7m0wn.fsf@ruckus.brouhaha.com> Alexander Schmolck writes: > > (defvar *x*) ;; makes it special > > (setf *x* 1) > > (print *x*) ;;-> 1 > > (let ((*x* 2)) > > (print *x*)) ;; -> 2 > > (print *x*) ;; -> 1 > > You seem to think that conflating special variable binding and lexical > variable binding is a feature and not a bug. What's your rationale? I thought special variables meant dynamic binding, i.e. (defvar *x* 1) (defun f () (print *x*) ;; -> 2 (let ((*x* 3)) (g))) (defun g () (print *x*)) ;; - > 3 That was normal behavior in most Lisps before Scheme popularlized lexical binding. IMO it was mostly an implementation convenience hack since it was implemented with a very efficient shallow binding cell. That Common Lisp adapted Scheme's lexical bindings was considered a big sign of CL's couthness. So I'm a little confused about what Ken Tilton is getting at. From mh at pixar.com Fri May 5 13:08:24 2006 From: mh at pixar.com (Mark Harrison) Date: Fri, 05 May 2006 17:08:24 GMT Subject: to thine own SELF be true... Message-ID: Is there a way to do something equivalent to "import * from self"? Perhaps I'm doing something wrong, but I'm having a headache when dealing with class instance data, forgetting to always put the "self." prefix For example, in my brain I'm thinking: optc,args=getopt.getopt(args,cmdopts[cmd][0], cmdopts[cmd][1]) but I'm having to type: self.optc,self.args=getopt.getopt(self.args,self.cmdopts[self.cmd][0], self.cmdopts[self.cmd][1]) Is there a way to get rid of those the "self." references, or is this just something I need to get my brain to accept? Many TIA, Mark -- Mark Harrison Pixar Animaion Studios From manlio_perilloNO at SPAMlibero.it Mon May 22 12:33:14 2006 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Mon, 22 May 2006 16:33:14 GMT Subject: [ANN] pglib 0.1 Message-ID: I'm pleasant to announce the first public release of pglib. pglib is an implementation of the PostgreSQL protocol, version 3.0. It is written in Twisted, and aims to be a complete replacement for libpq. In the current version the extended query sub protocol is not supported. The project can be found at: http://developer.berlios.de/projects/pglib/ Unfortunately, I still have to write some documentation. However there is a (hopefully) detailed README and a test case. Regards Manlio Perillo From alf at merlin.fayauffre.org Tue May 16 09:09:10 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Tue, 16 May 2006 13:09:10 +0000 (UTC) Subject: Unicode digit to unicode string References: <1147784739.786522.234280@v46g2000cwv.googlegroups.com> Message-ID: Le 16-05-2006, Gabriele nous disait: > Hi, I have a unicode digit stored into a variable ('0020' for example) > and I'd like to retrieve the corrisponding unicode character based on > the current encoding. How can i do that ? use the unichr builtin function -- Alexandre Fayolle 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 paddy3118 at netscape.net Sun May 14 14:29:57 2006 From: paddy3118 at netscape.net (Paddy) Date: 14 May 2006 11:29:57 -0700 Subject: Named regexp variables, an extension proposal. In-Reply-To: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> References: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> Message-ID: <1147631397.922734.167880@u72g2000cwu.googlegroups.com> I have another use case. If you want to match a comma separated list of words you end up writing what constitutes a word twice, i.e: r"\w+[,\w+]" As what constitues a word gets longer, you have to repeat a longer RE fragment so the fact that it is a match of a comma separated list is lost, e.g: r"[a-zA-Z_]\w+[,[a-zA-Z_]\w+]" - Paddy. From nobody at 127.0.0.1 Sun May 14 23:08:30 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 15 May 2006 03:08:30 GMT Subject: help using smptd References: Message-ID: Heiko Wundram wrote: > If you don't define an __init__() yourself (as it seems to be the case > here), MRO (and the rules associated with class methods) will take care > that the base class' __init__() gets called automatically. Yes __init__ is being called. smtpd.PureProxy doesn't define its own init either and it shows the same behavior as my class: binds to the port but doesn't respond to connections. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From nobody at 127.0.0.1 Wed May 17 19:56:42 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 23:56:42 GMT Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <_2Jag.88816$dW3.57801@newssvr21.news.prodigy.com> Message-ID: <_KOag.28655$4L1.23224@newssvr11.news.prodigy.com> William Studenmund wrote: > The problem is that tabs take you to the next tab stop, they don't > expand to a fixed number of spaces. Got it. You're talking about using tabs other than for initial line indentation on a source file. Yes, then tab expansion is not perfect. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From Serge.Orlov at gmail.com Wed May 10 07:57:17 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 10 May 2006 04:57:17 -0700 Subject: Use subprocesses in simple way... In-Reply-To: References: Message-ID: <1147262237.501896.177210@y43g2000cwc.googlegroups.com> Dara Durum wrote: [snip design of a multi-processor algorithm] I thought md5 algorithm is pretty light, so you'll be I/O-bound, then why bother with multi-processor algorithm? > 2.) > Do you know command line to just like FSUM that can compute file > hashes (MD5/SHA1), and don't have any problems with unicode alt. file > names ? I believe you can wrap the broken program with a simple python wrapper. Use win32api.GetShortPathName to convert non-ascii file names to DOS filenames. From kentilton at gmail.com Sun May 7 11:18:43 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sun, 07 May 2006 11:18:43 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> Message-ID: Thomas F. Burdick wrote: > Ken Tilton writes: > > >>As for: >> >> >>> At a syntax-sugar >>>level, for example, Lisp's choice to use parentheses as delimiter means >>>it's undesirable, even unfeasible, to use the single character '(' as an >>>ordinary identifier in a future release of the language. >> >>(defun |(| (aside) (format nil "Parenthetically speaking...~a." aside)) >>=> |(| >>(|(| "your Lisp /is/ rusty.") >>=> "Parenthetically speaking...your Lisp /is/ rusty.." >> >>:) No, seriously, is that all you can come up with? > > > Well, you have to quote your (s-as-identifiers. I tried a goofy hack > of a reader macro for ( to make this parse: > > (let (( ( 10))) ( )) > > [The spaces are just for readability, not necessary] > > Alas, short of cps-transforming the whole reader, I can't see a > reasonable way to get that to parse as a single sexp that, when > evaluated, returns 10. What my reader macro gave me was five sexps: > > \(, LET, \(, ((10)), NIL > > I'll follow up with the Lisp code (on c.l.l only), in case I'm missing > something simple. Stop, you are scaring the pythonistas. Even Alex thought I was serious with (|(| "Hi mom"). Ouch that is hard to type. > > >>OK, I propose a duel. We'll co-mentor this: >> >> http://www.lispnyc.org/wiki.clp?page=PyCells >> >>In the end Python will have a Silver Bullet, and only the syntax will >>differ, because Python has a weak lambda, statements do not always >>return values, it does not have macros, and I do not know if it has >>special variables. > > > I have no idea what the big problem with a multi-line lambda is in > Python, but I wonder if Cells wouldn't run against the same thing. I > often pass around anonymous formulas that eventually get installed in > a slot. Seems annoying to have to name every formula with a > labels-like mechanism. (a) Right. (b) Bloated syntax will hurt in a linear way. the decomposition of application complexity into so many tractable small rules is a nonlinear win. (ok, painful coding of X does diminish ones use of X, but Cells force one to use Cells everywhere or not at all, so it comes with its own press gang, er, discipline.) (c) (b) might convince GvR to fix (a) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From reply.in.the.newsgroup at my.address.is.invalid Tue May 9 16:19:56 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 09 May 2006 22:19:56 +0200 Subject: Can Python installation be as clean as PHP? References: Message-ID: Jack: >I have to run the installer to install dozens of directories and >hundreds of files, That's not unusual and not considered a problem by most people. >and I don't really know if all of them are necessary. Don't let that bother you. Life's too short. >Plus, lots of libraries are in .py, which is of course not as >efficient/clean as having all of the core functions built-in in >the C/C++ core, like in PHP. Performance-critical parts _are_ implemented in C/C++. But not everything falls into this category. Yes, there's probably room for more performance improvements. Just like there is with PHP. Did you know, for example, that PHP doesn't store and re-use compiled versions of the scripts by default? With PHP you need to fiddle with eAccelerator, Zend and the like. The Python interpreter does this automatically. There are advantages to having library code in Python too, such as being able to seemlessly debug it in a Python debugger. Also, Python API's tend to be a lot cleaner than PHP's. This probably reflects the language they're implemented in. -- Ren? Pijlman From laurent.pointal at limsi.fr Mon May 22 10:38:12 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 22 May 2006 16:38:12 +0200 Subject: Testing for file type In-Reply-To: <1273iims70cu3e6@corp.supernews.com> References: <1273iims70cu3e6@corp.supernews.com> Message-ID: Andrew Robert a ?crit : > Hi Everyone, > > Is there a way to test if a file is binary or ascii within Python? > > I'd prefer not to text against file extension. > > Any help you can provide would be greatly appreciated. May look at unix "file" command sources... A+ L.Pointal. From grflanagan at yahoo.co.uk Mon May 15 04:35:27 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 15 May 2006 01:35:27 -0700 Subject: comparing values in two sets References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> Message-ID: <1147682127.720957.200550@y43g2000cwc.googlegroups.com> John Salerno wrote: > I'd like to compare the values in two different sets to test if any of > the positions in either set share the same value (e.g., if the third > element of each set is an 'a', then the test fails). > > I have this: > > def test_sets(original_set, trans_letters): > for pair in zip(original_set, trans_letters): > if pair[0] == pair[1]: > return False > return True > > > zip() was the first thing I thought of, but I was wondering if there's > some other way to do it, perhaps a builtin that actually does this kind > of testing. > > Thanks. 'enumerate' is another possibility: s1 = 'abcd' s2 = 'zzzz' s3 = 'zbzz' s4 = 'zzbz' def are_itemwise_different( L1, L2 ): #if len(L1) != len(L2): return True for idx, value in enumerate(L1): if value == L2[idx]: return False return True #after Peter Otten def are_itemwise_different( L1, L2 ): #if len(L1) != len(L2): return True return True not in ( value == L2[idx] for idx, value in enumerate(L1) ) assert are_itemwise_different(s1,s2) assert not are_itemwise_different(s1,s3) assert are_itemwise_different(s1,s4) def itemwise_intersect( L1, L2 ): #if len(L1) != len(L2): raise for idx, value in enumerate(L1): if value == L2[idx]: yield value assert list(itemwise_intersect(s1,s2)) == [] assert list(itemwise_intersect(s1,s3)) == ['b'] assert list(itemwise_intersect(s1,s4)) == [] Gerard From nospam at foo.com Wed May 10 12:57:22 2006 From: nospam at foo.com (jayessay) Date: 10 May 2006 12:57:22 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> Message-ID: "Michele Simionato" writes: > Ken Tilton wrote: > > I was not thinking about the thread issue (of which I know little). The > > big deal for Cells is the dynamic bit: > > > > (let ((*dependent* me)) > > (funcall (rule me) me)) > > > > Then if a rule forces another cell to recalculate itself, *dependent* > > gets rebound and (the fun part) reverts back to the original dependent > > as soon as the scope of the let is exited. > > Python 2.5 has a "with" statement (yes, the name is Lispish on purpose) > that could be used to implement this. See > http://www.python.org/dev/peps/pep-0343 You are mistaken. In particular, VAR doesn't have dynamic scope. /Jon -- 'j' - a n t h o n y at romeo/charley/november com From runlevelten at gmail.com Mon May 29 13:24:19 2006 From: runlevelten at gmail.com (Ten) Date: Mon, 29 May 2006 18:24:19 +0100 Subject: send an email with picture/rich text format in the body In-Reply-To: <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> Message-ID: <200605291824.19581.runlevelten@gmail.com> On Monday 29 May 2006 11:28, Max M wrote: > Ben Finney wrote: > > "anya" writes: > >>Acctualy there is a solution: > >>see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 > > > > Again, sending anything but plain text as the message body ensures > > that your message is unreadable to a large number of people using a > > variety of software. It's your choice whether to restrict your > > audience in this way, but know that that's what you're doing. > > 90% of users are non-technical users who use standard email readers, > that can easily read html messages. > Even if your 90% were any kind of real statistic, 90% of everyone is not everyone, and there ends the technical debate. 100 != 90 As a matter of interest, I'm almost sure that on checking you'd find that of the widely available mail clients, only a minority will display such a mail properly without further interaction. You might find that platform neutrality and usefulness to people are genuine considerations for those with any kind of technical integrity, and that "most people use this particular piece of proprietary software so let's just say screw the rest" (whilst still benefiting from a platform-neutral medium, and bouncing it off open source servers) is widely considered a shabby and broken way of working. If people want to palm people off with excuses and generally implement things in a lazy, badly badly planned, mercenary and undisciplined way, they're probably better off spending their time with the non-technical management and not amongst programmers. Sorry for the rant, good luck to the guy if he's solved his problem, but damn, that "90% so let's not bother doing things properly" stuff makes my blood boil. -- There are 10 types of people in this world, those who understand binary, and those who don't. From larry.bates at websafe.com Fri May 5 10:25:57 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 05 May 2006 09:25:57 -0500 Subject: Is this a legal / acceptable statement ? In-Reply-To: <2AI6g.10201$9c6.5375@dukeread11> References: <2AI6g.10201$9c6.5375@dukeread11> Message-ID: <-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> Philippe Martin wrote: > Hi, > > This code works, but is it "appropriate" ? > > l_init = False > > if True == l_init and 1234 = l_value: > print 'l_value is initialized' > > I know I can do this with a try but ... > > Philippe > > 1) You have a syntax error 1234 == l_value (note ==) 2) This doesn't test to see if l_value is initialized because if it isn't you get: 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 "junk.py", line 1, in ? if True == l_init and 1234 == l_value: NameError: name 'l_init' is not defined 3) It is unclear what l_init is used for in this context. Setting it to True doesn't tell you anything about l_value. Normally you do something like: l_value=None . . Intervening code . if l_value is None: print "l_value uninitialized" Or (something I never use): if not locals().has_key('l_value'): print "l_value uninitialized" -Larry Bates From pwatson at redlinepy.com Fri May 5 16:39:05 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Fri, 05 May 2006 15:39:05 -0500 Subject: to thine own SELF be true... In-Reply-To: References: Message-ID: <4c1rf9F133dkdU1@individual.net> Michael Ekstrand wrote: > On Fri, May 05, 2006 at 05:08:24PM +0000, Mark Harrison wrote: > >>Is there a way to get rid of those the "self." references, or is this >>just something I need to get my brain to accept? > > > It's pretty much just something you'll need to get your brain to accept. > You can replace self with something shorter, like s, but that's sure to > cause mass confusion for other people who try to read your code. > > I, however, find that the self. references are a great benefit to > readability, as it makes the scope of a variable quite easy to tell. A > lot of my C++ code is littered with `this->' or similar > explicit-scope-description things... > > - Michael This fits perfectly with "Explicit is better than implicit." From justfuckengoogleit at justfuckengoogleit.com Fri May 26 22:01:12 2006 From: justfuckengoogleit at justfuckengoogleit.com (justfuckengoogleit at justfuckengoogleit.com) Date: 26 May 2006 19:01:12 -0700 Subject: justfuckengoogleit.com Message-ID: <1148695272.064743.90640@y43g2000cwc.googlegroups.com> Got a dumb question to ask, http://www.justfuckengoogleit.com or www.justfuckinggoogleit.net From prikryl at skil.cz Thu May 11 05:04:39 2006 From: prikryl at skil.cz (Petr Prikryl) Date: Thu, 11 May 2006 11:04:39 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <44606502$2$645$bed64819@news.gradwell.net> <4461c69d$0$647$bed64819@news.gradwell.net> Message-ID: "Chris Uppal" wrote: > Petr Prikryl wrote: > > > for element in aCollection: > > if element > 0: > > return True > > return False > > [I'm not sure whether this is supposed to be an example of some specific > language (Python ?) or just a generic illustration. I'll take it as the > latter, since it makes my point easier to express. I'll also exaggerate, just > a little...] Sorry, I do not know Smalltalk, but this was meant as the transcription of your... | E.g. consider the Smalltalk code (assumed to be the body of a method): | | aCollection | do: [:each | | each > 0 ifTrue: [^ true]]. | ^ false. into Python > But now, in order to hack around the absence of a sensible and useful > feature -- /only/ in order to do so -- you have added two horrible new > complications to your language. You have introduced a special syntax to > express conditionals, and (worse!) a special syntax to express looping. Not > only does that add a huge burden of complexity to the syntax, and semantics, of > the language (and, to a lesser extent, its implementation), but it also throws > out any semblance of uniformity. I guess that it is not me who is confused here. The subject clearly says that the thread is related to Python and to lambda supported by Python. It was only crossposted to other groups and I did not want to remove them -- other people may want to read the thread in the other newsgroups. So, I did not introduced any horible syntax, nor looping construct that would look strange to people used to classical procedural languages. The lambda syntax in Python is the thing that could be viewed as a complication, not the "for" loop or the "if" construction. If you take any English speaking human (even the non-programmer), I could bet that the Python transcription will be more understandable than your Smalltalk example. > E.g. in Java there's an unresolved, and irresolvable, tension between whether a > failing operation should return an error condition or throw an exception [...]. It is more a design problem than the language problem. And it is also the implementation problem (i.e. what is the price of exceptions in comparison with the other code). In Python, the exceptions are intesively used. > E.g. can you add three-way comparisons (less-than, same-as, greater-than to, > say, Python with corresponding three-way conditional control structures to > supplement "if" etc ? Are they on a semantic and syntactic par with the > existing ones ? In Smalltalk that is trivial (too trivial to be particularly > interesting, even), and I presume the same must be true of Lisp (though I > suspect you might be forced to use macros). Such built-in function already is in Python. But you could add it by hand if it were not: def cmp(x, y): if x < y: return -1 if x == y: return 0 return 1 and the "if" supplement (the "switch" or "case" command) could be replaced easily in Python using the hash-table (dictionary) structure. > I should say that if your example /is/ in fact Python, then I believe that > language allows fairly deep hooks into the execution mechanism, so that at > least the "for" bit can be mediated by the collection itself -- which is better > than nothing, but nowhere near what I would call "good". It is a dual point of view. Should the collection be passive data, or not? I believe that the "pure" object oriented view (there are no functions, only the object methods) is not very practical and does not reflect well the big part of the reality that is simulated by programs. Python and C++, for example, allow mixing functions and objects. You should try Python. The "for" construct iterates through a sequence or through all values of the generator, thus making the for loop much more generic than for example in C or other languages. Every language forms the way of thinking. Every language has its strong and weak points. Every language has its followers and haters. Not every language is practical enough to fly around the Earth in the space ship. pepr (Sorry for my broken English.) From andrew.arobert at gmail.com Thu May 18 16:43:21 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 18 May 2006 16:43:21 -0400 Subject: Conversion of perl unpack code to python - something odd In-Reply-To: References: <126ou0iapdasl8d@corp.supernews.com> Message-ID: <126pn3s8eoq6118@corp.supernews.com> Peter Otten wrote: > Andrew Robert wrote: > >> format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' > > You are trying to squeeze 10 items into just > >> d1,d2=struct.unpack(format,data) > > two variables (d1 and d2) > >> ValueError: too many values to unpack > > and Python is quite explicit that it doesn't like that once you realize that > 'unpack' doesn't refer to struct.unpack() but to tuple unpacking like > >>>> a, b = "ab" >>>> a, b = "abc" > Traceback (most recent call last): > File "", line 1, in ? > ValueError: too many values to unpack > > > Peter > Now I feel like a first class idiot. Thanks for the help. Added the extra eight variables and things worked perfectly. Going to go stand in the corner for an hour now :) From tim.golden at viacom-outdoor.co.uk Fri May 26 10:19:53 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 26 May 2006 15:19:53 +0100 Subject: hide python window Message-ID: [Bell, Kevin] | When I run a script, how can I make it run in the background? I don't | want to see the command window because it runs all day. I'm on | windows... Broadly, two options (depending on what "in the background" means): 1) Complex, but complete: run it as a service. See the examples in the pywin32 extensions, and various discussions on this and the python-win32 mailing list. Advantage: runs thile the machine runs Disadvantage: more complex to set up runs by default as a user with few privs 2) Simpler: run the script with the pythonw.exe executable (or rename it to .pyw). This will run without a console window. Advantage: simpler - just use a different exe Disadvantage: will stop running when you log off 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 mickey at tm.informatik.uni-frankfurt.de Wed May 3 10:26:34 2006 From: mickey at tm.informatik.uni-frankfurt.de (Michael 'Mickey' Lauer) Date: 3 May 2006 14:26:34 GMT Subject: PyQt 4.0beta1 Released References: Message-ID: <4brssqF12al07U1@news.dfncis.de> Phil Thompson wrote: > On Saturday 29 April 2006 1:27 pm, Skink wrote: > > Phil Thompson wrote: > > > Riverbank Computing is pleased to announce the release of PyQt v4.0beta1 > > > available from http://www.riverbankcomputing.co.uk/pyqt/. > > > > > > PyQt is a comprehensive set of Qt bindings for the Python programming > > > language and supports the same platforms as Qt (Windows, Linux and > > > MacOS/X). Like Qt, PyQt is available under the GPL and a commercial > > > license. > > > > > > PyQt v4 supports Qt v4 (http://www.trolltech.com/products/qt/index.html). > > > PyQt v3 is still available to support earlier versions of Qt. > > > > Phil, great news! > > However I have one question: my qt4 is built with QT_NO_ACCESSIBILITY > > and when I try to build pyqt I got errors no such method > > QWidget.setAccessibleName > > > > What should I do? Rebuild qt4 without QT_NO_ACCESSIBILITY #define? > > > > My qt is 4.1.2 > > Yes - the current code assumes a fully configured Qt. I have sent Phil a patch to make PyQt4 aware of some optional features. It's in the snapshots already. :M: -- [ Michael 'Mickey' Lauer ] -- From kent at kentsjohnson.com Wed May 10 11:15:38 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 10 May 2006 11:15:38 -0400 Subject: data entry tool In-Reply-To: <445f038f@news.maxnet.co.nz> References: <445f038f@news.maxnet.co.nz> Message-ID: <44620313$1_1@newspeer2.tds.net> Peter wrote: > This post seeks advice on whether python would be appropriate for a task, or > whether you can suggest another approach. > > The project is to transcribe historical records such as schools admissions, > ship passenger lists, birth/death/marriages, etc for genealogy studies. > What we need is a simple software tool that will give the user a form set > out like the page being transcribed, do some simple validation and put the > data in a file (can be fixed field length plain text). Data files from > volunteers will be compiled into a master database. > > This software tool needs to work on a variety of different computers; Win95, > Win98, WinXP, Mac, Linux. Take a look at Tkinter, it is pretty easy to get started with and good for making simple GUIs. Look at the csv module for writing the data to files. Kent From me+python at modelnine.org Sun May 21 11:11:24 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 21 May 2006 17:11:24 +0200 Subject: PEP-xxx: Unification of for statement and list-comp syntax Message-ID: <200605211711.25043.me+python@modelnine.org> Hi all! The following PEP tries to make the case for a slight unification of for statement and list comprehension syntax. Comments appreciated, including on the sample implementation. === PEP: xxx Title: Unification of for-statement and list-comprehension syntax Version: $Revision$ Last-Modified: $Date$ Author: Heiko Wundram Status: Active Type: Standards Track Content-Type: text/plain Created: 21-May-2006 Post-History: 21-May-2006 17:00 GMT+0200 Abstract When list comprehensions were introduced, they added the ability to add conditions which are tested before the expression which is associated with the list comprehension is evaluated. This is often used to create new lists which consist only of those items of the original list which match the specified condition(s). For example: [node for node in tree if node.haschildren()] will create a new list which only contains those items of the original list (tree) whose items match the havechildren() condition. Generator expressions work similarily. With a standard for-loop, this corresponds to adding a continue statement testing for the negated expression at the beginning of the loop body. As I've noticed that I find myself typing the latter quite often in code I write, it would only be sensible to add the corresponding syntax for the for statement: for node in tree if node.haschildren(): as syntactic sugar for: for node in tree: if not node.haschildren(): continue There are several other methods (including generator-expressions or list-comprehensions, the itertools module, or the builtin filter function) to achieve this same goal, but all of them make the code longer and harder to understand and/or require more memory, because of the generation of an intermediate list. Implementation details The implementation of this feature requires changes to the Python grammar, to allow for a variable number of 'if'-expressions before the colon of a 'for'-statement: for_stmt: 'for' exprlist 'in' testlist_safe ('if' old_test)* ':' suite ['else' ':' suite] This change would replace testlist with testlist_safe as the 'in'-expression of a for statement, in line with the definition of list comprehensions in the Python grammar. Each of the 'if'-expressions is evaluated in turn (if present), until one is found False, in which case the 'for'-statement restarts at the next item from the generator of the 'in'-expression immediately (the tests are thus short-circuting), or until all are found to be True (or there are no tests), in which case the suite body is executed. The behaviour of the 'else'-suite is unchanged. The intermediate code that is generated is modelled after the byte-code that is generated for list comprehensions: def f(): for x in range(10) if x == 1: print x would generate: 2 0 SETUP_LOOP 42 (to 45) 3 LOAD_GLOBAL 0 (range) 6 LOAD_CONST 1 (10) 9 CALL_FUNCTION 1 12 GET_ITER >> 13 FOR_ITER 28 (to 44) 16 STORE_FAST 0 (x) 19 LOAD_FAST 0 (x) 22 LOAD_CONST 2 (1) 25 COMPARE_OP 2 (==) 28 JUMP_IF_FALSE 9 (to 40) 31 POP_TOP 3 32 LOAD_FAST 0 (x) 35 PRINT_ITEM 36 PRINT_NEWLINE 37 JUMP_ABSOLUTE 13 >> 40 POP_TOP 41 JUMP_ABSOLUTE 13 >> 44 POP_BLOCK >> 45 LOAD_CONST 0 (None) 48 RETURN_VALUE where all tests are inserted immediately at the beginning of the loop body, and jump to a new block if found to be false which pops the comparision from the stack and jumps back to the beginning of the loop to fetch the next item. Implementation issues The changes are backwards-compatible, as they don't change the default behaviour of the 'for'-loop. Also, as the changes that this PEP proposes don't change the byte-code structure of the interpreter, old byte-code continues to run on Python with this addition unchanged. Implementation A sample implementation (with updates to the grammar documentation and a small test case) is available at: http://sourceforge.net/tracker/index.php?func=detail&aid=1492509&group_id=5470&atid=305470 Copyright This document has been placed in the public domain. === --- Heiko. From nogradi at gmail.com Mon May 1 15:51:23 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 1 May 2006 21:51:23 +0200 Subject: How do I take a directory name from a given dir? In-Reply-To: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> References: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> Message-ID: <5f56302b0605011251t2169bad1m70e3f5fc2198ffec@mail.gmail.com> > Hi, > > I am trying to write a script to backup all my company's server configs > weekly. The script will run in a cronjob, on whatever I set it. > > The issue I am currently having isto "extract" the directory name from > a given directory string. For example: from the string > "/home/testuser/projects/" I need to extract the "projects" part. The > problem is that the directory names that needs to be used will never be > the same lenght, so as far as my (very limited) knowledge stretches, > slicing and indicing is out of the question. > > Can anybody help me, or give me an idea of what I should look at, > seeing as I'm seriously stuck. I only started coding at the beginnig of > the year, and was never interested before that, so my knowlege is > basically non-existent. You can try this: >>> '/home/testuser/projects/'.strip( '/' ).split( '/' ) ['home', 'testuser', 'projects'] strip gets rid of the first and last / and split splits the remaining part and puts the results into a list. HTH :) From thomasbartkus at comcast.net Wed May 10 11:10:24 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 10 May 2006 10:10:24 -0500 Subject: MySQLdb trouble References: Message-ID: "John Salerno" wrote in message news:Xnm8g.2076$No6.45677 at news.tufts.edu... > Nicolay A. Vasiliev wrote: > > > def loc_connect_db(): > > """ > > The DB connection subroutine > > """ > > db = MySQLdb.connect(host = "localhost", > > user = "root", > > passwd="mysql", > > db="some_db") > > return db > > Hi. Sorry I can't help, but I'm interested in learning about mysqldb and > I was wondering why you chose to wrap the 'connect' function inside your > own function. > Does this accomplish something that I'm not seeing? Probably! 1) His code body will be less likely to cause migrane headaches when he tries to read and interpret what he did a year from now. If you are trying to figure out what is going on with the logic, user names and passwords can be so much chaff your brain needs to wade through in order to get to the central idea. 2) The coder won't have to repeat himself if he needs to re-open the databases. He can just call his less comples loc_connect_db() function. And know that #1 is a sufficient reason even if #2 doesn't apply! > Couldn't you just use the body of the loc_connect_db() function as your > actual code in order to get 'db'? Yes you could! It's really a matter of style and preference. Some programmers (myself included!) prefer many, very short and simple functions over fewer function with longer blocks of more complex code. It's hard to make a mistake by having too many short and simple functions. And much too easy to make them when you have too few ;-) Thomas Bartkus . From claird at lairds.us Tue May 30 13:05:46 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 30 May 2006 17:05:46 +0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> Message-ID: In article <127oj612scnl8a0 at corp.supernews.com>, Grant Edwards wrote: >On 2006-05-30, xkenneth wrote: > >> I'm using linux. > >[It's generally considered good practice to quote enough context >so that your post makes sense to people without access to older >postings.] > >Under Linux there isn't really anything. IIRC, many years ago, >somebody had written a kernel module that inserted itself >between application and serial port and logged operations, but >the last time I tried to find it, I was unsuccessful. > >If you feel like building a kernel, adding a few printk() calls >to either the low-level serial driver or the tty >line-discipline layer might do what you want. . . . !? I hadn't realized there's no such monitor ... What do you think of ? From nospamjynyl at yahoo.co.nz Mon May 8 04:38:39 2006 From: nospamjynyl at yahoo.co.nz (Peter) Date: Mon, 08 May 2006 20:38:39 +1200 Subject: data entry tool Message-ID: <445f038f@news.maxnet.co.nz> This post seeks advice on whether python would be appropriate for a task, or whether you can suggest another approach. The project is to transcribe historical records such as schools admissions, ship passenger lists, birth/death/marriages, etc for genealogy studies. What we need is a simple software tool that will give the user a form set out like the page being transcribed, do some simple validation and put the data in a file (can be fixed field length plain text). Data files from volunteers will be compiled into a master database. This software tool needs to work on a variety of different computers; Win95, Win98, WinXP, Mac, Linux. So, would python be a good choice for this, and how should I go about it? I'm not a programmer and have only done a few little python scripts that run from the command line. TIA Peter From blair.bethwaite at gmail.com Sun May 7 20:46:16 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 7 May 2006 17:46:16 -0700 Subject: utility functions within a class? References: <445e8992$0$9427$c3e8da3@news.astraweb.com> Message-ID: <1147049176.712585.205560@j73g2000cwa.googlegroups.com> It sounds like all you want is some encapsulation, the following makes methods __head__ and __body__ "private" - the double underscores are important. I'd suggest reading the Object bits of the python tutorial also. class HTMLWrapper: def generate(self, ...): ... self.__head__(foo) ... self.__body__(bar) ... def __head__(self, ...): ... def __body__(self, ...): ... From hudsyd at gmail.com Tue May 16 03:49:39 2006 From: hudsyd at gmail.com (Hudson Diederich) Date: Tue, 16 May 2006 08:49:39 +0100 Subject: accessing information in a class Message-ID: <998c0b980605160049r12d7a590hdd14b9ecea750816@mail.gmail.com> hello, I'm writing a gui evotign program and I need to access information inputted by a user through a radiobutton. the radobuttons are in a class and I cannot get the value of the radiobuttons -------------- next part -------------- An HTML attachment was scrubbed... URL: From possibilitybox at gmail.com Wed May 24 15:56:29 2006 From: possibilitybox at gmail.com (possibilitybox at gmail.com) Date: 24 May 2006 12:56:29 -0700 Subject: Finding Upper-case characters in regexps, unicode friendly. Message-ID: <1148499736.129270.196940@j73g2000cwa.googlegroups.com> I'm trying to make a unicode friendly regexp to grab sentences reasonably reliably for as many unicode languages as possible, focusing on european languages first, hence it'd be useful to be able to refer to any uppercase unicode character instead of just the typical [A-Z], which doesn't include, for example ?. Is there a way to do this, or do I have to stick with using the isupper method of the string class? From stormtoad at gmail.com Wed May 24 11:51:15 2006 From: stormtoad at gmail.com (Stormcoder) Date: 24 May 2006 08:51:15 -0700 Subject: John Bokma harassment In-Reply-To: <1148470149.596188.18500@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> Message-ID: <1148485875.338415.145070@g10g2000cwb.googlegroups.com> Five is not excessive when they are on topic and they are on topic. If you don't like his posts ignore them, killfile them, whatever. I took the time to write his ISP a supporting email because it is important to keep unpopular speech, even more than popular speech, free. Censoring usenet serves no good purpose. From http Thu May 25 01:40:11 2006 From: http (Paul Rubin) Date: 24 May 2006 22:40:11 -0700 Subject: Modify one character in a string References: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> Message-ID: <7xodxmr7b8.fsf@ruckus.brouhaha.com> "mp" writes: > How do I go about modifying one character in a string elegantly? > In other words, I want a function that will change 'aaaa' to 'aaza', > given the index 2 of the character in the string. Ehh, there are various ways, all ugly. x = 'aaaa' y = x[:2] + 'z' + x[3:] is the most direct. > Also, how do I do this when dealing with a file ; which file mode > should I use and what function should I use to modify a single > character once in that file mode? You mean you want to change a character in a file? f = open(file, 'r+') # open for reading and writing f.seek(2) # position at character index 2 f.write('z') # put a 'z' there f.seek(0) # rewind print f.read() # get entire contents and see the change You could also look at the mmap module. From steve at holdenweb.com Sat May 20 08:43:57 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 20 May 2006 13:43:57 +0100 Subject: misleading prefix ++ In-Reply-To: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> References: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> Message-ID: LuciferLeo at gmail.com wrote: > given i = 0, > I know i = i + 1 and i += 1 are all correct > but when I type: > >>>>i++ > > the interpreter replies: > File "", line 1 > i++ > ^ > SyntaxError: invalid syntax > > so I get the idea that suffix ++ is invalid in python > but when I input: > >>>>++i > > and the interpreter replies > 0 > > Don't you think it is misleading when you expect a variable to > increment? > Terribly. So stop expecting it to increment :) Seriously, --i is also valid Python. Both expressions apply two unary operators to a name. Would you have these become illegal, or start to mean increment/decrement? Either change would break years of backwards compatibility. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From mc79 at cse.buffalo.edu Mon May 1 03:58:31 2006 From: mc79 at cse.buffalo.edu (Madhusudhanan Chandrasekaran) Date: Mon, 1 May 2006 03:58:31 -0400 Subject: Converting floating point to string in non-scientific format Message-ID: Hi all: When I try to convert a float variable into string via repr() or str() function, i get the value as is, i.e '0.1e-7' in IEEE 754 format. Instead how can force the created string to represent the floating point in non-scientific fashion (non IEEE 754 format)? i.e something like 0.000000001 Thanks in advance for your help. -Madhu From andymcdonagh at earthlink.net Wed May 3 13:00:28 2006 From: andymcdonagh at earthlink.net (Andy McDonagh) Date: Wed, 3 May 2006 18:00:28 +0100 (GMT+01:00) Subject: NaN handling Message-ID: <18277502.1146675628355.JavaMail.root@elwamui-karabash.atl.sa.earthlink.net> Dear python experts, I am new to python and this site, so I apologize if this is off topic (i.e. is it a SciPy question?). I will try to demonstrate my problem below: -------------------------------------------------------- #!/usr/local/bin/python from scipy import * from scipy.stats import * a=norm(loc=0,scale=1) a_data = a.rvs(10) problem = zeros(10) print problem h_x1_x2 = -sum(problem * log2(a_data)) print h_x1_x2 #NaN ---------------------------------------------------------- I need a way of handling NaNs for example R has the 'na.omit' option. Does anybody know if this exists? Many thanks Andy From george.sakkis at gmail.com Thu May 25 22:11:01 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 25 May 2006 19:11:01 -0700 Subject: __getattr__ and functions that don't exist References: <44762cf8$1@nntp.zianet.com> <1148596303.833301.15190@g10g2000cwb.googlegroups.com> <447648ab$1@nntp.zianet.com> Message-ID: <1148609461.673565.52400@y43g2000cwc.googlegroups.com> Erik Johnson wrote: > Thanks for your reply, Nick. My first thought was "Ahhh, now I see. That's > slick!", but after playing with this a bit... > > >>> class Foo: > ... def __getattr__(self, attr): > ... def intercepted(*args): > ... print "%s%s" % (attr, args) > ... return intercepted > ... > >>> f = Foo() > >>> f > __repr__() > Traceback (most recent call last): > File "", line 1, in ? > TypeError: __repr__ returned non-string (type NoneType) > > > my thought is "Oooooh... that is some nasty voodoo there!" Especially > if one wants to also preserve the basic functionality of __getattr__ so that > it still works to just get an attribute where no arguments were given. > > I was thinking it would be clean to maintain an interface where you > could call things like f.set_Spam('ham') and implement that as self.Spam = > 'ham' without actually having to define all the set_XXX methods for all the > different things I would want to set on my object (as opposed to just making > an attribute assignment), but I am starting to think that is probably an > idea I should just simply abandon. You're right, you should probably abandon it because python is not java; there's no reason to bloat your API with getters and setters instead of the natural attribute access and assignment. Now if you've spent a lot of time in the java camp and can't live without verbose getters and setters, it's not hard to emulate them: class Foo(object): def __getattr__(self, attr): if not (attr.startswith('get_') or attr.startswith('set_')): raise AttributeError name = attr[4:] if attr[0] == 'g': return lambda: getattr(self,name) else: return lambda value: setattr(self,name,value) f = Foo() f.set_bar(1) print f.get_bar() print f.bar > I guess I don't quite follow the error above though. Can you explain > exactly what happens with just the evaluation of f? Several thing happen: 1. When you give an expression in the shell, its value is computed and then passed to the repr() function. The result of repr(f) is what's printed. 2. repr(f) attempts to call f.__repr__() 3. __repr__ is not defined in class Foo or any of its (zero) superclasses. 4. As a result, f.__getattr__('__repr__') is called instead and returns the intercept local function. 5. intercept() is called with zero arguments (remember, intercept is the result of f.__repr__) 6. intecept prints something but it doesn't return explicitly; thus it returns None. 7. There's a rule that __repr__ (like __str__ and __unicode__) has to return a string-type (I'm not sure where is this rule enforced, by the classobj maybe ?). Since you returned None, an exception is raised. Note that there is not an exception if - you replace print with return in __getattr__, or - Foo is a new-style class, i.e. extends object like this: class Foo(object): # rest remain the same The reason is that in step (3) above, __repr__ would be looked up in Foo's superclass, object, and object.__repr__ would be called instead of Foo.__getattr__. Try to use new-style classes in new code unless you have a good reason not to. > Thanks, > -ej HTH, George > "Nick Smallbone" wrote in message > news:1148596303.833301.15190 at g10g2000cwb.googlegroups.com... > > Erik Johnson wrote: > > > Maybe I just don't know the right special function, but what I am > wanting to > > > do is write something akin to a __getattr__ function so that when you > try to > > > call an object method that doesn't exist, it get's intercepted *along > with > > > it's argument*, in the same manner as __getattr__ intercepts attributes > > > references for attributes that don't exist. > > > > > > > > > This doesn't quite work: > > > > > > >>> class Foo: > > > ... def __getattr__(self, att_name, *args): > > > ... print "%s%s" % (att_name, str(tuple(*args))) > > > ... > > > >>> f = Foo() > > > > The problem is that the call to f.bar happens in two stages: the > > interpreter calls getattr(f, "foo") to get a function, and then it > > calls that function. When __getattr__ is called, you can't tell what > > the parameters of the function call will be, or even if it'll be called > > at all - someone could have run "print f.bar". > > > > Instead, you can make __getattr__ return a function. Then *that* > > function will be called as f.bar, and you can print out its arguments > > there: > > > > class Foo: > > def __getattr__(self, attr): > > def intercepted(*args): > > print "%s%s" % (attr, args) > > return intercepted > > From robin.meier at gmail.com Sun May 28 15:50:00 2006 From: robin.meier at gmail.com (robin) Date: 28 May 2006 12:50:00 -0700 Subject: html 2 plain text In-Reply-To: <6bmeg.15876$jP5.394845@twister1.libero.it> References: <1148840205.741356.209310@i40g2000cwc.googlegroups.com> <6bmeg.15876$jP5.394845@twister1.libero.it> Message-ID: <1148845800.476588.263190@u72g2000cwu.googlegroups.com> lucks yummy. merci beaucoup. robin From deets at nospam.web.de Thu May 4 12:00:15 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 May 2006 18:00:15 +0200 Subject: Tuple assignment and generators? References: Message-ID: <4bumpbF13dg69U1@uni-berlin.de> Tim Chase wrote: > Just as a pedantic exercise to try and understand Python a > bit better, I decided to try to make a generator or class > that would allow me to unpack an arbitrary number of > calculatible values. In this case, just zeros (though I > just to prove whatever ends up working, having a counting > generator would be nice). The target syntax would be > something like By using this: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/284742 I came up with a small decorator doing that: import inspect, dis def expecting(): """Return how many values the caller is expecting""" f = inspect.currentframe() f = f.f_back.f_back c = f.f_code i = f.f_lasti bytecode = c.co_code instruction = ord(bytecode[i+3]) if instruction == dis.opmap['UNPACK_SEQUENCE']: howmany = ord(bytecode[i+4]) return howmany elif instruction == dis.opmap['POP_TOP']: return 0 return 1 def variably_unpack(f): def d(*args, **kwargs): r = f(*args, **kwargs) exp = expecting() if exp < 2: return exp return (r.next() for i in xrange(exp)) return d @variably_unpack def test(): def gen(): i = 0 while True: yield i i += 1 return gen() a, b, c = test() print a,b,c a, b, c, d = test() print a,b,c, d Diez From lance at augustmail.com Tue May 16 14:17:45 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Tue, 16 May 2006 13:17:45 -0500 Subject: round numbers in an array without importing Numeric or Math? Message-ID: <446a1748$0$61168$ae4e5890@news.nationwide.net> Is there an easy way to round numbers in an array? I have Test = [1.1,2.2,3.7] and want to round so the values are print Test [1,2,4] Lance From elpX at adsihqX.com Sun May 28 11:00:32 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Sun, 28 May 2006 15:00:32 GMT Subject: Array? Please help. In-Reply-To: <4478bd43$1@nntp0.pdx.net> References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> <4478bd43$1@nntp0.pdx.net> Message-ID: No it is not home work. (I have not did any home work for more than 50 years.) I am a beginner, and just do not see a really proper way to program the question. Thanks anyhow. Scott David Daniels wrote: > Dr. Pastor wrote: > >> I need a row of 127 bytes that I will use as a >> circular buffer. Into the bytes (at unspecified times) >> a mark (0> After some time the "buffer" will contain the last 127 marks. > > > Sounds a lot like homework. > From phddas at yahoo.com Fri May 5 16:31:10 2006 From: phddas at yahoo.com (Gary Wessle) Date: 06 May 2006 06:31:10 +1000 Subject: print formate Message-ID: <87odyctdrl.fsf@localhost.localdomain> Hi import string import re accumulator = [] pattern = '(\S*)\s*(\S*)\s*(\S*)' for each text file in dir openfile and read into text data = re.compile(pattern, re.IGNORECASE).findall(text) accumulator = accumulator + data gives a list of tuples which when printed looks like ('jack', 'bony', 'J') ('sam', 'lee', 'S') ... how can I get the output in the formate jack bony J sam lee S ... thank you From miki.tebeka at gmail.com Mon May 29 04:34:11 2006 From: miki.tebeka at gmail.com (Miki) Date: 29 May 2006 01:34:11 -0700 Subject: HTMLParser chokes on bad end tag in comment In-Reply-To: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> References: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> Message-ID: <1148891651.141309.263190@38g2000cwa.googlegroups.com> Hello Rene, You can also check out BeautifulSoup (http://www.crummy.com/software/BeautifulSoup/) which is less strict than the regular HTML parser. HTH, Miki http://pythonwise.blogspot.com/ From roger.miller at nova-sol.com Tue May 2 15:58:14 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 2 May 2006 12:58:14 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> Message-ID: <1146599894.090292.69590@e56g2000cwe.googlegroups.com> Steve R. Hastings wrote: > a = 0 > b = 0 > a is b # always true Is this guaranteed by the Python specification, or is it an artifact of the current implementation? My understanding has been that an implementation is free to share integer objects or not, so using 'is' as an equality test takes you into undefined territory, regardless of the size of the value. From aleax at mac.com Tue May 9 01:44:57 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 8 May 2006 22:44:57 -0700 Subject: Python's DSLs References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <3mh4j3-9pm.ln1@lairds.us> Message-ID: <1hf1iaz.1qdpj4h1mj5f71N%aleax@mac.com> Cameron Laird wrote: ... > On this one isolated matter, though, I'm confused, Alex: I sure > think *I* have been writing DSLs as specializations of Python, > and NOT as "a language in its own right". Have I been fooling > myself, or are you making the point that Lisp-based DSLs live in > a larger syntactic universe than Python's, or ...? With Lisp (or Scheme, for that matter), a DSL "lives" in exactly the same world as the base language, while being able to add or tweak whatever syntax it needs; with Python (or C++ or Java, for that matter), a DSL is either a completely separate beast (parsed, compiled, perhaps interpreted in the "host" language), or else it uses exactly the same syntax as used in the host language. To rapidly build, experiment with, and tweak, DSL's, a language with macros is thus advantaged. As to how crucial that is for _production_ (as opposed to _research_) purposes, well, obviously I prefer having no macros (or else I'd use some form of Lisp, or perhaps Dylan -- at least for my own private purposes, such as my long-standing personal research into the fundamentals of contract bridge -- while in fact I prefer to use Python for those purposes just as for others). But that doesn't make me blind to the advantages of macros for DSL-building purposes (if I was totally sold on both Python AND macros, I think I might build a macro preprocessor on top of Python -- the current ASL-based compiler probably makes that task much more feasible than it used to be -- but, macros would be somewhat complicated as in Dylan, not extremely easy as in Scheme [[or, I guess, Common Lisp, though I have no real experience with those -- on the surface they look murkier than Scheme's, but that may be just an issue of habit on my part]]). Alex From william.boquist at gte.net Thu May 4 00:40:54 2006 From: william.boquist at gte.net (william.boquist at gte.net) Date: Thu, 04 May 2006 04:40:54 GMT Subject: Newbie question on code vetting References: Message-ID: Edward, I agree with your point, which is why I asked the question. Risk cannot be eliminated, but it can be understood and managed so that useful work can still be done. If there is any way I can find out what the commiters do prior to reaching a decision to accept or reject a particular submission, I would like to know about it. Thanks in advance, Bill "Edward Elliott" wrote in message news:y356g.81306$dW3.7774 at newssvr21.news.prodigy.com... > Dennis Lee Bieber wrote: > >> I work for a risk-averse company, and I want to compile a solid case for > >> obtaining and using Python at work. > >> > > Given the nature of the US Patent Office... You might as well lock > > the doors now... > > > > The Patent Office could issue a patent next week that makes all > > bytecode interpreted languages subject to some royalty... > > Risk isn't just what could happen, it's how likely it is and what effects it > would have. A patent affecting millions of installed interpreters is > pretty unlikely and would have many challengers. Even if it were upheld, > how many larger companies with deeper pockets would they go after before > his? And everyone stuck in the same boat would quickly work towards a > non-infringing solution. Cases like MS-EOLAS and RIM-NTP aren't exactly a > daily occurence. They also demonstrate why there really is safety in > numbers. > > Plus all the potential negatives have to weighed against the increased > productivity his company gains from using a scripting language. The gains > may more than offset any potential patent settlement. > > Risk-averse doesn't mean head-in-the-sand. > From sjmachin at lexicon.net Mon May 15 19:45:42 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2006 16:45:42 -0700 Subject: Large Dictionaries In-Reply-To: <1147699064.107490@teuthos> References: <1147699064.107490@teuthos> Message-ID: <1147736742.866357.267670@j55g2000cwa.googlegroups.com> 1. Why is two minutes to insert 5M keys "bad" for you? What would be "good"? What would be good/bad look-up times? Have you measured the typical look-up time? How often is the dict creation required to be done? How often does the data change? Is multi-user access required for (a) look-up (b) updating? Have you considered loading the dict from a pickle? 2. Assuming your code that is creating the dict looks in essence like this: adict = {} for k, v in some_iterable: adict[k] = v then any non-linear behaviour can only be in the actual CPython insertion code. Psyco can't help you there. Psyco *may* help with the linear part, *if* you have enough memory. What are the corresponding times without Psyco? In any case, if your code isn't (conceptually) that simple, then try cutting away the cruft and measuring again. 3. Which version of Python? What OS? OK, psyco -> Intel x86, but what chip exactly? How much free memory? 4. Consider printing time-so-far results, say every 100K keys. Multiple step-ups might indicate dict resizings. A dog-leg probably means running out of memory. Why "roughly" 5M keys??? 5. How large are your long_integers? 6. What is the nature of the value associated with each key? 7. Have you experimented with key = a * 2 ** 32 + b instead of key = (a, b)? HTH, John From robert.kern at gmail.com Thu May 18 18:08:30 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 May 2006 17:08:30 -0500 Subject: WTF? Printing unicode strings In-Reply-To: References: Message-ID: Ron Garret wrote: > In article , > Robert Kern wrote: > >>Ron Garret wrote: >> >>>I forgot to mention: >>> >>> >>>>>>sys.getdefaultencoding() >>> >>>'utf-8' >> >>A) You shouldn't be able to do that. > > What can I say? I can. See B). >>B) Don't do that. > > OK. What should I do instead? See below. >>C) It's not relevant to the encoding of stdout which determines how unicode >>strings get converted to bytes when printing them: >> >>>>>import sys >>>>>sys.stdout.encoding >> >>'UTF-8' >> >>>>>sys.getdefaultencoding() >> >>'ascii' >> >>>>>print u'\xbd' >> >>1?2 > > OK, so how am I supposed to change the encoding of sys.stdout? It comes > up as US-ASCII on my system. Simply setting it doesn't work: You will have to use a terminal that accepts UTF-8. -- 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 praveenkumar.117 at gmail.com Wed May 3 11:33:10 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 3 May 2006 08:33:10 -0700 Subject: May I know Which is the best programming guide for using Tix in python Message-ID: <1146670389.987183.29600@j73g2000cwa.googlegroups.com> Hi, Can anyone suggest best reference book of using Tix widgets in python. I want to know the prototype of widgets, its member functions and data members -Regards, praveen From tommy04 at gmail.com Sat May 27 10:42:07 2006 From: tommy04 at gmail.com (Tommy B) Date: 27 May 2006 07:42:07 -0700 Subject: Running External Commands + Seeing when they are Finished In-Reply-To: <1148721879.618230.49710@y43g2000cwc.googlegroups.com> References: <1148707745.744045.77770@g10g2000cwb.googlegroups.com> <1148721879.618230.49710@y43g2000cwc.googlegroups.com> Message-ID: <1148740927.205068.259650@i39g2000cwa.googlegroups.com> The problem is with that (which is what I'm doing already) is that one app is in a window and one app is on the command line. Thus, you end up with both apps running at the same time. Are there any modules that have functions for checking when windows are opened or closed? From deets at nospam.web.de Mon May 8 05:16:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 May 2006 11:16:13 +0200 Subject: data entry tool References: <445f038f@news.maxnet.co.nz> Message-ID: <4c8gkoF14mu9cU1@uni-berlin.de> Peter wrote: > > This post seeks advice on whether python would be appropriate for a task, > or whether you can suggest another approach. > > The project is to transcribe historical records such as schools > admissions, ship passenger lists, birth/death/marriages, etc for genealogy > studies. What we need is a simple software tool that will give the user a > form set out like the page being transcribed, do some simple validation > and put the > data in a file (can be fixed field length plain text). Data files from > volunteers will be compiled into a master database. > > This software tool needs to work on a variety of different computers; > Win95, Win98, WinXP, Mac, Linux. > > So, would python be a good choice for this, and how should I go about it? > I'm not a programmer and have only done a few little python scripts that > run from the command line. Make it a webapp. That will guarantee to make it runnable on the list of OSses you gave. Use Django/TurboGears/ZOPE for the application itself- whichever suits you best. Diez From apavluck at gmail.com Thu May 18 12:55:28 2006 From: apavluck at gmail.com (Alex Pavluck) Date: 18 May 2006 09:55:28 -0700 Subject: SPE output Message-ID: <1147971328.648561.222850@u72g2000cwu.googlegroups.com> Does anyone know if there is a way to configure the SPE output? IDLE and Pythonwin IDE both have nicely formatted output that shows tabs and spaces correctly. SPE seems to just print out the text without any formatting. SPE is amazing with the intellisense but maybe there is a better choice out there. Thanks, Alex From andychambers2002 at yahoo.co.uk Sat May 27 10:33:28 2006 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 27 May 2006 07:33:28 -0700 Subject: dynamic type changing Message-ID: <1148740408.226975.318050@u72g2000cwu.googlegroups.com> I'm working on a "TempFile" class that stores the data in memory until it gets larger than a specified threshold (as per PEP 42). Whilst trying to implement it, I've come across some strange behaviour. Can anyone explain this? The test case at the bottom starts a TempFile at size 50 and prints its type. It then increases the size to the threshold at which point "self" is changed to being a TemporaryFile. It seems that the next call correctly uses the write() method of TemporaryFile (since we don't see "changing type" in the output). However, type(tmp) still equals TempFile. Not only that, tmp can still access the method dummy() that exists only in TempFile. #!/usr/bin/env python from StringIO import StringIO import tempfile class TempFile(StringIO, object): """A temporary file implementation that uses memory unless either capacity is breached or fileno is requested, at which point a real temporary file will be created and the relevant details returned """ def __init__(self, buffer, capacity): """Creates a TempFile object containing the specified buffer. If capacity is specified, we use a real temporary file once the file gets larger than that size. Otherwise, the data is stored in memory. """ self.capacity = capacity if len(buffer) > capacity: self = tempfile.TemporaryFile() self.write(buffer) else: super(TempFile, self).__init__(buffer) def dummy(self): pass def write(self, str): self.seek(0, 2) # find end of file if((self.tell() + len(str)) >= self.capacity): print "changing type" flo = tempfile.TemporaryFile() flo.write(self.getvalue()) self = flo print type(self) else: super(TempFile, self).write(str) print "testing tempfile:" tmp = TempFile("", 100) ten_chars = "1234567890" tmp.write(ten_chars * 5) tmp.dummy() print "tmp < 100: " + str(type(tmp)) tmp.write(ten_chars * 5) tmp.dummy() print "tmp == 100: " + str(type(tmp)) tmp.write("the last straw") tmp.dummy() print "tmp > 100: " + str(type(tmp)) From mh at pixar.com Tue May 2 13:06:19 2006 From: mh at pixar.com (Mark Harrison) Date: Tue, 02 May 2006 17:06:19 GMT Subject: xml-rpc and 64-bit ints? Message-ID: I've got an API that deals with 64 bit int values. Is there any way of handling this smoothly? Right now I'm casting the values into and out of strings for the API. If not, are there any nice alternatives to XML-RPC that support this? Many TIA! Mark -- Mark Harrison Pixar Animation Studios From gdamjan at gmail.com Mon May 8 08:02:40 2006 From: gdamjan at gmail.com (Damjan) Date: Mon, 08 May 2006 14:02:40 +0200 Subject: Python Eggs Just install in *ONE* place? Easy to uninstall? References: <1146936395.028140.15640@i39g2000cwa.googlegroups.com> <1147056518.652933.27270@i39g2000cwa.googlegroups.com> Message-ID: <445f3360$0$15792$14726298@news.sunsite.dk> > But not matter where eggs are installed they > are never spread across multiple places > on hard drive right? An egg is all under > one node of tree right? >From what I've seen, no. For example installing TurboGears will also install the tg-admin script in /usr/bin/ and there are a lot of other projects that install custom scripts. -- damjan From gdamjan at gmail.com Mon May 8 15:20:13 2006 From: gdamjan at gmail.com (Damjan) Date: Mon, 08 May 2006 21:20:13 +0200 Subject: converting to scgi References: Message-ID: <445f99ee$0$15791$14726298@news.sunsite.dk> > I'm looking for a scgi modules that make it easy to convert a CGI using > the standard Python CGI module. I'm hoping for something that will run > my program either as scgi or cgi. > > I did find something called paste which purports to be some sort of CGI > Bridge framework but from the documentation, it appears that the > flexibility has eliminated the simplicity. If you write web application for WSGI, then you could as easilly run them in SCGI, CGI, mod_python, fast_cgi, in twisted or in a standalone HTTP server. Some resources: http://groovie.org/articles/2005/10/06/wsgi-and-wsgi-middleware-is-easy http://blog.ianbicking.org/wsgi-sample-apps-and-middleware.html http://pythonpaste.org/do-it-yourself-framework.html PythPaste of course provides a lot of tools to use with WSGI: http://pythonpaste.org Flup provides scgi, fastcgi and AJP absed WSGI servers: http://www.saddi.com/software/flup/ The WSGI specification: http://www.python.org/peps/pep-0333.html ps. It would be nice if others supplied some interesting WSGI resources too. -- damjan From larry.bates at websafe.com Fri May 26 18:05:24 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 26 May 2006 17:05:24 -0500 Subject: hide python window, con'td In-Reply-To: <447772B6.3080501@jessikat.plus.net> References: <447772B6.3080501@jessikat.plus.net> Message-ID: <0audnaHolMU95urZRVn-jg@comcast.com> It is just the nature of "things that run in the background all day" to be things that should probably be daemons or services. They almost always sleep, check, process, sleep, ... and as windows services do that better than processes in loops that sleep. They are daunting at first, but services aren't really all that hard to write after you first one. Larry Bates Robin Becker wrote: > Larry Bates wrote: >> Something that runs all day in the background is a perfect candidate >> for being turned into a Service. That and servicemanager has a good >> way of managing the task so that it doesn't take up lots of excess >> CPU cycles that a "normal" application would take while sleeping >> or unnecessarily looping. Pick up a copy of Mark Hammond's Python >> Programming on Win32 book for example services in Python. You could >> then start/stop the service with service manager or with net start/ >> net stop commands. >> >> -Larry Bates >> >> Bell, Kevin wrote: >>> Great! And now that it's hiding w/ .pyw, how would I kill it if I want? >>> Just log off, or is there a better way? >>> >>> Kevin >>> >>> > It is possible to get a background process in windows especially with > Python-2.4, but it's fairly hard. > > try using > > python runner.py dingo.py > > where > > ###### runner.py > def bgScript(script,scriptArgs): > from _subprocess import CreateProcess > class STARTUPINFO: > dwFlags = 0 > hStdInput = None > hStdOutput = None > hStdError = None > class pywintypes: > error = IOError > import sys > exe = sys.executable.replace('n.exe','nw.exe') > startupinfo = STARTUPINFO() > args = ''.join([' "%s"' % a for a in scriptArgs]) > cmd = '"%s" "%s" %s' % (exe,script,args) > try: > hp, ht, pid, tid = CreateProcess(None, cmd, > # no special security > None, None, > 0, #don't inherit standard handles > 0x208, > None, > None, > startupinfo) > except pywintypes.error, e: > print str(e) > > if __name__=='__main__': > import sys > bgScript(sys.argv[1],sys.argv[2:]) > ###### dingo.py > if __name__=='__main__': > import time > for i in xrange(15): > time.sleep(1) > ###### > > dingo.py shoul be running in the background detached from the console. > Of course as others point out, the official way to do this stuff is to > use all the M$ paraphernalia and have stuff start up at boot time etc etc. From george.sakkis at gmail.com Fri May 19 00:58:00 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 May 2006 21:58:00 -0700 Subject: how could I get all email address in a html page? In-Reply-To: <1148013399.715307.326120@j55g2000cwa.googlegroups.com> References: <1148013399.715307.326120@j55g2000cwa.googlegroups.com> Message-ID: <1148014680.188713.230120@g10g2000cwb.googlegroups.com> dongdong wrote: > how could I get all email address in a html page? Have any modle can do > this? > like the htmldata.urlextract . As if there arent' enough spammers already... From microschulz at web.de Sat May 20 20:20:42 2006 From: microschulz at web.de (Nikolaus Schulz) Date: Sun, 21 May 2006 00:20:42 +0000 (UTC) Subject: CRLF handling in the rfc822 module Message-ID: Hi, while playing with the rfc822 module and imaplib, I've found the following weird behaviour. Quickstart: rfc822.Message(fp) instantiates a rfc822.Message object from a file object fp. The docs for the rfc822 module say here: Input lines as read from the file may either be terminated by CR-LF or by a single linefeed; a terminating CR-LF is replaced by a single linefeed before the line is stored. I've tested that with a message read from an IMAP server and a locally generated message; since I'm running Linux, the local one has LF line terminators, while the IMAP message uses CRLF. The following code snippet demonstrates that these two cases yield different line terminators in the resulting rfc822.Message object. #v+ #!/usr/bin/python import imaplib import rfc822 # Assignments omitted # imap_server = # imap_username = # imap_password = # imap_folder = def print_header(msg_str): import cStringIO msg = rfc822.Message(cStringIO.StringIO(msg_str)) print repr(msg.headers[1]) print repr(msg.getrawheader('Envelope-to')) print repr(msg.getheader('Envelope-to')) imap_srv = imaplib.IMAP4_SSL(imap_server) imap_srv.login(imap_username, imap_password) imap_srv.select(imap_folder) result, response = imap_srv.fetch(1, '(RFC822)') imap_srv.close() imap_srv.logout() print_header(response[0][1]) local_msg = """\ Return-path: gargravarr at gargravarr.org Envelope-to: nikolaus at localhost Delivery-date: Fri, 12 May 2006 05:37:22 +0200 Message-ID: <12345 at bogus.org> Date: Thu, 11 May 2006 20:30:44 -0700 From: Grargravarr To: Nikolaus Schulz Subject: Bogus CRLF handling in Python Content-Type: text/plain; charset=us-ascii Content-Transfer-Encoding: 7bit Dummy mail body. """ print_header(local_msg) # EO: demo #v- Running the demo script gives this: #v+ 'Envelope-to: nikolaus at localhost\r\n' ' nikolaus at localhost\r\n' 'nikolaus at localhost' 'Envelope-to: nikolaus at localhost\n' ' nikolaus at localhost\n' 'nikolaus at localhost' #v- Isn't that inconsistent? Have I hit a bug? Please enlighten me! Have a nice day, Nikolaus From tdelaney at avaya.com Thu May 4 21:27:34 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Fri, 5 May 2006 11:27:34 +1000 Subject: Newbie question on code vetting Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6C6@au3010avexu1.global.avaya.com> william.boquist at gte.net wrote: > It seems to me that Open Source generally would be more pervasive if > there was more transparency with respect to the practices observed > within the projects. You mean something like: http://www.python.org/dev/ Tim Delaney From f.braennstroem at gmx.de Thu May 11 02:20:23 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Thu, 11 May 2006 08:20:23 +0200 Subject: problem with array and for loop References: Message-ID: Hi Robert, * Robert Kern wrote: > Fabian Braennstroem wrote: >> Hi, >> >> I have a 'simple' problem with a multidimension array in a >> for loop. It looks like this: >> >> wert= zeros([127,2]) >> wert1= zeros(127) >> m=1 >> l=1 >> >> for pos in [pos1,pos2,pos3]: >> for i in range(1,125): >> wert[l,m]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i); >> # wert1[i]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i); >> m=m+1; >> l=l+1; >> >> It works for the 1D 'wert1'. Does anyone have an idea? > > Oy vey. > > So the first time through, you are setting the second column of wert. Then l > (btw, never, ever use lower-case "l" as a single-letter variable name; it looks > like "1") gets incremented to 2, which would try to put data into the third > column of wert. However, wert only has two columns. Thanks! I misunderstood the declaration of a multid-dim array; it works now. > > Are you aware that numpy array indices start with 0, not 1? > > You will probably want to ask numpy questions on the numpy-discussion mailing list: > > http://www.scipy.org/Mailing_Lists I thought a simple for loop-array-declaration question would fit in this group ... it actually help for this simple problem. Thanks! Greetings! Fabian From timothy.grant at gmail.com Mon May 15 17:02:16 2006 From: timothy.grant at gmail.com (Timothy Grant) Date: Mon, 15 May 2006 14:02:16 -0700 Subject: Test professionalism (was: count items in generator) In-Reply-To: References: Message-ID: On 5/15/06, Cameron Laird wrote: > In article , > Delaney, Timothy (Tim) wrote: > . > . > . > >That's exactly my point. Assuming your test coverage is good, such an > >error would be caught by the MemoryError. An infinite loop should also > >be caught by timing out the tests, but that's much more dependent on the > >test harness. > > > >Tim Delaney > > Gulp. OK, you've got me curious: how many people habitually frame > their unit tests with resource constraints? I think I take testing > seriously, and certainly also am involved with resource limits often, > but I confess I've never aimed to write all my tests in terms of > bounds on time (and presumably memory and ...). You've got me > thinking, Tim. > -- > http://mail.python.org/mailman/listinfo/python-list > I'm a huge proponent of unittest and believe I take them very seriously also. I try never to write a line of code unless I have a test to prove I need it. I have written tests that take into account resource constraints, but ONLY when I've written code that, while passing all tests, shows resource consumption problems. Creating resource contstraint tests out of the gate *may* fall into the category of premature optimization. -- Stand Fast, tjg. From pthibault33 at yahoo.ca Thu May 4 16:30:12 2006 From: pthibault33 at yahoo.ca (Pierre Thibault) Date: 4 May 2006 13:30:12 -0700 Subject: Unable to use py2app Message-ID: <1146774612.590477.82260@e56g2000cwe.googlegroups.com> Hello, I am unable to use py2app. I have an error when I try to import it: ImportError: No module named py2app I have installed pyobjc-1.3.7. I am on Mac OS 10.4.6. It does not work. It does not work with python 2.4 and it does not work with python 2.3. Is it working with someone else? From ptmcg at austin.rr._bogus_.com Fri May 12 15:34:47 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 12 May 2006 19:34:47 GMT Subject: Discussion: Python and OpenMP References: Message-ID: "Carl J. Van Arsdall" wrote in message news:mailman.5638.1147456348.27775.python-list at python.org... > Hey everyone, > > I know I've posted several questions regarding python and python's > parallel capabilities so bear with me as I've never attempted to incite > discussion. However, today I'm interested in sparking discussion over > having an OpenMP style of interface in python. > > For those of you familiar with OpenMP, its a pragmatic api for > parallelizing software. For more information I invite anyone to do some > google searches, there's a plethora of information available. Just to > give a simple example of what i'm talking about, in OpenMP you would > insert a pragma above a section of code you want to parallelize. > > In C it might look something like: > > int main(int argc, char* argv[]) > { > #pragma omp parallel > printf("Hello, world.\n"); > return 0; > } > > In which case threads are spawn and handled. OpenMP of course has more > than this available for developers, but I'm just trying to paint a > picture before I start asking questions. > > Anyhow, onto the meat of the discussion. Would the python community be > interested in parallel programming this way? Although I understand > python already supports threading I thought that this was a real > interesting (and easy) way of writing parallel code. > > For example, new keywords could be added to the python interpreter, such > as parallel: > > Ex: > ####### > #!usr/bin/python > > parallel: > print "I am a thread" > > ####### > > > Taking this a step further, OpenMP or an OpenMP style implementation > could be added to python. In addition easy to use/read, one possible > benefit I could see of writing parallel python code this way would be > providing a layer of abstraction between parallel code and threading > constructs. For example, as a developer or community standards change > threading in python code would not have to be re-written. Developers > would create an interface between python's OpenMP style code and > whatever their new threading libraries may be (this is one of many ways > it could happen). Ultimately providing more code portability between > people using different threading standards (should they ever become > available). I see other use cases as well, but I just wanted to throw a > couple ideas to see if this was worth thinking about further. > > Thanks for reading this one, I know it was long but I'd really > appreciate your comments! > > > > -Carl > > > -- > > Carl J. Van Arsdall > cvanarsdall at mvista.com > Build and Release > MontaVista Software > My first reaction to this post was that an @parallel decorator might be a reasonable approach, since this would not require any hacking into the Python interpreter. Googling "python parallel decorator" led me to this recipe in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/474127. While this uses yield to create generators to simulate threads (and if you can simulate threads without incurring the overhead, is that so wrong?), it may give you some additional ideas on some implementation alternatives. -- Paul From yaronb at telus.net Thu May 18 16:10:58 2006 From: yaronb at telus.net (Yaron Butterfield) Date: Thu, 18 May 2006 13:10:58 -0700 Subject: Python, Mysql, insert NULL Message-ID: <446CD4D2.3040109@telus.net> Hi, I've been having problems using Python to insert data into a MySQL database. I've donw web searches and pulled my hairs out getting it to work but cannot. I have no trouble doing select queries, but when I use Python to insert, though I do not receive any errors from python, the table does not get populated. I've just followed the information from here by Steve Holden: http://mail.python.org/pipermail/python-list/2005-October/302405.html to the tee. No errors and the same output as shown in the above example. Yet, there isn't any data in my table. Am I missing something so obvious?? Please help! This has frustrated me for days now. regards, Yaron From scott.daniels at acm.org Tue May 16 19:00:07 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 16 May 2006 16:00:07 -0700 Subject: calling upper() on a string, not working? In-Reply-To: References: Message-ID: <446a5583$1@nntp0.pdx.net> John Salerno wrote: Others have shown you where the bug was. You might want to change encrypt_quote like this: XXX> def encrypt_quote(original): def encrypt_quote(original, casemap=True): XXX> original_letters = filter_letters(original) if casemap: original_letters = filter_letters(original.upper()) else: original_letters = filter_letters(original) XXX> new_letters = list(string.ascii_uppercase) if len(original_letters) > 26: new_letters = list(string.ascii_uppercase + string.ascii_lowercase) casemap = False else: new_letters = list(string.ascii_uppercase) > while True: > random.shuffle(new_letters) > trans_letters = ''.join(new_letters)[:len(original_letters)] > if test_code(original_letters, trans_letters): XXX> trans_table = string.maketrans(original_letters, trans_letters) if casemap: trans_table = string.maketrans( original_letters + original_letters.lower(), trans_letters + trans_letters.lower()) else: trans_table = string.maketrans(original_letters, trans_letters) > break > return original.translate(trans_table) --Scott David Daniels scott.daniels at acm.org From oliver at first.in-berlin.de Tue May 16 12:15:23 2006 From: oliver at first.in-berlin.de (Oliver Bandel) Date: Tue, 16 May 2006 18:15:23 +0200 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147793491.658982.131450@v46g2000cwv.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> Message-ID: <1147796116.826750@elch.in-berlin.de> opalpa at gmail.com opalinski from opalpaweb wrote: >>Simply put, tabs is proper, and spaces are improper. >>Why? This may seem >>ridiculously simple given the de facto ball of confusion: the semantics >>of tabs is what indenting is about, while, using spaces to align code >>is a hack. > > > The reality of programming practice trumps original intent of tab > characters. The tab character and space character are pliable in that > if their use changes their semantics change. [...] Yes, as I started programming I also preferred tabs. And with growing experience on how to handle this in true life (different editors/systems/languages...) I saw, that converting the "so fine tabs" was annoying. The only thing that always worked were spaces. Tab: nice idea but makes programming an annoyance. Ciao, Oliver From junk.rubbish at alma-services.abel.co.uk Mon May 1 17:52:28 2006 From: junk.rubbish at alma-services.abel.co.uk (Sandy) Date: Mon, 1 May 2006 22:52:28 +0100 Subject: SciTE: Printing in Black & White Message-ID: <0DcfmOAcMoVENwUq@alma-services.abel.co.uk> Dear Pythonic People, I recently discovered SciTE (1.68) as a programming editor, and I find it just beautiful. Small, fast, elegant and beautiful. I particularly like syntax highlighting features -- not simply different colours, but styles and fonts too. I don't know whether this is the right place to ask this type of question, but... ...I like to study large files of (hobby) code on paper. I have a black and white bubble-jet printer. However, my (Win NT4) screen syntax-highlighting setup has a couple of problems when it comes to doing print-outs. The _chief_ problem is that my on-screen background colour is not bright white -- it's an off-white cream, which is so much easier on my eyes: SciTEGlobal.properties... ... # Global default styles for all languages # Default style.*.32=$(font.base),back:#EDE1D5,fore:#000000 ... However, each page of printout appears as black (or darkish) characters, on top of a filled rectangle of light texture, as the above "background". Ideally, I'd like to be able to configure SciTE printouts with a different highlighting style from the appearance on the screen. Instead of colour variations, I'd use combinations of bold, underlined, and italics, and different font faces -- all in plain black print -- for printouts on my b&w printer. How can I go about doing this? If I understand things right, I can configure my SciTE installation using Lua. But I hesitate slightly at this prospect, if there's a simpler (but more plodding) way. (I've already noticed that exporting as say RTF, and then changing the RTF styles for printing with a regular-expression script, is one possible, messy and very kludgey solution.) With kind regards, Sandy -- Alexander Anderson (Yorkshire, England) Where there is no vision, the people perish. From robert.kern at gmail.com Mon May 1 14:54:51 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 May 2006 13:54:51 -0500 Subject: How to efficiently read binary files? In-Reply-To: <125cfokq609se5d@corp.supernews.com> References: <125acgep357kbd8@corp.supernews.com> <125c8sbqsd7a952@corp.supernews.com> <125cfokq609se5d@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-05-01, Robert Kern wrote: > >>>>>Perhaps the numarray module? >>>> >>>>numpy for new code, please. >>> >>>So numarray and numpy were both written to replace numeric? >> >>numpy was written to replace both Numeric and numarray. > > too many batteries... Too many cryptic complaints... -- 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 Thu May 4 05:03:01 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 4 May 2006 02:03:01 -0700 Subject: Dispatching operations to user-defined methods In-Reply-To: References: Message-ID: <1146733381.556818.121600@u72g2000cwu.googlegroups.com> Apparently Guido fell in love with generic functions, so (possibly) in future Python versions you will be able to solve dispatching problems in in an industrial strenght way. Sometimes however the simplest possible way is enough, and you can use something like this : class SimpleDispatcher(object): """A dispatcher is a callable object that looks in a "namespace" for callable objects and calls them with the signature ``(, , <*args>, <**kw>)`` The "namespace" can be a module, a class, a dictionary, or anything that responds to ``getattr`` or (alternatively) to ``__getitem__``. Here is an example of usage: >>> call = SimpleDispatcher(globals()) >>> def manager_showpage(): ... return 'Manager' >>> def member_showpage(): ... return 'Member' >>> def anonymous_showpage(): ... return 'Anonymous' >>> call('showpage', 'anonymous') 'Anonymous' >>> call('showpage', 'manager') 'Manager' >>> call('showpage', 'member') 'Member' """ def __init__(self, ns): self._ns = ns def __call__(self, funcname, classname, *args, **kw): try: func = getattr(self._ns, '%s_%s' % (classname, funcname)) except AttributeError: func = self._ns['%s_%s' % (class From n.estner at gmx.de Sun May 21 19:38:34 2006 From: n.estner at gmx.de (nikie) Date: 21 May 2006 16:38:34 -0700 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <1148254714.668727.298420@y43g2000cwc.googlegroups.com> Xah Lee wrote: > Software Needs Philosophers > > by Steve Yegge, 2006-04-15. > > Software needs philosophers. > > This thought has been nagging at me for a year now, and recently it's > been growing like a tumor. One that plenty of folks on the 'net would > love to see kill me. No, we all wish you a long and quiet life! Although some of us are a little annoyed that you keep cross-posting articles wildly to completely unrelated newsgroups... > People don't put much stock in philosophers these days. The popular > impression of philosophy is that it's just rhetoric, just frivolous > debating about stuff that can never properly be answered. "Spare me > the philosophy; let's stick to the facts!" > > The funny thing is, it's philosophers who gave us the ability to think > rationally, to stick to the facts. If it weren't for the work of > countless philosophers, facts would still be getting people tortured > and killed for discovering and sharing them. > > Does it ever strike you as just a teeny bit odd that after a brief > period where philosophy flourished, from maybe 400 B.C.E. to ~100 C.E., > we went through a follow-on period of well over one thousand five > hundred years during which the Roman Catholic Church enslaved > everyone's minds and killed anyone who dared think differently? I wonder where you get your historical "facts" form? (Monty Python movies?) Let's just add a few fun facts: Yes, philosophy did flourish in ancient greece, but liberty certainly didn't. Yes, Athens was (at least most of the time) a democracy - which by the way, most philosophers thought was a very bad thing. But still, about 90% of the population of Athens were slaves at that time. Not just "mentally enslaved", no, real, physical slaves. Also, it was dangerous to have oppinions that authorities didn't like (Socrates for example was sentenced to death because of impiety, Anaxagoras and Aristoteles had to flee because of similar charges, Hipposus, who _proved_ a flaw in Pythagoras' number theory was drowned). And, sad to say, if philosophers would have been in charge, things would probably have been even worse (Ever read Plato's "The State"?) Also, has the roman catholic church really "killed anyone who dared think differently"? The Spanish Inquisition for example killed about 1000-2000 people in two centuries. That's bad enough, no question, but "anyone who dared think differently"? Hardly. > What's weirder is that we tend to pretend it didn't really happen. We > like to just skip right over the dominance of religion over our minds > for a hundred generations, and think of religion today as a kindly old > grandpa who's just looking out for us kids. No harm, no foul. Let > bygones be bygones. Sure, there were massacres and crusades and > genocides and torture chambers with teeth grinding and eyes bleeding > and intestines torn out in the name of God. But we were all just kids > then, right? Nobody does that kind of thing today, at least not in > civilized countries. Hmmm. There were massacres in the name of liberty to, e.g. in the French Revolution. Does that make liberty (and those who value it) equally evil? (The same is of course true for money, love, or probably anything else people like) > We try not to think about the uncivilized ones. We do! Let's think about some of them: The Khmers rouges come to my mind, also China, and a few years back the Soviet Union. Notice something? Right, no religion. In fact, they were more or less following the works of the philosopher Karl Marx. > It was philosophers that got us out of that Dark Ages mess, and no > small number of them lost their lives in doing so. In the "Dark Ages" pretty much the only chance to get a decent education was to become a monk or at least be taught by monks. So, it isn't surprising that almost all of the philosophers at the time (like William of Occam or Roger Bacon) were monks. Therefore, philosophy was never clearly separated from theology during that time. The end of the middle ages is probably marked by the renaissance and the reformation, the latter of course started by a priest. What have we learned? Yes, Religion was an important power in the development of europe over the last 3000 years (yes, I'm including the Antiquity in this, it didn't just take a break to watch the philosophy channel). So were money, and military power, technology, social factors, and of course philosophy. Yes, it did have bad consequences, and it did have good ones. The same is true for all the other powers as well. (BTW: Have you ever considered the possibility that philosophers might not be interested in tab-versus-spaces-debates in the first place? Maybe they have more interesting matters to discuss. Just like the rest of us.) From joesb.coe9 at gmail.com Tue May 9 02:35:57 2006 From: joesb.coe9 at gmail.com (Pisin Bootvong) Date: 8 May 2006 23:35:57 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147123648.914726.212680@i39g2000cwa.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1147123648.914726.212680@i39g2000cwa.googlegroups.com> Message-ID: <1147156556.952331.29450@i39g2000cwa.googlegroups.com> Kaz Kylheku wrote: > > Now imagine you had to do this with every object. > > def add_five(x) > # return x + 5 <-- anonymous integer literal, not allowed!!! > five = 5 # define it first > return x + five > I mentioned that as Slippery slope fallacious argument in other reply. > [...] > That doesn't mean you can't develop scalable solutions to all kinds of > problems using Python. But it does mean that the scalability of the > overall solution comes from architectural details that are not related > to Python itself. Like, say, having lots of machines linked by a fast > network, working on problems that decompose along those lines quite > nicely. Is there such language that allow scalability without any need for design on the underlying architecture? Python doesn't obscure or become obstacle in utilise those architecture. Python allow one to design scalable architecture. So Python IS scalable, isn't it? Only when Python prevent the up-scaling or Python made scaled up project unmanagable that you can say that Python is not scalable. In 'Team scalable' axis, Python is easy to learn for average programmer. So it is easier for Python to scale up. 'Data scalable' axis is language neutral, it depends on how you architecture your database, etc. 'User requirement scalable' axis require both infrastructure and language to provide: No matter how scalable your language is, you cannot make a 100MHz/128MB server serve 100,000 client a second over the internet. No matter how many server and load balancing you have, you cannot practically program gmail using purely MS-DOS bat file. From kentilton at gmail.com Sat May 6 17:21:20 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 17:21:20 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Ken Tilton wrote: > > >>Martin P. Hellwig wrote: >> >>>Bill Atkins wrote: >>> >>> >>>>How do you define scalability? >>>> >>> >>>http://www.google.com/search?hl=en&q=define%3Ascalability&btnG=Google+Search >>> >> >>Damn! Google can do that?! Omigod!!! Not joking, I never knew that,a > > > You're welcome; we do have several little useful tricks like that. > > >>lways used dictionary.com. Thx! I meant: >> >> >>>The ability to add power and capability to an existing system without >>>significant expense or overhead. www.yipes.com/care/cc_glossary.shtml > > > Excellent -- just the definition of "scalability" that Google and its > competitor live and die by ((OK, OK, I'm _not_ implying that such issues > as usability &c don't matter, by no means -- but, I live mostly in the > world of infrastructure, where scalability and reliability reign)). > > > >>The number of definitions explains why most respondents should save >>their breath. Natural language is naturally ambiguous. Meanwhile Usenet >>is the perfect place to grab one meaning out of a dozen and argue over >>the implications of that one meaning which of course is never the one >>originally intended, as any reasonable, good faith reader would admit. > > > However, you and I are/were discussing exactly the same nuance of > meaning, either by a funny quirk of fate or because it's the one that > really matters in large-scale programming (and more generally, > large-scale systems). E.g., if your existing system can gracefully > handle your current traffic of, say, a billion queries of complexity X, > you want to be able to rapidly add a feature that will increase the > average query's complexity to (X+dX) and attract 20% more users, so > you'll need to handle 1.2 billion queries just as gracefully: i.e., you > need to be able to add power and capability to your existing system, > rapidly and reliably, just as that definition says. > > When this is the challenge, your choice of programming language is not > the first order of business, of course ... Looks like dictionaries are no match for the ambiguity of natural language. :) Let me try again: it is Python itself that cannot scale, as in gain "new power and capability", and at least in the case of lambda it seems to be because of indentation-sensitivity. Is that not what GvR said? By contrast, in On Lisp we see Graham toss off Prolog in Chapter 22 and an object system from scratch in Chapter 25. Lite versions, to be sure, but you get the idea. My sig has a link to a hack I developed after doing Lisp for less than a month, and without lambda (and to a lesser degree macros) it would be half the tool it is. It adds a declarative paradigm to the CL object system, and is built on nothing but ansi standard Lisp. Yet it provides new power and capability. And that by an application programmer just working on a nasty problem, never mind the language developer. I just find it interesting that sexpr notation (which McCarthy still wants to toss!) is such a huge win, and that indentation seems to be so limiting. -- your hardware and network > architecture loom large, and so does the structuring of your > applications and infrastructure software across machines and networks. > Still, language does matter, at a "tertiary" level if you will. Among > the potential advantages of Lisp is the fact that you could use Lisp > across almost all semantic levels ("almost" because I don't think "Lisp > machines" are a realistic option nowadays, so lower levels of the stack > would remain in C and machine language -- but those levels may probably > be best handled by a specialized squad of kernel-level and device-driver > programmers, anyway); among the potential advantages of Python, the fact > that (while not as suited as Lisp to lower-level coding, partly because > of a lack of good solid compilers to make machine language out of it), > it brings a powerful drive to uniformity, rather than a drive towards a > host of "domain-specific" Little Languages as is encouraged by Lisp's > admirably-powerful macro system. > > One key axis of scalability here is, how rapidly can you grow the teams > of people that develop and maintain your software base? I am with Brooks on the Man-Month myth, so I am more interested in /not/ growing my team. If Lisp is times more expressive than Python, you need exponentially fewer people. In some parallel universe Norvig had the cojones to dictate Lisp to Google and they listened, and in that universe... I don't know, maybe GMail lets me click on the sender column to sort my mail? :) > To meet all the > challenges and grasp all the opportunities of an exploding market, > Google has had to almost-double its size, in terms of number of > engineers, every year for the last few years -- I believe that doing so > while keeping stellar quality and productivity is an unprecedented feat, > and while (again!) the choice of language(s) is not a primary factor > (most kudos must go to our management and its approaches and methods, of > course, and in particular to the strong corporate identity and culture > they managed to develop and maintain), it still does matter. The > uniformity of coding style and practices in our codebase is strong. Well, you said it for me. Google hires the best and pays a lot. Hey, I wrote great code in Cobol. So as much as you want to brag on yourself and Google , your success does not address: Indentation-sensitivity: Is it holding Python back? > > We don't demand Python knowledge from all the engineers we hire: for any > "engineering superstar" worth the adjective, Python is really easy and > fast to pick up and start using productively -- I've seen it happen > thousands of times, both in Google and in my previous career, and not > just for engineers with a strong software background, but also for those > whose specialties are hardware design, network operations, etc, etc. The > language's simplicity and versatility allow this. Python "fits people's > brains" to an unsurpassed extent -- in a way that, alas, languages > requiring major "paradigm shifts" (such as pure FP languages, or Common > Lisp, or even, say, Smalltalk, or Prolog...) just don't -- they really > require a certain kind of mathematical mindset or predisposition which > just isn't as widespread as you might hope. Talk about Lisp myths. The better the language, the easier the language. And the best programmers on a team get to develop tools and macrology that empower the lesser lights, so (a) they have fun work that keeps them entertained while (b) the drones who just want to get through the day are insanely productive, too. Another myth (or is this the same?) is this "pure FP" thing. Newbies can and usually do code as imperatively as they wanna be. Until someone else sees their code, tidies it up, and the light bulb goes on. But CL does not force a sharp transition on anyone. > Myself, I do have more or > less that kind of mindset, please note: while my Lisp and scheme are > nowadays very rusty, proficiency with them was part of what landed me my > first job, over a quarter century ago (microchip designers with a good > grasp of lisp-ish languages being pretty rare, and TI being rather > hungry for them at the time) -- but I must acknowlegde I'm an exception. > > Of course, the choice of Python does mean that, when we really truly > need a "domain specific little language", we have to implement it as a > language in its own right, rather than piggybacking it on top of a > general-purpose language as Lisp would no doubt afford; see > for such a DSLL developed > at Google. No lambdas? Static typing?! eewwwewww. :) Loved the movie, tho. Come on, try just one meaty Common Lisp project at Google. Have someone port Cells to Python. I got halfway done but decided I would rather be doing Lisp. uh-oh. Does Python have anything like special variables? :) Kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From OlafMeding at gmail.com Tue May 9 10:49:32 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 9 May 2006 07:49:32 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1147186172.100334.219270@i39g2000cwa.googlegroups.com> Robin and Roel Thanks for trying and reporting the results. Both of you and Tim and Dave have run the .py program now (all on hyper-threaded CPUs) and none of you were able to reproduce the problem. So that indicates that there is something special about our PC. We are planing to re-install Windows XP (and nothing else) and try again. Also, we have one other PC (with a different configuration/CPU) and are planing to do the same to that PC. Olaf From aleaxit at yahoo.com Sat May 6 03:13:49 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 00:13:49 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> Message-ID: <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> Ken Tilton wrote: ... > > Absolutely. That's why firms who are interested in building *seriously* > > large scale systems, like my employer (and supplier of your free mail ... > > Obviously will not scale. Never. > > > > Well... hardly ever! > > You are talking about being incredibly popular. I was talking about Who, me? I'm talking about the deliberate, eyes-wide-open choice by *ONE* firm -- one which happens to more or less *redefine* what "large scale" computation *means*, along many axes. That's got nothing to do with Python being "incredibly popular": it has everything to do with scalability -- the choice was made in the late '90s (and, incidentally, by people quite familiar with lisp... no less than the reddit.com guys, you know, the ones who recently chose to rewrite their side from Lisp to Python...?), based on scalability issues, definitely not "popularity" (Python in the late '90s was a very obscure, little-known language). > kenny (who is old enough to have seen many a language come and go) See your "many a language" and raise you one penny -- besides sundry Basic dialects, machine languages, and microcode[s], I started out with Fortran IV and APL, and I have professionally programmed in Pascal (many dialects), Rexx, Forth, PL/I, Cobol, Lisp before there was a "Common" one, Prolog, Scheme, Icon, Tcl, Awk, EDL, and several proprietary 3rd and 4th generation languages -- as well of course as C and its descendants such as C++ and Java, and Perl. Many other languages I've studied and played with, I've never programmed _professionally_ (i.e., been paid for programs in those languages), but I've written enough "toy" programs to get some feeling for (Ruby, SML, O'CAML, Haskell, Snobol, FP/1, Applescript, C#, Javascript, Erlang, Mozart, ...). Out of all languages I know, I've deliberately chosen to specialize in Python, *because it scales better* (yes, functional programming is _conceptually_ perfect, but one can never find sufficiently large teams of people with the right highly-abstract mathematical mindset and at the same time with sufficiently down-to-earth pragmaticity -- so, for _real world_ uses, Python scales better). When I was unable to convince top management, at the firm at which I was the top programmer, that the firm should move to Python (beyond the pilot projects which I led and gave such stellar results), I quit, and for years I made a great living as a freelance consultant (mostly in Python -- once in a while, a touch of Pyrex, C or C++ as a vigorish;-). That's how come I ended up working at the firm supplying your free mail (as Uber Tech Lead) -- they reached across an ocean to lure me to move from my native Italy to California, and my proven excellence in Python was their prime motive. The terms of their offer were just too incredible to pass by... so, I rapidly got my O1 visa ("alien of exceptional skills"), and here I am, happily ubertechleading... and enjoying Python and its incredibly good scalability every single day! Alex From xkenneth at gmail.com Tue May 30 00:06:59 2006 From: xkenneth at gmail.com (xkenneth) Date: 29 May 2006 21:06:59 -0700 Subject: Watching serial port activity. In-Reply-To: <127ncut3mpadoc5@corp.supernews.com> References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> Message-ID: <1148962019.355956.124420@38g2000cwa.googlegroups.com> I'm using linux. From george.sakkis at gmail.com Sun May 14 11:32:26 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 14 May 2006 08:32:26 -0700 Subject: SQl to HTML report generator Message-ID: <1147620745.892500.250800@j73g2000cwa.googlegroups.com> I'm kinda surprised that while many web frameworks provide both some ORM and a template language, they do very little to combine them into higher level blocks, like report generation. So I'm wondering if I have missed any toolkit out there that can 1) take a SQL select (either raw or the equivalent expressed in an ORM) as input 2) generate nice looking HTML templates in some template language, e.g. Cheetah (preferably with associated CSS for customization) and 3) run the query on a specified backend and populate the template with the results ? If not, what do people here use for report generation ? Thanks, George From Mark.Geyzer at gmail.com Wed May 17 11:24:40 2006 From: Mark.Geyzer at gmail.com (volcano) Date: 17 May 2006 08:24:40 -0700 Subject: How to couple pyunit with GUI? Message-ID: <1147879480.640335.252950@y43g2000cwc.googlegroups.com> I am desperately looking for an info how to combine a testing application with decent GUI interface - the way most xUnits do. I believe I have seen something about using Tkinter, but I do not remember - where. I am working on a complex testing application built over unittest module, and I need GUI interface that will alllow me to select tests at different levels of test hierarchy tree. I am new to python, so say everything slow and repeat it twice:) From a.schmolck at gmail.com Sun May 7 12:45:24 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 07 May 2006 17:45:24 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> Message-ID: [trimmed groups] Ken Tilton writes: > yes, but do not feel bad, everyone gets confused by the /analogy/ to > spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief > period I swore off the analogy because it was so invariably misunderstood. > Even Graham misunderstood it. Count me in. > > But it is such a great analogy! > > > but what's the big deal about PyCells? > > Here is 22-lines barebones implementation of spreadsheet in Python, > > later I create 2 cells "a" and "b", "b" depends on a and evaluate all > > the cells. The output is > > a = negate(sin(pi/2)+one) = -2.0 > > > b = negate(a)*10 = 20.0 > > Very roughly speaking, that is supposed to be the code, not the output. So you > would start with (just guessing at the Python, it has been years since I did > half a port to Python): > > > v1 = one > a = determined_by(negate(sin(pi/2)+v1) > b = determined_by(negate(a)*10) > print(a) -> -2.0 ;; this and the next are easy > print(b) -> 20 > v1 = two ;; fun part starts here > print(b) -> 40 ;; of course a got updated, too > do you mean 30? I've translated my interpretation of the above to this actual python code: from math import sin, pi v1 = cell(lambda: 1) a = cell(lambda:-(sin(pi/2)+v1.val), dependsOn=[v1]) b = cell(lambda: -a.val*10, dependsOn=[a], onChange=lambda *args: printChangeBlurp(name='b',*args)) print 'v1 is', v1 print 'a is', a # -2.0 ;; this and the next are easy print 'b is', b # 20 v1.val = 2 # ;; fun part starts here print 'v1 now is', v1 print 'b now is', b # 30 ;; of course a got updated, too I get the following printout: v1 is 1 a is -2.0 b is [cell 'b' changed from <__main__.unbound object at 0xb4e2472c> to 20.0, it was not bound]20.0 [cell 'b' changed from 20.0 to 30.0, it was bound ] v1 now is 2 b now is 30.0 Does that seem vaguely right? > The other thing we want is (really inventing syntax here): > > on_change(a,new,old,old-bound?) print(list(new, old, old-bound?) Is the above what you want (you can also dynamically assign onChange later on, as required or have a list of procedures instead)? > > Then the print statements Just Happen. ie, It is not as if we are just hiding > computed variables behind syntax and computations get kicked off when a value > is read. Instead, an underlying engine propagates any assignment throughout > the dependency graph before the assignment returns. Updating on write rather than recalculating on read does in itself not seem particularly complicated. > My Cells hack does the above, not with global variables, but with slots (data > members?) of instances in the CL object system. I have thought about doing it > with global variables such as a and b above, but never really seen much of > need, maybe because I like OO and can always think of a class to create of > which the value should be just one attribute. OK, so in what way does the quick 35 line hack below also completely miss your point? # (NB. for lispers: 'is' == EQ; '==' is sort of like EQUAL) def printChangeBlurp(someCell, oldVal, newVal, bound, name=''): print '[cell %r changed from %r to %r, it was %s]' % ( name, oldVal, newVal, ['not bound', 'bound '][bound]), _unbound = type('unbound', (), {})() # just an unique dummy value def updateDependents(dependents): seen = {} for dependent in dependents: if dependent not in seen: seen[dependent] = True dependent.recalculate() updateDependents(dependent._dependents) class cell(object): def __init__(self, formula, dependsOn=(), onChange=None): self.formula = formula self.dependencies = dependsOn self.onChange = onChange self._val = _unbound for dependency in self.dependencies: if self not in dependency._dependents: dependency._dependents.append(self) self._dependents = [] def __str__(self): return str(self.val) def recalculate(self): newVal = self.formula() if self.onChange is not None: oldVal = self._val self.onChange(self, oldVal, newVal, oldVal is not _unbound) self._val = newVal def getVal(self): if self._val is _unbound: self.recalculate() return self._val def setVal(self, value): self._val = value updateDependents(self._dependents) val = property(getVal, setVal) 'as From alisonken1 at gmail.com Thu May 11 15:14:53 2006 From: alisonken1 at gmail.com (alisonken1) Date: 11 May 2006 12:14:53 -0700 Subject: find all index positions In-Reply-To: <44636625$1@nntp0.pdx.net> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <44636625$1@nntp0.pdx.net> Message-ID: <1147374893.689965.134730@j33g2000cwa.googlegroups.com> Scott David Daniels wrote: > micklee74 at hotmail.com wrote: > print list(positions('1234', 'abcd efgd 1234 fsdf gfds abcde 1234')) > > prints: > [10, 31] > Nicer than mine ;) Shows I need to get a job where I use python more! From claird at lairds.us Mon May 15 11:02:10 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 15 May 2006 15:02:10 +0000 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> <1hfc2sb.8hxfcv13c5v6nN%aleax@mac.com> Message-ID: In article <1hfc2sb.8hxfcv13c5v6nN%aleax at mac.com>, Alex Martelli wrote: >Cameron Laird wrote: > >> In article <1hfarom.1lfetjc18leddeN%aleax at mac.com>, >> Alex Martelli wrote: >> . >> . >> . >> >My preference would be (with the original definition for >> >words_of_the_file) to code >> > >> > numwords = sum(1 for w in words_of_the_file(thefilepath)) >> . >> . >> . >> There are times when >> >> numwords = len(list(words_of_the_file(thefilepath)) >> >> will be advantageous. > >Can you please give some examples? None comes readily to mind... . . . Maybe in an alternative universe where Python style emphasizes functional expressions. This thread--or at least the follow-ups to my rather frivolous observation--illustrate how distinct is Python's direction. If we could neglect memory impact, and procedural side-effects, then, sure, I'd argue for my len(list(...)) formulation, on the expressive grounds that it doesn't require the two "magic tokens" '1' and 'w'. Does category theory have a term for formulas of the sort that introduce a free variable only to ignore (discard, ...) it? There certainly are times when that's apt ... From jnair at ensim.com Mon May 15 23:42:37 2006 From: jnair at ensim.com (jnair at ensim.com) Date: 15 May 2006 20:42:37 -0700 Subject: Multiple inheritance : waht does this error mean ? Message-ID: <1147750957.673439.154420@g10g2000cwb.googlegroups.com> I am using Python 2.4.3 >>>class K(object,list): ...: pass ...: ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? TypeError: Error when calling the metaclass bases Cannot create a consistent method resolution order (MRO) for bases object, list Regards Jitendra Nair From robert.kern at gmail.com Wed May 10 18:43:57 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 10 May 2006 17:43:57 -0500 Subject: segmentation fault in scipy? In-Reply-To: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> Message-ID: conor.robinson at gmail.com wrote: > I'm running operations large arrays of floats, approx 25,000 x 80. > Python (scipy) does not seem to come close to using 4GB of wired mem, > but segments at around a gig. Everything works fine on smaller batches > of data around 10,000 x 80 and uses a max of ~600mb of mem. Any Ideas? > Is this just too much data for scipy? > > Thanks Conor > > Traceback (most recent call last): > File "C:\Temp\CR_2\run.py", line 68, in ? > net.rProp(1.2, .5, .000001, 50.0, input, output, 1) > File "/Users/conorrob/Desktop/CR_2/Network.py", line 230, in rProp > print scipy.trace(error*scipy.transpose(error)) > File "D:\Python24\Lib\site-packages\numpy\core\defmatrix.py", line > 149, in > __mul__ > return N.dot(self, other) > MemoryError This is not a segfault. Is this the only error you see? Or are you actually seeing a segfault somewhere? If error.shape == (25000, 80), then dot(error, transpose(error)) will be returning an array of shape (25000, 25000). Assuming double precision floats, that array will take up about 4768 megabytes of memory, more than you have. The memory usage doesn't go up near 4 gigabytes because the allocation of the very large returned array fails, so the large chunk of memory never gets allocated. There are two possibilities: 1. As Travis mentioned, numpy won't create the array because it is still 32-bit-limited due to the Python 2.4 C API. This has been resolved with Python 2.5. 2. The default build of numpy uses plain-old malloc(3) to allocate memory, and it may be failing to create such large chunks of memory. -- 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 scott.daniels at acm.org Mon May 8 21:06:53 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 18:06:53 -0700 Subject: Multi-line lambda proposal. In-Reply-To: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> Message-ID: <445fe772$1@nntp0.pdx.net> Kaz Kylheku wrote: > I've been reading the recent cross-posted flamewar, and read Guido's > article where he posits that embedding multi-line lambdas in > expressions is an unsolvable puzzle. > > So for the last 15 minutes I applied myself to this problem and come up > with this off-the-wall proposal for you people. Perhaps this idea has > been proposed before, I don't know. Well, ask yourself, what is the complexity, and what is the benefit. You are solving a problem that causes very little pain, and introducing a mechanism that is likely to inspire thousands of lines of unmaintainable code. Essentially, a rule that says, "if it is not a simple expression, pick a name for it" is just not a bad idea. --Scott David Daniels scott.daniels at acm.org From bdesth.quelquechose at free.quelquepart.fr Wed May 3 19:58:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 May 2006 01:58:10 +0200 Subject: Possibly dumb question about dicts and __hash__() In-Reply-To: References: <1146686634.117498.313470@j73g2000cwa.googlegroups.com> Message-ID: <445914d8$0$2654$636a55ce@news.free.fr> Joel Hedlund a ?crit : (snip) > How illegal is it? If I document it and put it in an opensource project, > will people throw tomatoes? Don't know, but they'll sure do if you insist on top-posting !-) From deets at nospam.web.de Mon May 22 10:36:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 May 2006 16:36:50 +0200 Subject: enumerate() question References: <1148308146.493287.323770@38g2000cwa.googlegroups.com> Message-ID: <4de0l5F192lcgU1@uni-berlin.de> Gregory Petrosyan wrote: > Hello! > I have a question for the developer[s] of enumerate(). Consider the > following code: > > for x,y in coords(dots): > print x, y > > When I want to iterate over enumerated sequence I expect this to work: > > for i,x,y in enumerate(coords(dots)): > print i, x, y > > Unfortunately, it doesn't =( and I should use (IMHO) ugly > > for i,pair in enumerate(coords(dots)): > print i, pair[0], pair[1] > > So, why enumerate() works this way and is there any chance of changing > the behaviour? It works that way because enumerate returns a tuple - index, value. And it doesn't care what is inside value. Actually, it can't - how would you then write something like this? l = [1, ('a', 'tuple'), 3] for i, value in enumerate(l): print i, value But your problem can be solved in an elegant fashion anyway. When *you* know the structure of the values (and who else does?), you can simply use nested sequence unpacking: for i, (x, y) in enumerate(coords): pass HTH, Diez From sjmachin at lexicon.net Wed May 31 20:21:05 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 10:21:05 +1000 Subject: beginner: using parameter in functions In-Reply-To: References: Message-ID: <447e32f3@news.eftel.com> On 1/06/2006 9:24 AM, 3rdshiftcoder wrote: > hi- > > i am having trouble using parameter values in my function and to be honest a > little trouble with > member variables. i am trying to pass in the argument 'd' representing > delete. > what the code will do is if it is 'd' it will make a delete query template > string. > if it is an 'i' then insert query etc. > > this is the results of my attempt to print the contents of the parameter > values. > <__main__.getQryStr instance at 0x01151D50> ('d',) me mad Exactly right, first parameter is the object itself, second parameter is a 1-tuple of the supplied args. See more explanation below. > > > (and on a side note if i dont include the *args i get an invalid number of > parameters supplied message.) > why is it returning the value in this format ('d',) ? > i cant get x == d > i guess that value 'd' is stored in a tuple and i'd like to get it out of > there. No, 'd' is stored as the value of the attribute you've named "x". One of the main points of the whole OO caper is that objects have attributes -- please see later remarks about the tutorial. > > so basically the function returns nope as it stands > > python is sure different from other languages i have used. > > thanks for any help, > jim > > > class getQryStr: > def __init__(self,op): > print op > self.x = 'd' You probably meant self.x = op > def returnStr(x,*args): Like the first (__init__) method, this should have the mandatory "self" argument, plus *one* other arg .. *if* you need it. It's not apparent why you are calling the constructor *and* the returnStr method *each* with 'd'. > > print '%s %s me mad' % (x,args) > if x == 'd': Here x is the object that you have created. The first argument to a method is the object itself, and is conventionally named "self". It must be declared in the method itself def amethod(self, arg1, arg2): but is supplied automatically when you invoke it anobj.amethod('foo', 42) [snip] Please consider working your way through the Python tutorial http://docs.python.org/tut/node11.html and/or one of the free e-books e.g. http://www.byteofpython.info/ At the end of this post is a modified version of your script which shows what is going on under normal expected usage. HTH, John 8<=== demo script === C:\junk>type use_self.py class getQryStr: def __init__(self, op): print '__init__ ... op:%r' % op self.x = op def returnStr(self, arg): print 'returnStr ... self.x:%r arg:%r' % (self.x, arg) return '=%s=%s=' % (self.x, arg) obj = getQryStr('blah') print '__main__ ... obj.x:%r' % obj.x s = obj.returnStr('yadda') print '__main__ ... s:%r' % s 8<=== output from demo script === C:\junk>use_self.py __init__ ... op:'blah' __main__ ... obj.x:'blah' returnStr ... self.x:'blah' arg:'yadda' __main__ ... s:'=blah=yadda=' 8<=== end === From http Mon May 22 12:23:09 2006 From: http (Paul Rubin) Date: 22 May 2006 09:23:09 -0700 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> Message-ID: <7xu07if2qa.fsf@ruckus.brouhaha.com> "SamFeltus" writes: > As for the blind issue,that makes no sense to me. Is the suggestion > that we should give up using images in web sites since some people > can't see them. Might as well throw out the use of the img tag while > we are at it? Img tags should always have alt text describing the image, for those unable or unwilling to view the image ("unwilling" might be because of the download time). That bypasses the need to view the image. A heck of a lot of flash sites have no way to bypass the flash. Perhaps Python is not a great language to focus on for someone with a strong interest in Flash and little interest in HTML? Shrug, I don't see much relation, except that Python programmers tend to be tasteful and not care about Flash much. Maybe if you stick around here, you'll see the light ;-). From buzzard at urubu.freeserve.co.uk Fri May 26 13:23:31 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 26 May 2006 18:23:31 +0100 Subject: how to clear up a List in python? In-Reply-To: <1148662012.600336.113660@j33g2000cwa.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148653059.381151.113360@j73g2000cwa.googlegroups.com> <44772de5.0@entanet> <1148662012.600336.113660@j33g2000cwa.googlegroups.com> Message-ID: <44773ba7.0@entanet> chris brat wrote: > Doesnt this do what the original poster is try accomplish? > Not what the OP asked for, no. Clearing a list implies that list1 should still be bound to the same list (which might be important if there are other names bound to the same list). If it wasn't important that it be bound to the same list then I would probably go with linnorm's approach (which isn't really 'clearing' the list). >>> list1 = [0,1,2,3] >>> id(list1) 10772728 >>> del list1[:] >>> list1 [] >>> id(list1) 10772728 # i.e. the same list >>> list1 = [0,1,2,3] >>> id(list1) 10675264 >>> list1 = [] >>> id(list1) 10603576 # i.e. a different list >>> Duncan From skip at pobox.com Fri May 19 13:41:26 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 19 May 2006 12:41:26 -0500 Subject: WTF? Printing unicode strings In-Reply-To: References: Message-ID: <17518.838.312717.829981@montanaro.dyndns.org> John> Hmm, not that this helps me any :) >>>> import sys >>>> sys.stdout.encoding John> 'cp1252' Sure it does. You can print Unicode objects which map to cp1252. I assume that means you're on Windows or that for some perverse reason you have your Mac's Terminal window set to cp1252. (Does it go there? I'm at work right now so I can't check). Skip From OlafMeding at gmail.com Wed May 3 16:58:50 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 13:58:50 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <1146689031.533474.320570@v46g2000cwv.googlegroups.com> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> Message-ID: <1146689930.600243.65340@v46g2000cwv.googlegroups.com> > What do you mean "stop responding"? Both threads print their thread numbers (either 1 or 2) approximately every 10 seconds. However, after a while (minutes to hours) both programs (see above) hang! Pressing ctrl-c (after the printing stops) causes the threads to "wake up" from their sleep statement. And since the sleep took more than 1 seconds the thread number and the duration of the sleep is printed to the screen. Do you have a hyper-threading/dual/multi core CPU? Did you try this? Olaf From rrrn at yahoo.com Sat May 13 09:49:17 2006 From: rrrn at yahoo.com (Butternut squash) Date: Sat, 13 May 2006 13:49:17 GMT Subject: python soap web services References: <4cjaj2F14ufcoU1@uni-berlin.de> Message-ID: Diez B. Roggisch wrote: > Butternut squash wrote: > >> Is there any reason why there isn't any python library that makes >> using soap as easy as how microsoft .net makes it. >> >> I mean I write rudimentary asmx files call them from a webbrowser. >> The WSDL is generated and then there is documentation and a form to >> invoke a function. > > The WSDL will never as easily be created as in .NET/JAVA, as Python lacks > static typing annotations that are used by the WSDL-generators. So either > someone defines his own type annotation theme for that purpose that can be > used to infer the WSDL - or you write WSDL yourself. Which is a major > PITA, as the whole SOAP mess. > > Ravi OTH has pointed out _running_ a SOAP service is easy as cake. > I agree python soap is pretty easy to use. Just a bit harder to use the c# classic way to call a web service. From johnjsal at NOSPAMgmail.com Sun May 14 14:36:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 14 May 2006 14:36:16 -0400 Subject: any plans to make pprint() a builtin? In-Reply-To: <446735ea$1_1@newspeer2.tds.net> References: <44669e46$0$5337$c3e8da3@news.astraweb.com> <446735ea$1_1@newspeer2.tds.net> Message-ID: <4467791c$0$1956$c3e8da3@news.astraweb.com> Kent Johnson wrote: > Duncan Booth wrote: >> Personally I'd just like to see 'python' a builtin shorthand for importing >> a name you aren't going to use much >> e.g. >> >> python.pprint.pprint(x) > > Would you settle for > import py > py.std.pprint.pprint(x) ? > > http://codespeak.net/py/current/doc/misc.html#the-py-std-hook > > Kent Interesting, but that could start to get a little too messy I think. I'd rather just have the 'authentic' code in my program (i.e. pprint.pprint) instead of the py.std prefix as well. It's a good point not to pollute the builtin namespace with too much, so I think I'd rather just import pprint when needed instead of using the py.std call. From sgblookatme22 at aol.com Thu May 18 09:47:29 2006 From: sgblookatme22 at aol.com (Chuck) Date: 18 May 2006 06:47:29 -0700 Subject: If you were given a mall would you take it? Message-ID: <1147960049.178725.183640@38g2000cwa.googlegroups.com> http://www.telebay.com/esolutions/opp.html From johnjsal at NOSPAMgmail.com Wed May 3 12:10:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 03 May 2006 16:10:16 GMT Subject: what is the 'host' for SMTP? In-Reply-To: References: <44581205$0$25583$c3e8da3@news.astraweb.com> Message-ID: Steve R. Hastings wrote: > Take a look at your email client. Find where it specifies the server for > outgoing mail. Use whatever it says there. > > For example, I am a customer of blarg.net; I am therefore permitted to use > mail.blarg.net, which has a mail server running on it. If your ISP is > example.com, you probably will be using one of these: > > mail.example.com > smtp.example.com Thanks for all the information. Very helpful. But I'm still a little confused, because it seems like that's not enough information. If all I put in is, for example, smtp.gmail.com, how is that directed to my own email address? Do I still need to include other, more specific (i.e. personal) information elsewhere? From vbgunz at gmail.com Wed May 24 15:46:44 2006 From: vbgunz at gmail.com (vbgunz) Date: 24 May 2006 12:46:44 -0700 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474604.279491.71090@j55g2000cwa.googlegroups.com> <1148475029.108300.250810@i40g2000cwc.googlegroups.com> Message-ID: <1148500003.864284.296140@g10g2000cwb.googlegroups.com> > Thanks vbgunz that was the reply I was looking for! > Do you think it is wise to hold back for a 3rd edition? No, 2nd edition is literally perfect. The reason why is because almost nothing significant enough has changed since it's publication. In other words, you will not learn any outdated material. everything you learn in Learning Python is still applicable in the latest version of Python (2.4.3, 2.5). I will not be surprised in the least if typos are the only items corrected in the 3rd edition, perhaps along with a little bit of some new material. The fundamentals, the basics, the only real knowledge necessary to start getting busy in Python is found in the book. Good luck, I hope you enjoy it! From inigoserna at terra.es Sat May 6 19:21:23 2006 From: inigoserna at terra.es (=?ISO-8859-1?Q?I=F1igo?= Serna) Date: Sun, 07 May 2006 01:21:23 +0200 Subject: ANN: pynakotheka v1.0.2 Message-ID: <1146957683.6954.3.camel@inigo.katxi.org> Hi there, I'm pleased to announce a new bug-fix release of Pynakotheka. Pynakotheka is a simple GPL-licensed python script which generates static HTML photo albums to be added to web sites or to be burnt in CDs. It includes some templates and it's easy to create more. It depends on python, CheetahTemplate, EXIF and PIL. Read more and download it from: http://inigo.katxi.org/devel/pynakotheka or http://www.terra.es/personal7/inigoserna/pynakotheka Changes from v1.0.1 to v1.0.2: ============================== * now albums are sorted by creation time As always, all comments, suggestions etc. are welcome. Best regards, -- I?igo Serna Katxijasotzaileak -------------- next part -------------- A non-text attachment was scrubbed... Name: signature.asc Type: application/pgp-signature Size: 196 bytes Desc: Esta parte del mensaje est? firmada digitalmente URL: From khoa.coffee at gmail.com Wed May 17 17:47:05 2006 From: khoa.coffee at gmail.com (Khoa Nguyen) Date: Wed, 17 May 2006 17:47:05 -0400 Subject: Pyparsing: Specify grammar at run time Message-ID: <3d00e6dc0605171447n6dc57915q35b1978cd64b841f@mail.gmail.com> I run into another issue with my grammar: My input record contains a common part and an extended part. Based on the value of the common part, the extended part will be different. So, I am thinking of parsing the common part first and check the common's value and then parse again for the rest of the record. How do I tell pyparsing to start the 2nd parse at the exact location where the 1st parse left off? ###################################### from pyparsing import * common = Word('aA').setResultsName('value') extend1 = Word('b') extend2 = Word('c') result = common.parseString(record) if result.value == 'a': result1 = extend1.parseString(???) else: result2 = extend2.parseString(???) ###################################### Thanks, Khoa From grante at visi.com Tue May 30 09:51:09 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 30 May 2006 13:51:09 -0000 Subject: wait() on Popen4 object from thread? References: <127ndd2pcisrr0c@corp.supernews.com> Message-ID: <127ojedfa8inq56@corp.supernews.com> On 2006-05-30, Dennis Lee Bieber wrote: > On Tue, 30 May 2006 03:01:54 -0000, Grant Edwards > declaimed the following in comp.lang.python: > >> watching = False > > You do realize that this is a LOCAL definition, and is NOT the same > "watching" your later loop is waiting on... > >> while watching: >> time.sleep(0.1) Oops, forgot the global declaration. However, the presence/absence of the global affect whether the OSError happens or not. -- Grant Edwards grante Yow! Do I hear th' at SPINNING of various visi.com WHIRRING, ROUND, and WARM WHIRLOMATICS?! From phddas at yahoo.com Sun May 7 22:46:09 2006 From: phddas at yahoo.com (Gary Wessle) Date: 08 May 2006 12:46:09 +1000 Subject: Numerical Python Tutorial errors References: <87fyjlaht8.fsf@localhost.localdomain> Message-ID: <877j4x9qtq.fsf@localhost.localdomain> Robert Kern writes: > Gary Wessle wrote: > > Hi > > > > is the Numerical Python tutorial maintained? > > http://www.pfdubois.com/numpy/html2/numpy.html > > seams to have some errors and no email to mail them to when found. > > No, it is not since Numeric itself is no longer maintained. The successor to > Numeric is numpy and is being actively developed: > > http://numeric.scipy.org thank you From paul at boddie.org.uk Wed May 24 11:59:40 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 24 May 2006 08:59:40 -0700 Subject: Web framework comparison video References: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> <_7qdnQSQu6PZQ-7ZnZ2dnUVZ_tWdnZ2d@comcast.com> Message-ID: <1148486380.364694.101740@j55g2000cwa.googlegroups.com> AndyL wrote: > > Indeed it was. The headache factor is 1, for some reason my Mandrake > 2006 media players mute the sound. Had to boot to M$ :-(. Yes, these Web 2.0 pretenders just love their proprietary formats: Flash, QuickTime, etc. But then I guess Web 2.0 to them is all about compromising the open nature of the Web, accessibility, interoperability, with shiny things that are "OK because they work on my iBook". Paul From kent at kentsjohnson.com Sun May 7 12:59:38 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 07 May 2006 12:59:38 -0400 Subject: Designing Plug-in Systems in Python In-Reply-To: <1146893983.268034.206080@e56g2000cwe.googlegroups.com> References: <1146893983.268034.206080@e56g2000cwe.googlegroups.com> Message-ID: <445e2703$1_1@newspeer2.tds.net> mystilleef wrote: > Hello, > > I need to design a plug-in system for a project. The goal is > to allow third party developers interact with an application > via plug-ins in a clean and robust manner. At this point I > am overwhelmed by my inexperience with designing plug-in > systems. One of these might be helpful: http://developer.berlios.de/projects/plugboard/ http://termie.pbwiki.com/SprinklesPy Kent From petr at tpc.cz Tue May 2 15:54:22 2006 From: petr at tpc.cz (Petr Jakes) Date: 2 May 2006 12:54:22 -0700 Subject: Polling from keyboard In-Reply-To: <4bpm1qF124s7vU1@uni-berlin.de> References: <1146593098.744039.89340@u72g2000cwu.googlegroups.com> <4bpm1qF124s7vU1@uni-berlin.de> Message-ID: <1146599662.715742.23010@i39g2000cwa.googlegroups.com> I am using following code which I have found on http://www.ibiblio.org/obp/py4fun/ few months ago. It works well for my purposes. Another way is to use Curses library. HTH Petr Jakes #!/usr/local/bin/python # # t t y L i n u x . p y # # getLookAhead reads lookahead chars from the keyboard without # echoing them. It still honors ^C etc # import termios, sys, time if sys.version > "2.1" : TERMIOS = termios else : import TERMIOS def setSpecial () : "set keyboard to read single chars lookahead only" global oldSettings fd = sys.stdin.fileno() oldSettings = termios.tcgetattr(fd) new = termios.tcgetattr(fd) new[3] = new[3] & ~TERMIOS.ECHO # lflags new[3] = new[3] & ~TERMIOS.ICANON # lflags new[6][6] = '\000' # Set VMIN to zero for lookahead only termios.tcsetattr(fd, TERMIOS.TCSADRAIN, new) def setNormal () : "restore previous keyboard settings" global oldSettings fd = sys.stdin.fileno() termios.tcsetattr(fd, TERMIOS.TCSADRAIN, oldSettings) def readLookAhead () : "read max 1 chars (arrow escape seq) from look ahead" return sys.stdin.read(1) From pmartin at snakecard.com Fri May 5 11:22:39 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 10:22:39 -0500 Subject: Is this a legal / acceptable statement ? References: <2AI6g.10201$9c6.5375@dukeread11> <-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> <445b67bb$0$16736$626a54ce@news.free.fr> Message-ID: <35K6g.8733$B42.4422@dukeread05> bruno at modulix wrote: > Philippe Martin wrote: > (snip) >> >> l_init really is a boolean parameter and l_value a value that _might_ >> exist in a shelve. >> >> So I just want to have a parameter to a method so if the first value >> tested is false (l_init) then the second (l_value) does not get tested >> ... because it is the second in the statement and only seems to get >> evaluated if the first one is true. > > s/seems to get/is/ > > But this is a really unpythonic way to do things IMHO. Either use a > try/except block (probably the most straightforward solution), or, as in > Larry's post, test for the existence of 'l_value' in locals(). > > 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('@')])" Well, that was the question - I wanted to avoid that because I'm already in a try/except and do not like to imbricate them too much. Philippe From seberino at spawar.navy.mil Sun May 7 22:48:19 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 7 May 2006 19:48:19 -0700 Subject: Python Eggs Just install in *ONE* place? Easy to uninstall? In-Reply-To: <2199622.7zKjNmN3Qs@jupiter.g2ctech> References: <1146936395.028140.15640@i39g2000cwa.googlegroups.com> <2199622.7zKjNmN3Qs@jupiter.g2ctech> Message-ID: <1147056499.732347.106350@y43g2000cwc.googlegroups.com> But not matter where eggs are installed they are never spread across multiple places on hard drive right? An egg is all under one node of tree right? From rschroev_nospam_ml at fastmail.fm Mon May 1 07:03:37 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 01 May 2006 11:03:37 GMT Subject: critique this little script, if you like In-Reply-To: <874q0aa8em.fsf@localhost.localdomain> References: <44554a32$0$11750$c3e8da3@news.astraweb.com> <874q0aa8em.fsf@localhost.localdomain> Message-ID: Dave Jones schreef: > Hi John! > > About the path and the \'s, take a look at the os.path.join function. > The function is smart enough to add the correct slash when joining > directories. But watch out with leading backslashes, as in subdirs = [r'\cgi-bin', r'\images', r'\styles'] os.path.join will assume they are meant to be absolute paths, and will discard all previous components: >>> os.path.join('base', 'subdomain', r'\images') '\\images' In fact I think it's best to specify components without leading or trailing backslashes (unless you really want an absolute path): >>> os.path.join('base', 'subdomain', 'images') 'base\\subdomain\\images' -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From alet at librelogiciel.com Fri May 19 13:22:22 2006 From: alet at librelogiciel.com (Jerome Alet) Date: Fri, 19 May 2006 19:22:22 +0200 Subject: [ANNOUNCE] ipplib : python IPP and CUPS API Message-ID: Hi there, I'm pleased to announce a new project of mine, named ipplib, which offers IPP requests parsing and/or building, and (basic) support for the CUPS' API. This project is written in 100% Python, and is available under the terms of the GNU GPL. It's very young, although the parsing code is two years old and I believe well tested, so it's currently only downloadable from subversion for now : $ cd /tmp $ svn co svn://svn.librelogiciel.com/ipplib/trunk ipplib $ cd ipplib $ python setup.py install (for the last line to work, you need the python-dev package installed). Examples of use in Python programs : --- CUT --- # Parsing.py EXAMPLE from ipplib import ipplib # Read IPP datas from a CUPS control file myfile = open("/var/spool/cups/c00155") ippdatas = myfile.read() myfile.close() # Parse these datas request = ipplib.IPPRequest(ippdatas) request.parse() print request --- CUT --- --- CUT --- # Building.py EXAMPLE from ipplib import ipplib request = ipplib.IPPRequest(operation_id=ipplib.CUPS_GET_DEFAULT) request.operation["attributes-charset"] = ("charset", "utf-8") request.operation["attributes-natural-language"] = ("naturalLanguage", "en-us") ippdatas = request.dump() newrequest = ipplib.IPPRequest(ippdatas) newrequest.parse() print newrequest.operation["attributes-natural-language"] --- CUT --- --- CUT --- # CUPS' API from ipplib import ipplib cups = ipplib.CUPS() # High level API : retrieve info about job 3 : answer = cups.getJobAttributes(3) print answer.job["document-format"] # Lower level API : request = cups.newRequest(ipplib.IPP_GET_PRINTER_ATTRIBUTES) request.operation["printer-uri"] = ("uri", cups.identifierToURI("printers", "HP2100")) for attribute in ("printer-uri-supported", "printer-type", "member-uris") : request.operation["requested-attributes"] = ("nameWithoutLanguage", attribute) answer = request.doRequest() print answer --- CUT --- Of course several parameters can be used to customize things a bit if the default values (e.g. http://localhost:631 for server) are not what you want. The long term goal is to implement most of the CUPS' API, but currently only getDefault() and getJobAttributes(jobid) are fully implemented... Currently the documentation is inexistant, and the docstrings in the source suck, but this will be improved in the near future. Any comment is more than welcome. Any help is more than welcome. bye Jerome Alet From dale at riverhall.nospam.co.uk Tue May 9 03:23:13 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Tue, 09 May 2006 08:23:13 +0100 Subject: Import data from Excel References: Message-ID: Try this: from win32com.client import GetObject, constants def GetExcelData(self, strFilePath): """ Extract the data from the Excel sheet. Returns tuple of tuples representing the rows and cells.""" # The following line extracts # all the data from sheet 1 of the spreadsheet return GetObject(strFilePath).Sheets(1).UsedRange.Value N/A wrote: > Hi, > Is it possible to import data from Excel for doing numerical analysis in > Python? If so how? Thank u! -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From davidschein at alumni.tufts.edu Tue May 9 10:29:33 2006 From: davidschein at alumni.tufts.edu (David S.) Date: Tue, 9 May 2006 14:29:33 +0000 (UTC) Subject: distutils Message-ID: I have a what I a typical source tree, something like: fsi\ - common\ # some modules - db\ # some modules - someutility\ # my script I would like to create a setup script to install my script as a script as well as the modules that is depends on, but where should the setup.py file live? If I put it in ./someutility/ it can not find fsi.common or fsi.db. package_dir does not seem to work and I am confused. The documentation is, I am sure thorough, but something that fit on fewer pages would help. So I appreciate any help for this particular problem as well as any suggestions for other documentation or guides to using distutils. Peace, David S. From phddas at yahoo.com Sun May 7 12:02:21 2006 From: phddas at yahoo.com (Gary Wessle) Date: 08 May 2006 02:02:21 +1000 Subject: NumTut view of greece Message-ID: <87k68xakmq.fsf@localhost.localdomain> Hi not sure if this would be the right place to ask this question! using the shell prompt :~$ python Python 2.3.5 (#2, Mar 6 2006, 10:12:24) [GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import Numeric >>> from NumTut import * >>> view(greece) >>> shows a photo of the street in a tk window. but if I have this file **************** tut.py **************** #!/usr/bin/env python import Numeric from NumTut import * view(greece) print "done" **************************************************************** and then type $ ./tut.py done $ and not tk view of greece. thanks From jantod at gmail.com Mon May 29 04:56:57 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 29 May 2006 01:56:57 -0700 Subject: itertools.count() as built-in In-Reply-To: <1hg24o2.18odi4uzoiraoN%aleax@mac.com> References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> <1148860241.048549.269330@j73g2000cwa.googlegroups.com> <1hg24o2.18odi4uzoiraoN%aleax@mac.com> Message-ID: <1148893017.099404.39750@38g2000cwa.googlegroups.com> Zipping an xrange? I'm having trouble visualizing how you do that to avoid x*i+y. -Janto From levub137 at wi.rr.com Sat May 6 11:33:14 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 06 May 2006 15:33:14 GMT Subject: Class Library for Numbers now available for Windows Message-ID: <_k37g.2686$WP5.441@tornado.rdc-kc.rr.com> Due to the contribution of Frank Palazzolo, a Windows binary installer and build instructions are available for the clnum package. This also makes ratfun and rpncalc usable on the Windows platform. The clnum package adds rational numbers and arbitrary precision floating point numbers in real and complex form to Python. It also provides arbitrary precision floating point replacements for the functions in the math and cmath standard library modules. For more information, see Home page: http://calcrpnpy.sourceforge.net/clnum.html From tfb at conquest.OCF.Berkeley.EDU Sat May 6 04:22:41 2006 From: tfb at conquest.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 06 May 2006 01:22:41 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> Message-ID: Ken Tilton writes: > Hopefully it can be a big issue and still not justify a flame war. > > Mileages will always vary, but one reason for lambda is precisely not > to have to stop, go make a new function for this one very specific > use, come back and use it as the one lambda statement, or in C have an > address to pass. but, hey, what are editors for? :) > > the bigger issue is the ability of a lambda to close over arbitrary > lexically visible variables. this is something the separate function > cannot see, so one has to have a function parameter for everything. > > but is such lexical scoping even on the table when Ptyhon's lambda > comes up for periodic review? This is second-hand, as I don't actually follow Python closely, but from what I've heard, they now have reasonable scoping rules (or maybe they're about to, I'm not sure). And you can use def as a Scheme-style inner define, so it's essentially a LABELS that gets the indentation wrong. This means they have proper closures, just not anonymous ones. And an egregiously misnamed lambda that should be fixed or thrown out. If Python gets proper macros it won't matter one bit that they only have named closures, since you can macro that away in a blink of an eye. From duncan.booth at invalid.invalid Mon May 8 11:15:16 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 8 May 2006 15:15:16 GMT Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> Message-ID: Nick Craig-Wood wrote: > Which translates to > > match = re.search('(blue|white|red)', t) > if match: > print "Colour:", match.group(1) > else: > match = re.search('(socks|tights)', t) > if match: > print "Garment:", match.group(1) > else: > match = re.search('(boot|shoe|trainer)', t) > if match: > print "Footwear:", match.group(1) > # indented ad infinitum! This of course gives priority to colours and only looks for garments or footwear if the it hasn't matched on a prior pattern. If you actually wanted to match the first occurrence of any of these (or if the condition was re.match instead of re.search) then named groups can be a nice way of simplifying the code: PATTERN = ''' (?Pblue|white|red) | (?Psocks|tights) | (?Pboot|shoe|trainer) ''' PATTERN = re.compile(PATTERN, re.VERBOSE) TITLES = { 'c': 'Colour', 'g': 'Garment', 'f': 'Footwear' } match = PATTERN.search(t) if match: grp = match.lastgroup print "%s: %s" % (TITLES[grp], match.group(grp)) For something this simple the titles and group names could be the same, but I'm assuming real code might need a bit more. From kent at kentsjohnson.com Tue May 23 11:52:12 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 23 May 2006 11:52:12 -0400 Subject: can't figure out error: module has no attribute... In-Reply-To: <1148392551.118437.255680@i39g2000cwa.googlegroups.com> References: <1148392551.118437.255680@i39g2000cwa.googlegroups.com> Message-ID: <44732ee1$1_3@newspeer2.tds.net> Chris_147 wrote: > but it seems to depend on from where I start the Python shell. > > so I've got a module selfservicelabels.py with some variables defined, > like this: > BtnSave = "link=label.save" > DeliveryAutomaat = "//input[@id='deliveryMethod' and @value='AU']" > This module is in the Lib directory. > > Now when I do > import selfservicelabels > selfservicelabels.BtnSave > -> link=nmbs.label.save > selfservicelabels.DeliveryAutomaat > -> AttributeError: 'module' object has no attribute > 'DeliveryAutomaat' > > to make it more strange: PyCrust and Idle recognise DeliveryAutomaat > perfectly. > Everything above is done with Python 2.4.3 on Windows XP SP2 > > So after some testing it seems to depend on from which partition I > start Python. Probably you have multiple copies of selfservicelabels.py or an old selfservicelabels.pyc that is being imported. Try import selfservicelabels print selfservicelabels.__file__ to see where the import is coming from. Kent > So open commandline and navigate to a dir on C: everything works > perfectly. > Close python shell en navigate to D: some variables in > selfservicelabels.py are not known. > What is going on here? Is this a known error? > From leo at lspace.org Mon May 8 08:11:36 2006 From: leo at lspace.org (Leo Breebaart) Date: 8 May 2006 12:11:36 GMT Subject: Logging vs printing References: <4c6o1sF14hhjuU1@individual.net> <1147035825.643595.139800@e56g2000cwe.googlegroups.com> Message-ID: <4c8qroF14g6feU1@individual.net> "alisonken1" writes: > Leo Breebaart wrote: > > > I am writing fairly large console scripts in Python. They > > have quite a few command-line options, which lead to > > configuration variables that are needed all over the program > > (e.g. the "--verbose" option alone is used by just about > > every function and method). > > > > One question I have is about the "--verbose" option. > > If you're doing something that is equivalent to logging to > , rather than continuing to pass the > '--verbose' flag around, why not just use the built-in logging > facility to manage the extra output? Good point. It's not a real conscious decision, and I have one or two other projects lying around where I do in fact use logging. I think the main reason why I am not using it by default is because, when all is said and done, it still comes easier to me to resort to guarded print statements then to set up and use the logging machinery. This may well be a false economy in the long run, but it is nevertheless how I perceive it in day-to-day programming. (Related to this is that while I found e.g. the optparse documentation very clear and relevant to my needs, the logging documentation and examples, while readable, just never seem to relate to what I actually need. This is not a complaint -- just a subjective observation.) But you are right. Especially for the larger projects I really should bite the bullet and start using the logging module. -- Leo Breebaart From johnzenger at gmail.com Tue May 16 12:00:36 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 16 May 2006 09:00:36 -0700 Subject: regex help In-Reply-To: <4469eba9$0$61166$ae4e5890@news.nationwide.net> References: <4469eba9$0$61166$ae4e5890@news.nationwide.net> Message-ID: <1147795236.212075.312000@v46g2000cwv.googlegroups.com> Why not use split instead of regular expressions? >>> ln = "32 32 23 9 9 - 9 9 - 9 11 1 10" >>> ln.split() ['32', '32', '23', '9', '9', '-', '9', '9', '-', '9', '11', '1', '10'] Much simpler, yes? Just find the line that comes after a line that begins with "TIGER," split it, and pick the number you want out of the resulting list. Lance Hoffmeyer wrote: > I have the following table and I am trying to match percentage the 2nd column on the 2nd Tiger line (9.0). > > I have tried both of the following. I expected both to match but neither did? Is there a modifier > I am missing? What changes do I need to make these match? I need to keep the structure of the regex > the same. > > TIGER.append(re.search("TIGER\s{10}.*?(?:(\d{1,3}\.\d)\s+){2}", target_table).group(1)) > TIGER.append(re.search("^TIGER.*?(?:(\d{1,3}\.\d)\s+){2}", target_table).group(1)) > > > BASE - TOTAL TIGER 268 268 173 95 101 - 101 57 - 57 78 2 76 268 192 76 230 21 > > DOG 79 79 44 35 31 - 31 17 - 17 25 1 24 79 55 24 75 1 > 29.5 29.5 25.4 36.8 30.7 - 30.7 29.8 - 29.8 32.1 50.0 31.6 29.5 28.6 31.6 32.6 4.8 > > CAT 46 46 28 18 20 - 20 7 - 7 14 - 14 46 32 14 39 4 > 17.2 17.2 16.2 18.9 19.8 - 19.8 12.3 - 12.3 17.9 - 18.4 17.2 16.7 18.4 17.0 19.0 > > LAMB 32 32 23 9 10 - 10 8 - 8 12 - 12 32 20 12 28 1 > 11.9 11.9 13.3 9.5 9.9 - 9.9 14.0 - 14.0 15.4 - 15.8 11.9 10.4 15.8 12.2 4.8 > > TRIPOD 32 32 23 9 9 - 9 9 - 9 11 1 10 32 22 10 28 3 > 11.9 11.9 13.3 9.5 8.9 - 8.9 15.8 - 15.8 14.1 50.0 13.2 11.9 11.5 13.2 12.2 14.3 > > TIGER 24 24 16 8 5 - 5 10 - 10 7 - 7 24 17 7 18 2 > 9.0 9.0 9.2 8.4 5.0 - 5.0 17.5 - 17.5 9.0 - 9.2 9.0 8.9 9.2 7.8 9.5 From kguan at corp.netease.com Thu May 4 07:44:24 2006 From: kguan at corp.netease.com (Kyo Guan) Date: Thu, 4 May 2006 19:44:24 +0800 Subject: about the implement of the PyString_InternFromString Message-ID: <000301c66f70$1f0995e0$3500a8c0@kyom> Hi guys: I have a question about the this API. PyObject * PyString_InternFromString(const char *cp) { PyObject *s = PyString_FromString(cp); if (s == NULL) return NULL; PyString_InternInPlace(&s); return s; } Why it always try to call PyString_FromString first? if char* cp is already in the interned dict, this PyString_FromString call is waster. so I think this API should implement as: 1. check the interned dict 2. if cp is not in the dict, then call PyString_FromString, and insert the new string in the dict 3. else : call Py_INCREF and return. Is this right? Kyo. From groups at theyoungfamily.co.uk Mon May 15 06:46:31 2006 From: groups at theyoungfamily.co.uk (Ben) Date: 15 May 2006 03:46:31 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <44681F95.9040400@gmail.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <44681F95.9040400@gmail.com> Message-ID: <1147689991.541829.129550@u72g2000cwu.googlegroups.com> Nothing you have described sounds that complicated, and you never come up with concrete objections to other peoples code (apart that it took 10 years to write in Lisp, so it must be really hard) Why are you running a SoC project for PyCells if you dislike the language so much. People who do like Python can implement it if they need it (which I haven't seen any good examples that they do) Please don't force a student to create a macro system just to port a system to Python, as it won't really be python then. Use Pythonic methodology instead. There are already plenty of ways to hide complicated functionality, just not necessarily the way you want to do it. Cheers, Ben From klachemin at comcast.net Fri May 5 15:12:33 2006 From: klachemin at comcast.net (Kamilche) Date: 5 May 2006 12:12:33 -0700 Subject: easy way to dump a class instance? In-Reply-To: <8SL6g.73271$H71.63860@newssvr13.news.prodigy.com> References: <8SL6g.73271$H71.63860@newssvr13.news.prodigy.com> Message-ID: <1146856353.555944.281870@i39g2000cwa.googlegroups.com> Mark Harrison wrote: > Is there a way to automatically print all the instance > data in a class? print self.__dict__ From johnjsal at NOSPAMgmail.com Sun May 14 01:17:05 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 14 May 2006 01:17:05 -0400 Subject: do/while structure needed Message-ID: <4466bddd$0$18984$c3e8da3@news.astraweb.com> 1 random.shuffle(letters) 2 trans_letters = ''.join(letters)[:len(original_set)] 3 trans_table = string.maketrans(original_set, trans_letters) So what I'd like to do is have lines 1 and 2 run once, then I want to do some comparison between original_set and trans_letters before running line 3. If the comparison passes, line 3 runs; otherwise, lines 1 and 2 run again. A do/while would be good for this, but perhaps I'm looking at it in the wrong way? Or is there some kind of do/while type of idiom that I could use? Thanks. From vbgunz at gmail.com Fri May 12 11:55:37 2006 From: vbgunz at gmail.com (vbgunz) Date: 12 May 2006 08:55:37 -0700 Subject: find all index positions In-Reply-To: <1147448743.445465.124200@u72g2000cwu.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <1147374826.341124.129260@g10g2000cwb.googlegroups.com> <4463C188.3030202@lexicon.net> <1147448743.445465.124200@u72g2000cwu.googlegroups.com> Message-ID: <1147449337.164504.307670@j73g2000cwa.googlegroups.com> I forgot to explain my reason for over shadowing the 'string' built-in within my iterator. To me, it doesn't matter because the string identifier is temporary within the function and dies when the function dies. Also, I personally don't use the string function and prefer ''.join('hi'), etc. Also, at least for me just starting out in Python, I find 'string' to be as readable as possible :) what do you think about that? From diego at pxes.org Fri May 19 06:06:45 2006 From: diego at pxes.org (Diego Torres Milano) Date: Fri, 19 May 2006 10:06:45 +0000 Subject: Python and Test Driven Development Message-ID: First part of a series of articles about Python and Test Driven Development can be found at http://dtmilano.blogspot.com/2006/05/python-and-test-driven-development.html. These articles include some scripts to ease automatic test suite creation in Python. Comments are gladly welcome. -------------- next part -------------- An HTML attachment was scrubbed... URL: From alisonken1 at gmail.com Fri May 5 12:03:37 2006 From: alisonken1 at gmail.com (alisonken1) Date: 5 May 2006 09:03:37 -0700 Subject: Drop Down Menus... In-Reply-To: References: Message-ID: <1146845017.689207.115860@v46g2000cwv.googlegroups.com> Hello Bruce - bruce wrote: > Hi... > > Never used python, but I have a question regarding Drop Down Menus. Does > Python allow me to create a website, that will permit the user to create > Drop Down menus that can be initiated with the right mouse click? If it can, > is it fairly easy to implement? If you are talking about client-side menu's, you should be looking at Java or Java-Script. Python is good at server-side scripting, but there is no >widely installed< python interpreter on peoples browsers that would work, whereas java and javascript are pretty much the standard in client-side scripting in web browsers. From pmartin at snakecard.com Fri May 5 10:42:38 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 09:42:38 -0500 Subject: Is this a legal / acceptable statement ? References: <2AI6g.10201$9c6.5375@dukeread11> <-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> Message-ID: Larry Bates wrote: > Philippe Martin wrote: >> Hi, >> >> This code works, but is it "appropriate" ? >> >> l_init = False >> >> if True == l_init and 1234 = l_value: >> print 'l_value is initialized' >> >> I know I can do this with a try but ... >> >> Philippe >> >> > 1) You have a syntax error 1234 == l_value (note ==) > 2) This doesn't test to see if l_value is initialized > because if it isn't you get: > > 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 "junk.py", line 1, in ? > if True == l_init and 1234 == l_value: > NameError: name 'l_init' is not defined > > 3) It is unclear what l_init is used for in this context. > Setting it to True doesn't tell you anything about l_value. > > Normally you do something like: > > l_value=None > . > . Intervening code > . > if l_value is None: > print "l_value uninitialized" > > Or (something I never use): > > if not locals().has_key('l_value'): > print "l_value uninitialized" > > > -Larry Bates l_init really is a boolean parameter and l_value a value that _might_ exist in a shelve. So I just want to have a parameter to a method so if the first value tested is false (l_init) then the second (l_value) does not get tested ... because it is the second in the statement and only seems to get evaluated if the first one is true. Philippe From steve at holdenweb.com Mon May 1 07:52:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 01 May 2006 12:52:47 +0100 Subject: basic python programing In-Reply-To: <125a1cneqrb5qec@corp.supernews.com> References: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> <125a1cneqrb5qec@corp.supernews.com> Message-ID: Grant Edwards wrote: > On 2006-04-30, fxlogx at gmail.com wrote: > > >>here we discuss the most basic concepts about python. > > > Yes we do. > > As well as the most basic concepts about Usenet. > Yes, sir. BasicConceptsRUs. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From xkenneth at gmail.com Mon May 29 22:24:33 2006 From: xkenneth at gmail.com (xkenneth) Date: 29 May 2006 19:24:33 -0700 Subject: Watching serial port activity. Message-ID: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> Hi, I'm writing a couple python applications that use the serial port (RS-232) quite extensively. Is there any way I can monitor all activity on the serial port and have it printed as the transactions occur? I'm trying to reverse engineer a microcontroller serial routine and I'd like to see any response the chip sends back. Regards, Ken From bitsandbytes88 at hotmail.com Tue May 30 11:00:21 2006 From: bitsandbytes88 at hotmail.com (bitsandbytes88 at hotmail.com) Date: 30 May 2006 08:00:21 -0700 Subject: sybase open client 15_0 In-Reply-To: References: Message-ID: <1149001221.702041.171010@j55g2000cwa.googlegroups.com> Eduardo Gonzalez-Solares wrote: > See: > > http://www.object-craft.com.au/pipermail/python-sybase/2006-May/000471.html > > Dan wrote: > > I'm running SLES 9.3 on Tyan with 2 single core 64-bit Opteron & 8 GB of > > memory and SWAP. > > > > OCS-15_0 > > sybperl-2.18 > > python 2.3.5 > > > > > > > > "Dan" wrote in message > > news:NPOdnbx8s-CdcejZRVn-iw at speakeasy.net... > >> I have compiled and installed sybase-.037 , the module to add sybase to > >> python. However, when I try to use it I get Import error: > >> /usr/local/lib/python2.3/site-packages/sybasect.so > >> > >> undefined symbol: cs_dt_info > >> > >> I've seen some posts on the internet with other people having this issue. > >> But nothing they've suggested has resolved this issue. Maybe python just > >> needs to be installed again or upgraded to support sybase Open Client. > >> > >> Thanks, > >> ~DjK > >> > > > > From jordan.taylor2 at gmail.com Thu May 25 10:06:02 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 25 May 2006 07:06:02 -0700 Subject: wincerapi In-Reply-To: References: Message-ID: <1148565962.826347.70300@i39g2000cwa.googlegroups.com> I know this isn't helpful at all, but now I'm curious. What's wincer? From rpdooling at gmail.com Wed May 3 19:32:09 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 3 May 2006 16:32:09 -0700 Subject: Gettings subdirectories In-Reply-To: References: <1146683720.748769.36490@g10g2000cwb.googlegroups.com> <1146695904.623400.128100@y43g2000cwc.googlegroups.com> Message-ID: <1146699129.273331.32480@i40g2000cwc.googlegroups.com> Sorry that I was unclear. I sorta know how os.walk works. It's the .next() trick that I had never seen before. For instance, if you run that statement without the .next() on it, it says "Too many items to unpack" but with the .next() it stops it somehow, right where I want it to stop. It's an iterator method, right? I found it in Beazely, now I'll try to understand it. Sorry to trouble you. rick From kevin.bell at slcgov.com Fri May 26 11:22:45 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Fri, 26 May 2006 09:22:45 -0600 Subject: hide python window, con'td Message-ID: <2387F0EED10A4545A840B231BBAAC7226083B8@slcimail1.slcgov.com> Great! And now that it's hiding w/ .pyw, how would I kill it if I want? Just log off, or is there a better way? Kevin From harisekhon at gmail.com Wed May 17 05:50:41 2006 From: harisekhon at gmail.com (Hari Sekhon) Date: Wed, 17 May 2006 10:50:41 +0100 Subject: Strange IO Error when extracting zips to a network location Message-ID: <446AF1F1.9040907@gmail.com> Hi, I've written a script to run on windows to extract all zips under a given directory path to another directory path as such: python extractzips.py The purpose of this script is to retrieve backup files which are individually zipped under a backup directory tree on a backup server. This scripts works nicely and has input validation etc, exiting gracefully and telling you if you gave a non existent start or target path... When running the script as follows python extractzips.py \\backupserver\backupshare\machine\folder d:\unziphere the script works perfectly, but if I do python extractzips.py \\backupserver\backupshare\machine\folder \\anetworkmachine\share\folder then it unzips a lot of files, recreating the directory tree as it goes but eventually fails with the traceback: File "extractzips.py", line 41, in zipextract outfile.write(zip.read(x)) IOError: [Errno 22] Invalid argument But I'm sure the code is correct and the argument is passed properly, otherwise a hundred files before it wouldn't have extracted successfully using this exact same piece of code (it loops over it). It always fails on this same file every time. When I extract the same tree to my local drive it works fine without error. I have no idea why pushing to a network share causes an IO Error, shouldn't it be the same as extracting locally from our perspective? It pulls fine, why doesn't it push fine? Thanks for any help or suggestions anybody can give me. Hari From deets at nospam.web.de Mon May 22 07:13:16 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 May 2006 13:13:16 +0200 Subject: string.count issue (i'm stupid?) References: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> Message-ID: <4ddkneF19kjaeU1@uni-berlin.de> Matteo Rattotti wrote: > Hi all, > > i've noticed a strange beaviour of string.count: > > in my mind this code must work in this way: > > str = "a_a_a_a_" > howmuch = str.count("_a_") > print howmuch -> 3 > > but the count return only 2 > > Ok this can be fine, but why? The doc string tell that count will > return the number of substring in the master string, if we spoke about > substring i count 3 substring... It appears to be a documentation bug. It should say something about non-overlapping occurences. Better would be of course to introduce a parameter that defines the behavior, either overlapping or not. Diez From ibr at radix50.net Wed May 24 04:52:17 2006 From: ibr at radix50.net (Baurzhan Ismagulov) Date: Wed, 24 May 2006 10:52:17 +0200 Subject: logging In-Reply-To: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> References: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> Message-ID: <20060524085217.GA5814@radix50.net> Hello Vinay, On Tue, May 23, 2006 at 04:13:38PM -0700, Vinay Sajip wrote: > > [logger_root] > > level=CRITICAL > > handlers=console > > > > [logger_l01] > > level=DEBUG > > qualname=l01 > > handlers=console > > > > I want logger_root to go to /dev/null, so I've configured it with level > > CRITICAL. My understanding is that in this way debug messages are not > > printed on logger_root's handler. However, running the program results > > in the message being printed twice. What is the problem? > > You've defined the handler against both the root logger and l01. You > only need it configured for the root logger - events passed to l01 will > be passed to all handlers up the hierarchy. So remove the > "handlers=console" line from [logger_l01] and it should print the > message just once. Thanks for the idea! I think this should work for the example I sent. However, I have more than one module, and I want to log only l01. How can I do that? Thanks in advance, Baurzhan. From Andreas.Ames at comergo.com Fri May 12 09:24:07 2006 From: Andreas.Ames at comergo.com (Ames Andreas) Date: Fri, 12 May 2006 15:24:07 +0200 Subject: multi-threaded c++ callback problem Message-ID: <552B6B925278EF478EA8887D7F9E5AC3937900@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 pydev > Sent: Tuesday, April 11, 2006 9:23 PM > Subject: multi-threaded c++ callback problem > > void pyCallEventCallback( CALL hCall, > LINE hLine, > CALLSTATE_MAJOR eMajor, > CALLSTATE_MINOR eMinor, > PyObject* def ) > { > if( !PyCallable_Check( def ) ) > { > PyErr_SetString( PyExc_TypeError, "Need a callable object!" ); > return; > } > printf( "EventCallback hCall: %i, hLine: %i, eMajor: %i, > eMinor: %i\n", hCall, hLine, eMajor, eMinor); > PyObject* arglist = Py_BuildValue("(iiii)", hCall, hLine, > eMajor, eMinor); > > // if i comment out next line it works! > PyEval_CallObject( def, arglist ); > > Py_XDECREF(arglist); > } > //-----------------------------------------------------------// Wild guess because of lack of context: It's a race condition because you haven't acquired the GIL before calling pyCallEventCallback. You can do so by using PyEval_SaveThread and friends. You have to make sure to call PyEval_InitThreads somewhere, e.g. when embedding from within the interpreter initialisation boilerplate, when extending for instance from within the extension module initialisation. cheers, aa -- Andreas Ames | Programmer | Comergo GmbH | Voice: +49 69 7505 3213 | ames AT avaya . com From johnjsal at NOSPAMgmail.com Thu May 4 16:24:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 04 May 2006 20:24:52 GMT Subject: using urllib with ftp? Message-ID: I've tried this already and it seems to work, but I'm curious if it's okay to use urllib when trying to access a url that begins with ftp:// instead of http://. Does this matter? It's only a text file, so it's not really an FTP server I'm accessing, I don't think. I wasn't sure if using ftplib would be overkill in this case, or if you even could use it at all if you just want to get the page itself (the txt file). Thanks. From kay.schluehr at gmx.net Sat May 6 05:12:49 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 May 2006 02:12:49 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <87hd43bme3.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1146900379.023190.164640@u72g2000cwu.googlegroups.com> <87hd43bme3.fsf@rpi.edu> Message-ID: <1146906768.994288.262300@j33g2000cwa.googlegroups.com> Bill Atkins wrote: > "Kay Schluehr" writes: > > > And then the 12th vanished Lisper returns and Lispers are not > > suppressed anymore and won't be loosers forever. The world will be > > The mark of a true loser is the inability to spell 'loser.' Zing! There is not much lost. > > them as zealots, equipped with the character of suicide bombers. No, > > A very reasonable comparison. Yes, the more I think about it, we Lisp > programmers are a lot like suicide bombers. Allah Inschallah From sjmachin at lexicon.net Fri May 12 05:57:23 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 May 2006 19:57:23 +1000 Subject: deleting texts between patterns In-Reply-To: <1147421468.912908.271280@i39g2000cwa.googlegroups.com> References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <1147421468.912908.271280@i39g2000cwa.googlegroups.com> Message-ID: <44645C03.3070500@lexicon.net> On 12/05/2006 6:11 PM, Ravi Teja wrote: > mickle... at hotmail.com wrote: >> hi >> say i have a text file >> >> line1 [snip] >> line6 >> abc >> line8 <---to be delete [snip] >> line13 <---to be delete >> xyz >> line15 [snip] >> line18 >> >> I wish to delete lines that are in between 'abc' and 'xyz' and print >> the rest of the lines. Which is the best way to do it? Should i get >> everything into a list, get the index of abc and xyz, then pop the >> elements out? or any other better methods? >> thanks > > In other words ... > lines = open('test.txt').readlines() > for line in lines[lines.index('abc\n') + 1:lines.index('xyz\n')]: > lines.remove(line) I don't think that's what you really meant. >>> lines = ['blah', 'fubar', 'abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy'] >>> for line in lines[lines.index('abc\n') + 1:lines.index('xyz\n')]: ... lines.remove(line) ... >>> lines ['abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy'] Uh-oh. Try this: >>> lines = ['blah', 'fubar', 'abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy'] >>> del lines[lines.index('abc\n') + 1:lines.index('xyz\n')] >>> lines ['blah', 'fubar', 'abc\n', 'xyz\n', 'xyzzy'] >>> Of course wrapping it in try/except would be a good idea, not for the slicing, which behaves itself and does nothing if the 'abc\n' appears AFTER the 'xyz\n', but for the index() in case the sought markers aren't there. Perhaps it might be a good idea even to do it carefully one piece at a time: is the abc there? is the xyz there? is the xyz after the abc -- then del[index1+1:index2]. I wonder what the OP wants to happen in a case like this: guff1 xyz guff2 abc guff2 xyz guff3 or this: guff1 abc guff2 abc guff2 xyz guff3 > for line in lines: > print line, > > Regular expressions are better in this case Famous last words. > import re > pat = re.compile('abc\n.*?xyz\n', re.DOTALL) > print re.sub(pat, '', open('test.txt').read()) > I don't think you really meant that either. >>> lines = ['blah', 'fubar', 'abc\n', 'blah', 'fubar', 'xyz\n', 'xyzzy'] >>> linestr = "".join(lines) >>> linestr 'blahfubarabc\nblahfubarxyz\nxyzzy' >>> import re >>> pat = re.compile('abc\n.*?xyz\n', re.DOTALL) >>> print re.sub(pat, '', linestr) blahfubarxyzzy >>> Uh-oh. Try this: >>> pat = re.compile('(?<=abc\n).*?(?=xyz\n)', re.DOTALL) >>> re.sub(pat, '', linestr) 'blahfubarabc\nxyz\nxyzzy' ... and I can't imagine why you're using the confusing [IMHO] undocumented [AFAICT] feature that the first arg of the module-level functions like sub and friends can be a compiled regular expression object. Why not use this: >>> pat.sub('', linestr) 'blahfubarabc\nxyz\nxyzzy' >>> One-liner fanboys might prefer this: >>> re.sub('(?i)(?<=abc\n).*?(?=xyz\n)', '', linestr) 'blahfubarabc\nxyz\nxyzzy' >>> HTH, John From bj_666 at gmx.net Fri May 5 17:20:43 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 05 May 2006 23:20:43 +0200 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> <125ir8gpofq3i1c@corp.supernews.com> <1146798159.209695.4190@j33g2000cwa.googlegroups.com> Message-ID: In <1146798159.209695.4190 at j33g2000cwa.googlegroups.com>, OlafMeding wrote: >> IIRC it was something like an NTP daemon that caused the clock to >> "jump" a little and (Window's) sleep was confused. > > The problem is not a "jump" but a permanet lockup of the sleep statement. The "jump" of the system clock might confuse the systems `sleep` implementation. Ciao, Marc 'BlackJack' Rintsch From tganss_at_t_dash_online_dot_de-remove-all-after-first-real-dash at yahoo.com Mon May 29 03:09:50 2006 From: tganss_at_t_dash_online_dot_de-remove-all-after-first-real-dash at yahoo.com (Thomas Ganss) Date: Mon, 29 May 2006 08:09:50 +0100 Subject: Large Dictionaries In-Reply-To: <1148514158.790760.205630@i40g2000cwc.googlegroups.com> References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> Message-ID: Klaas schrieb: > 4. Insert your keys in sorted order. This advice is questionable - it depends on the at least on the db vendor and probably sometimes on the sort method, if inserting pre-sorted values is better. My gut feeling on this matter is: IF the insert times of pre-sorted values is far better than the times of unsorted values, there is a chance that the resulting tree is unbalanced: only 1 compare operation after insert and no re-balancing of the tree. re-indexing will probably give you far better access times in this case. Another option is to drop non RI indexes used only for query optimization and recreate them after batch insert. my 0.02 EUR thomas From ullrich at math.okstate.edu Wed May 31 06:17:13 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Wed, 31 May 2006 05:17:13 -0500 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> Message-ID: On 30 May 2006 21:53:32 -0700, "greenflame" wrote: >Thank you all for all of your help. Also I got the shuffle function to >work. Do not worry I will be back soon with more shuffling! However, I >do not quite understand this DSU that you mention, although it looks >useful. I didn't see any DSU in his post, although I didn't read it very carefully. DSU is "Decorate Sort Undecorate" - it's an idiom for efficient sorting. Say you have a list and you want to sort it using some custom compare function. That can be very slow. Sorting a list with the builtin comparison is much faster. DSU is a trick that lets you use the fast builtin comparison to sort according to a custom compare. Say you have a list [x,y,z], these objects have an attribute "a", and you want to sort on the "a" field. You "decorate" the list, constructing a new list of tuples [(x.a, x), (y.a, y), (z.a, z)] You sort the decorated list using the standard sort(). Tuples get compared lexicographically, so this sorts on the "a" field. Then you "undecorate" the sorted list, stripping off the first element of each tuple. ****************** That's DSU for _sorting_ a list. I read about this, thought it was pretty neat. I thought that the fact that you could use the same trick for _shuffling_ a list was my idea, gonna make me rich and famous. I guess I'm not the only one who thought of it. Anyway, you can use DSU to _shuffle_ a list by decorating the list with random numbers. In fairly old-fashioned Python: from random import random def shuffle(data): decorated = map(lambda x: (random(), x), data) decorated.sort() return map(lambda x: x[1], decorated) print shuffle(range(10)) This prints [4, 2, 7, 8, 9, 3, 5, 1, 6, 0] . Seems kinda neat - I have no idea how the efficiency compares with the standard sort of "bubble shuffle" you were trying to use in your OP, but the point is that various off-by-one errors simply don't come up. (The same thing in extremely awful Python, in case you're mystified by map and lambda: from random import random def shuffle(data): decorated = [] for x in data: decorated.append((random(), x)) decorated.sort() res = [] for x in decorated: res.append(x[1]) return res .) ************************ David C. Ullrich From ullrich at math.okstate.edu Sun May 28 09:11:29 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Sun, 28 May 2006 08:11:29 -0500 Subject: dynamic type changing References: <1148740408.226975.318050@u72g2000cwu.googlegroups.com> <44787bc6$0$19572$636a55ce@news.free.fr> <1148803636.370761.55540@j33g2000cwa.googlegroups.com> Message-ID: <638j72lp3oslcu7ar5gcmhvv9uco6dcjna@4ax.com> On 28 May 2006 01:07:16 -0700, andychambers2002 at yahoo.co.uk wrote: >>> I'm working on a "TempFile" class that stores the data in memory until >>> it gets larger than a specified threshold (as per PEP 42). Whilst >>> trying to implement it, I've come across some strange behaviour. Can >>> anyone explain this? > >>> The test case at the bottom starts a TempFile at size 50 and prints its >>> type. It then increases the size to the threshold at which point >>> "self" is changed to being a TemporaryFile. > >> Changed how ?-) > >Just by being assigned with a TemporaryFile object. I thought that if >you do > >instance = TempFile() > >that "instance" and "self" defined in the Class were the same thing so >that if you changed the class of self, the class of instance would also >change. > >Thanks very much for your example. It has solved my problem and helped >me understand a new pattern at the same time. Bruno says you _can_ assign to __class__ but calls that "risky". If you ever do feel the urge to assign a new value to some object's __class__ it might be a good idea to first make certain you can predict the behavior of the following: class A: msg = 'A' def hmm(self): print self.msg class B: msg = 'B' def hmm(self): print self.msg x = A() x.hmm() x.__class__ = B x.hmm() class C: def __init__(self): self.msg = 'C' def hmm(self): print self.msg class D: def __init__(self): self.msg = 'D' def hmm(self): print self.msg x = C() x.hmm() x.__class__ = D x.hmm() ************************ David C. Ullrich From phddas at yahoo.com Tue May 2 01:49:03 2006 From: phddas at yahoo.com (Gary Wessle) Date: 02 May 2006 15:49:03 +1000 Subject: string.find first before location Message-ID: <87hd49m0xc.fsf@localhost.localdomain> Hi I have a string like this text = "abc abc and Here and there" I want to grab the first "abc" before "Here" import string string.find(text, "Here") # I am having a problem with the next step. thanks From bussieremaillist at gmail.com Thu May 25 06:01:39 2006 From: bussieremaillist at gmail.com (bussiere) Date: Thu, 25 May 2006 12:01:39 +0200 Subject: Qrcode and python Message-ID: <000001c67fe2$3844b080$6801a8c0@Iris> I'am loooking for some information on qrcode module for python (making qrcode in python qrcode is a special kind of barcode) Or i only found japanese documentation If someone have english or french documentation i twill be nice Regards Bussiere I have some problems with this email and i dunnow if my old post i've been sent, if so excuse me -------------- next part -------------- An HTML attachment was scrubbed... URL: From chris.cavalaria at free.fr Thu May 18 10:52:46 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 16:52:46 +0200 Subject: Question about exausted iterators In-Reply-To: <6K%ag.432621$_c4.11671650@phobos.telenet-ops.be> References: <446b48e2$0$5293$626a54ce@news.free.fr> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <446c7f44$0$7128$626a54ce@news.free.fr> <6K%ag.432621$_c4.11671650@phobos.telenet-ops.be> Message-ID: <446c8a64$0$7121$626a54ce@news.free.fr> Roel Schroeven a ?crit : > Fredrik Lundh schreef: >> so what is a valid answer? > > > I think he wants to know why the spec has been written that way. > > The rationale mentions exhausted iterators: > > "Once a particular iterator object has raised StopIteration, will > it also raise StopIteration on all subsequent next() calls? > Some say that it would be useful to require this, others say > that it is useful to leave this open to individual iterators. > Note that this may require an additional state bit for some > iterator implementations (e.g. function-wrapping iterators). > > Resolution: once StopIteration is raised, calling it.next() > continues to raise StopIteration." > > This doesn't, however, completey answer the OP's question, I think. It > is about raising or not raising StopIteration on subsequent next() calls > but doesn't say anything on possible alternatives, such as raising > another exception (I believe that's what the OP would like). Exactly ! > Not that I know of use cases for other exceptions after StopIteration; > just clarifying what I think the OP means. There are no use cases yet for me. I want those exceptions as an hard error for debuging purposes. From ptmcg at austin.rr._bogus_.com Sun May 28 10:56:44 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 28 May 2006 14:56:44 GMT Subject: unexpected behaviour for python regexp: caret symbol almost useless? References: <1148815719.082410.313870@38g2000cwa.googlegroups.com> Message-ID: "conan" wrote in message news:1148815719.082410.313870 at 38g2000cwa.googlegroups.com... > This regexp > '' > > works well with 'grep' for matching lines of the kind > > > on a XML .glade file > As Peter Otten has already mentioned, this is the difference between the re "match" and "search" methods. As purely a lateral exercise, here is a pyparsing rendition of your program: ------------------------------------ from pyparsing import makeXMLTags, line # define pyparsing patterns for begin and end XML tags widgetStart,widgetEnd = makeXMLTags("widget") # read the file contents glade_file_name = 'some.glade' gladeContents = open(glade_file_name).read() # scan the input string for matching tags for widget,start,end in widgetStart.scanString(gladeContents): print "good:", line(start, gladeContents).strip() print widget["class"], widget["id"] print "Class: %(class)s; Id: %(id)s" % widget ------------------------------------ Not quite an exact match, only the good lines get listed. But also check out some of the other capabilities. To do this with re's, you have to clutter up the re expression with field names, as in: (r'".*") id="(?P.*)">') The parsing patterns generated by makeXMLTags give dict-like and attribute-like access to any attributes included with the tag. If not for the unfortunate attribute name "class" (which is a Python keyword), you could also reference these values as widget.class and widget.id. If you are parsing HTML, there is also a makeHTMLTags method, which creates patterns that are less rigid about upper/lower case and other XML strictnesses. -- Paul From me at privacy.net Tue May 16 14:47:11 2006 From: me at privacy.net (Dan Sommers) Date: Tue, 16 May 2006 14:47:11 -0400 Subject: round numbers in an array without importing Numeric or Math? References: <446a1748$0$61168$ae4e5890@news.nationwide.net> <446a1ce0$0$61167$ae4e5890@news.nationwide.net> Message-ID: On Tue, 16 May 2006 13:41:37 -0500, Lance Hoffmeyer wrote: > May have a complicating issue with the array? Have > the numbers have been interpreted as strings? I have > been pulling them from a Word doc using regex's > print Test > [u'9.0', u'58.6', u'97.8', u'10.0', u'9.6', u'28.1'] Then you'll have to convert your strings to floats first: [int(float(x)+0.5) for x in Test] HTH, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From fb at frank-buss.de Sun May 7 15:50:37 2006 From: fb at frank-buss.de (Frank Buss) Date: Sun, 7 May 2006 21:50:37 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <1vspxcmldcqa5.t1b4abyraqom.dlg@40tude.net> <1heytyi.lope5l1p029gfN%aleaxit@yahoo.com> <19qhkvgj0bdmg.1ex2haasqrgrj.dlg@40tude.net> <1heyw5k.1997033mne3xrN%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > Not sure what the &key means here, but omitting that > > def black_white(function, limit): > def result(x,y): > if function(x, y) > limit: return 1.0 > else: return 0.0 > return result &key is something like keyword arguments in Python. And looks like you are right again (I've tested it in Pyhton) and my assumption was wrong, so the important thing is to support closures, which Python does, even with local function definitions. -- Frank Buss, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From lcaamano at gmail.com Tue May 9 14:20:17 2006 From: lcaamano at gmail.com (lcaamano) Date: 9 May 2006 11:20:17 -0700 Subject: Finding defining class in a decorator In-Reply-To: <1147193305.181356.48930@i40g2000cwc.googlegroups.com> References: <1147183919.996287.60140@j73g2000cwa.googlegroups.com> <1147193305.181356.48930@i40g2000cwc.googlegroups.com> Message-ID: <1147198817.198903.80970@y43g2000cwc.googlegroups.com> Nice. I had to call _getframe(2) to account for the wrapper but the idea seems to work OK, that is, save the name of the decorator's original caller at definition time while creating the wrapper function. Much better than doing that at runtime. Thanks -- Luis P Caamano Atlanta, GA USA From ptmcg at austin.rr._bogus_.com Tue May 16 22:33:54 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 17 May 2006 02:33:54 GMT Subject: help with a function References: <446a85c6$0$61170$ae4e5890@news.nationwide.net> Message-ID: "Lance Hoffmeyer" wrote in message news:446a85c6$0$61170$ae4e5890 at news.nationwide.net... > Hey all, > > I'm new to python. I keep getting an error when running this. > I'm sure there is an easy fix but I can't figure it out. > What am I doing wrong? How do I fix it? > > def even_odd_round(num): > if(round(num,2) + .5 == int(round(num,2)) + 1): > if(int(num,0) % 2): #an odd number > rounded_num = round(num,2) + .1 > else: #an even number > rounded_num = round(num,2) - .1 > rounded_num = int(rounded_num) > return rounded_num > > even_odd_round(5.5) > > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in even_odd_round > TypeError: int() can't convert non-string with explicit base > >>> 1 def even_odd_round(num): 2 if(round(num,2) + .5 == int(round(num,2)) + 1): 3 if(int(num,0) % 2): #an odd number 4 rounded_num = round(num,2) + .1 5 else: #an even number 6 rounded_num = round(num,2) - .1 7 rounded_num = int(rounded_num) 8 return rounded_num 9 10 even_odd_round(5.5) > Traceback (most recent call last): > File "", line 1, in ? > File "", line 3, in even_odd_round > TypeError: int() can't convert non-string with explicit base This From ag at mirada-solutions.com Thu May 25 09:56:26 2006 From: ag at mirada-solutions.com (Alexandre Guimond) Date: 25 May 2006 06:56:26 -0700 Subject: tkFileDialog.Open to select a large number of files Message-ID: <1148565386.640017.146030@u72g2000cwu.googlegroups.com> Hi. I've noticed that when i select a large number of files (> 400) using tkFileDialog.Open i get an empty list. Does anyone knows the limits of that interface regarding the maximum number of files that can be selected, or the maximum length of the resulting list? Does anyone have any work around? thx. alex. From deets at nospam.web.de Thu May 18 10:35:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 May 2006 16:35:11 +0200 Subject: Question about exausted iterators References: <446b48e2$0$5293$626a54ce@news.free.fr> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <446c7f44$0$7128$626a54ce@news.free.fr> Message-ID: <4d3f10F18q0d9U1@uni-berlin.de> Christophe wrote: > Fredrik Lundh a ?crit : >> Christophe wrote: >> >>> Because I'm still waiting for a valid answer to my question. The >>> answer "Because it has been coded like that" or is not a valid one. >> >> >> it's been coded like that because that's what the specification says: >> >> http://www.python.org/dev/peps/pep-0234/ > > I didn't though I had to mention that "Because the spec has been writen > like that" wasn't a valid answer either. The important thing is: it _is_ specified. And what about code like this: iterable = produce_some_iterable() for item in iterable: if some_condition(item) break do_something() for item in iterable: do_something_with_the_rest() If it weren't for StopIteration raised if the iterable was exhausted, you'd have to clutter that code with something like try: for item in iterable: do_something_with_the_rest() except IteratorExhausted: pass What makes you say that this is better than the above? Just because _you_ had some cornercases that others seems not to have (at least that frequently, I personally can't remember I've ever bitten by it) isn't a valid reason to _not_ do it as python does. Besides that: it would be a major change of semantics of iterators that I seriously doubt it would make it into anything before P3K. So - somewhat a moot point to discuss here I'd say. Diez From a.schmolck at gmail.com Fri May 12 19:42:40 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 13 May 2006 00:42:40 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Duane Rettig writes: > My reason for responding to you in the first place was due to your poor use > of the often misused term "bug". You could have used many other words or > phrases to describe the situation, and I would have left any of those alone. I'm happy to accept your terminology of bug (not conforming to a certain specification) for the remainder of this discussion so that we can stop quibbling over words. [...] > > I'd be even more interested in what you think (seriously; should > > you consider it a design feature (for reasons other than backwards > > compatiblity constraints), I'm pretty sure you would also give a justification > > that would merrit consideration). > > Well, OK, let's change the conversation away from "bug"-ness and toward any of > the other negatives we discussed above. I actually doubt that I can provide > a justification in a small space without first understanding who you are > and from what background you are coming, so let me turn it around and ask > you instead to knock down a straw-man: > > You seem to be saying that pure lexical transparency is always preferable > to statefulness (e.g. context). No. > Can we make that leap? If not, set me straight. I think that in most contexts lexical transparency is desirable so that deviations from lexical transparency ought to be well motivated. I also believe that a construct that is usually used to establish a lexically transparent binding shouldn't be equally used for dynamic bindings so that it isn't syntactically obvious what's going on. I've already provided some reasons why CL's design wrt. binding special and lexical variables seems bad to me. I don't think these reasons were terribly forceful but as I'm not aware of any strong motivation why the current behaviour would be useful I'm currently considering it a minor wart. To make things more concrete: What would be the downside of, instead of doing something like: (let ((*x* ...)) [(declare (special *x*))] ...) ; where [X] denotes maybe X doing any of the below: a) using a different construct e.g. (fluid-let ((*x* ...)) ...) for binding special variables b) having to use *...* (or some other syntax) for special variables c) using (let ((q (special *x*) (,a ,b , at c)) (values 1 2 '(3 4 5 6))) (list q ((lambda () (incf *x*))) a b c)) ; => (1 3 3 4 (5 6)) (It's getting late, but hopefully this makes some vague sense) > If so, tell me: how do we programmatically model those situations in life > which are inherently contextual in nature, where you might get a small piece > of information and must make sense of it by drawing on information that is > _not_ given in that information, but is (globally, if you will) "just known" > by you? How about conversations in English? And, by the way, how do you > really know I'm writing to you in English, and not some coded language that > means something entirely different? We can skip that part. 'as From 63q2o4i02 at sneakemail.com Tue May 16 16:03:53 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 16 May 2006 13:03:53 -0700 Subject: Using python for a CAD program In-Reply-To: <1147808333.652756.5180@u72g2000cwu.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <1147808333.652756.5180@u72g2000cwu.googlegroups.com> Message-ID: <1147809833.650020.142570@j33g2000cwa.googlegroups.com> Yes, I figured I should be pretty expert at what's out there first before redoing something and making in inferior to the existing solution. I took a quick peek at cadence courses, and they're out of my personal price range. I have a new job coming up which should lead into IC design after some time, and I should probably ask them to send me to the course. From tim.leeuwvander at nl.unisys.com Tue May 16 11:24:08 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 16 May 2006 08:24:08 -0700 Subject: Windows & Apache 1.3 & mod_python.dll In-Reply-To: <1147792362.619557.74360@j33g2000cwa.googlegroups.com> References: <1147792362.619557.74360@j33g2000cwa.googlegroups.com> Message-ID: <1147793048.514488.103130@g10g2000cwb.googlegroups.com> Any particular reason for not using Apache 2, and mod_python 3.x? Anyways, looks to me like there's a problem with the path where the DLL is installed, vs. where it's search for by Apache? I had no particular problems installing Apache 2 and mod_python 3.x on WinXP, using the mod_python installer. Sorry, but that's best I can offer! From python.list at tim.thechases.com Fri May 26 13:42:32 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 26 May 2006 12:42:32 -0500 Subject: sort a dictionary by keys in specific order In-Reply-To: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> References: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> Message-ID: <44773E08.4090900@tim.thechases.com> > hi i have a normal dictionary with key and value pairs. now i wanna > sort by the keys BUT in a specific order i determine in a list !? any > ideas > > dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'} > > list = [key2, key3, key1] 1) it's bad practice to shadow the list() command...funky stuff can happen. 2) I presume your list is a list of strings, not of references: order = ['key2', 'key3', 'key1'] 3) As a dictionary is an unordered collection, I presume you want a resulting list of key/value pairs. If both #2 and #3 hold, you can use results = [(k,dic[k]) for k in order] which will return a list of tuples in the desired key order. -tkc From edmond at le-comte-de-monte-cristo.biz Wed May 17 18:40:40 2006 From: edmond at le-comte-de-monte-cristo.biz (Edmond Dantes) Date: Wed, 17 May 2006 18:40:40 -0400 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> <1147796116.826750@elch.in-berlin.de> Message-ID: <1147905290_7@news-east.n> Oliver Bandel wrote: > opalpa at gmail.com opalinski from opalpaweb wrote: ... > Yes, as I started programming I also preferred tabs. > And with growing experience on how to handle this in true life > (different editors/systems/languages...) I saw, that > converting the "so fine tabs" was annoying. > > The only thing that always worked were spaces. > Tab: nice idea but makes programming an annoyance. > > Ciao, > Oliver It all depends on your editor of choice. Emacs editing of Lisp (and a few other languages, such as Python) makes the issue more or less moot. I personally would recommend choosing one editor to use with all your projects, and Emacs is wonderful in that it has been ported to just about every platform imaginable. The real issue is, of course, that ASCII is showing its age and we should probably supplant it with something better. But I know that will never fly, given the torrents of code, configuration files, and everything else in ASCII. Even Unicode couldn't put a dent in it, despite the obvious growing global development efforts. Not sure how many compilers would be able to handle Unicode source anyway. I suspect the large majority of them would would choke big time. Oh well... -- -- Edmond Dantes, CMC And Now for something Completely Different: http://gift-basket.prosperitysprinkler.com http://sewing-machine.womencraft.com http://coveralls.whiteboystuff.com http://eyewear.blackboystuff.com http://dinette.funiturenow.com http://wheels.whiteboystuff.com http://patio.funiturenow.com Posted Via Usenet.com Premium Usenet Newsgroup Services ---------------------------------------------------------- ** SPEED ** RETENTION ** COMPLETION ** ANONYMITY ** ---------------------------------------------------------- http://www.usenet.com From iddw at hotmail.com Wed May 17 14:53:18 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 17 May 2006 13:53:18 -0500 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <_2Jag.88816$dW3.57801@newssvr21.news.prodigy.com> Message-ID: On Wed, 17 May 2006 17:28:26 GMT in comp.lang.python, Edward Elliott wrote: >Sybren Stuvel wrote: > >> Andy Sy enlightened us with: >>> Like I said, you'll *NEVER* get that fancy shmancy 'semantic >>> indentation' idea to work properly in the most basic utilities which >>> have the 8-space tabs assumption hardcoded in them. >> >> Fair enough. How much code is viewed with less and cat, and how much >> is viewed using smart viewers/editors? I think the majority is viewed >> using the latter. > >Just for the sake of completeness: > >cat file |sed 's/\t/ /g' That doesn't always work. If you don't see why, you don't understand my objection to TAB characters in text files. >less -x4 file That will work. As long as the creator of file used four-space TABs, anyway... Regards, -=Dave -- Change is inevitable, progress is not. From maxm at mxm.dk Wed May 31 10:27:40 2006 From: maxm at mxm.dk (Max M) Date: Wed, 31 May 2006 16:27:40 +0200 Subject: Variable name has a typo, but code still works. Why? In-Reply-To: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> Message-ID: <447da771$0$38682$edfadb0f@dread12.news.tele.dk> mateus wrote: > print "hello world" > > I have a nested loop where the outer loop iterates over key value pairs > of a dictionary and the inner loop iterates over a list each list of > which is a mapped value from the dictionary > > def showReport(self): > for dev, sessions in self.logger.items(): > for tree in session: > self.addTestItem(self, tree) > > What I don't understand is why this executes w/o any problems when > "sessions" was spelled as plural (sessionS) while later being spelled > in the singular (session). > > Is there some type of name resolution of local variables where Python > makes assumptions? No. You are probably running your script in an ide that keeps an old variable hanging around. Try it from a command promt. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From steve at holdenweb.com Wed May 24 06:56:06 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 May 2006 11:56:06 +0100 Subject: how to change sys.path? In-Reply-To: <1148434309.969730.50700@i39g2000cwa.googlegroups.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <4473867f$0$7721$626a54ce@news.free.fr> <1148434309.969730.50700@i39g2000cwa.googlegroups.com> Message-ID: Ju Hui wrote: > yes, we can change PYTHONPATH to add some path to sys.path value, but > how to remove item from sys.path? > That would be del sys.path[3] for example. Of course you may need to search sys.path to determine the exact element you need to delete, but sys.path is just like any other list in Python and can (as many people have already said in this thread) be manipulated just like al the others. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From sybrenUSE at YOURthirdtower.com.imagination Wed May 17 10:16:02 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 17 May 2006 16:16:02 +0200 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: Andy Sy enlightened us with: > Now... if you say you SHOULDN'T mix tabs and spaces (indeed this is > generally regarded as a BAD idea esp. in Python code) I indeed say so. > then WHAT THE HECK do you need to use tab characters in the source > code for anyway (besides saving a measly few bytes) ??!? To separate layout (how much indentation is used) from semantics (how many intentation levels). > Tab characters are EVIL *AND* STUPID. And someone who needs to resort to all-caps words (which many consider shouting) needs to relax and use proper arguments. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From ask at me Thu May 11 08:01:33 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 08:01:33 -0400 Subject: redirecting print to a a file Message-ID: <7JudnYwllewrrv7ZRVn-vA@comcast.com> Hi, Can I redirect print output, so it is send to a file, not stdout. I have a large program and would like to avoid touching hundreds of print's. Thx, Andy From catdude at catfolks.net Fri May 12 11:08:07 2006 From: catdude at catfolks.net (CatDude) Date: Fri, 12 May 2006 08:08:07 -0700 Subject: where do you run database scripts/where are DBs 'located'? References: Message-ID: On Fri, 12 May 2006 14:01:51 +0000, John Salerno wrote: > Ok, I've been browsing through the MySQLdb docs, and I *think* I know > the kind of code I need to write (connect, cursor, manipulate data, > commmit, etc. -- although I probably need to get more familiar with > actual SQL commands too), but here's my problem: I don't know where > these scripts are supposed to be executed, or how they are supposed to > 'find' the database. I'm kind of a noob myself, but I'll see if I can't offer some useful info anyhow. When you issue your MySQLdb.connect, that determines where the database actions occur. If you specify "host='localhost'", then you are trying to connect to your local machine. If you specify "host='db.smurgle.net'", you're trying to connect to my home db server. You can specify the hostname in any format that your local machine understands; for example, if you are on a Linux box, and your /etc/hosts file contains a line like: 10.0.0.10 myDBserver then you can use "host='myDBserver'". This isn't so much a web programming issue as it is using MySQL's network interface. MySQL by default uses port 3306 (I think) to handle database connections over the network. > But my question is, can these DB scripts be executed anywhere, and they > will find the DB based on the connect() parameters? Or do I need to do > something special with them? It seems like a similar problem to when you > don't have your PYTHONPATH variable set up properly. I've tried some DB > stuff, but it doesn't seem to work. Your scripts that make connections can be executed from anywhere that: 1) knows how to communicate with the specified database server, and 2) has some sort of MySQL client available. > So without actually giving you some code and tracebacks, is there any > general advice about how to set up these scripts? Also, is there any > better documentation than this: > http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307 If you are having problems, by all means post some code. > It doesn't seem too thorough, and it also doesn't cover actual SQL > queries that you'd have to pass to the query method. Maybe I will just > have to find that information in a MySQL tutorial. A couple of good MySQL tutorials would most likely be a big help. The standard docs (the ones you pointed out) are not of a great deal of help if you're totally new to SQL. You might want to do a Google search. This will lead you to pages like: http://www.kitebird.com/articles/pydbapi.html http://www.devshed.com/c/a/Python/MySQL-Connectivity-With-Python/ and the like. Dan From http Thu May 25 21:58:52 2006 From: http (Paul Rubin) Date: 25 May 2006 18:58:52 -0700 Subject: Speed up this code? References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> Message-ID: <7x8xopv95v.fsf@ruckus.brouhaha.com> aomighty at gmail.com writes: > Does anybody know a faster way to do this? (finding the difference all > items in list a that are not in list b)? >>> a = [3, 7, 16, 1, 2, 19, 13, 4, 0, 8] # random.sample(range(20),10) >>> b = [15, 11, 7, 2, 0, 3, 9, 1, 12, 16] # similar >>> sorted(set(a)-set(b)) >>> [4, 8, 13, 19] but you probably don't want to use that kind of implementation. Here's a version using generators: def sieve_all(n = 100): # yield all primes up to n stream = iter(xrange(2, n)) while True: p = stream.next() yield p def s1(p, stream): # yield all non-multiple of p return (q for q in stream if q%p != 0) stream = s1(p, stream) # print all primes up to 100 print list(sieve_all(100)) It's cute, but horrendous once you realize what it's doing ;-) From john at castleamber.com Tue May 23 09:49:09 2006 From: john at castleamber.com (John Bokma) Date: 23 May 2006 13:49:09 GMT Subject: freeze tool like perl2exe? References: <1148329713.916486.68410@i40g2000cwc.googlegroups.com> Message-ID: Jarek Zgoda wrote: > Jerry napisal: > >> I am looking for a freeze tool for Python that is similar to perl2exe >> in that I can "compile" a script on one platform that is built for >> another. Basically, I would like to be able to build a Python script >> for Solaris using my Windows workstation. Is there any tool that fits >> the bill? > > AFAIK Python tools like py2exe tend to bundle together whole VM > (interpreter + all needed library modules) along with your code. Anyway, > I didn't use (nor even find) anything similar. Afaik perl2exe and the free PAR tool do this as well (I am sure about PAR). -- 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 skip at pobox.com Mon May 29 22:38:38 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 29 May 2006 21:38:38 -0500 Subject: Any other config parsing modules besides ConfigParser ? In-Reply-To: <16de708d0605290147p18a392qaf28102c0fbfe08e@mail.gmail.com> References: <16de708d0605290147p18a392qaf28102c0fbfe08e@mail.gmail.com> Message-ID: <17531.45102.613556.823956@montanaro.dyndns.org> Arthur> Are there any other good config parser modules for python? I am Arthur> looking for something a bit more versatiles than ConfigParser. You'll need to evaluate the candidates, but this might be a useful place to start looking: http://wiki.python.org/moin/ConfigParserShootout Skip From nobody at 127.0.0.1 Tue May 16 23:12:56 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 03:12:56 GMT Subject: [silly] Does the python mascot have a name ? References: Message-ID: Carl J. Van Arsdall wrote: > Well, we could call the perl camel Joe but I don't know if the perlcores > (read: hardcore PERL users) would be down for that ;) Hmmm. Perl is like smoking, it feels great and gives you cancer. Yes, there's definitely potential here. ;) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From vbgunz at gmail.com Fri May 26 06:15:55 2006 From: vbgunz at gmail.com (vbgunz) Date: 26 May 2006 03:15:55 -0700 Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148636521.026385.171410@y43g2000cwc.googlegroups.com> Message-ID: <1148638555.440810.277540@i40g2000cwc.googlegroups.com> > You perhaps shouldn't become so excited. Next time, if you're not sure of > the correctness of your solution, try to wait a bit before posting it, > and see if someone other comes up with the same thing you would have posted. George, if Frederik's first reply was replaced with yours chances are this little waste of time would have never had taken place. I am not an animal and I am capable of understanding my mistakes but trying to embarass me and belittle me in front of all of my peers here when all I tried to do was help is absolutely pathetic the first time around. I don't try to come off as a know it all here and I don't feel I should post a gospel warning label on my help signature but Fredrik could have delivered his message in a much better tone. I too am learning Python and if maybe my answer was not evident enough of that then how smart is Fredrik to persecute me for it? I don't wish to question Fredriks knowledge or his position in the whole scheme of Python but to disrespect me in the name of arrogance and call it just is a mislabel. I don't wish to carry on with this, I don't... I just have no love for a bully and Fredrik is proving himself to be just that. Good day George! From bdesth.quelquechose at free.quelquepart.fr Fri May 5 18:49:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 06 May 2006 00:49:10 +0200 Subject: easy way to dump a class instance? In-Reply-To: <1146856353.555944.281870@i39g2000cwa.googlegroups.com> References: <8SL6g.73271$H71.63860@newssvr13.news.prodigy.com> <1146856353.555944.281870@i39g2000cwa.googlegroups.com> Message-ID: <445ba79e$0$30111$636a55ce@news.free.fr> Kamilche a ?crit : > Mark Harrison wrote: > >>Is there a way to automatically print all the instance >>data in a class? > > > print self.__dict__ > Yeps - if you don't mind missing class attributes and data descriptors. From nobody at 127.0.0.1 Thu May 4 02:30:10 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 04 May 2006 06:30:10 GMT Subject: stripping unwanted chars from string References: <44598a93$1@news.eftel.com> Message-ID: Bryan wrote: > >>> keepchars = set(string.letters + string.digits + '-.') Now that looks a lot better. Just don't forget the underscore. :) From andrew.arobert at gmail.com Fri May 5 12:33:37 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Fri, 05 May 2006 12:33:37 -0400 Subject: MQSeries based file transfers using the pymqi module Message-ID: <125mvj5pmi2au7e@corp.supernews.com> Hi everyone, Has anyone developed a pymqi module based file transfer method for use with WebSphere MQSeries v5.3? If so, would it be possible to point me towards examples of how this was done? Any help that can be provided would be greatly appreciated. Thanks From kay.schluehr at gmx.net Tue May 23 15:11:36 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 23 May 2006 12:11:36 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <44681F95.9040400@gmail.com> Message-ID: <1148411496.691868.53440@j73g2000cwa.googlegroups.com> Ken Tilton wrote: > Is there any experiemntal macro package out there for Python? Maybe a > preprocessor, at least? Or are there ways to actually hack Python to > extend the syntax? Yes. I've just released EasyExtend that does this kind of job: http://www.fiber-space.de/EasyExtend/doc/EE.html It fits quite nice with Python and is conceptually simple, safe and reasonably fast. Using EasyExtend PyCells could be made an own language ( including Python ) defined in a Python package ( i.e. no C-code and complex build process is required ). I would be interested in user experience. I wouldn't consider EE as "experimental" i.e. open for severe changes. It still lacks some comfort but it also improves gradually in this respect. From roy at panix.com Sat May 13 21:48:54 2006 From: roy at panix.com (Roy Smith) Date: Sat, 13 May 2006 21:48:54 -0400 Subject: Question regarding checksuming of a file References: <126d1u4ke4itg7f@corp.supernews.com> Message-ID: In article <126d1u4ke4itg7f at corp.supernews.com>, Andrew Robert wrote: > Good evening, > > I need to generate checksums of a file, store the value in a variable, > and pass it along for later comparison. > > The MD5 module would seem to do the trick but I'm sketchy on implementation. > > > The nearest I can see would be > > import md5 > > m=md5.new() > contents = open(self.file_name,"rb").read() > check=md5.update(contents) > > However this does not appear to be actually returning the checksum. > > Does anyone have insight into where I am going wrong? After calling update(), you need to call digest(). Update() only updates the internal state of the md5 state machine; digest() returns the hash. Also, for the code above, it's m.update(), not md5.update(). Update() is a method of an md5 instance object, not the md5 module itself. Lastly, the md5 algorithm is known to be weak. If you're doing md5 to maintain compatability with some pre-existing implementation, that's one thing. But, if you're starting something new from scratch, I would suggest using SHA-1 instead (see the sha module). SHA-1 is much stronger cryptographically than md5. The Python API is virtually identical, so it's no added work to switch to the stronger algorithm. From andrew.arobert at gmail.com Tue May 16 14:28:14 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 16 May 2006 14:28:14 -0400 Subject: Option parser question - reading options from file as well as command line In-Reply-To: References: <126k3273j7kb28f@corp.supernews.com> Message-ID: <126k6ed517nf73e@corp.supernews.com> Max Erickson wrote: > Andrew Robert wrote in > news:126k3273j7kb28f at corp.supernews.com: > <\snip> > Check parser.usage, it is likely to look a lot like your infile. > > I'm not sure, but I think you need to pass your alternative arguments > to parser.parse_args. > > max > Hi Max, I tried passing in the read line like so: infile= open(sys.argv[1],"rb").read() parser=OptionParser() print infile (options, args) = parser.parse_args(infile) I end up getting the following traceback. Traceback (most recent call last): File "C:\Documents and Settings\Andrew Robert\My Documents\receiver.py", line 327, in ? (options, args) = parser.parse_args(infile) File "C:\Python24\lib\optparse.py", line 1275, in parse_args stop = self._process_args(largs, rargs, values) File "C:\Python24\lib\optparse.py", line 1322, in _process_args del rargs[0] TypeError: object doesn't support item deletion Any ideas? From khoa.coffee at gmail.com Wed May 17 14:05:15 2006 From: khoa.coffee at gmail.com (Khoa Nguyen) Date: Wed, 17 May 2006 14:05:15 -0400 Subject: Pyparsing: Grammar Suggestion. 2nd thought Message-ID: <3d00e6dc0605171105u3ff919ffke9e07b6b6f71dc08@mail.gmail.com> > > for tokens,start,end in commaSeparatedList.scanString(data): > print tokens > > > This returns: > > ['f1', 'f2', 'f3', 'f4', 'f5', 'f6'] > ['f1', 'f2'] > ['f1', 'f2', '', 'f4', '', 'f6'] > Thanks for your reply. This looks promising, but I have a few more questions: 1. If f(i) is non-terminal (e.g f(i) is another grammar expression), how would I adapt your idea to a more generic way? 2. The field delimiter is not always ',' in my case. So I guess I'll have to use delimtedList instead? Thanks again, Khoa ======== On 2nd thought, I don't think this will check for the correct order of the fields. For example, the following would be incorrectly accepted: f1,f5,f2 END_RECORD Thanks, Khoa From umut.tabak at gmail.com Wed May 3 11:40:03 2006 From: umut.tabak at gmail.com (utab) Date: 3 May 2006 08:40:03 -0700 Subject: Numeric Python Message-ID: <1146670803.379440.19010@g10g2000cwb.googlegroups.com> Dear all, I am new to python however not new to programming world, I have got the Numeric package I think because the output seems OK >>> from Numeric import * >>> seems OK but when I try to view a picture file which is supplied in the install and test documentation of numpy it fails >>>view(greece) Traceback (most recent call last): File "", line 1, in ? NameError: name 'view' is not defined There it is written that the numpy directory must be under the demo directory but I do not have a demo directory under the python directory. Sth is missing I guess but could not figure out, actually I did not have much time to search and find the error :) , hope for your understanding. I am seeking a step by step installation description so your help is very much appreciated. Regards, U.T. From OlafMeding at noSpam.compuserve.com Thu May 4 08:24:32 2006 From: OlafMeding at noSpam.compuserve.com (Olaf Meding) Date: Thu, 4 May 2006 07:24:32 -0500 Subject: Because of multithreading semantics, this is not reliable. References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <1146691613.911363.242620@e56g2000cwe.googlegroups.com> <4459c03b$0$2633$636a55ce@news.free.fr> Message-ID: <4459f1dd$1_2@newspeer2.tds.net> > return result before that line, some other thread added a value ! Sure, but that is the nature of using threads and a mutex. I hope you are you not saying that every function that uses a mutex should have a comment saying this is not "reliable"? Olaf From eurleif at ecritters.biz Mon May 22 10:39:49 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 22 May 2006 10:39:49 -0400 Subject: enumerate() question In-Reply-To: <1148308146.493287.323770@38g2000cwa.googlegroups.com> References: <1148308146.493287.323770@38g2000cwa.googlegroups.com> Message-ID: <4471cc31$0$3688$4d3efbfe@news.sover.net> Gregory Petrosyan wrote: > Hello! > I have a question for the developer[s] of enumerate(). Consider the > following code: > > for x,y in coords(dots): > print x, y > > When I want to iterate over enumerated sequence I expect this to work: > > for i,x,y in enumerate(coords(dots)): > print i, x, y > > Unfortunately, it doesn't =( and I should use (IMHO) ugly > > for i,pair in enumerate(coords(dots)): > print i, pair[0], pair[1] Use: for i, (x, y) in enumerate(coords(dots)): print i, x, y > So, why enumerate() works this way and is there any chance of changing > the behaviour? Because enumerate has no way to distinguish between iterables you do and don't want unpacked. So, for example, this wouldn't work under your proposal: for index, string in ["foo", "bar", "baz"]: print "String number %s is %s." % (index, string) But this would: for index, x, y, z in ["foo", "bar", "baz"]: print "First character of string number %s is %s." % (index, x) From lolmcbride at googlemail.com Thu May 11 02:13:25 2006 From: lolmcbride at googlemail.com (lolmcbride at googlemail.com) Date: 10 May 2006 23:13:25 -0700 Subject: python sqlite3 api question In-Reply-To: References: <1147282942.425241.214990@g10g2000cwb.googlegroups.com> Message-ID: <1147328005.086459.107140@q12g2000cwa.googlegroups.com> Ah, je comprend. Thanks for pointing that out to me - I'll just have to spend more time at the code face to get the job done. Many thanks, Lol From scott.daniels at acm.org Mon May 15 16:00:01 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 15 May 2006 13:00:01 -0700 Subject: common practice for creating utility functions? In-Reply-To: References: Message-ID: <4468d9d5$1@nntp0.pdx.net> John Salerno wrote: >> How can I create two separate conditions in a for loop? >... > I tried this: > > punc_space = string.punctuation + string.whitespace > for char in punc_space: That's probably best. If the sources are not so simple, you could use: import itertools for char in itertools.chain(onesource, anothersource, yetanother): ... --Scott David Daniels scott.daniels at acm.org From Serge.Orlov at gmail.com Mon May 1 08:21:11 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 May 2006 05:21:11 -0700 Subject: How to prevent this from happening? References: <1146452135.108199.109180@e56g2000cwe.googlegroups.com> Message-ID: <1146486071.637284.240240@i39g2000cwa.googlegroups.com> phil_nospam_schmidt at yahoo.com wrote: > Regarding this expression: 1 << x > > I had a bug in my code that made x become Very Large - much larger than > I had intended. This caused Python, and my PC, to lock up tight as a > drum, and it appeared that the Python task (Windows XP) was happily and > rapidly consuming all available virtual memory. > > Presumably, Python was trying to create a really really long integer, > just as I had asked it. > > Is there a way to put a limit on Python, much like there is a stack > limit, so that this sort of thing can't get out of hand? This is a general problem regardless of programming language and it's better solved by OS. Windows has API for limiting resource usage but it lacks user tools. At least I'm not aware of them, maybe *you* can find them. There is Windows System Resource Manager http://www.microsoft.com/technet/downloads/winsrvr/wsrm.mspx It won't run on Windows XP, but you may take a look at its distribution CD image. If you're lucky maybe there is a command line tool for Windows XP. Alternatively you can switch to a better OS ;) Any Unix-like (Max OS X, Linux, *BSD, etc...), they all have resource usage limiting tools out of the box. From phddas at yahoo.com Sun May 7 13:03:15 2006 From: phddas at yahoo.com (Gary Wessle) Date: 08 May 2006 03:03:15 +1000 Subject: Numerical Python Tutorial errors Message-ID: <87fyjlaht8.fsf@localhost.localdomain> Hi is the Numerical Python tutorial maintained? http://www.pfdubois.com/numpy/html2/numpy.html seams to have some errors and no email to mail them to when found. if interested, read about the errors below **************************************************************** (1) http://www.pfdubois.com/numpy/html2/numpy-6.html#pgfId-35606 Creating arrays from scratch the html showing code lines below on the top of text lines from the surrounding paragraphs, I was surprise to be able to copy and paste the lines below as they are not visually clear on the page. >>> x,y,z = 1,2,3 >>> a = array([x,y,z]) # integers are enough for 1, 2 and 3 >>> print a [1 2 3] >>> a = array([x,y,z], Float) # not the (2) http://www.pfdubois.com/numpy/html2/numpy-5.html#pgfId-57136 Universal Functions >>> print add.reduce([1,2,4,5]) 12 # 1 + 2 + 3 + 4 + 5 <---- is 12 # 1 + 2 + 4 + 5 <---- should be From cvanarsdall at mvista.com Wed May 24 15:49:38 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 24 May 2006 12:49:38 -0700 Subject: simple print is not working.. In-Reply-To: <1148499666.824598.313720@i40g2000cwc.googlegroups.com> References: <1148499666.824598.313720@i40g2000cwc.googlegroups.com> Message-ID: <4474B8D2.5010706@mvista.com> lahirister at gmail.com wrote: > What is wrong with this script? > > #!/usr/bin/python > fsfile = open('/tmp/fs_info.al', 'r') > for line in fsfiles.readlines(): > print line > fsfile.close() > > > Did you cut and paste that code? I see a couple typos First, on the line for line in fsfiles.readlines(): There's an extra s in fsfile Secondly, the line: print line should have an indentation to denote that its the block of code that the for loop will execute on. .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From n.estner at gmx.de Fri May 5 08:15:46 2006 From: n.estner at gmx.de (nikie) Date: 5 May 2006 05:15:46 -0700 Subject: Can I use python for this .. ?? References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> Message-ID: <1146831346.298953.144110@e56g2000cwe.googlegroups.com> san wrote: > Hi > > I am using windows xp and have installed python and win32. I am > familiar with basic Python. I wanted to control some of the > applications via python script. > > I would like to write a python script to say: > 1. Open firefox and log on to gmail > 2. Another firefox window to visit slickdeals > 3. Open winamp and tune in to a shoutcast station > 4. Open groupwise ... > etc .. > > These are the task I do every day whenever I log on my computer .. it > just seems repetitive and hence probably can be coded in python. > > Can I do this in python? Where do I find the COM objects/interfaces for > all these different programs? Are there any sample codes ? I just googled for "iTunes com python", there are lots of samples. If you can't find any, or want to find out about an applications interfaces yourself, you can sill use MakePy to find out what com interfaces are installed on your computer, and simply use the "dir" and "help" commands in the interactive console on those interfaces to find out what they do. (There are other tools to explore COM interfaces, like OleView, but if you're familiar with Python already, using dir/help is probably going to be easier) Reading Mark Hammond's excellent book (or at least the sample chapter on automation) wouldn't hurt either ;-) From nobody at 127.0.0.1 Sun May 14 13:14:54 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 14 May 2006 17:14:54 GMT Subject: send an email with picture/rich text format in the body References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> Message-ID: anya wrote: > I want to send an email message with picture in it. I dont want to put > it as attachment but make it in the body of the mail, so every one who > open the email will see the picture.. Step 1: convert image to ascii art Step 2: send Step 3: hope recipient uses a fixed-width font -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From godoy at ieee.org Wed May 17 22:51:02 2006 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 17 May 2006 23:51:02 -0300 Subject: Tabs versus Spaces in Source Code References: <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> <1147862865.142339.117610@j55g2000cwa.googlegroups.com> <1147868309.125766.112550@u72g2000cwu.googlegroups.com> <1352828.BsCtm2PuaN@jupiter.g2ctech> <1147874691.650993.54610@j33g2000cwa.googlegroups.com> Message-ID: <1879277.IQhJsv9DuJ@jupiter.g2ctech> achates wrote: > Jorge Godoy wrote > >>Emacs guess what's used in the file and allows me to use tabs all the >>time, doing the correct thing... > > That sounds like useful behaviour. > > Maybe this is an area where modern editors might be able to save us > from ourselves. I'll admit I'm suspicious of relying on editor > functionality - I'm happier if I know I can also use the old-school > methods just in case.. Sometimes adding intelligence to an interface > can be a usability disaster if it makes wrong assumptions about what > you want. But if people are hell-bent on converting tabs to spaces, > maybe it's the best way to accommodate them. If you don't want the functionality, simply disable it. This is why configuration files and options exist... -- Jorge Godoy "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From http Sun May 14 20:38:39 2006 From: http (Paul Rubin) Date: 14 May 2006 17:38:39 -0700 Subject: comparing values in two sets References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> Message-ID: <7xslncdsvk.fsf@ruckus.brouhaha.com> John Salerno writes: > I'd like to compare the values in two different sets to test if any of > the positions in either set share the same value (e.g., if the third > element of each set is an 'a', then the test fails). I think by "sets" you mean "lists". Sets are unordered, as a few people have mentioned. > I have this: > > def test_sets(original_set, trans_letters): > for pair in zip(original_set, trans_letters): > if pair[0] == pair[1]: > return False > return True That's fairly reasonable. You could use itertools.izip instead of zip, which makes a generator instead of building up a whole new list in memory. A more traditional imperative-style version would be something like: def test_sets(original_set, trans_letters): for i in xrange(len(original_set)): if original_set[i] == trans_letters[i]: return True return False You could even get cutesy and say something like (untested): from itertools import izip def test_sets(original_set, trans_letters): return not sum(a==b for a,b in izip(original_set, trans_letters)) but that can be slower since it always scans both lists in entirety, even if a matching pair of elements is found right away. I don't offhand see a builtin function or not-too-obscure one-liner that short-circuits, but maybe there is one. Note that all the above examples assume the two lists are the same length. Otherwise, some adjustment is needed. From daniel.huangfei at gmail.com Tue May 16 10:47:24 2006 From: daniel.huangfei at gmail.com (daniel) Date: 16 May 2006 07:47:24 -0700 Subject: what is the difference between tuple and list? Message-ID: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> is there any typical usage that shows their difference? thanks daniel From shejo284 at gmail.com Wed May 24 06:32:38 2006 From: shejo284 at gmail.com (Sheldon) Date: 24 May 2006 03:32:38 -0700 Subject: ftputil.py In-Reply-To: <1148458063.643620.222120@i39g2000cwa.googlegroups.com> References: <1148454897.089654.46130@j33g2000cwa.googlegroups.com> <1148458063.643620.222120@i39g2000cwa.googlegroups.com> Message-ID: <1148466758.303259.178160@u72g2000cwu.googlegroups.com> Thanks! Sheldon From johnjsal at NOSPAMgmail.com Tue May 23 11:43:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 15:43:26 GMT Subject: question about shadowing built-in names Message-ID: I understand that if you reassign a built-in name to your own variable, such as: str = 'hello' then you lose the use of the built-in (in this case str()), but is this also the case in terms of imported names? For example: import MySQLdb db = connect(blah blooh blee) cursor = db.cursor() Now, in the above, did I reassign the value of the cursor method, or is this different? Actually, now that I think about it, that's not exactly the same because cursor is a method of a connection object, not simply a function. So I suppose my real question is, does the 'shadowing' of built-in names also happen when you import other names, whether they are functions, methods or whatever else they could be? Thanks. From oliver at first.in-berlin.de Tue May 16 11:23:13 2006 From: oliver at first.in-berlin.de (Oliver Bandel) Date: Tue, 16 May 2006 17:23:13 +0200 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147792985.724640@elch.in-berlin.de> Xah Lee wrote: > Tabs versus Spaces in Source Code > > Xah Lee, 2006-05-13 > > In coding a computer program, there's often the choices of tabs or > spaces for code indentation. There is a large amount of confusion about > which is better. It has become what's known as ?religious war? ? > a heated fight over trivia. In this essay, i like to explain what is > the situation behind it, and which is proper. > > Simply put, tabs is proper, and spaces are improper. [...] I fullheartedly disagree :) So, no "essay" on this is necessary to read :-> Ciao, Oliver From antroy at gmail.com Wed May 17 04:16:16 2006 From: antroy at gmail.com (Ant) Date: 17 May 2006 01:16:16 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> Message-ID: <1147853776.367091.254700@u72g2000cwu.googlegroups.com> I think Duncan has hit the nail on the head here really. I totally agree that conceptually using tabs for indentation is better than using spaces. Pragmatically though, you can't tell in an editor where spaces are used and where tabs are used. Perhaps if editors colored the background of tab characters differently from spaces this wouldn't be a problem, or if Python was more restrictive and did not actually allow a mix of tabs and spaces for indentation there would be no problem - the compiler could throw out an exception for mixed characters. In reality, neither of these are likely to be implemented any time soon! The following quote sums things up nicely I think: "In theory there is no difference between theory and practice, but in practice there is." (No idea where I got that from BTW - someone's tag-line probably) From onurb at xiludom.gro Wed May 17 12:46:13 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 17 May 2006 18:46:13 +0200 Subject: \t not working In-Reply-To: <1147883344.070704.127080@g10g2000cwb.googlegroups.com> References: <1147883344.070704.127080@g10g2000cwb.googlegroups.com> Message-ID: <446b53bc$0$7047$636a55ce@news.free.fr> Alex Pavluck wrote: > I am just learning Python and I am using the book, "Thinking like a > Computer Scientist". There is an exercise that I am not able to get > working and it is really easy so I thought I would ask for help here. > > > Q: As an exercise, write a single string that: > Procuces > this > output. > > > A? > print "produces",'\n',"\t","this","\n","\t","output." Which results in: produces this output. I think the problem should be *really* obvious. Hint : count the "\t". -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From maric at aristote.info Wed May 31 06:29:24 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 31 May 2006 12:29:24 +0200 Subject: Best Python Editor In-Reply-To: References: Message-ID: <200605311229.24636.maric@aristote.info> Le Mercredi 31 Mai 2006 12:03, Manoj Kumar P a ?crit?: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. I didn't see on this list much PyQT users, is there a consensus about it ? I vote for linux+kdevelop for a good IDE (didn't try Pydev). -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From xah at xahlee.org Fri May 5 20:26:26 2006 From: xah at xahlee.org (Xah Lee) Date: 5 May 2006 17:26:26 -0700 Subject: A critic of Guido's blog on Python's lambda Message-ID: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Python, Lambda, and Guido van Rossum Xah Lee, 2006-05-05 In this post, i'd like to deconstruct one of Guido's recent blog about lambda in Python. In Guido's blog written in 2006-02-10 at http://www.artima.com/weblogs/viewpost.jsp?thread=147358 is first of all, the title ?Language Design Is Not Just Solving Puzzles?. In the outset, and in between the lines, we are told that ?I'm the supreme intellect, and I created Python?. This seems impressive, except that the tech geekers due to their ignorance of sociology as well as lack of analytic abilities of the mathematician, do not know that creating a language is a act that requires little qualifications. However, creating a language that is used by a lot people takes considerable skill, and a big part of that skill is salesmanship. Guido seems to have done it well and seems to continue selling it well, where, he can put up a title of belittlement and get away with it too. Gaudy title aside, let's look at the content of his say. If you peruse the 700 words, you'll find that it amounts to that Guido does not like the suggested lambda fix due to its multi-line nature, and says that he don't think there could possibly be any proposal he'll like. The reason? Not much! Zen is bantered about, mathematician's impractical ways is waved, undefinable qualities are given, human's right brain is mentioned for support (neuroscience!), Rube Goldberg contrivance phraseology is thrown, and coolness of Google Inc is reminded for the tech geekers (in juxtaposition of a big notice that Guido works there.). If you are serious, doesn't this writing sounds bigger than its content? Look at the gorgeous ending: ?This is also the reason why Python will never have continuations, and even why I'm uninterested in optimizing tail recursion. But that's for another installment.?. This benevolent geeker is gonna give us another INSTALLMENT! There is a computer language leader by the name of Larry Wall, who said that ?The three chief virtues of a programmer are: Laziness, Impatience and Hubris? among quite a lot of other ingenious outpourings. It seems to me, the more i learn about Python and its leader, the more similarities i see. So Guido, i understand that selling oneself is a inherent and necessary part of being a human animal. But i think the lesser beings should be educated enough to know that fact. So that when minions follow a leader, they have a clear understanding of why and what. ---- Regarding the lambda in Python situation... conceivably you are right that Python lambda is perhaps at best left as it is crippled, or even eliminated. However, this is what i want: I want Python literatures, and also in Wikipedia, to cease and desist stating that Python supports functional programing. (this is not necessarily a bad publicity) And, I want the Perl literatures to cease and desist saying they support OOP. But that's for another installment. ---- This post is archived at: http://xahlee.org/UnixResource_dir/writ/python_lambda_guido.html ? ? Xah ? ? xah at xahlee.org ? http://xahlee.org/ From mwilson-to at sympatico.ca Sun May 7 18:16:22 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Sun, 07 May 2006 18:16:22 -0400 Subject: printing list In-Reply-To: References: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> Message-ID: Tim Chase wrote: > compboy wrote: > >> How do you print elements of the list in one line? >> >> alist = [1, 2, 5, 10, 15] >> >> so it will be like this: >> 1, 2, 5, 10, 15 > > > >>> print ', '.join(alist) > 1, 2, 5, 10, 15 ??? Python 2.4.2 (#1, Jan 23 2006, 21:24:54) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> a=[1,2,3,4,5] >>> print ', '.join (a) Traceback (most recent call last): File "", line 1, in ? TypeError: sequence item 0: expected string, int found >>> print ', '.join ('%d'%x for x in a) 1, 2, 3, 4, 5 From kano.priv at gmail.com Mon May 15 10:48:39 2006 From: kano.priv at gmail.com (Lee Caine) Date: Mon, 15 May 2006 15:48:39 +0100 Subject: taking qoutes in arguments Message-ID: <98063b170605150748h3d0fffddibd6f8de28fff3d4f@mail.gmail.com> hi all, Im new to python and am in need of a little help.... Im attempting to write a program that finds and replaces text in all files in a given directory. example of running the program with arguments >python far.py /home/lee/Documents/ find replace I have managed to get it all working apart from one thing, if the find or replace arguments contain quotes e.g( content="somat" ), it doesnt work, so I print the string and it shows as content=somat, without the quotes. So i tryed this... >python far.py /home/lee/Documents content=\"somat\" content=\"somat else\" and this works, but I would like a way of not having to do this when i run the program any help would be greatly appreciated. thanks Lee. -------------- next part -------------- An HTML attachment was scrubbed... URL: From mhellwig at xs4all.nl Thu May 4 19:31:45 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Fri, 05 May 2006 01:31:45 +0200 Subject: Can I use python for this .. ?? In-Reply-To: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> Message-ID: <445a8ee9$0$31637$e4fe514c@news.xs4all.nl> san wrote: > Hi > > I am using windows xp and have installed python and win32. I am > familiar with basic Python. I wanted to control some of the > applications via python script. > > I would like to write a python script to say: > 1. Open firefox and log on to gmail > 2. Another firefox window to visit slickdeals > 3. Open winamp and tune in to a shoutcast station > 4. Open groupwise ... > etc .. > > These are the task I do every day whenever I log on my computer .. it > just seems repetitive and hence probably can be coded in python. > > Can I do this in python? Where do I find the COM objects/interfaces for > all these different programs? Are there any sample codes ? > > Thanks. > Santosh. > What you want looks like a way to automate the windows gui using python. Since I never done this myself I gave google a try with this query: http://www.google.com/search?hl=en&q=windows+gui+automation+python&btnG=Google+Search It looks like pywinauto seems to be a good candidate. hth -- mph From luismgz at gmail.com Thu May 25 10:36:47 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 25 May 2006 07:36:47 -0700 Subject: IronPython 1.0 Beta 7 Released References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> <1148518396.856710.173810@g10g2000cwb.googlegroups.com> <1148532003.624344.88030@38g2000cwa.googlegroups.com> <1148536183.520726.289960@i39g2000cwa.googlegroups.com> Message-ID: <1148567807.423964.5210@y43g2000cwc.googlegroups.com> Ravi Teja wrote: > Also, IronPython cannot access CPython libraries. So it cannot be used > as a drop-in replacement for CPython in most non-trivial apps. Python > for .NET however allows you to both use both CPython and .NET > libraries. It will be able to access the standard libraries, as long as they are rewriten in a .NET language. People are doing it already, it's just a matter of time... From nospam at nospam.nospam Mon May 15 12:13:30 2006 From: nospam at nospam.nospam (Nic) Date: Mon, 15 May 2006 18:13:30 +0200 Subject: List and order References: <446842f7$0$14785$4fafbaef@reader4.news.tin.it> <1147691967.998184.285120@u72g2000cwu.googlegroups.com> <446872cb$0$18288$4fafbaef@reader1.news.tin.it> Message-ID: <4468a8b7$0$29719$4fafbaef@reader2.news.tin.it> Many thanks. Both the cases are OK. The only problem is that from: 12 22 21 In spite of writing 12 12 22 it writes 12 21 22 Do you know how is it possible to delete also this last trouble? Thanks a bunch, Nic "Peter Otten" <__peter__ at web.de> ha scritto nel messaggio news:e49u2k$3i2$02$1 at news.t-online.com... > Nic wrote: > >> I tried to insert and execute the code, but the following error happens: >> >> Traceback (most recent call last): >> File "grafodna.py", line 10, in ? >> edges.sort(key = lambda u, v: (ddeg(u), ddeg(v))) >> TypeError: () takes exactly 2 arguments (1 given) >> >> Do you know how is it possible to delete it? > > Note that > > lambda a, b: ... > > takes two arguments while > > lambda (a, b): ... > > takes one argument which must be a sequence (list, string, generator,...) > of > two items. > > So the above should probably be > > edges = list(G.edges()) > edges.sort(key=lambda (u, v): (ddeg[u], ddeg[v])) > for u, v in edges: > print ddeg[u], ddeg[v], > print > > > Here's how I would do it: > > edges = [(ddeg[u], ddeg[v]) for u, v in G.edges()] > edges.sort() > for a, b in edges: > print a, b, > print > > (all untested) > > Peter From johnjsal at NOSPAMgmail.com Wed May 24 10:52:22 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 24 May 2006 14:52:22 GMT Subject: Python Programming Books? In-Reply-To: <1148479166.809729.85880@j33g2000cwa.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> <1148479166.809729.85880@j33g2000cwa.googlegroups.com> Message-ID: Brian wrote: > One book that I think you should definitely look at is Beginning Python > from Novice to Professional. I think that it is one of the best books > out there on the subject, is an easy read, has clear and concise > examples, and does a great job of explaining the whys without making > you think you are reading a PhD thesis. I disagree, and I'm surprised so many people think this book is that great. I found it to be way too cursory of an introduction to the language. Fortunately I had already read Learning Python, so Beginning Python made sense to me, but even still, as I was reading it I kept saying to myself "I know this passage here, or this sentence there, would make no sense to me if I didn't already understand it from LP." Beginning Python does not do a good job of explaining how Python works, it only introduces all the parts of it, rather too quickly, IMO, for someone just learning the language. From nogradi at gmail.com Fri May 5 05:48:39 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 5 May 2006 11:48:39 +0200 Subject: Tuple assignment and generators? In-Reply-To: References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> Message-ID: <5f56302b0605050248n6801babfvc27fceccffad34b8@mail.gmail.com> > > Given this though, what other such beauties are lurking in the > > interpreter, under the name of 'implementation accidents'? One of the > > things that drew me to python is the claimed consistency and > > orthogonality of both language and implementation, not sacrificing > > clarity for performance, minimizing ad-hoc design hacks and weird > > gotcha's, etc... > > so anything you don't understand, and cannot be bothered to look up in > the documentation, just has to be an inconsistent ad-hoc weird-gotcha > design ? > > I think we can all safely *plonk* you know. I was just at a point when I thought I learned something but got confused again after trying the following and unfortunately didn't find an answer in the docs. >>> a = 10 >>> b = 10 >>> id(a) 134536516 >>> id(b) 134536516 So the two memory addesses are the same, but >>> a = 10000 >>> b = 10000 >>> id(a) 134604216 >>> id(b) 134604252 and they are not the same (I restarted the interpreter between the two cases). So how is this now? Sorry if it's too trivial, but I simply don't get it. From NA at NA.com Tue May 9 04:27:06 2006 From: NA at NA.com (N/A) Date: Tue, 09 May 2006 16:27:06 +0800 Subject: clear memory? how? Message-ID: Hi all, I am learning Python. Just wondering how to clear saved memory in Python? Like in Matlab I can simply use "clear all" to clear all saved memory. Thank u! From tbrkic at yahoo.com Thu May 18 15:27:42 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 12:27:42 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <446cc017$0$12808$636a55ce@news.free.fr> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147958226.200557.264850@j33g2000cwa.googlegroups.com> <1147975275.206451.107730@j73g2000cwa.googlegroups.com> <446cc017$0$12808$636a55ce@news.free.fr> Message-ID: <1147980462.464427.323030@u72g2000cwu.googlegroups.com> > We already have this (quite close to) this syntax: > > class (super): > = * > [class *] > > There's also the Zope3 'implements' trick, that allow to modify the > class namespace without assignement: > > class : > (*args, **kw)* > > So what you want is very certainly doable without any syntax change. It's not obvious me how you would do it it with the above syntax. Could you give me an example? For example how would you do: root = ET.Element("html") node root: attr head("head"): node title("title): for i in sections: node section(): attr Text = section[i] From laurent.pointal at limsi.fr Mon May 22 10:35:19 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 22 May 2006 16:35:19 +0200 Subject: enumerate() question In-Reply-To: <1148308146.493287.323770@38g2000cwa.googlegroups.com> References: <1148308146.493287.323770@38g2000cwa.googlegroups.com> Message-ID: Gregory Petrosyan a ?crit : > Hello! > I have a question for the developer[s] of enumerate(). Consider the > following code: > > for x,y in coords(dots): > print x, y > > When I want to iterate over enumerated sequence I expect this to work: > > for i,x,y in enumerate(coords(dots)): > print i, x, y > > Unfortunately, it doesn't =( and I should use (IMHO) ugly Try: for i,(x,y) in enumerate(coords(dots)) : ... > > for i,pair in enumerate(coords(dots)): > print i, pair[0], pair[1] > > So, why enumerate() works this way and is there any chance of changing > the behaviour? No chance, behavior is correct. A+ L.Pointal. From nospam at foo.com Fri May 12 11:52:34 2006 From: nospam at foo.com (jayessay) Date: 12 May 2006 11:52:34 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> Message-ID: "Michele Simionato" writes: > I was interested in a proof of concept, to show that Python can > emulate Lisp special variables with no big effort. OK, but the sort of "proof of concept" given here is something you can hack up in pretty much anything. So, I wouldn't call it especially convincing in its effect and capability. /Jon -- 'j' - a n t h o n y at romeo/charley/november com From brian at brianandkate.com Fri May 19 07:11:55 2006 From: brian at brianandkate.com (Brian Blazer) Date: Fri, 19 May 2006 06:11:55 -0500 Subject: Newbie append() question In-Reply-To: References: Message-ID: <564FD0A2-BCDE-4CBF-A6C7-B643B297734C@brianandkate.com> Thanks guys. Your solutions worked. I'm still not sure why it was grabbing the prompt string though. Thanks again, Brian brian at brianandkate.com From gherron at islandtraining.com Thu May 11 13:08:27 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 11 May 2006 10:08:27 -0700 Subject: find all index positions In-Reply-To: <7xbqu4ec4y.fsf@ruckus.brouhaha.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <7xbqu4ec4y.fsf@ruckus.brouhaha.com> Message-ID: <44636F8B.1080103@islandtraining.com> Paul Rubin wrote: >micklee74 at hotmail.com writes: > > >>say i have string like this >>astring = 'abcd efgd 1234 fsdf gfds abcde 1234' >>if i want to find which postion is 1234, how can i achieve this...? i >>want to use index() but it only give me the first occurence. I want to >>know the positions of both "1234" >> >> > >Most straightforwardly with re.findall -- see the docs. > > Not quite. The findall will list the matching strings, not their positions. -- He'll get ['1234','1234']. The finditer function will work for his requirements. See my other post to this thread. From Serge.Orlov at gmail.com Thu May 11 10:40:21 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 May 2006 07:40:21 -0700 Subject: How to encode html and xml tag datas with standard python modules ? References: <44586183.2030903@gmail.com> Message-ID: <1147358421.107990.24350@v46g2000cwv.googlegroups.com> DurumDara wrote: > Hi ! > > I probed this function, but that is not encode the hungarian specific > characters, like ???????o??u: so the chars above chr(127). > Have the python a function that can encode these chars too, like in Zope ? > The word encode is ambiguous. What do you mean? The example Fredrik gave to you does encode: >>> import cgi >>> cgi.escape(u"???????o??u").encode("ascii", "xmlcharrefreplace") 'áéíóüóöőúüű' From pmartin at snakecard.com Mon May 1 08:32:51 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 01 May 2006 07:32:51 -0500 Subject: OOP techniques in Python References: <1146158190.320947.108480@t31g2000cwb.googlegroups.com> <3%84g.4111$B42.3689@dukeread05> <0n7352hcbkucdnbgku759n5afnntb0na4v@4ax.com> Message-ID: Thanks, Did not know that. Philippe Dennis Lee Bieber wrote: > On Thu, 27 Apr 2006 14:32:15 -0500, Philippe Martin > declaimed the following in comp.lang.python: > >> >> What then is the point of the double underscore (if any) ?: > > To prevent masking/shadowing of inherited attributes... > >>>> class A(object): > ... def __init__(self): > ... self.__WhoMe = "From A" > ... print "A : ", dir(self) > ... super(A, self).__init__() > ... >>>> class B(object): > ... def __init__(self): > ... self.__WhoMe = 42 > ... print "B : ", dir(self) > ... super(B, self).__init__() > ... >>>> class Confusion(A, B): > ... def __init__(self): > ... self.__WhoMe = "I'm confuzzled" > ... print "Confusion: ", dir(self) > ... super(Confusion, self).__init__() > ... >>>> cab = Confusion() > Confusion: ['_Confusion__WhoMe', '__class__', '__delattr__', > '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', > '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', > '__setattr__', '__str__', '__weakref__'] > A : ['_A__WhoMe', '_Confusion__WhoMe', '__class__', '__delattr__', > '__dict__', '__doc__', '__getattribute__', '__hash__', '__init__', > '__module__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', > '__setattr__', '__str__', '__weakref__'] > B : ['_A__WhoMe', '_B__WhoMe', '_Confusion__WhoMe', '__class__', > '__delattr__', '__dict__', '__doc__', '__getattribute__', '__hash__', > '__init__', '__module__', '__new__', '__reduce__', '__reduce_ex__', > '__repr__', '__setattr__', '__str__', '__weakref__'] >>>> > > Note that A, B, and Confusion each have "__WhoMe". Also notice how > each __init__ invokes the parent module __init__; each one adds its > __WhoMe to the object without masking those defined in others. > > Without the __, you'd have only ONE attribute after all of that; as > shown next... > >>>> class A(object): > ... def __init__(self): > ... self._WhoMe = "From A" > ... print "A : ", dir(self) > ... super(A, self).__init__() > ... >>>> class B(object): > ... def __init__(self): > ... self._WhoMe = 42 > ... print "B : ", dir(self) > ... super(B, self).__init__() > ... >>>> class Confusion(A, B): > ... def __init__(self): > ... self._WhoMe = "I'm confuzzled" > ... print "Confusion: ", dir(self) > ... super(Confusion, self).__init__() > ... >>>> cab2 = Confusion() > Confusion: ['_WhoMe', '__class__', '__delattr__', '__dict__', > '__doc__', '__getattribute__', '__hash__', '__init__', '__module__', > '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', > '__str__', '__weakref__'] > A : ['_WhoMe', '__class__', '__delattr__', '__dict__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__weakref__'] > B : ['_WhoMe', '__class__', '__delattr__', '__dict__', '__doc__', > '__getattribute__', '__hash__', '__init__', '__module__', '__new__', > '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', > '__weakref__'] >>>> > -- > > ============================================================== < > > wlfraed at ix.netcom.com | Wulfraed Dennis Lee Bieber KD6MOG < > > wulfraed at dm.net | Bestiaria Support Staff < > > ============================================================== < > > Home Page: < > > Overflow Page: < From duncan.booth at invalid.invalid Thu May 11 10:27:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 11 May 2006 14:27:48 GMT Subject: String concatenation performance References: <1147355908.655992.5720@g10g2000cwb.googlegroups.com> Message-ID: Cristian.Codorean wrote: > I was just reading a "Python Speed/Performance Tips" article on the > Python wiki > http://wiki.python.org/moin/PythonSpeed/PerformanceTips > and I got to the part that talks about string concatenation and that > it is faster when using join instead of += because of strings being > immutable. ... snip ... > So what am I doing wrong ? > What you are doing wrong is failing to search the newsgroup to see if anyone else has asked the same question within the last few days. In particular see the thread titled 'which is better, string concatentation or substitution?' message <445ec45e$0$1965$c3e8da3 at news.astraweb.com> http://groups.google.co.uk/group/comp.lang.python/browse_frm/thread/2d060eb94730bedb/06412fc21aa1fe8c?#06412fc21aa1fe8c From george.sakkis at gmail.com Thu May 25 20:22:53 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 25 May 2006 17:22:53 -0700 Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> Message-ID: <1148602972.946639.40220@38g2000cwa.googlegroups.com> vbgunz wrote: > I will not try and stop helping others because you don't like my > answers. I found a perfectly good way how not to do something that > wasn't exactly wrong anyway. if you can take another persons honest > attempt to help someone and twist it into something it is not, I can > only suggest you look in the mirror and only if you're truly perfect > you continue your banter. > > by the way, I am not here to promote Python. but if this is of your > concern, perhaps maybe you should rethink how you respond in kind > towards post you do not exactly agree with. Others are reading this and > it might not come off as promotional material. Also, if you're having a > bad day, take a rest and relax. You just might deserve it. I guess Fredrik's message was more along the lines of ``don't try to "help" others after a week or two toying with the language because you might be offering disservice, despite your good intentions; leave this to more experienced users``. The words might have been a bit harsher but that's just his style; you'll get used to it if you hang around here often. George From russell_turpin at hotmail.com Fri May 26 11:46:34 2006 From: russell_turpin at hotmail.com (Russell) Date: 26 May 2006 08:46:34 -0700 Subject: How does a generator object refer to itself? In-Reply-To: <447513cb$0$2690$ed2619ec@ptn-nntp-reader01.plus.net> References: <1148311069.417177.254550@y43g2000cwc.googlegroups.com> <447513cb$0$2690$ed2619ec@ptn-nntp-reader01.plus.net> Message-ID: <1148658394.005096.102610@38g2000cwa.googlegroups.com> Michael wrote: > You don't need python 2.5 at all to do this. You do need to > have a token mutable first argument though, as you can see. Thank you. That's a pattern similar to one we're using, where a new object refers to the generator. The problem we're seeing is that it seems to fool the garbage collector. We're not positive about that. But we are suspicious. Interesting page you have. I've bookmarked it. Thanks, again. From jimburton1 at gmail.com Wed May 3 04:37:12 2006 From: jimburton1 at gmail.com (jimburton) Date: 3 May 2006 01:37:12 -0700 Subject: Zope Guru... In-Reply-To: References: Message-ID: <1146645432.111219.211270@e56g2000cwe.googlegroups.com> The Zope book is a good starting point - http://www.zope.org/Documentation/Books/ZopeBook/2_6Edition/view From Dorit.Gross at fao.org Fri May 12 10:27:18 2006 From: Dorit.Gross at fao.org (Gross, Dorit (SDRN)) Date: Fri, 12 May 2006 16:27:18 +0200 Subject: How to pass variables between scripts Message-ID: <5290E77B1FE2FE40B82AA54158825F0601F2C94C@hqosex01.fao.org> Dear list, I am an absolute newbie to python and would appreciate your help very much :) I am trying to write a little python script that wraps a set of external scripts. The external scripts are either also written in python or are simple bash scripts. My wrapping script should be able to send an argument to the first script, to execute it, to read its results and to send them then as arguments into the next script. This is the first part that I have written so far: #! /usr/local/bin/python # test_exec.py import os, sys, glob fileList = glob.glob('/data/*.ZIP') for f in fileList: try: globvars = {'infile' : f} locvars = {} execfile('/scripts/second.py', globvars(), locvars) except IOError: exit(0) print locvars And this is what happens when calling test_exec.py ./test_exec.py Traceback (most recent call last): File "./test_exec.py", line 19, in ? execfile('/scripts/second.py', vars(), results) TypeError: 'dict' object is not callable I tried already to modify the script in different ways but wasn't successful so far to make it running. Could you maybe help what I am missing? Further, I am not sure how the second python has to look like to actually read what is given in "globvars" and to sent its results into "locvars". Or might os.popen* be a better option? -------------- next part -------------- An HTML attachment was scrubbed... URL: From alisonken1 at gmail.com Sun May 7 17:03:45 2006 From: alisonken1 at gmail.com (alisonken1) Date: 7 May 2006 14:03:45 -0700 Subject: Passing options around your program References: <4c6o1sF14hhjuU1@individual.net> Message-ID: <1147035825.643595.139800@e56g2000cwe.googlegroups.com> Leo Breebaart wrote: > I have another question where I am not so much looking for a > solution but rather hoping to get some feedback on *which* > solutions people here consider good Pythonic ways to approach a > issue. > > The situation is this: I am writing fairly large console scripts > in Python. They have quite a few command-line options, which lead > to configuration variables that are needed all over the program > (e.g. the "--verbose" option alone is used by just about every > function and method). One question I have is about the "--verbose" option. If you're doing something that is equivalent to logging to , rather than continuing to pass the '--verbose' flag around, why not just use the built-in logging facility to manage the extra output? By having the different modules call logging( , ") throughout your programs, you only need to set the initial level from where you're checking options (whether from command line or configuration file) rather than having to pass the '--verbose' option around. From akameswaran at gmail.com Thu May 18 21:46:26 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 18:46:26 -0700 Subject: Quoting relevant material for response (was: Re: python vs perl lines of code) In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <1147996169.818933.252420@u72g2000cwu.googlegroups.com> <1148002073.419819.295180@38g2000cwa.googlegroups.com> Message-ID: <1148003186.350496.67670@g10g2000cwb.googlegroups.com> Thanks Ben, I actually don't spend a whole lot of time on newsgroups. I don't use my gmail account and use the groups thru the web interface. If that quoting mechanism is available on the web interface and I haven't found it - I'd love to know how to use it. Also i use the threaded view on the web client, so I have little trouble figuring out what is being referenced. My comment about John being funny in fact was a generic comment, and while the remainder of my response was on topic - it still was not in response to 1 specific statement or another. Quoting previous comments is useful, but not required to be in thread - IMHO. >> In any case, I realize I was completley wrong. Please allow me to >> retract my statement. >It's hard to see what that is, since you don't provide any >context. Are we expected to re-read the entire thread to guess what >you're referring to? Secondly, I meant I was wrong about John being hilarious - and in that context the quotes would have been useful. From lonetwin.nospam at yahoo.com Tue May 16 05:19:03 2006 From: lonetwin.nospam at yahoo.com (Steve) Date: Tue, 16 May 2006 14:49:03 +0530 Subject: [silly] Does the python mascot have a name ? Message-ID: umm, was just wondering, does the python mascot have a name ? We are naming the conference rooms in our office you see :o). Also, is there a place I could get some neat, good quality pics of the python ? - steve From pmartin at snakecard.com Thu May 4 12:15:43 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 04 May 2006 11:15:43 -0500 Subject: Progamming python without a keyboard References: Message-ID: That reminds me a session in an R&D lab a long time ago One of the guys kept talking to himself, commenting code, bugs ..... he drove me nuts Eventually (weeks later) another guy silently stood up, went to the first guy, and without a word attempted to strangle him. He got stopped ... but did not get fired (I guess even the management was tired of the first guy rambling) We should be aware of all types of RSI. (I'm still laughing) Philippe Rony Steelandt wrote: > http://www.newscientisttech.com/article/dn9066 > > To nice to be true ? > > R_ > > -- > --- > Rony Steelandt > BuCodi > rony dot steelandt (at) bucodi dot com > > Visit the python blog at http://360.yahoo.com/bucodi From panos.laganakos at gmail.com Thu May 4 16:01:17 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 4 May 2006 13:01:17 -0700 Subject: Python 2.4.2 to 2.4.3 transition issue Message-ID: <1146772876.641098.166110@g10g2000cwb.googlegroups.com> OS: Windows XP + SP1 On this particular box, I hadn't moved to 2.4.3 yet. So, earlier today, I uninstalled Python2.4.2 and installed 2.4.3 using the .msi installer. It seems though everything looked great, that when I invoke 'python' from the command line, I get Python2.4.2 (as the header states), instead of 2.4.3. I looked at the registry and at the PATH variables of both system and current user, but they are just stating 'C:\Python24\'. When I explicitly call C:\Python24\python.exe though, 2.4.3 comes up. Any ideas what seems to be the problem here? From aaronb at mrxfx.com Thu May 11 13:58:24 2006 From: aaronb at mrxfx.com (Aaron Barclay) Date: Thu, 11 May 2006 13:58:24 -0400 Subject: Reg Ex help In-Reply-To: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> Message-ID: <44637B40.4020509@mrxfx.com> Hi don, there may well be a better way then regex, although I find them usefull and use them a lot. The way they work would be dependant on knowing some things. For example, if the dir you are after is always 4 deep in the structure you could try something like... path = '/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4' p = re.compile('/\S*/\S*/\S*/(\S*)/') m = re.search(p, path) . if m: print m.group(1) This is a good reference... http://www.amk.ca/python/howto/regex/ Hope that helps, aaron. don wrote: >I have a string from a clearcase cleartool ls command. > >/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT >from /main/parallel_branch_1/release_branch_1.0/4 > >I want to write a regex that gives me the branch the file was >checkedout on ,in this case - 'dbg_for_python' > >Also if there is a better way than using regex, please let me know. > >Thanks in advance, >Don > > > From opalpa at gmail.com Tue May 16 11:31:31 2006 From: opalpa at gmail.com (opalpa@gmail.com opalinski from opalpaweb) Date: 16 May 2006 08:31:31 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147793491.658982.131450@v46g2000cwv.googlegroups.com> > Simply put, tabs is proper, and spaces are improper. > Why? This may seem > ridiculously simple given the de facto ball of confusion: the semantics > of tabs is what indenting is about, while, using spaces to align code > is a hack. The reality of programming practice trumps original intent of tab characters. The tab character and space character are pliable in that if their use changes their semantics change. > ... and the solution is to advance > the sciences such that your source code in some way > embed such information. If/when time comes where such info is embeded perhaps then tabs will be OK. --------------------------------------------------------------- I use spaces because of the many sources I've opened I have many times sighed on opening tabed ones and never done so opening spaced ones. I don't get mad, but sighing is a clear indicator of negativity. Anyway, the more code I write and read the less indentation matters to me. My brain can now parse akward source correctly far bettter than it did a few years ago. All the best, Opalinski opalpa at gmail.com http://www.geocities.com/opalpaweb/ From nobody at 127.0.0.1 Mon May 1 18:19:42 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 01 May 2006 22:19:42 GMT Subject: Add file to zip, or replace file in zip References: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> <1146257509.963417.250250@g10g2000cwb.googlegroups.com> <4455010f@nntp0.pdx.net> <4456464c$1@nntp0.pdx.net> <2uu5g.483$fb2.452@newssvr27.news.prodigy.net> <44567dc7$1@nntp0.pdx.net> Message-ID: <2Qv5g.534$fb2.75@newssvr27.news.prodigy.net> Scott David Daniels wrote: > Actually I think it was a combination of CP/M and DOS that popularized > the ZIP format; essentially the floppy-disk set, for whom the zip format > was a godsend. Ah you're right. I just lump all Microsoft OSes under the term 'Windows' now, though I suppose that's unfair to Xenix. From michele.simionato at gmail.com Wed May 10 03:07:22 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 May 2006 00:07:22 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <%F38g.16$RR.4@fe10.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> Message-ID: <1147244842.745710.250560@j73g2000cwa.googlegroups.com> Ken Tilton wrote: > I was not thinking about the thread issue (of which I know little). The > big deal for Cells is the dynamic bit: > > (let ((*dependent* me)) > (funcall (rule me) me)) > > Then if a rule forces another cell to recalculate itself, *dependent* > gets rebound and (the fun part) reverts back to the original dependent > as soon as the scope of the let is exited. Python 2.5 has a "with" statement (yes, the name is Lispish on purpose) that could be used to implement this. See http://www.python.org/dev/peps/pep-0343 Michele Simionato From scott.daniels at acm.org Thu May 11 12:44:35 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 11 May 2006 09:44:35 -0700 Subject: find all index positions In-Reply-To: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> Message-ID: <44636625$1@nntp0.pdx.net> micklee74 at hotmail.com wrote: > astring = 'abcd efgd 1234 fsdf gfds abcde 1234' > i want to find all positions of '1234' in astring. def positions(target, source): '''Produce all positions of target in source''' pos = -1 try: while True: pos = source.index(target, pos + 1) yield pos except ValueError: pass print list(positions('1234', 'abcd efgd 1234 fsdf gfds abcde 1234')) prints: [10, 31] --Scott David Daniels scott.daniels at acm.org From michele.petrazzo at TOGLIunipex.it Mon May 15 04:17:47 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 15 May 2006 08:17:47 GMT Subject: Starting/launching eric3 In-Reply-To: <1147626313.331126.90200@y43g2000cwc.googlegroups.com> References: <1147624798.827349.286970@y43g2000cwc.googlegroups.com> <1147626313.331126.90200@y43g2000cwc.googlegroups.com> Message-ID: Byte wrote: > OK, now I've managed to get it working, but when I run it the eric3 > splash screen pops up, and then it says (in terminal): > > eoin at laptop:~$ eric3 > Traceback (most recent call last): > File "/usr/lib/site-python/eric3/eric3.py", line 147, in ? > main() > File "/usr/lib/site-python/eric3/eric3.py", line 132, in main > mw = UserInterface(loc, splash) > File "/usr/lib/site-python/eric3/UI/UserInterface.py", line 265, in > __init__ > self.sbv = SBVviewer(dbs, self.sbvDock, 1) > File "/usr/lib/site-python/eric3/UI/SBVviewer.py", line 75, in > __init__ > self.stackComboBox.sizePolicy().hasHeightForWidth())) > TypeError: argument 1 of QSizePolicy() has an invalid type > Segmentation fault > eoin at laptop:~$ > > Its not ment to do that... how to make it work right?? Just happen on my costumer ubuntu (and an old eric3 release). I have solve it downloading the last (3.9.x if I remember correctly) from eric3 home and overwrite the site-packages/eric directory. Now all work great. > > -- /usr/bin/byte > Michele From raghavan.viswanathan at wipro.com Fri May 19 00:18:47 2006 From: raghavan.viswanathan at wipro.com (raghu) Date: 18 May 2006 21:18:47 -0700 Subject: Reference Counts In-Reply-To: References: <1147933695.752344.195350@u72g2000cwu.googlegroups.com> <1147937632.918370.300350@j55g2000cwa.googlegroups.com> Message-ID: <1148012327.849813.282080@i39g2000cwa.googlegroups.com> Hmm... I tried the gc.collect(). It aint helping. The reference count still keeps growing till 5 after it which it drops. As you said, it is not gonna hurt right away. The only downside in that mysterious up and down thingie is that , we could get to a wrong conclusion about a leak, if we ran the algo for say 3 times. Right ? Thanks Heiko for all the help. And in case, you get to decode the mystery behind the increase before the decrease ..kindly let me know. Bye, Raghavan V From No.Spam at Spam.none Mon May 1 19:41:00 2006 From: No.Spam at Spam.none (I. Myself) Date: Mon, 01 May 2006 23:41:00 GMT Subject: Can Python kill a child process that keeps on running? Message-ID: Suppose we spawn a child process with Popen. I'm thinking of an executable file, like a compiled C program. Suppose it is supposed to run for one minute, but it just keeps going and going. Does Python have any way to kill it? This is not hypothetical; I'm doing it now, and it's working pretty well, but I would like to be able to handle this run-on condition. I'm using Windows 2000, but I want my program to be portable to linux. Thanks Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From phddas at yahoo.com Sun May 14 15:02:14 2006 From: phddas at yahoo.com (Gary Wessle) Date: 15 May 2006 05:02:14 +1000 Subject: copying files into one References: <874pztgsd5.fsf@localhost.localdomain> Message-ID: <87ejywwhu1.fsf@localhost.localdomain> thanks, I was able 'using pdb' to fix the problem as per Edward's suggestion. From faino80 at yahoo.com Mon May 8 06:46:50 2006 From: faino80 at yahoo.com (I Made Putrama) Date: Mon, 8 May 2006 03:46:50 -0700 (PDT) Subject: yahoo sender name Message-ID: <20060508104650.89925.qmail@web52511.mail.yahoo.com> You can go to Options menu, then klik Mail menu. Under Management tab, klik Mail Adresses Then edit your account there.. regards, faino --------------------------------------------------------------------------------------------------------------------------- >> hey...I know this is off the "python" topic....but I have yahoo mail and would like to change my "sender name" I have gone to the "edit account" area and have changed all names that can be edited to a consistent name other than the current sender name...but for some reason it will not change the sender name...is anybody familiar with yahoo mail and changing names? -thanks in advance- --------------------------------- How low will we go? Check out Yahoo! Messenger?s low PC-to-Phone call rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: From onurb at xiludom.gro Thu May 11 10:10:15 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 11 May 2006 16:10:15 +0200 Subject: Python memory deallocate In-Reply-To: <1147355266.189030.131420@y43g2000cwc.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <-yy*V4mgr@news.chiark.greenend.org.uk> <1147355266.189030.131420@y43g2000cwc.googlegroups.com> Message-ID: <4463462a$0$297$626a54ce@news.free.fr> mariano.difelice at gmail.com wrote: > Ok, this is true. > > Well, you consider that my app has a first windows, where I choose, for > example, the application 1. > The application 1 will be started, and it will allocate 200Mb total. > Now I want to abort this operation, and i will return to main initial > window. The memory usage remain to 200Mb, even if I've destroyed the > application 1 object with app1.Destroy() and del app1. > When from initial windows i re-choose application1, the memory usage > don't stay to 200Mb, but will increase to 360-380Mb memory, and I think > this is not good!!! > > If I will repeat this procedure for 5-6 times, the application will > crash... Either there are references somewhere keeping some objects alive, or you're facing a known problem with pymalloc() [1]. In the second case, the good news is that this problem seems to be solved in Python 2.5 [2]. The bad news is that Python 2.5 is still alpha... Just a question: do you really need your app to be monolithic ? If you're application is really composed of many applications (which is what I understand from your example), you should probably have many distinct applications, one of them being in charge of running the others. This way, 'aborting' an app would kill the corresponding process, and free memory. [1] or it's yet another problem, of course - CS wouldn't be that fun if it was so simple :( [2] http://docs.python.org/dev/whatsnew/section-other.html 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 usenet at local.machine Thu May 25 22:31:36 2006 From: usenet at local.machine (=?ISO-8859-2?Q?Dra=BEen_Gemi=E6?=) Date: Fri, 26 May 2006 04:31:36 +0200 Subject: John Bokma harassment In-Reply-To: <1148570221.386411.160660@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <87ejyjv40w.fsf@rpi.edu> <1148570221.386411.160660@j33g2000cwa.googlegroups.com> Message-ID: Kay Schluehr wrote: > Sounds like me. In rare moments I believe that I'm not alone on usenet > but there are other people as well. I wanted to go to the doctor > because I believed I had a multiple personality but than I discovered > that the doctor was me too. That's bad, because all of you must be in different shifts, so you never meet each other in person. DG From danmcleran at yahoo.com Tue May 16 10:57:36 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 16 May 2006 07:57:36 -0700 Subject: what is the difference between tuple and list? In-Reply-To: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> References: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> Message-ID: <1147791456.760794.100670@j55g2000cwa.googlegroups.com> Lists are mutable, i.e. one can do this: a = [1,2,3] a[0] = 100 You can't do that with a tuple. a = (1,2,3) a[0] = 100 # error From sybrenUSE at YOURthirdtower.com.imagination Tue May 2 06:41:20 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 2 May 2006 12:41:20 +0200 Subject: Non-web-based templating system References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> Message-ID: qscomputing at gmail.com enlightened us with: > I'm creating a small application in Python that uses lists and > dictionaries to create a rudimentary database. I'd like to create > some "fill-in-the-blanks" reports from this data, ideally by taking > an RTF or plaintext file as a template and replacing placeholder > tags with my data. I'd go for Cheetah: http://www.cheetahtemplate.org/ Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From deets at nospam.web.de Tue May 16 09:28:57 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 16 May 2006 15:28:57 +0200 Subject: Python script for remotely shutting down Windows PC from Linux ? References: <1147784786.317200.238780@v46g2000cwv.googlegroups.com> Message-ID: <4cu2dcF17t9juU1@uni-berlin.de> > Next, I wrote a script that would log me in and also shut the windows > pc down, so I wrote a script > > ssh Admin at IP_ADDR # connects me fine now without problems (LOCAL) > shutdown -s # This is a windows command (REMOTE) > > Now, when I run this script, it successfully logs me into the windows > box but doesn't run the second part of the script which is to shut down > the windows PC. Can you please tell me why ?? Because you execute both commands locally. ssh opens a connection to the remote machine. Then if that connection is terminated, the next command is executed. LOCALLY! Use ssh Admin at IP_ADDR shutdown -s to execute commands remote using ssh. > Is there a way using Python script to perform this operation ? use the subprocess module or shellutils to execute the above. Diez From phpbird at gmail.com Fri May 5 11:56:07 2006 From: phpbird at gmail.com (Ju Hui) Date: 5 May 2006 08:56:07 -0700 Subject: how to remove 50000 elements from a 100000 list? In-Reply-To: <4c14snF13tbobU1@uni-berlin.de> References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> <4c13mdF13esivU1@uni-berlin.de> <4c14snF13tbobU1@uni-berlin.de> Message-ID: <1146844567.717687.228160@j33g2000cwa.googlegroups.com> cool! thanks you all! I choose a=set(range(100000)) b=set(range(50000)) a.symmetric_difference(b) certainly,the real data not range(), I am satisfied the performance of set.difference thank you all again! From diesch at spamfence.net Fri May 19 09:24:49 2006 From: diesch at spamfence.net (Florian Diesch) Date: Fri, 19 May 2006 15:24:49 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> Message-ID: <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> bruno at modulix wrote: > SamFeltus wrote: >> I am trying to figure out why so little web development in Python uses >> Flash as a display technology. It seems most Python applications >> choose HTML/CSS/JS as the display technology, yet Flash is a far more >> powerful and elegant display technology. On the other hand, HTML/JS >> seems clunky and antiquated. I am a gardener, and not a coder by >> trade, but Flash seems to integrate just fine with Python. Anyways, >> what are the technical reasons for this? >> > > - Flash is a proprietary technology requiring a proprietary plugin. There seem to be at least two free implementations: Package: libswfdec0.3 Description: SWF (Macromedia Flash) decoder library A decoder library for Macromedia Flash animations, which are often found on web sites. This is the run-time portion of the library. Package: libflash0c2 Description: GPL Flash (SWF) Library - shared library The GPL Flash library is a set of functions that can be used by applications to play Flash movies. The core of the library is a portable graphic renderer that can be used to add SWF support to an application. . This package contains shared libraries needed to run programs that have been build against the library. > - There aint actually no working Flash plugin for Mozilla on a 64bit > processor - I just *can't* read Flash anims on my computer There are plugins based on the above libs. Maybe they work on 64 bit platforms. > - Flash is meant to display animations, not web content > - Flash content is not indexed by search engines > - Flash content cannot be manipulated by normal text/HTML/XML tools - In Flash you can't set bookmarks - In Flash you can't use your browser's navigation functions - You can't print animations > (x)html/css/js is neither 'clunky' nor 'antiquated' is a nice example what you can do with pure HTML and CSS Florian -- From bdesth.quelquechose at free.quelquepart.fr Thu May 11 20:16:42 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 May 2006 02:16:42 +0200 Subject: String concatenation performance In-Reply-To: <1147355908.655992.5720@g10g2000cwb.googlegroups.com> References: <1147355908.655992.5720@g10g2000cwb.googlegroups.com> Message-ID: <4463a4f7$0$286$636a55ce@news.free.fr> Cristian.Codorean a ?crit : > I was just reading a "Python Speed/Performance Tips" article on the > Python wiki > http://wiki.python.org/moin/PythonSpeed/PerformanceTips > and I got to the part that talks about string concatenation and that it > is faster when using join instead of += because of strings being > immutable. This is somewhat obsolete. String concatenation have been subject to some optimization since 2.3.x (IIRC - else please someone correct me). NB: this is only true for CPython. But the "".join() idiom is, well, still idiomatic... > So I have tried it: > > from time import time > t=time() > > s='almfklasmfkmaskmkmasfkmkqemkmqeqw' > for x in range(40): > #s+= s[len(s)/2:] > s="".join((s,s[len(s)/2:])) Lol... I'm afraid you didn't get the idiom right. The point is to avoid useless allocations in the loop body. The idiom is: buf = [] for x in range(42): buf.append(s) s = "".join(buf) > print 'duration', time() - t timeit may be a better choice for microbenchmarks. From sybrenUSE at YOURthirdtower.com.imagination Wed May 17 04:07:16 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 17 May 2006 10:07:16 +0200 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> Message-ID: Duncan Booth enlightened us with: > It is strange. You use many of the same words as me, but they don't make > any sense. You forgot to add "to me" to the end of that sentence. Personally, Achates' words made perfect sense to me. > The point is about separating the presentation of the source file > from the semantic content. When displaying the file you can choose > to expand tabs to any suitable positions. These may be evenly spaced > every n characters, or may vary across the page. True. > However the important thing is that a tab does not map to a single > indentation level in Python: it can map to any number of indents, True, but doesn't the same hold for spaces? An indent level can be made from any number of spaces. You could use two spaces to indent a class' contents, four for functions, and two again for loops. > and unless I know the convention you are using to display the tabs I > cannot know how many indents are equivalent to a tabstop. That is only true if you mix spaces and tabs. If you use only tabs OR only spaces to indent, everything is perfectly clear. >> Seriously people, this is about separating the content of a source >> file from how it is displayed. It's about letting people work >> together while also allowing them to have control over their own >> environments, something which is and always has been central to the >> hacker ethos. > > Precisely. Using spaces everywhere allows this No it doesn't! I have tabstops every four characters, which is a pleasant indent level for me. Other people have trouble reading the code that way, and want two or eight character wide indents. When using tabs, everybody can place the tabstops for themselves, and as long as tabstop N is more to the left than tabstop N+1, everything is fine. By using spaces, the writer of the code determines the size of the indentation, not the viewer. Since code is generally read more than it is written, the viewer is quite important. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From wnoise at ofb.net Sun May 7 16:38:04 2006 From: wnoise at ofb.net (Aaron Denney) Date: Sun, 7 May 2006 20:38:04 +0000 (UTC) Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1146990071.634244.83380@i39g2000cwa.googlegroups.com> Message-ID: ["Followup-To:" header set to comp.lang.functional.] On 2006-05-07, brian at sweetapp.com wrote: > - it fits most programmers brains i.e. it is similar enough to > languages that most programmers have experience with and the > differences are usually perceived to beneficial (exception: > people from a Java/C/C++ background often perceive dynamic > typing as a misfeature and have to struggle with it) It is a misfeature. It's just less of a misfeature than the typing of Java/C/C++, etc. -- Aaron Denney -><- From digitalorganics at gmail.com Tue May 23 08:27:35 2006 From: digitalorganics at gmail.com (Cloudthunder) Date: Tue, 23 May 2006 08:27:35 -0400 Subject: Accessing object parent properties Message-ID: I have two classes. I later create instances. One class creates an instance of the other class within itself. My question, is how does the child access the parent's properties, since it doesn't know ahead of time that it's going to be "adopted"? Example: class Boo: pass class Foo: X = 1 __init__(self): self.test = boo() How in this case does the boo instance (self.test) access variable X? I need to write a function in the Boo class that assume the Boo instance is going to be instantiated within another class instance which will have certain variables it needs to access. How do I do this? Am I making sense? Thank you to anyone who can help. - Cloudthunder -------------- next part -------------- An HTML attachment was scrubbed... URL: From paddy3118 at netscape.net Fri May 12 01:52:40 2006 From: paddy3118 at netscape.net (Paddy) Date: 11 May 2006 22:52:40 -0700 Subject: Reg Ex help References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> <1147412848.145617.308680@q12g2000cwa.googlegroups.com> Message-ID: <1147413160.250608.4390@q12g2000cwa.googlegroups.com> P.S. This is how it works: >>> s ="/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4" >>> s '/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4' >>> s.split() ['/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT', 'from', '/main/parallel_branch_1/release_branch_1.0/4'] >>> s.split()[0] '/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT' >>> s.split()[0].split('/') ['', 'main', 'parallel_branch_1', 'release_branch_1.0', 'dbg_for_python', 'CHECKEDOUT'] >>> s.split()[0].split('/')[-1] 'CHECKEDOUT' >>> s.split()[0].split('/')[-2] 'dbg_for_python' >>> s ="/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4" >>> s.split()[0].split('/')[-2] 'dbg_for_python' >>> - Paddy. From dongdonglove8 at hotmail.com Sun May 28 10:47:30 2006 From: dongdonglove8 at hotmail.com (python) Date: 28 May 2006 07:47:30 -0700 Subject: iteration over non-sequence ,how can I resolve it? In-Reply-To: References: <1148822420.452617.79720@u72g2000cwu.googlegroups.com> Message-ID: <1148827650.075896.124970@g10g2000cwb.googlegroups.com> To BJ?rn Lindqvist : thank you . how to write the code specifically ?Could you give a example? From miki.tebeka at gmail.com Mon May 15 03:09:56 2006 From: miki.tebeka at gmail.com (Miki) Date: 15 May 2006 00:09:56 -0700 Subject: Compile Python References: <_yU9g.163762$P01.96284@pd7tw3no> Message-ID: <1147676996.534369.146210@j55g2000cwa.googlegroups.com> Hello Zoidberg, > How would one compile python with Visual Studio 2005? By reading the section "Building on non-UNIX systems" in the README file (hint: chceck out the "PC" directory) Miki http://pythonwise.blogspot.com/ From aleax at mac.com Fri May 12 01:47:13 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 11 May 2006 22:47:13 -0700 Subject: Time to bundle PythonWin References: Message-ID: <1hf737g.1oyxbs31plch4nN%aleax@mac.com> Dave Benjamin wrote: ... > It's time to bundle PythonWin. No: the Python Standard Distribution, in 2.5, includes instead ctypes, which is lower-level than PythonWin but more general (exists for other platforms, lets you call other DLLs on Windows and not just those wrapped for you by the author). Alex From grante at visi.com Mon May 1 15:57:09 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 01 May 2006 19:57:09 -0000 Subject: How to efficiently read binary files? References: <125acgep357kbd8@corp.supernews.com> <125c8sbqsd7a952@corp.supernews.com> <125cfokq609se5d@corp.supernews.com> <125cmm985vbaf@corp.supernews.com> Message-ID: <125cq0ls6dbm0b1@corp.supernews.com> On 2006-05-01, Robert Kern wrote: > Oh, I saw the smiley. I knew it was meant to be humorous. I > just didn't understand it. The only "batteries" reference I > know of in this context is the "batteries included" philosophy > of the stdlib. Of course, none of Numeric, numarray, or numpy > have anything to do with the stdlib, so again I am confused. Sorry. I forgot about the distinction between the standard library and the "third-party" packages like scientific packages. -- Grant Edwards grante Yow! I think I'll make at SCRAMBLED EGGS!! They're visi.com each in LITTLE SHELLS... From lordlandon at gmail.com Wed May 3 18:59:16 2006 From: lordlandon at gmail.com (Lord Landon) Date: Wed, 3 May 2006 18:59:16 -0400 Subject: scope of variables In-Reply-To: <87zmhyagqq.fsf@localhost.localdomain> References: <874q06bz4c.fsf@localhost.localdomain> <87zmhyagqq.fsf@localhost.localdomain> Message-ID: <682277700605031559w3623e7e6lbb53e6f3614d6ffc@mail.gmail.com> Try >>> prnt() o.o' On 04 May 2006 08:25:01 +1000, Gary Wessle wrote: > "Steve R. Hastings" writes: > > > On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote: > > > b = 3 > > > def adding(a) > > > print a + b > > > > > > it seams not to see the up-level scope where b is defined. > > > > Assuming you put a ':' after the "def adding(a)", this should work in > > recent versions of Python. In Python 2.0 and older, this will not work. > > the example was an in-accuretlly representation of a the problem I am > having. my apologies. > > a = [] > def prnt(): > print len(a) > > >>> prnt > > > I expect to get 0 "the length of list a" > -- > http://mail.python.org/mailman/listinfo/python-list > -- Lord Landon rules over all! From xah at xahlee.org Wed May 24 04:29:37 2006 From: xah at xahlee.org (Xah Lee) Date: 24 May 2006 01:29:37 -0700 Subject: John Bokma harassment In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> I'm sorry to trouble everyone. But as you might know, due to my controversial writings and style, recently John Bokma lobbied people to complaint to my web hosting provider. After exchanging a few emails, my web hosting provider sent me a 30-day account cancellation notice last Friday. I'm not sure I will be able to keep using their service, but I do hope so. I do not like to post off-topic messages, but this is newsgroup incidence is getting out of hand, and I wish people to know about it. I wrote some full detail here: http://xahlee.org/Periodic_dosage_dir/t2/harassment.html If you believe this lobbying to my webhosting provider is unjust, please write to my web hosting provider abuse at dreamhost.com Your help is appreciated. Thank you. Xah xah at xahlee.org ? http://xahlee.org/ From s.schmeier at gmail.com Wed May 10 05:39:16 2006 From: s.schmeier at gmail.com (s.schmeier at gmail.com) Date: 10 May 2006 02:39:16 -0700 Subject: advanced number recognition in strings? In-Reply-To: References: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> Message-ID: <1147253956.002287.291320@g10g2000cwb.googlegroups.com> Thank you all for your suggestions. After a few modifications the approach with the regexps works well! Sebastian From phpbird at gmail.com Tue May 23 21:31:50 2006 From: phpbird at gmail.com (Ju Hui) Date: 23 May 2006 18:31:50 -0700 Subject: how to change sys.path? In-Reply-To: References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <4473867f$0$7721$626a54ce@news.free.fr> Message-ID: <1148434309.969730.50700@i39g2000cwa.googlegroups.com> yes, we can change PYTHONPATH to add some path to sys.path value, but how to remove item from sys.path? From taleinat at gmail.com Mon May 1 03:43:05 2006 From: taleinat at gmail.com (taleinat at gmail.com) Date: 1 May 2006 00:43:05 -0700 Subject: self modifying code References: <445399A1.9020506@jessikat.plus.net> <44548536.7060409@jessikat.plus.net> Message-ID: <1146469385.334797.128930@i39g2000cwa.googlegroups.com> First of all, the test can be optimized by adding a boolean flag which indicates if the data has been initialized or not, and then just testing a boolean value instead of doing an "is" comparison, at the cost of an extra global variable. But this is still ugly (actually uglier IMO). I think this is a more Pythonic way to do it. This class implements a function which initializes itself upon the first call: class InitializingFunction(object): def __init__(self, init): def initializer(*args, **kw): self.func = init() return self(*args, **kw) self.func = initializer def __call__(self, *args, **kw): return self.func(*args, **kw) Now you can write your function almost exactly like you did before: def init(): data = somethingcomplexandcostly() def foo(a): return simple(data, a) return foo func = InitializingFunction(init) What have we gained from this? Two major advantages: * no ugly 'global' statement * no reliance on the function's name And now you can easily create such functions forever using this class to abstract away the ugly implementation ;) Notice that since Function Decorators were introduced in Python2.4, you can use InitializingFunction as a Decorator to achieve the same effect, this time even without the need for a temporary name for a function: @InitializingFunction def func(): data = somethingcomplexandcostly() def foo(a): return simple(data, a) return foo And finally I must note that no matter which way you turn this around, it will still be hard to read! From steve at holdenweb.com Sat May 27 06:34:47 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 27 May 2006 11:34:47 +0100 Subject: Method Delegation To Subinstances In-Reply-To: References: Message-ID: Cloudthunder wrote: > In the example: > > class Boo: > def __init__(self, parent): > self.parent = parent > print self.parent.testme > def run(): > print "Yahooooo!" > > class Foo: > testme = "I love you!" > def __init__(self): > test = Boo(self) > > A = Foo() > > > How can I set up method delegation so that I can do the following: > > A.run() > > and have this call refer to the run() method within the boo instance? > Also, what if I have tons of functions like run() within the boo > instance and I want all them to be directly accessible as if they were > part of their parent (the Foo instance)? > The usual way is to provide a __getattr__ method, since this is invoked after the usual mechanisms have failed to produce a sought attribute. class Boo: def run(self): print "Yahooooo!" def identify(self): print repr(self) class Foo: testme = "I love you!" def __init__(self): self.test = Boo() def __getattr__(self, attname): return getattr(self.test, attname) A = Foo() B = Boo() B.run() B.identify() A.run() A.identify() sholden at bigboy ~/Projects/Python $ python test49.py Yahooooo! <__main__.Boo instance at 0x186c002c> Yahooooo! <__main__.Boo instance at 0x186b9d4c> regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From joe.hrbek at gmail.com Mon May 1 08:03:49 2006 From: joe.hrbek at gmail.com (joe.hrbek at gmail.com) Date: 1 May 2006 05:03:49 -0700 Subject: python and xulrunner In-Reply-To: References: <1146439953.280364.309130@e56g2000cwe.googlegroups.com> Message-ID: <1146485029.892845.45380@i40g2000cwc.googlegroups.com> Well, it's my understanding (I could be wrong), that pyxpcom is to enable firefox/mozilla to use python. My interest is more in the area of xulrunner. I've read that page several times and pulled compiler/linker build steps from it, but never followed it exactly. I suppose I can try pyxpcom instead. Maybe if i can compile that i could coax xulrunner into compiling. Unfortunately, most of the windows pieces are listed as "todo" and "there are no special build instructions", which is why i've been taking pieces from several different sources and trying to make it work. :( From vbgunz at gmail.com Fri May 5 10:03:45 2006 From: vbgunz at gmail.com (vbgunz) Date: 5 May 2006 07:03:45 -0700 Subject: Is this a legal / acceptable statement ? In-Reply-To: <2AI6g.10201$9c6.5375@dukeread11> References: <2AI6g.10201$9c6.5375@dukeread11> Message-ID: <1146837825.644979.313120@j33g2000cwa.googlegroups.com> you don't have to say: if True == l_init it is suggested you simply say: if l_init: Remember the and operator requires expressions on both sides to be true to continue. If you notice, your expression on the right side of the 'and' is an assignment and so this is forbidden (SyntaxError). assignments only work on lines by themselves and no where else. if you meant == rather than = remember this, l_value doesn't exist and would pull up a NameError *but* because the first expression evaluates as false the second expression is never evaluated. refactor your code ASAP. good luck! From skn at skn.com Wed May 3 08:42:56 2006 From: skn at skn.com (Shankar) Date: Wed, 3 May 2006 18:12:56 +0530 Subject: Running compiled Python files Message-ID: Hello, I am trying to run compiled Python files (*.pyc and *.pyo) using Python C API. I am using the method PyRun_FileFlags() for this purpose. The code snippet is as follows:- PyCompilerFlags myFlags; myFlags.cf_flags=1; // I tried all values 0, 1 and 2 PyRun_FileFlags(script, file, Py_file_input, globals, locals, &myFlags); But unfortunately I get the following exception:- "DeprecationWarning: Non-ASCII character '\xf2' in file E:\test.pyc on line 1, but no encoding declared; see http://www.python.org/peps/pep-0263.html for details" When I run the .py file, then things work fine. The .py file contains only one statement, print "Hello World" Which Python C API should I use to run compiled Python files(*.pyc and *.pyo) in the scenario where the source file (*.py) is not present. Thanks in advance, Regards, skn From mystilleef at gmail.com Wed May 10 08:17:28 2006 From: mystilleef at gmail.com (mystilleef) Date: 10 May 2006 05:17:28 -0700 Subject: Python editor recommendation. In-Reply-To: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1147263448.737381.198050@j73g2000cwa.googlegroups.com> The powerful no-nonsense, no-frills, no-hassle, no-fuzz editor, Scribes. Supports everything you'd want in an editor, it's nimble, fast and agile, and it has virtually no learning curve. http://scribes.sourceforge.net/ http://scribes.sourceforge.net/snippets.htm (Flash Demo) http://www.minds.nuim.ie/~dez/images/blog/scribes.html (GIF Demo) From larry.bates at websafe.com Tue May 23 16:46:24 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 23 May 2006 15:46:24 -0500 Subject: real time info to web browser from apache side ? In-Reply-To: <1148408900.176202.281530@g10g2000cwb.googlegroups.com> References: <1148408900.176202.281530@g10g2000cwb.googlegroups.com> Message-ID: Joseph wrote: > I know about writing CGI application using Perl and Apache to refresh a > static webpage that displays on the browser. But now i have an > application requirement that I hope someone can help me. > > The server side sits in another room down the factory plant, its > monitoring some hardware environment, namely temperatures and pressures > etc inside the plant. This server of course have Apache running. I > would like to be able to have a browser in the comfortable office > somewhere point to the apache server, and after I enter the password, > it would display the temperature and pressures etc in the plant (in > real time, ie. as the temperate changes from a degree to another, the > browser will immediately display this). So I am looking more for a > push technology than a pull from teh browser (user hit Ctrl-R to > refresh is a pull). > > What are the current technology that allows for this. I know its > possible because I can use my browser sometimes to chat with people > online, and I swear that I don't have to do a Control-R everytime to > see that the other person's typing is updating constantly on my > browser. > > Thanks in advance, > Push technology wannabe > I would use AJAX so that I could query the server via XMLrpc calls to update the browser. You can have much higher refresh rates using this method. The alternative is to just have the browser refresh every few seconds by imbedding a header at the top. Something like: Refresh every 10 seconds. -Larry Bates would refresh every 10 seconds. From williams.jasonscott at gmail.com Mon May 15 23:34:30 2006 From: williams.jasonscott at gmail.com (williams.jasonscott at gmail.com) Date: 15 May 2006 20:34:30 -0700 Subject: C API: getting sys.argv In-Reply-To: <1147749997.535248.71490@g10g2000cwb.googlegroups.com> References: <1147748640.699770.285430@g10g2000cwb.googlegroups.com> <1147749997.535248.71490@g10g2000cwb.googlegroups.com> Message-ID: <1147750469.993824.112780@g10g2000cwb.googlegroups.com> John Machin wrote: > > PyObject *_argv = PyImport_ImportModule("sys.argv"); > > What does the name of the function tell you? You can't do that in one > hit. Start with > PyObject *_sys = PyImport_ImportModule("sys"); > then you need to get the module's argv attribute. I just figured this out, doh. Thanks. > However a better design might be have your extension module have an arg > which can be *any* list of strings. That makes it more flexible, at the > expense of making the caller pass sys.argv. But it would save you > having to muck about with importing "sys", then plucking out the > module's argv attribute. but this is great advice. Thanks! From maxm at mxm.dk Mon May 29 10:19:24 2006 From: maxm at mxm.dk (Max M) Date: Mon, 29 May 2006 16:19:24 +0200 Subject: send an email with picture/rich text format in the body In-Reply-To: <447af3f0$1@nntp0.pdx.net> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <1148797671.937857.151250@y43g2000cwc.googlegroups.com> <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> <447af3f0$1@nntp0.pdx.net> Message-ID: <447b0294$0$38640$edfadb0f@dread12.news.tele.dk> Scott David Daniels wrote: > Max M wrote: > >> 90% of users are non-technical users who use standard email readers, >> that can easily read html messages. >> >> In my experience the kind of user that receives emails with html and >> pictures often prefer it that way. >> >> So why bother with the lecture? I cannot remember when I have last >> received a relevant email that I could not read in text mode. > > > Because > (A) This _is_ a technical newsgroup with mores you are violating. *I* am? How? By disagreeing on how technology should be used? > (B) Some of us "technical users" avoid such email/news readers > precisely because they can cause tracking across the web. Yes but some times it's just simpler to send formatted text and images. I also use text only email. But I don't believe everybody else has to. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From pmartin at snakecard.com Fri May 12 09:59:40 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 12 May 2006 08:59:40 -0500 Subject: nix logon in Python Message-ID: Hi, Are there any (even prototypes/proof of concept) gdm/kdm/xdm.../-style packages written in Python ? Regards, Philippe From onurb at xiludom.gro Fri May 5 10:55:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 16:55:26 +0200 Subject: Is this a legal / acceptable statement ? In-Reply-To: References: <2AI6g.10201$9c6.5375@dukeread11> <-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> Message-ID: <445b67bb$0$16736$626a54ce@news.free.fr> Philippe Martin wrote: (snip) > > l_init really is a boolean parameter and l_value a value that _might_ exist > in a shelve. > > So I just want to have a parameter to a method so if the first value tested > is false (l_init) then the second (l_value) does not get tested ... because > it is the second in the statement and only seems to get evaluated if the > first one is true. s/seems to get/is/ But this is a really unpythonic way to do things IMHO. Either use a try/except block (probably the most straightforward solution), or, as in Larry's post, test for the existence of 'l_value' in locals(). 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 onurb at xiludom.gro Fri May 5 04:54:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 10:54:04 +0200 Subject: Python for Perl programmers In-Reply-To: References: Message-ID: <445b1309$0$16429$626a54ce@news.free.fr> A.M wrote: > Hi, > > Is there any efficient online resource or book that help experienced Perl > programmers to Python? > My fellow coworker - experimented Perl coder - confirms that the official tutorial and diveintopython should be enough to get you started. Also, the Python Cookbook and reading this group may help you grasp pythonic idioms. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From robert.kern at gmail.com Thu May 11 01:52:03 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 00:52:03 -0500 Subject: problem with array and for loop In-Reply-To: References: Message-ID: Fabian Braennstroem wrote: > Hi, > > I have a 'simple' problem with a multidimension array in a > for loop. It looks like this: > > wert= zeros([127,2]) > wert1= zeros(127) > m=1 > l=1 > > for pos in [pos1,pos2,pos3]: > for i in range(1,125): > wert[l,m]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i); > # wert1[i]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i); > m=m+1; > l=l+1; > > It works for the 1D 'wert1'. Does anyone have an idea? Oy vey. So the first time through, you are setting the second column of wert. Then l (btw, never, ever use lower-case "l" as a single-letter variable name; it looks like "1") gets incremented to 2, which would try to put data into the third column of wert. However, wert only has two columns. Are you aware that numpy array indices start with 0, not 1? You will probably want to ask numpy questions on the numpy-discussion mailing list: http://www.scipy.org/Mailing_Lists -- 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 tedlandis at gmail.com Mon May 8 11:44:33 2006 From: tedlandis at gmail.com (Ted) Date: 8 May 2006 08:44:33 -0700 Subject: which is better, string concatentation or substitution? In-Reply-To: References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> Message-ID: <1147103073.724710.177040@y43g2000cwc.googlegroups.com> Thank you Roy. It seems if you lurk here long enough you eventually get all you questions answered without even asking! ;-) Roy Smith wrote: > John Salerno wrote: > >Roy Smith wrote: > > > >> One may be marginally faster, but they both require copying the source > >> string, and are thus both O(n). > > > >Sorry, I'm not familiar with the O(n) notation. > > OK, here's a quick tutorial to "big-oh" notation. It's a way of > measuring algorithmic complexity. The O stands for "on the Order > of". > > For any algorithm, if you process n things (in the case of the strings > we're talking about, n would be the total number of characters in all > the strings), you can compute the number of steps it takes to complete > all the processing as some function of n. > > For example, let's say a given algorithm took 4n^2 + 5n + 17 steps to > complete. It doesn't take much experimentation to prove to yourself > that for all but the very smallest values of n, the constant 17 is > completely insignificant. In fact, n doesn't have to get very big > before the 5n term becomes insignificant too. To a reasonable > approximation, you could say that the algorithm takes 4n^2 steps and > be close enough. For small values of n, this will be a bad > approximation, but it doesn't really matter for small values of n. > For large values of n (think hundreds, thousands or even millions), > it's just fine. > > So, the first rule of O() notation is that when looking at how fast an > algorithm runs, you need only consider the highest order term > (i.e. the one with the biggest exponent). > > But, it gets even better. Let's compare two algorithms, the one > above, which takes (approximately) 4n^2 steps, and another one which > takes 10n steps, for varous values of n: > > n 10n 4n^2 > --- ------ ------ > 1 10 4 > 2 20 16 > 3 30 36 > 4 40 64 > 5 50 100 > 6 60 144 > 7 70 196 > 8 80 256 > 9 90 324 > 10 100 400 > 11 110 484 > 12 120 576 > 13 130 676 > 14 140 784 > 15 150 900 > 16 160 1024 > 17 170 1156 > 18 180 1296 > 19 190 1444 > 20 200 1600 > > Notice that it doesn't take long for the fact that n^2 grows a lot > faster than n to swamp the fact that 10 is bigger than 4. So the next > step in simplification is to say that not only don't the lower-order > terms matter, but the coefficient on the highest order term doesn't > even matter. For a large enough n, all that matters is the exponent > (for the moment, I'm making a further simplification that all > algorithms can be described by polynomials with integer exponents). > > So, we get things like: > > O(n^0), which is almost always written as O(1). This is a "constant > time" algorithm, one which takes the same amount of steps to execute > no matter how big the input is. For example, in python, you can > write, "x = 'foo'". That assignment statement takes the same amount > of time no matter how long the string is. All of these execute in the > same number of steps: > > x = '' > x = 'foo' > x = 'a very long string with lots and lots of characters' > > We can say that "assignment is constant time", or "assignment is > O(1)". > > The next step up is O(n). This is "linear time" algorithm. It takes > a number of steps which is directly proportional to the size of the > input. A good example might be "if 'x' in 'bar'". The obvious way to > implement this (and, I assume, the way it is implemented in Python), > is to loop over the string, comparing 'x' to each character in 'bar', > one by one. This takes as many steps as there are characters in the > string. > > Next comes O(n^2), also knows as "quadratic time". This means if your > input is of size n, the algorithm will take n^2 steps to run. > Quadratic algorithms are generally considered very slow, and to be > avoided if at all possible. > > Once you get used to thinking like this, it's easy to look at a piece > of code and say, "oh, that's quadratic", or "that's linear", and > instantly know which is faster for some some large input. And once > you've started thinking like that, you've made one of the big jumps > from thinking like a coder to thinking like a computer scientist (or, > if you prefer, like a software engineer). > > Google "algorithmic complexity" or "big o notation" (perhaps spelled > "big oh") for more info. I would normally recommend Wikipedia, but I > just took a quick look at their "Big O notation" article, and noticed > it's full of formal mathematical gobbledygook which just serves to > obscure what is really a fairly easy concept. From duncan.booth at invalid.invalid Fri May 12 10:25:48 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 May 2006 14:25:48 GMT Subject: NEWBIE: Tokenize command output References: <44648ed3$0$12812$636a55ce@news.free.fr> Message-ID: bruno at modulix wrote: >> Otherwise, just to be informed, what advantage does rstrip() have over >> [:-1] (if the two cases are considered uneventfully the same)? > > 1/ if your line doesn't end with a newline, line[:-1] will still remove > the last caracter. > In particular, if the last line of the file doesn't end with a newline then the last line you read won't have a newline to be stripped. From python.list at tim.thechases.com Thu May 11 11:45:17 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 11 May 2006 10:45:17 -0500 Subject: NEWBIE: Tokenize command output In-Reply-To: References: Message-ID: <44635C0D.9070608@tim.thechases.com> Lorenzo Thurman wrote: > This is what I have so far: > > // > #!/usr/bin/python > > import os > > cmd = 'ntpq -p' > > output = os.popen(cmd).read() > // > > The output is saved in the variable 'output'. What I need to do next is > select the line from that output that starts with the '*' Well, if you don't need "output" for anything else, you can just iterate over the lines with import os cmd = 'ntpq -p' p = os.popen(cmd) starLines = [line for line in p.readlines() if line.startswith("*")] or you may optionally want to prune of the "\n" characters in the process: starLines = [line[:-1] for line in p.readlines() if line.startswith("*")] If there's only ever one, then you can just use myLine = starLines[0] Otherwise, you'll have to react accordingly if there are zero lines or more than one line that begin(s) with an asterisk. > remote refid st t when poll reach delay offset > jitter [cut] > *caesar.cs.wisc. 128.105.201.11 2 u 635 1024 377 29.514 -0.231 > 0.077 > >>From there, I need to tokenize the line using the spaces as delimiters. > Can someone give me some pointers? Again, you can use the one-line pythonizm of "tuple unpacking" here (the split() method takes an optional parameter for the delimiter, but defaults to whitespace): remote, refid, st, t, when, poll, reach, delay, offset, jitter = myLine.split() If you just want one of them, you can do it by offset: delay = myLine.split()[7] HTH, -tkc From thirsteh at gmail.com Tue May 23 18:48:08 2006 From: thirsteh at gmail.com (Patrick M. Nielsen) Date: Wed, 24 May 2006 00:48:08 +0200 Subject: Telnet linebreaks Message-ID: <28dc07920605231548w6fd48d25t463f510338044da8@mail.gmail.com> Hey guys. I have begun playing with the Simple MUD server example from the Stackless website ( http://www.stackless.com/Members/rmtew/code/mud.py ) and it's all good so far, however, I've come to notice something that I remember from back in the days (some old mud code), but I don't remember what I did to fix it. While the MUD reads lines from Telnet clients just fine, clients such as Gmud are practically ignored, probably because Gmud doesn't send Telnet-valid data ('\x08'?). However, a MUD that is not accessible to one such client or others isn't much good, so I'd appreciate some help in pinpointing the problem. These are the code blocks that need modification (I believe) def read(self): # TELNET ret = self.readChannel.receive() if self.echo: if ret == '\x08': self.send(ret+" ") self.send(ret) return ret def readline(self): # TELNET buf = self.readBuffer while True: if buf.find('\r\n') > -1: # MUD clients that aren't using the telnet protocol i = buf.index('\r\n') # need to be able to do stuff. ret = buf[:i+2] self.readBuffer = buf[i+2:] while '\x08' in ret: i = ret.index('\x08') if i == 0: ret = ret[1:] else: ret = ret[:i-1]+ret[i+1:] return ret buf += self.read() I'm suspecting that Gmud doesn't send '\x08', since from looking at some old DIKU code, I see that the if '\n' || '\r' are there as well, but there is no check for '\x08'. If this is indeed the cause of my problem, how would I go about doing it? Thanks in advance. -------------- next part -------------- An HTML attachment was scrubbed... URL: From tdelaney at avaya.com Sun May 14 22:35:35 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 15 May 2006 12:35:35 +1000 Subject: count items in generator Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6F1@au3010avexu1.global.avaya.com> George Sakkis wrote: > Delaney, Timothy (Tim) wrote: >> >> list(itertools.count()) will eventually fail with a MemoryError. > > That's more of a theoretical argument on why the latter is worse. How > many real-world programs are prepared for MemoryError every time they > call list(), catch it and handle it graciously ? I'd say that the only > reason an exception would be preferable in such case would be > debugging; it's nice to have an informative traceback instead of a > program that entered an infinite loop. That's exactly my point. Assuming your test coverage is good, such an error would be caught by the MemoryError. An infinite loop should also be caught by timing out the tests, but that's much more dependent on the test harness. Tim Delaney From skip at pobox.com Mon May 22 10:51:47 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 22 May 2006 09:51:47 -0500 Subject: Win32: Detecting when system is locked or sleeping In-Reply-To: <1148308038.487624.201690@i40g2000cwc.googlegroups.com> References: <1148308038.487624.201690@i40g2000cwc.googlegroups.com> Message-ID: <17521.53251.112559.122300@montanaro.dyndns.org> rod> I have written an application which works perfectly when the rod> machine is operating under normal conditions, however when the rod> screen becomes locked it imediately starts to fill up several rod> hundred MB's of memory. What do you mean by "locked"? Unresponsive to mouse or keyboard activity? Blue screen? What is your application doing while it's filling up memory? Which memory, disk or RAM? rod> Is there a way to detect when the system is locked? Perhaps Nagios can help: . In general, I don't think a system can be relied upon to detect its own demise, as the recent PC/Mac commercial about restarting illustrates: . Skip From http Sun May 14 01:50:06 2006 From: http (Paul Rubin) Date: 13 May 2006 22:50:06 -0700 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1147584805.462908.201300@g10g2000cwb.googlegroups.com> Message-ID: <7x7j4pjgtt.fsf@ruckus.brouhaha.com> "George Sakkis" writes: > As clunky as it seems, I don't think you can beat it in terms of > brevity; if you care about memory efficiency though, here's what I use: > > def length(iterable): > try: return len(iterable) > except: > i = 0 > for x in iterable: i += 1 > return i Alex's example amounted to something like that, for the generator case. Notice that the argument to sum() was a generator comprehension. The sum function then iterated through it. From seberino at spawar.navy.mil Sat May 6 13:26:35 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 6 May 2006 10:26:35 -0700 Subject: Python Eggs Just install in *ONE* place? Easy to uninstall? Message-ID: <1146936395.028140.15640@i39g2000cwa.googlegroups.com> It appears that apps distributed as Python Eggs are either a single compressed blob in site-packages directory or a directory under site-packages directory. Is this ALWAYS true? So by just erasing stuff under site-packages I can do a COMPLETE uninstallation of an Egg? Chris From pmartin at snakecard.com Thu May 4 08:42:41 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Thu, 04 May 2006 07:42:41 -0500 Subject: Gettings subdirectories References: Message-ID: <5Fm6g.10137$9c6.6757@dukeread11> Hi, The second edition of "Programming Python - O'REILLY - Mark Lutz" shows how to do that using "os.path.walk" Philippe Florian Lindner wrote: > Hello, > how can I get all subdirectories of a given directories? os.listdir() > gives me all entries and I've found no way to tell if an object is a file > or a directory. > > Thanks, > > Florian From steve at hastings.org Wed May 3 15:16:57 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 03 May 2006 12:16:57 -0700 Subject: NewB question on text manipulation References: <1146634624.622224.323010@u72g2000cwu.googlegroups.com> <1146677395.523919.319760@i39g2000cwa.googlegroups.com> Message-ID: On Wed, 03 May 2006 10:29:55 -0700, ProvoWallis wrote: > I only have one issue that I can't figure out. When I print the new > string I'm getting all of the values in the lt list rather than just > the one that corresponds to the original entry. I did not realize that each entry would have its own LT value. I had thought that there were several sets of and with one . You only showed one example... I have modified the program to collect LT values at the same time it collects SC and XC values. Also, it now collects whatever code appears before the first SC code. I don't know what this code is for so I just called the variable "before". Notes on the code: * Instead of doing this: title = m.group(2) title = title.strip() I just do this: title = m.group(2).strip() You can apply string methods on any string, and it's convenient to do it all in one line. There are several lines like that. * There are two patterns to detect the LT code. The first one is for finding it, and the second one is only for removing it. The second one uses '^' to anchor the pattern, so it will only remove the LT code if the LT code is the first thing in the string. The first pattern does not have the '^' anchor so it will look ahead, past any number of codes, to find the next code. * Otherwise this is pretty much like the first version. It collects data, saves it in a list, and then prints its output from the list. I am busy now, so I won't have any time to make any more versions of this for you. I hope you can study what I have done and understand how to apply the ideas to your problems. Good luck! -- cut here -- cut here -- cut here -- cut here -- cut here -- import re s = "<1>APPEAL40-24; 40-46; 42-46; 42-48; 42-62; 42-63 " + \ "<1>PROC GUIDE921(b)(1)" + \ "<1>FAM LAW ENF259-232-687" + \ "<1>APPEAL40-38; 40-44; 44-18; 45-151" s_space = " " # a single space s_empty = "" # empty string pat_sc = re.compile("\s*(<[^<]+)([^<]+)([^<]+)") pat_lt = re.compile("([^<]+)") pat_lt_remove = re.compile("^([^<]+)") lst = [] lt = None while True: m = pat_sc.search(s) if not m: break before = m.group(1).strip() title = m.group(2).strip() xc = m.group(3).replace(s_space, s_empty) s = pat_sc.sub(s_empty, s, 1) m = pat_lt.search(s) if m: lt = m.group(1) lt = lt.strip() s = pat_lt_remove.sub(s_empty, s, 1) tup = (before, title, xc, lt) lst.append(tup) for before, title, xc, lt in lst: lst_pp = xc.split(";") for pp in lst_pp: print "%s%s%s%s" % (before, title, pp, lt) -- cut here -- cut here -- cut here -- cut here -- cut here -- -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From timr at probo.com Wed May 24 01:12:35 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 24 May 2006 05:12:35 GMT Subject: Doubt with wx.CallAfter References: Message-ID: carlosperezs at alumnos.uvigo.es wrote: > >Hello together:: > >I have programmed this fuction: > >def OnNewMovie(self, event): > """ Local user receives a new movie event from a user""" > > #self.log.debug( "Got OnNewMovie, " + `event`) > if event.data[0] == self.pubId: > fDep.write("New movie equal\n") > fDep.flush() > #self.log.debug( "Returning, it's my movie") > # This lets two users connect at the same time > self.lockInitSession.acquire() > if self.vInitSession == False: > self.vInitSession = True > self.lockInitSession.release() > else: > self.lockInitSession.release() > return > > #self.log.debug( "Doing remote load event id = " + `event.data[0]` + ", >myid=" + `self.pubId`) > self.lockInitSession.acquire() > self.vInitSession = False > self.lockInitSession.release() > > self.sharedAppClient.UpdateDataCache() > self.GetState() > wx.CallAfter(self.sm.RemoteLoadMovie) > >This function is a handler that is executed when a event occurs. At the end is >wx.CallAfter call. >Imagine that two events occur simultaneously. Two events cannot occur simultaneously. It is impossible. There is only one message queue for your window. All messages will funnel through that one queue. There is one message loop for the thread that owns the window, which is pulling messages from the queue and dispatching them to message handlers. It cannot pull another message from the queue until you have finished processing this one and returned to the message loop. >This function takes one event. >After executing ax.CallAfter call would tke the second event. Then , my doubt >would be, would be there 2 threads simultanously executing: one belongs to >self.sm.RemoteLoadMovie and the another one belongs to the handler for the >second event? No. wxCallAfter basically posts another message to the message queue, which will be handled after all the existing messages have been dispatched. Windows message handling is quite synchronous. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From siona at chiark.greenend.org.uk Thu May 4 10:41:02 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 May 2006 15:41:02 +0100 (BST) Subject: python strings References: <1146684876.311829.297280@i39g2000cwa.googlegroups.com> <445908D1.7040008@ghaering.de> Message-ID: Bryan wrote: > >>> s = '\x00' > >>> s[0] == chr(0) >True That's a little excessive when: >>> s = '\0' >>> s[0] == chr(0) True Oh, and to reassure the OP that that null really is *in* the string: >>> len(s) 1 -- \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 Wed May 10 04:52:19 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 10 May 2006 10:52:19 +0200 Subject: Memory leak in Python References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> Message-ID: diffuser78 at gmail.com enlightened us with: > My program is a simulation program with four classes and it mimics > bittorrent file sharing systems on 2000 nodes. Wouldn't it be better to use an existing simulator? That way, you won't have to do the stuff you don't want to think about, and focus on the more interesting parts. There are plenty of discrete-event and discrete-time simulators to choose from. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From aylwyn at cantab.net Wed May 17 11:00:55 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 08:00:55 -0700 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: <1147878055.475472.118270@j73g2000cwa.googlegroups.com> Andy Sy >I guess this *REALLY* is how a misguided tab user exercises his 'logic': >Syntax replication (e.g. so-called 'argument construction') is enough, >semantics don't matter. That's quite amusing.. you've unwittingly stumbled on a pretty concise statement of Hilbert's first postulate of formal logic, proved by Godel in 1930.. >ROTFLMAO! Indeed. From defcon8 at gmail.com Fri May 19 02:26:15 2006 From: defcon8 at gmail.com (defcon8) Date: 18 May 2006 23:26:15 -0700 Subject: Getting URL's Message-ID: <1148019975.277742.253400@y43g2000cwc.googlegroups.com> How do I get all the URL's in a page? From nicogrubert at gmail.com Tue May 23 07:32:54 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Tue, 23 May 2006 13:32:54 +0200 Subject: How to open https Site and pass request? Message-ID: <4472F2E6.9040204@gmail.com> Hi there, I am trying to open an https site and pass a request to it in order to simulate the submit of an HTML form on a https site that sets an authentication cookie for a tomcat application, so the the URL I am trying to open points to a web form provided by the tomcat webserver. I tried (Python 2.3.5): >>> import urllib >>> import urllib2 >>> the_url = "https://myserver/application/login.do" >>> user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' >>> headers = { 'User-Agent' : user_agent } >>> values = { 'username' : 'myuser', 'password' : 'mypasswd' } >>> data = urllib.urlencode(values) >>> req = urllib2.Request(the_url, data) >>> handle = urllib2.urlopen(req) This raises the following exception: Traceback (most recent call last): File "", line 1, in ? File "/usr/local/lib/python2.3/urllib2.py", line 129, in urlopen return _opener.open(url, data) File "/usr/local/lib/python2.3/urllib2.py", line 331, in open 'unknown_open', req) File "/usr/local/lib/python2.3/urllib2.py", line 306, in _call_chain result = func(*args) File "/usr/local/lib/python2.3/urllib2.py", line 914, in unknown_open raise URLError('unknown url type: %s' % type) urllib2.URLError: Any idea, what I did wrong? Regards, Nico From fredrik at pythonware.com Thu May 4 07:26:27 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 13:26:27 +0200 Subject: pleac References: <1146740749.200368.173590@g10g2000cwb.googlegroups.com> Message-ID: "jonas" wrote: > After a search on > http://pleac.sourceforge.net/pleac_python/index.html > why python have a low %? why not ask the pleac maintainers? (it might be that pythoneers have better things to do with their time than translating old Perl stuff to Python... if you want Python cook- book stuff, start here: http://aspn.activestate.com/ASPN/Python/Cookbook/ ) From rydis at CD.Chalmers.SE Tue May 9 17:36:24 2006 From: rydis at CD.Chalmers.SE (Martin Rydstr|m Martin Rydstr|m) Date: 09 May 2006 23:36:24 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1hf1hlk.uf6b5hc60js1N%aleax@mac.com> Message-ID: aleax at mac.com (Alex Martelli) writes: > Didn't want to trigger some flamewar;-), but, yes, if that was my only > choice, I'd much rather use small, simple Scheme than huge, complicated, > rich, powerful Common Lisp. ((But in this case I'm biased by early > experiences, since when I learned and used Lisp-ish languages there WAS > no Common Lisp, while Scheme was already there, although not quite the > same language level as today, I'm sure;-)). If that was in the early to mid eighties, which I seem to recall you mentioning, the Lisp dialects mostly in use were huger, more complicated, richer and more powerful than Common Lisp in many, if not most, respects, as far as I can tell. Common Lisp is a (later) augmented least common denominator of those Lisps. The really big thing that's newer and greater in CL is CLOS and the condition system. ',mr -- [Emacs] is written in Lisp, which is the only computer language that is beautiful. -- Neal Stephenson, _In the Beginning was the Command Line_ From finite.automaton at gmail.com Mon May 15 18:36:50 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 15 May 2006 15:36:50 -0700 Subject: How to guess the language of a given textstring? In-Reply-To: <1147731412.848833.225910@j55g2000cwa.googlegroups.com> References: <1147731412.848833.225910@j55g2000cwa.googlegroups.com> Message-ID: <1147732610.377194.236970@u72g2000cwu.googlegroups.com> A search to see how many words from the text belong to english/german/spanish common word dictionaries would be an easy way to get a crude guess at the language. From aylwyn at cantab.net Wed May 17 19:13:54 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 16:13:54 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) References: <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <446B6AD1.4080104@mvista.com> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> Message-ID: <1147907634.532463.63730@u72g2000cwu.googlegroups.com> Carl J. Van Arsdall wrote: > The converse can also be said, "it's difficult to make sure everyone > uses spaces and not tabs". > > I think we've just about beat this discussion to death... nice work > everyone! Yeah - we've got to the repeating ourselves stage. But that's the problem with this issue: it's really hard to get the space-indenters to actually think about it and to address what is being said. Every time it comes up, there's always a few people trying to explain why tabs give are a good idea, facing a whole raft of others spouting stuff like: 'mixing spaces and tabs is bad so use spaces only' 'tabs are x spaces and I like to use y spaces' 'tabs are bad end of story' and these non-arguments are repeated over and over within the same thread. At times it's like talking to a child - and not a bright one at that. Does it matter? Perhaps not if we can use tools which enable us to bridge the divide, like indent auto-detection in emacs and vim. I'm prepared to do that in cases where I have to work with an existing group of coders uasing spaces. But unfortunately the situation is worse than that: tab indentation needs to be actively defended. Most of the coding 'style guides' you'll find (including Python's) advocate spaces only. There are plenty of people who would like tabs removed from the language as an acceptable indentation method - look at the responses to Guido's April Fools blog entry last year. Unlikely perhaps. I hope so. It's a cruel irony that Python's creator didn't appreciate the benefits that tab indentation would bring to his own language - the only major language in which indentation levels actually have semantic significance. From akameswaran at gmail.com Tue May 30 18:31:53 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 30 May 2006 15:31:53 -0700 Subject: Strange behavior with iterables - is this a bug? In-Reply-To: References: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> Message-ID: <1149024968.720932.197940@g10g2000cwb.googlegroups.com> DOH!! thanks a lot. had to be something stupid on my part. Now I get it :) From nospam at nospam.com Fri May 19 14:03:26 2006 From: nospam at nospam.com (3c273) Date: Fri, 19 May 2006 11:03:26 -0700 Subject: Why does the _winreg module start with an underscore Message-ID: Does it signify something? Just curious. Louis From ed at leafe.com Wed May 24 19:50:43 2006 From: ed at leafe.com (Ed Leafe) Date: Wed, 24 May 2006 19:50:43 -0400 Subject: Web frameworks and credit cards Message-ID: <37FBB44B-74F0-4EC7-A55E-3335E6CBFCEC@leafe.com> I may have an opportunity to develop an online ordering system for a client, and will have the ability to develop using any tool I choose. Given the fact that there are more web frameworks in Python than keywords ;-) , what I need to know is any experience anyone out there has had integrating credit card processing with the various Python web frameworks. Until now, my only practical experience is with Zope 2.x, but I'm open to any and all alternatives, so long as it's Python! -- Ed Leafe -- http://leafe.com -- http://dabodev.com From rpdooling at gmail.com Tue May 9 11:00:25 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 9 May 2006 08:00:25 -0700 Subject: Python editor recommendation. References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1147186825.409484.158860@i40g2000cwc.googlegroups.com> >> Vim Yes, and enjoy the month off work while you are learning how to use it ;> From chris at foote.com.au Tue May 16 05:39:42 2006 From: chris at foote.com.au (Chris Foote) Date: Tue, 16 May 2006 19:09:42 +0930 Subject: Large Dictionaries In-Reply-To: <1147738318.330346.231310@j33g2000cwa.googlegroups.com> References: <1147699064.107490@teuthos> <1147738318.330346.231310@j33g2000cwa.googlegroups.com> Message-ID: <1147774466.391591@teuthos> lcaamano wrote: > Sounds like PyTables could be useful. > > http://www.pytables.org In browsing their excellent documentation, it seems that all concepts are built around storing and reading HDF5 format files. Not suitable for this project unfortunately. Cheers, Chris From bdesth.quelquechose at free.quelquepart.fr Tue May 2 21:27:12 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 03:27:12 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> Message-ID: <4457d83f$0$21106$626a54ce@news.free.fr> Edward Elliott a ?crit : > bruno at modulix wrote: > (snip) > >>You skipped the interesting part, so I repost it and ask again: how >>could the following code work without the instance being an explicit >>parameter of the function to be used as a method ? >> >>def someFunc(obj): >> try: >> print obj.name >> except AttributeError: >> print "obj %s has no name" % obj >> >>import types >>m = MyObj('parrot') >>m.someMeth = types.MethodType(someFunc, obj, obj.__class__) >>m.someMeth() > > > I posted the only part that needs modification. Nope. > Here it is again with the > entire segment: > > class MyObj(object): > def __init__(name): > self.name = name <== interpreter binds name 'self' to object instance. > compiler adds 'self' to method sig as 1st param. > > def someFunc(obj): > try: > print obj.name <== 'obj' gets bound to first arg passed. when bound > as a method, first arg will be object instance. > when called as func, it will be first actual arg. > except AttributeError: > print "obj %s has no name" % obj > > import types > m = MyObj('parrot') > m.someMeth = types.MethodType(someFunc, obj, obj.__class__) <== binds obj > to first parameter of someFunc as usual > m.someMeth() > > > >>You see, wrapping a function into a method is not done at compile-time, >>but at runtime. And it can be done manually outside a class statement. >>In the above example, someFunc() can be used as a plain function. > > > All the parameter information has been preserved. > Method signatures are > unchanged from their current form, > so the interpreter has no trouble > deducing arguments. You just don't actually declare self yourself. In this exemple, it was named 'obj', to make clear that there was nothing special about 'self'. As you can see from the call, I didn't actually passed the fist param, since the method wrapper takes care of it... So if we were to implement your proposition (which seems very unlikely...), the above code *would not work* - we'd get a TypeError because of the missing argument. > When > binding a function to an object as above, the interpreter sees and does > exactly the same thing as now. I'm sorry, but you're just plain wrong. *Please* take time to read about the descriptor protocol and understand Python's object model. > >>This >>wouldn't work with some automagical injection of the instance in the >>function's local namespace, because you would then have to write >>"method"'s code diffently from function's code. > > > Maybe this will make it clearer: > > Programmer's view Compiler Interpreter's view > def func (a, b) func (a, b) -> func (a, b) func (a, b) > def method (a) method (a) -> method (self, a) method (self, a) > > IOW the compiler adds 'self' to the front of the parameter list when > processing a method declaration. 1/ there is *no* 'method declaration' in Python 2/ wrapping functions into methods happens at runtime, *not* at compile time. (snip) >>>And the rest should work fine. When the interpreter sees a method >>>declaration, >> >>The interpreter never sees a 'method declaration', since there is no >>such thing as a 'method declaration' in Python. The def statement >>creates a *function* object: > > > Fine, whatever, compiler sees method declaration, There ain't *nothing* like a 'method declaration' in Python. Zilch, nada, none, rien... All there is is the def statement that creates a *function* (and the class statement that creates a class object). > >>>Complete non-sequitor, what does this have to do with self? >> >>It has to do that the obj.name() syntax doesn't imply a *method* call - >>it can as well be a plain function call. > > Ok I see your point, Not quite, I'm afraid. > >>Also, and FWIW: >> >>>>>def moduleFunc(): >> >>... print self.name >>... >> >>>>>moduleFunc() >> >>Traceback (most recent call last): >>NameError: global name 'self' is not defined > > > Exactly, that was my point in the first place. I'm afraid we don't understand each other here. This was supposed to come as an illustration that, if some black magic was to 'inject' the instance (here named 'self') in the local namespace of a 'method' (the way you see it), we would loose the possibility to turn a function into a method. Try to re-read both examples with s/obj/self/ in the first one and s/self/obj/ in this last one. Edward, I know I told you so at least three times, but really, seriously, do *yourself* a favor : take time to read about descriptors and metaclasses - and if possible to experiment a bit - so you can get a better understanding of Python's object model. Then I'll be happy to continue this discussion (. FWIW, I too found at first that having to explicitely declare the instance as first param of a 'function-to-be-used-as-a-method' was an awful wart. And by that time (Python 1.5.2), it actually *was* a wart IMVHO - just like the whole 'old-style-class' stuff should I say. But since 'type-unification' and new-style-classes, the wart has turned into a feature, even if this only become obvious once you get a good enough understanding of how the whole damn thing works. Following it's overall design philosophy, Python exposes (and so let you take control of) almost any detail of the object model implementation. The purpose here is to make simple things simple *and* complex things possibles, and the mean is to have a restricted yet consistent set of mechanisms. It may not be a jewel of pure beauty, but from a practical POV, it ends up being more powerful than what you'll find in most main-stream OOPLs - where simple things happens to be not so simple and complex things sometime almost impossible - and yet much more usable than some more powerful but somewhat cryptic OOPLs (like Common Lisp - which is probably the most astonishing language ever) where almost anything is possible but even the simplest things tend to be complex. Oh, also - should I mention it here ? - Ruby is another pretty nice and powerful OOPL, with a more 'pure' object model (at least at first sight - I have not enough experience with it to know if it holds its promises). While Python is My Favourite Language(tm), I'm not too much religious about this, and can well understand that someone's feature is someone else's wart - thanks the Lord, everyone is different and unique -, and you may feel better with Ruby. From linuxnow at gmail.com Mon May 8 02:15:03 2006 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: 7 May 2006 23:15:03 -0700 Subject: why _import__ only works from interactive interpreter? In-Reply-To: References: <1147041996.232232.165820@i39g2000cwa.googlegroups.com> <1147043686.558715.124540@j73g2000cwa.googlegroups.com> <1147044060.998898.140740@i40g2000cwc.googlegroups.com> Message-ID: <1147068903.306169.52130@i40g2000cwc.googlegroups.com> You are absolutely right, it's that empty entry that allows the absolute path to work. I'll probably add the path to sys.path, but as this is only a config file from which I need just a few vars, I'll try to use execfile, looking in past threads it looks like a better option for this use, I really don't need the new path, it could introduce subtle bugs as it is not something expected. Any equivalent way of doing the same with execfile? From nick at craig-wood.com Wed May 10 06:30:05 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 10 May 2006 05:30:05 -0500 Subject: Incrementally converting a C app to Python References: Message-ID: BJ?rn Lindqvist wrote: > Hello. At work I'm the sole maintainer and developer of a medium sized > ~50k line C application. The lion share of this app was written before > my time so it is pretty hard to read and also contain lots of bugs. > I'm contemplating converting the project to Python because I think > that, in the long run, maintenance will become much easier. And also > because is so much more fun than C. As long as python is fast enough, then go for it! > The app is to big to be rewritten from scratch so I'm thinking of a > way to rewrite it "incrementally." Something like one module, or file, > at a time. Using tools like SWIG, Pyrex or embedding Python in C it > seems like this would be possible. My question is what tools should I > apply and what strategy should I use? Would it be best to use a > top-down approach and rewrite the main files first and work my way > down wrapping the remaining C files using SWIG? Or should I convert > the isolated code files to Python and then embedd it in the C code? > Maybe Pyrex help me with this task? Any insight on this matter is > greatly appreciated. Surely someone has done the exact same thing as > me before. In my experience it is easier to embed C into python than python into C. This is because there are lots of tools to help you with embedding C into python (eg swig or ctypes), but the other way round you are more on your own. So I would re-write the main application loop in python, then swig all the C files and mash them all together. This approach will work well if the C app is well modularised. If not you'll have to work the other way round, embedding bits of modularised python into C. I'd try to convert as much as possible into python in the first pass though. Anything involving string manipulation, hash lookups, linked lists etc will be much easier in python and you'll find you'll make 1 line of python for 5-10 lines of C probably - so maybe that 50k LOC doesn't look so scary as 5k-10k LOC in Python. I bet your C code doesn't have unit tests either... Make sure you write those as you are going along in Python. It will make more code, but it will give you a wonderful feeling of confidence that your code will actually work, and work the same as the C code. -- Nick Craig-Wood -- http://www.craig-wood.com/nick From bignose+hates-spam at benfinney.id.au Mon May 1 17:44:41 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 02 May 2006 07:44:41 +1000 Subject: Setting a module package to use new-style classes References: <1146496624.798907.327060@e56g2000cwe.googlegroups.com> Message-ID: <87y7xlctdi.fsf@benfinney.id.au> "Panos Laganakos" writes: > Is there a way to have a whole module package use the new-style > classes, without having to specify it per module-file or even worse, > per class definition? TTBOMK, you do that with a single statement per module, before any class definitions: __metaclass__ = object In general, code in one module doesn't magically affect other modules. > Maybe by declaring the __metaclass__ in the module's __init__.py? Presumably you mean "the package's __init__.py", which is itself a separate module; so no. -- \ "I hate it when my foot falls asleep during the day, because | `\ that means it's gonna be up all night." -- Steven Wright | _o__) | Ben Finney From python.list at tim.thechases.com Thu May 11 14:07:12 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 11 May 2006 13:07:12 -0500 Subject: Reg Ex help In-Reply-To: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> Message-ID: <44637D50.2090500@tim.thechases.com> > /main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT > from /main/parallel_branch_1/release_branch_1.0/4 > > I want to write a regex that gives me the branch the file was > checkedout on ,in this case - 'dbg_for_python' > > Also if there is a better way than using regex, please let me know. Well, if you have it all in a single string: s = "/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4" you can do branch = s.split("/")[4] which returns the branch, assuming the path from root is the same for each item in question. If not, you can tinker with something like r = re.compile(r'/([^/]*)/CHECKEDOUT') m = r.match(s) and which should make m.groups(1) the resulting item. You don't give much detail regarding what is constant (the number of subdirectories in the path? the CHECKEDOUT portion?, etc) so it's kinda hard to figure out what is most globally applicable. -tkc From andrew.arobert at gmail.com Wed May 24 12:22:43 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 24 May 2006 12:22:43 -0400 Subject: Conversion of perl based regex to python method Message-ID: <127923enb2dbh21@corp.supernews.com> I have two Perl expressions If windows: perl -ple "s/([^\w\s])/sprintf(q#%%%2X#, ord $1)/ge" somefile.txt If posix perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge' somefile.txt The [^\w\s] is a negated expression stating that any character a-zA-Z0-9_, space or tab is ignored. The () captures whatever matches and throws it into the $1 for processing by the sprintf In this case, %%%2X which is a three character hex value. How would you convert this to a python equivalent using the re or similar module? I've begun reading about using re expressions at http://www.amk.ca/python/howto/regex/ but I am still hazy on implementation. Any help you can provide would be greatly appreciated. Thanks, Andy From zhushenli at gmail.com Mon May 8 03:21:50 2006 From: zhushenli at gmail.com (Davy) Date: 8 May 2006 00:21:50 -0700 Subject: Python's regular expression? Message-ID: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> Hi all, I am a C/C++/Perl user and want to switch to Python (I found Python is more similar to C). Does Python support robust regular expression like Perl? And Python and Perl's File content manipulation, which is better? Any suggestions will be appreciated! Best regards, Davy From duncan.booth at invalid.invalid Tue May 16 15:35:08 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 19:35:08 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> Message-ID: achates wrote: > You haven't explained why you think there's a problem with having a > character which, in an unambiguous and non-implementation-specific way, > means 'one level of indentation'. In Python, of all languages, it makes > sense to have such a character because 'one level of indentation' is a > syntactical token processed by the interpreter. > Because it doesn't mean 'one level of indentation', it means 'move to next tabstop' and a tabstop isn't necessarily the same as a level of indentation. In particular a common convention is to have indentations at 4 spaces and tabs expanding to 8 spaces. From defcon8 at gmail.com Sun May 14 04:52:45 2006 From: defcon8 at gmail.com (defcon8) Date: 14 May 2006 01:52:45 -0700 Subject: Cellular automata and image manipulation In-Reply-To: <1147596298.106352.245420@j33g2000cwa.googlegroups.com> References: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> <1147595982.184878.25800@d71g2000cwd.googlegroups.com> <1147596298.106352.245420@j33g2000cwa.googlegroups.com> Message-ID: <1147596765.468995.292560@v46g2000cwv.googlegroups.com> Sorry this is the latest, the previous didn't work so well: import Image x = [] buff = [] buff = [[0 for y in range(41)] for x in range(21)] buff[0][(len(buff[0])-1)/2] = 1 def rule1(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: if buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1: buff[i+1][j] = 1 def rule2(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: buff[i+1][j] = 1 elif buff[i][j-1] == 1 and buff[i][j+1] != 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1 and buff[i][j-1] != 1: buff[i+1][j] = 1 elif buff[i][len(buff[0])-1] == 1 or buff[i][0] == 1: break rule2() nim = Image.new("1", (50,50)) nim.putdata(buff) nim.resize((400,600)).save("output.png") for a in buff: for x in a: if x == 1: print "X", elif x == 0: print " ", print "" for a in buff: print a From softwindow at gmail.com Sat May 20 02:40:26 2006 From: softwindow at gmail.com (softwindow) Date: 19 May 2006 23:40:26 -0700 Subject: FAQ for XML with Python In-Reply-To: References: <3esbg.19024$Lm5.1740@newssvr12.news.prodigy.com> Message-ID: <1148107225.968773.269310@g10g2000cwb.googlegroups.com> Thanks! is very usefull for me From gavinpaterson at yahoo.com Tue May 9 04:50:13 2006 From: gavinpaterson at yahoo.com (gavinpaterson) Date: Tue, 09 May 2006 08:50:13 -0000 Subject: Embedding Python in C++ Problem Message-ID: Dear Pythoners, I am trying to embed a Python script into a C++ application for the first time. Although I have used the example 5.3 Pure Embedding I am having problems with calling the function defined in my program. If I define function multiply in module "multiply.py" def multiply(a,b): print "Will compute", a, "times", b c = 0 for i in range(0, a): c = c + b return c Then call the program with the following arguments: multiply multiply 2 3 Then I'd expect to see the result appear in stdout. The compiled module is found but the program fails to get past: if (pFunc && PyCallable_Check(pFunc)) I am using VC7.1 on windows XP. Where am I going wrong? From paddy3118 at netscape.net Mon May 29 05:09:10 2006 From: paddy3118 at netscape.net (Paddy) Date: 29 May 2006 02:09:10 -0700 Subject: Any other config parsing modules besides ConfigParser ? In-Reply-To: References: Message-ID: <1148893750.356850.312400@i40g2000cwc.googlegroups.com> ConfigObj? http://www.voidspace.org.uk/python/configobj.html - Pad. From jdsalt_AT_gotadsl.co.uk Tue May 23 16:17:09 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Tue, 23 May 2006 15:17:09 -0500 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> Message-ID: Eli Gottlieb wrote in news:bLEcg.6900$8G3.3785 at twister.nyroc.rr.com: [Snips] > I correct: We live in a paradise where we finally have to processing > power to realize all those ideas that were too inefficient 20 years > ago. That sounds more reasonable. In my more jaundiced moments, I think that progress in software will not resume until we stop the annual doubling of resources for bloatware to consume. All the best, John. From belred at gmail.com Fri May 12 02:01:14 2006 From: belred at gmail.com (Bryan) Date: Thu, 11 May 2006 23:01:14 -0700 Subject: matplotlib Message-ID: does anyone know if matplotlib is robust enough to use in a commercial application? are there any existing commercial or popular open source programs that use it? thanks, bryan From roy at panix.com Mon May 8 13:16:20 2006 From: roy at panix.com (Roy Smith) Date: Mon, 8 May 2006 17:16:20 +0000 (UTC) Subject: advanced number recognition in strings? References: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> Message-ID: s.schmeier at gmail.com wrote: >we want extract numbers from strings and wonder if there is already a >module around for doing this. An example in our case would look like >this: > >0.032 +/- 0.5 x 10(-4) > >it would even be helpful to have a routine which does not recognise the >+/- , but at least the 10(-4). Is there some reason the numbers need to be written in that exact format? People have been writing machine-parsable floating point numbers for eons, using the e-notation, and Python is happy to convert a string in e-notation directly to a float: >>> float ("0.032e-4") 3.1999999999999999e-06 That being said, e-notation does not represent uncertainty, but then again, neither does an IEEE float. To keep the uncertainty, you need to create a new numeric class which stores the mantissa, the uncertainty, and the exponent. Perhaps you could get away with storing the mantissa and exponent as a standard float, but you'd still need to store the uncertainty. Then you'd (presumably) need to define a whole set of math operators which did something useful with these numbers. For example, what should: x = 0.032 +/- 0.5 x 10(-4) y = 0.032 +/- 1.0 x 10(-4) print x == y print out? From nobody at 127.0.0.1 Wed May 3 18:20:14 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 22:20:14 GMT Subject: Because of multithreading semantics, this is not reliable. References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> Message-ID: Tim Peters wrote: > That puts them in the > "attractive nuisance" category for many people. Argh. That gives me bad flashbacks to my torts final from Mon, which had a bona-fide "attractive nuisance" problem on it. Damn you, Tim Peters! ;) From Serge.Orlov at gmail.com Wed May 17 07:40:50 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 May 2006 04:40:50 -0700 Subject: Strange IO Error when extracting zips to a network location References: Message-ID: <1147866050.659569.65410@y43g2000cwc.googlegroups.com> Hari Sekhon wrote: > Hi, > I've written a script to run on windows to extract all zips under a > given directory path to another directory path as such: > > python extractzips.py files under this dir> > > The purpose of this script is to retrieve backup files which are > individually zipped under a backup directory tree on a backup server. > > This scripts works nicely and has input validation etc, exiting > gracefully and telling you if you gave a non existent start or target > path... > > When running the script as follows > > python extractzips.py \\backupserver\backupshare\machine\folder d:\unziphere > > the script works perfectly, but if I do > > python extractzips.py \\backupserver\backupshare\machine\folder > \\anetworkmachine\share\folder > > then it unzips a lot of files, recreating the directory tree as it goes > but eventually fails with the traceback: > > File "extractzips.py", line 41, in zipextract > outfile.write(zip.read(x)) > IOError: [Errno 22] Invalid argument > > > But I'm sure the code is correct and the argument is passed properly, > otherwise a hundred files before it wouldn't have extracted successfully > using this exact same piece of code (it loops over it). It always fails > on this same file every time. When I extract the same tree to my local > drive it works fine without error. > > I have no idea why pushing to a network share causes an IO Error, > shouldn't it be the same as extracting locally from our perspective? It looks like http://support.microsoft.com/default.aspx?scid=kb;en-us;899149 is the answer. From andrew.arobert at gmail.com Wed May 17 18:21:41 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 17 May 2006 18:21:41 -0400 Subject: Process forking on Windows - or what is MQSeries In-Reply-To: References: <126mgi2j7fl4b4b@corp.supernews.com> <446b45b1$0$7132$636a55ce@news.free.fr> <126mi8q1t31r9e0@corp.supernews.com> Message-ID: <126n8g6669ml2b6@corp.supernews.com> Gary Herron wrote: > Andrew Robert wrote: > > > The windows CreateProcess call has many of the same semantics as the > Unix fork, i.e., a new process is created sharing all the resources of > the original process. The "subprocess" modules uses CreateProcess, but > if that does not give you sufficient control over the process creation, > you can call CreateProcess directly via the "win32process" module in the > win32all package. > > However, I still don't understand *what* the "MQSeries trigger monitor" > is or *how* it would create the need for such a solution. > > Gary Herron > > MQSeries is a rather interesting piece of middle-ware offered by IBM that allows you to link disparate hosts/applications together via XML messaging and application specific queues. In the broadest sense, think of MQSeries like a large switchboard connecting everything together. Message queues can be programmed to do something via a mq application process such as a rule to take action when first, 5th, etc message arrives. The state of queues and their linked processes are controlled by the trigger monitor. The trigger monitor can only deal with one running process at a time. In this situation, it is possible for a process(my python program) to monopolize and block other processes from being triggered. Ideally, this needs to be avoided through the use of a fork. If you are interested, you can get all kinds of Websphere MQSeries and Websphere Message Broker information at http://www-306.ibm.com/software/integration/wmq/library/ On a side note, I use the pymqi module to make calls to MQSeries. From robert.kern at gmail.com Wed May 3 14:01:55 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 May 2006 13:01:55 -0500 Subject: A python problem about int to long promotion just see the idle session In-Reply-To: <1146676227.349286.280250@v46g2000cwv.googlegroups.com> References: <1146676227.349286.280250@v46g2000cwv.googlegroups.com> Message-ID: gen_tricomi wrote: > from the above you can see what int to long promotion is causing > i dont need to say much please see for yourself. is this a bug or > a feature. This is expected behavior. Why is it problematic for you? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From bignose+hates-spam at benfinney.id.au Wed May 31 00:20:30 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 31 May 2006 14:20:30 +1000 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <871wua25bl.fsf@benfinney.id.au> "greenflame" writes: > I would like to make a function that takes a list, more specificaly a > list of strings, and shuffles its elements, like a pile of cards. Sounds like a job for (ta-da-daa) DSU[0]. That said, here are some comments on your implementation. > ---------- > testdeck = list('qwertyuiop') > > def pileshuffle(DECK, NUMPILES): Ouch. Why use uppercase for the parameter names? This implies either shouting, or constants, neither of which is appropriate. > """Split the deck given into NUMPILES piles. Then also put the > piles""" \ > """ together to make the deck again.""" Remember that triple-quoted strings don't terminate until the next triple-quote delimiter. This means not having to close and open them every newline, which is a primary reason to choose them for doc strings. def pileshuffle(deck, numpiles): """ Split the deck bla bla bla bla bla bla. """ > # Define a list of lists which is the piles > PILES = [[]] * NUMPILES More shouting :-( That will create a list with many references to the *same* list; almost certainly not what you want. This creates the desired number of new lists:: piles = [] for _ in range(numpiles): piles.append(list()) The '_' name is convention for "We're not going to use this value". For something more Pythonic, try a list comprehension:: piles = [list() for _ in range(numpiles)] > card = 0 > pilenum = 0 > while card < len(DECK): > PILES[pilenum].append(DECK[card]) > card += 1 > if pilenum < NUMPILES: > pilenum += 1 > else: > pilenum = 0 Please don't write C in Python. The 'for' statement allows iteration directly over a sequence, no need to maintain an index. Also, the modulus operator is called for with your cycling of the pile index. pile_index = 0 for card in deck: piles[pile_index].append(card) pile_index = (pile_index + 1) % numpiles Rather than having the function print the result, it should return it; that way, the caller gets to decide what happens with the result. return piles Here's my result with your test input:: >>> def pileshuffle(deck, numpiles): ... """ Split the deck into piles """ ... piles = [list() for _ in range(numpiles)] ... pile_index = 0 ... for card in deck: ... piles[pile_index].append(card) ... pile_index = (pile_index + 1) % numpiles ... return piles ... >>> deck = list("qwertyuiop") >>> print pileshuffle(deck, 5) [['q', 'y'], ['w', 'u'], ['e', 'i'], ['r', 'o'], ['t', 'p']] >>> print pileshuffle(deck, 3) [['q', 'r', 'u', 'p'], ['w', 't', 'i'], ['e', 'y', 'o']] For actually implementing this, and to allow the flexibility you said you wanted, using DSU would be most obvious to me. [0] Decorate-Sort-Undecorate -- \ "Pity the meek, for they shall inherit the earth." -- Donald | `\ Robert Perry Marquis | _o__) | Ben Finney From Dennis.Benzinger at gmx.net Sun May 21 08:46:03 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Sun, 21 May 2006 14:46:03 +0200 Subject: File encoding strategy question In-Reply-To: <126v3aufq22ip31@corp.supernews.com> References: <126v3aufq22ip31@corp.supernews.com> Message-ID: <44706106$1@news.uni-ulm.de> Andrew Robert schrieb: > Hi everyone, > > I am in the process of creating a file transmit/receiver program using > MQSeries. > > The way it works is through creation of an XML message. > > Elements within the XML message contain things such as file name, size, > and the file contents. > > The file contents are encoded, currently using Base64, for support of > both binary and text data. > > This works great but there is a small rub to the problem. > > I would like to be able to view the contents of the file if it is text > while still maintaining the ability to transmit binary data. > > Does anyone know of an encoding format that would make this possible? > [...] Yes. You could use the Quoted-Printable encoding. See RFC 2045 Multipurpose Internet Mail Extensions (MIME) Part One: Format of Internet Message Bodies Dennis From diffuser78 at gmail.com Tue May 9 09:50:43 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 9 May 2006 06:50:43 -0700 Subject: Memory leak in Python In-Reply-To: References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> Message-ID: <1147182643.738945.166000@j33g2000cwa.googlegroups.com> I am using Ubuntu Linux. My program is a simulation program with four classes and it mimics bit torrent file sharing systems on 2000 nodes. Now, each node has lot of attributes and my program kinds of tries to keep tab of everything. As I mentioned its a simulation program, it starts at time T=0 and goes on untill all nodes have recieved all parts of the file(BitTorrent concept). The ending time goes to thousands of seconds. In each sec I process all the 2000 nodes. Psuedo Code Time = 0 while (True){ For all nodes in the system{ Process + computation } Time++ If (DownloadFinished == True) exit; } Dennis Lee Bieber wrote: > On 8 May 2006 18:15:02 -0700, diffuser78 at gmail.com declaimed the > following in comp.lang.python: > > > I have a python code which is running on a huge data set. After > > starting the program the computer becomes unstable and gets very > > diffucult to even open konsole to kill that process. What I am assuming > > is that I am running out of memory. > > > > What should I do to make sure that my code runs fine without becoming > > unstable. How should I address the memory leak problem if any ? I have > > a gig of RAM. > > > Does the memory come back after the process exits? > > You don't show any sample of code or data... Nor do you mention what > OS/processor is involved. > > Many systems do not return /allocated/ memory to the OS until the > top-level process exits, even if the memory is "freed" from the > viewpoint of the process. > -- > 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 chris at foote.com.au Mon May 15 23:13:30 2006 From: chris at foote.com.au (Chris Foote) Date: Tue, 16 May 2006 12:43:30 +0930 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> Message-ID: <1147751294.699031@teuthos> Roy Smith wrote: > In article <1147699064.107490 at teuthos>, Chris Foote > wrote: > >> I have the need to store a large (10M) number of keys in a hash table, >> based on a tuple of (long_integer, integer). The standard python >> dictionary works well for small numbers of keys, but starts to >> perform badly for me inserting roughly 5M keys: >> >> # keys dictionary metakit (both using psyco) >> ------ ---------- ------- >> 1M 8.8s 22.2s >> 2M 24.0s 43.7s >> 5M 115.3s 105.4s > > Are those clock times or CPU times? User + system CPU time. > How much memory is your process using and how much is available on your > machine? A very large amount of space is consumed, which is why I didn't give times for the 10M version which would have eaten my 1G of RAM and into swap :-) > I'm guessing a integer takes 4 bytes and a long integer takes roughly one > byte per two decimal digits. Plus a few more bytes to bundle them up into > a tuple. You've probably got something like 20 bytes per key, so 5M of > them is 100 meg just for the keys. > > To get reasonable hashing performance, the hash table needs to be maybe > half full, and figure a hash key is 4 bytes, so that's another 40 meg for > the hash table itself. > > Plus whatever the values stored in the dictionary take up. Even if you're > not storing any values (i.e., there's probably 4 bytes for a null pointer > (or reference to None), so that's another 40 meg. > > These are all vague guesses, based on what I think are probably > conservative estimates of what various objects must take up in memory, but > you see where this is going. We're already up to 180 meg. Yep, that size sounds about right (my dictionary values are all None). > I wonder if the > whole problem is that you're just paging yourself to death. A few minutes > watching your system memory performance with ps or top while your program > is running might give you some idea if this is the case. Definitely not. Thanks anyway, Chris From george.sakkis at gmail.com Wed May 17 17:55:06 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 17 May 2006 14:55:06 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <1147902906.321303.133160@j73g2000cwa.googlegroups.com> glomde wrote: > i I would like to extend python so that you could create hiercical > tree structures (XML, HTML etc) easier and that resulting code would be > more readable than how you write today with packages like elementtree > and xist. Given that python doesn't have syntactic sugar for something as prevalent as regular expressions, it's not that hard to predict the luck of this proposal. Good luck pushing it forward. George From onurb at xiludom.gro Fri May 5 05:00:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 11:00:05 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> <4459c050$0$3552$626a54ce@news.free.fr> Message-ID: <445b1472$0$16429$626a54ce@news.free.fr> Edward Elliott wrote: > bruno at modulix wrote: > >>Edward Elliott wrote: >> >>>Ah, well then, there's no need for a full-blown parser. It should >>>suffice to recognize a class definition and modify the parameter list of >>>every def indented one level further than that. >> >>won't do : >> >>class CounterExample(object): >> if compute_some_const_according_to_phase_of_moon(): >> def meth(...): >> do_something(self, 42) > > > Uuuhhhhnn, you got me pardner. (cough, cough) my hands, they're so cold. > bruno? where'd you go, bruno? i can't see you anymore. are we back on > the farm? tell ma i love her. (clunk) > "We'll remember you foreeeeeever Eddy..." -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From durumdara at gmail.com Wed May 10 07:01:17 2006 From: durumdara at gmail.com (Dara Durum) Date: Wed, 10 May 2006 13:01:17 +0200 Subject: Use subprocesses in simple way... Message-ID: <9e384ef60605100401s59bd5f04p@mail.gmail.com> Hi ! Py2.4, Win32. I need to optimize a program that have a speciality: hash (MD5/SHA1) the file contents (many files). Now I do this in a simple python program, because (what a pity) the FSUM utility died in a file with unicode filename... (It is unknown error: I used alternate file name, but it not found). And FSUM have some problematics with it's parameterizing. So now I want choose the best solution to get hash values: 1.) Creating pyshamd5.exe with py2exe and python, and call this program with CreateProcess and Params ? 2.) Creating pyshamd5.exe with py2exe and python, and call this program with popen - use pipes ? 3.) Using external utility ? 4.) Other things ? So I want to avoid the passive times like "many process starting and ending", "many file operation", etc. Need to use unicode filenames, so the outer program can handle these files (alternate file names ?). I "send" the filename to the subprocess, and it is send the hash results (or error codes) to my main process. Pipe good for this, but PIPE-s are sync. (synchronous) things. For sync. things I need threads. If I use subprocess.Popen object, it is better, because I not use threads (I can use poll to get return code) - I can manage the subprocesses from onethreaded code (from main thread). (I need more process, because it speeding up my hashing. If I have one ISO, the hashing of this file block all operations in one thread/process. A multiprocessor code can hash more files in one time.) So: I need a solution that not need multithreading chaos, where I can poll my processes. Better, If I have persistent suprocesses, because I avoid starting/ending "neutral gear" of subprocesses. The working in pseudocode: while HaveAnyFile or HaveOpenedProcesses: if not Processes: CreateProcess(MaxProcesses) if HaveUsableProcesses: fn=GetNextFile if fn: SendToSubProcess(fn) PollProcessesAndStoreResults() The questions 1.) Do you know a "method" that can send/receive datas to/from presistent subprocesses without blocking ? 2.) Do you know command line to just like FSUM that can compute file hashes (MD5/SHA1), and don't have any problems with unicode alt. file names ? 3.) PIPE-s better than CreateProcess(params) ? Important: the sockets are unavailable in this project. I don't use them, because users forbid to me. Thanks for any help: dd __________________________________________________________________ Python mailing list Levelcim: Python at lists.fsn.hu Webfelulet: https://lists.fsn.hu/mailman/listinfo/python Web oldalak: http://www.python.hu vagy http://www.python.org ?llom?nyba menteni | Nem biztos?gos k?pek elrejt?se Delete & Prev | Delete & Next Move to: From harlinseritt at yahoo.com Tue May 23 07:18:38 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 23 May 2006 04:18:38 -0700 Subject: Valid SQL? Message-ID: <1148383118.187847.197700@j33g2000cwa.googlegroups.com> I have this string that I am sending via a Cursor.execute() using MySQLdb: insert into table Ping82_eb13__elearn__ihost__com (`dateTime`, `values`) values( "Fri May 12 11:39:02 2006", "1") Does anyone see anything wrong with this SQL syntax? Thanks, Harlin Seritt From eval.apply at gmail.com Wed May 10 13:04:53 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 10 May 2006 10:04:53 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hf33s3.1bdn2e4juoow0N%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1147194791.809735.251500@g10g2000cwb.googlegroups.com> <1hf33s3.1bdn2e4juoow0N%aleax@mac.com> Message-ID: <1147280693.450683.95790@j73g2000cwa.googlegroups.com> Alex Martelli wrote: > Joe Marshall wrote: > ... > > The problem is that a `name' is a mapping from a symbolic identifier to > > an object and that this mapping must either be global (with the > > attendant name collision issues) or within a context (with the > > attendant question of `in which context'). > > Why is that a problem? Even for so-called "global" names, Python > supports a structured, hierarchical namespace, so there can never be any > collision betwen the "globals" of distinct modules (including modules > which happen to have the same name but live in distinct packages or > subpackages) -- I did mention that names could usefully be displayed in > some strcutured form such as apackage.somemodule.thefunction but perhaps > I was too tangential about it;-). Can you refer to inner functions from the global context? Suppose I have this Python code: def make_adder(x): def adder_func(y): sum = x + y return sum return adder_func Can I refer to the inner adder_func in any meaningful way? > > > > Matthias Felleisen once suggested that *every* internal function should > > be named. I just said `continuations'. He immediately amended his > > statement with `except those'. > > If I used continuations (I assume you mean in the call/cc sense rather > than some in which I'm not familiar?) I might feel the same way, or not, > but I don't (alas), so I can't really argue the point either way for > lack of real-world experience. I meant continuations as in the receiver function in continuation-passing-style. If you have a function that has to act differently in response to certain conditions, and you want to parameterize the behavior, then one possibility is to pass one or more thunks to the function in addition to the normal arguments. The function acts by selecting and invoking one of the thunks. A classic example is table lookup. It is often the case you wish to proceed differently depending upon whether a key exists in a table or not. There are several ways to provide this functionality. One is to have a separate `key-exists?' predicate. Another is to have a special return value for `key not found'. Another is to throw an exception when a key is not found. There are obvious advantages and drawbacks to all of these methods. By using continuation-passing-style, we can parameterize how the table lookup proceeds once it determines whether or not the key is found. We have the lookup procedure take two thunks in addition to the key. If the key is found, the first thunk is invoked on the associated value. If the key is not found, the second thunk is invoked. We can subsume all the previous behaviors: (define (key-exists? key table) (lookup key table (lambda (value) #t) ;; if found, ignore value, return true (lambda () #f))) ;; if not found, return false. (define (option1 key table) (lookup key table (lambda (value) value) (lambda () 'key-not-found))) (define (option2 key table) (lookup key table (lambda (value) value) (lambda () (raise 'key-not-found-exception)))) (define (option3 key table default-value) (lookup key table (lambda (value) value) (lambda () default-value))) The unnamed functions act in this regard much like a `local label'. We wrap two chunks of code in a lambda and the lookup function `jumps' to the appropriate chunk. (If the compiler knows about thunks, the generated assembly code really will have local labels and jump instructions. It can be quite efficient.) This may look odd and cumbersome, but with a little practice the lambdas fade into the background and it becomes easy to read. My point with Matthias, however, was that defining all these continuations (the thunks) as named internal functions was not only cumbersome, but it obscured the control flow. Notice: (define (named-option3 key table default-value) (define (if-found value) value) (define (if-not-found) default-value) (lookup key table if-found if-not-found)) When we enter the function, we skip down to the bottom (past the internal definitions) to run lookup, which transfers control to a function defined earlier in the code. There are many reasons to avoid this style in Python, so this probably won't win you over, but my point is that there are times where anonymous functions have an advantage over the named alternative and that disallowing anonymous functions can be as cumbersome as disallowing anonymous integers. From johnjsal at NOSPAMgmail.com Tue May 16 21:09:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 21:09:17 -0400 Subject: help with this simple DB script Message-ID: <446a7849$0$1901$c3e8da3@news.astraweb.com> Ok, before I contact my server host, I figured I should make sure I'm not just making a Python mistake. I get an Internal Server Error with this script: !#/usr/bin/python import MySQLdb db = MySQLdb.connect(host='xxx', user='xxx', passwd='xxx', db='xxx') # changed this stuff cursor = db.cursor() cursor.execute("CREATE TABLE test (first varchar(10), second number(2))") cursor.execute("INSERT INTO test (first, second) VALUES ('Hello', 33)") cursor.execute("SELECT first, second FROM test") cursor.fetchall() cursor.close() db.close() All I do is run it directly with my URL, not sure if there's more to it. From bignose+hates-spam at benfinney.id.au Wed May 17 19:31:32 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 09:31:32 +1000 Subject: How to tell if function was passed a list or a string? References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> <1147907798.819913.146580@i40g2000cwc.googlegroups.com> Message-ID: <87wtckmdnv.fsf@benfinney.id.au> trebucket at gmail.com writes: > >>> import types > >>> type("") is types.ListType > False > >>> type("") is types.StringType > True > >>> type([]) is types.StringType > False > >>> type([]) is types.ListType > True This is even worse than an 'isinstance' check; it refuses even subclasses of the types you accept, breaking polymorphism *and* inheritance. -- \ "What you have become is the price you paid to get what you | `\ used to want." -- Mignon McLaughlin | _o__) | Ben Finney From scott.daniels at acm.org Mon May 29 09:39:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 29 May 2006 06:39:50 -0700 Subject: Large Dictionaries In-Reply-To: References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <1148514158.790760.205630@i40g2000cwc.googlegroups.com> Message-ID: <447af556$1@nntp0.pdx.net> Thomas Ganss wrote: > Klaas schrieb: >> 4. Insert your keys in sorted order. > This advice is questionable -.... > > My gut feeling on this matter is: > IF the insert times of pre-sorted values is far better > than the times of unsorted values, there is a chance > that the resulting tree is unbalanced: only 1 compare > operation after insert and no re-balancing of the tree. > > re-indexing will probably give you far better access times > in this case. Another option is to drop non RI indexes used only > for query optimization and recreate them after batch insert. Don't use your gut for such issues. Pre-sorted data is such a common special case (in fact, the only easily describable special case) that many systems handle this specially. For example, time timsort (Python's internal sort) on pre-sorted data; you'll find it is handled faster than random data. If you are using your gut without testing, go ahead and presort. In any case, reading documents and testing beats gut feels every time. --Scott David Daniels scott.daniels at acm.org From deets at nospam.web.de Mon May 29 08:20:57 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 May 2006 14:20:57 +0200 Subject: saving settings References: Message-ID: <4e07c8F1c7r6jU1@uni-berlin.de> SuperHik wrote: > aum wrote: >> On Mon, 29 May 2006 09:05:36 +0200, SuperHik wrote: >> >>> Hi, >>> >>> I was wondering how to make a single .exe file, say some kind od clock, >>> and be able to save some settings (alarm for example) into the same >>> file? Basically make code rewrite it self... >>> >>> thanks! >> >> Yikes!!! >> >> I'd strongly suggest you read the doco for ConfigParser, and load/save >> your config file to/from os.path.join(os.path.expanduser("~")). >> >> Another option - save your stuff in the Windows Registry >> > > but if I copy this file on the other computer settings will be lost... It _might_ come as a shock to you, but when you install e.g. Word on another computer, there aren't any documents coming with it. Especially not the ones you wrote on that other machine. Seriously: Who is going to copy a executable around? Do you know of any other program that behaves like that? Diez From ryan at cs.uoregon.edu Fri May 5 21:37:53 2006 From: ryan at cs.uoregon.edu (Ryan Forsythe) Date: Fri, 05 May 2006 18:37:53 -0700 Subject: Replace In-Reply-To: References: Message-ID: <445BFDF1.5010302@cs.uoregon.edu> Eric wrote: > I have a string... > > str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" > > I want to replace the characters after each '=', what I ended up doing is > somthing like this... > > buf = list(str) > newchr = '#' > > count = 0 > for i in range(len(buf)): > if buf[count] == '=': > buf[count + 1] = newchr > count = count + 1 > else: > count = count + 1 > > newstr = ''.join(buf) So you want to turn "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" into "tyrtrbd =#fgtyuf =# =#yryr =#=# ttttff"? I'd probably end up writing it like you have (except the else is redundant -- just end the test block and increment your counter in any case) > Is there a better, faster way of doing it? Using somthing like > str.index() dosn't work because... > > str = "hello world" You don't want to use str as a variable name -- it shadows the str() builtin: >>> x = 1 >>> str(x) 1 >>> str = "spam" >>> str(x) ------------------------------------------------------------ Traceback (most recent call last): File "", line 1, in ? TypeError: 'str' object is not callable > for i in str: > print str.index(i) (snip) > Every 'e' in "hello world" has the same index value. Am i missing somthing? Because `"hello".index("l")` returns the first place "l" appears in "hello". It's always going to be 2. --Ryan From LittlePython at lost.com Sat May 27 18:44:51 2006 From: LittlePython at lost.com (LittlePython) Date: Sat, 27 May 2006 22:44:51 GMT Subject: Using a package like PyInstaller References: Message-ID: Thx for the tip. I am referring more to the use of PyInstaller or py2exe. Packages that create exe files that basically have your py script and a small py interpreter all rolled up into one. This way py does not need to be installed on a system to execute a py script. I am being advised that python is installed onto systems (windows) it should not be on. I am new to python and these types of packages and am not too sure how dumb a question this really is.. but can these packages bleed out files, dll, exe ect. to systems they are run on? "James Stroud" wrote in message news:e5ab5l$tkm$1 at daisy.noc.ucla.edu... > LittlePython wrote: > > Is it possible when using packages like PyInstaller to create an .exe for > > distribution that parts of the package can bleed out and be left on a system > > when the .exe is executed? > > > > Thx > > > > > > Look at innosetup. > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From m.sloyko at gmail.com Wed May 24 03:55:32 2006 From: m.sloyko at gmail.com (Maxim Sloyko) Date: 24 May 2006 00:55:32 -0700 Subject: Best way to handle exceptions with try/finally In-Reply-To: References: Message-ID: <1148457332.582609.98490@38g2000cwa.googlegroups.com> I guess the following standard method will help : class MyLocker(object): def __init__(self, lock): self.lock = lock self.lock.acquire() def __del__(self): self.lock.release() Then whenever you need to acquire a lock: templock = MyLocker(self.__mutex) del templock # will release the lock (provided you didn't create an extra link to this object) From nospam at nospam.net Thu May 11 03:59:50 2006 From: nospam at nospam.net (Matthew Graham) Date: Thu, 11 May 2006 08:59:50 +0100 Subject: Nested loops confusion In-Reply-To: References: Message-ID: <2uCdnY7CIt9qc__ZnZ2dnUVZ8qGdnZ2d@giganews.com> Thanks very much for the advice, have tidied it up and tested and seems to be working as needed. I'm still not sure what was stopping the inner loop from working earlier - but removing the redundancy in "j=0" and so on seems to have solved it. Matt Dennis Lee Bieber wrote: > If that worked, you've got some weird code -- and it isn't what was > posted... Zeroing "j" does NOTHING, since the for loop assigns all > values to it, from 0..n-1 > > for loop indices do not need to be pre-initialized. From tbrkic at yahoo.com Fri May 12 18:51:22 2006 From: tbrkic at yahoo.com (glomde) Date: 12 May 2006 15:51:22 -0700 Subject: compiling module from string and put into namespace In-Reply-To: <4464754a$0$306$626a54ce@news.free.fr> References: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> <4464754a$0$306$626a54ce@news.free.fr> Message-ID: <1147474282.618115.60590@u72g2000cwu.googlegroups.com> Tanks but that isn't what I am looking for. I really want a function that you can call and imports the module into the calling functions namespace. I dont want the caller to call import but a function. From fredrik at pythonware.com Fri May 19 04:10:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 10:10:19 +0200 Subject: Complex evaluation bug In-Reply-To: <446d79da$0$7144$626a54ce@news.free.fr> References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> <446d79da$0$7144$626a54ce@news.free.fr> Message-ID: Christophe wrote: >> So, putting them together, you could expect >> eval(repr(a)) >> to reproduce a, and in fact it does so. > > Says who ? > > Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on > win32 > Type "help", "copyright", "credits" or "license" for more information. > >>> repr(1+3j) > '(1+3j)' > >>> complex(repr(1+3j)) > Traceback (most recent call last): > File "", line 1, in ? > ValueError: complex() arg is a malformed string > >>> in what language is "eval" spelled "complex" ? From ogahejini at yahoo.com Wed May 3 13:12:44 2006 From: ogahejini at yahoo.com (gen_tricomi) Date: 3 May 2006 10:12:44 -0700 Subject: problem with reload(sys) (doing reload on the sys module) Message-ID: <1146676364.470772.232350@y43g2000cwc.googlegroups.com> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "copyright", "credits" or "license()" for more information. **************************************************************** Personal firewall software may warn about the connection IDLE makes to its subprocess using this computer's internal loopback interface. This connection is not visible on any external interface and no data is sent to or received from the Internet. **************************************************************** IDLE 1.1.2 >>> import sys >>> sys.modules.keys() ['tkFileDialog', 'random', 'struct', 'tempfile', 'idlelib.cPickle', 'imp', 'collections', 'zipimport', 'string', 'SocketServer', 'repr', 'idlelib.string', 'idlelib.bdb', 'itertools', 'idlelib.SocketServer', 'ConfigParser', 'signal', 'idlelib.IOBinding', 'threading', 'tkMessageBox', 'idlelib.warnings', 'idlelib.struct', 'idlelib.cStringIO', 'cStringIO', 'locale', 'idlelib.threading', 'idlelib.TreeWidget', 'idlelib.rpc', 'atexit', 'idlelib.re', 'encodings', 'idlelib.RemoteDebugger', 'idlelib.tempfile', 'idlelib.codecs', '_tkinter', 'bdb', 're', 'idlelib.RemoteObjectBrowser', 'ntpath', 'idlelib.imp', 'idlelib.locale', 'idlelib.thread', 'math', 'idlelib.Debugger', 'Tkinter', 'idlelib.traceback', 'idlelib.marshal', 'UserDict', 'Queue', 'idlelib.StackViewer', 'codecs', 'idlelib.copy_reg', '_locale', 'socket', 'thread', 'sre', 'idlelib.time', 'traceback', 'idlelib.socket', 'idlelib.CallTipWindow', 'os', 'marshal', 'idlelib.tkFileDialog', '_sre', '__builtin__', 'select', 'idlelib.os', 'idlelib.ZoomHeight', 'idlelib.ConfigParser', 'errno', '_socket', 'binascii', 'sre_constants', 'types', 'idlelib.__builtin__', 'idlelib.tkMessageBox', 'cPickle', '_codecs', 'encodings.cp1252', 'idlelib.repr', 'idlelib.Queue', 'idlelib.__main__', 'idlelib.sys', 'encodings.aliases', 'exceptions', 'sre_parse', 'FixTk', 'copy_reg', 'sre_compile', '_random', 'site', 'SimpleDialog', '__main__', 'idlelib.types', 'tkCommonDialog', 'strop', 'encodings.codecs', 'encodings.exceptions', 'nt', 'idlelib.linecache', 'stat', '_ssl', 'warnings', 'encodings.types', 'sys', 'idlelib.Tkinter', 'idlelib.CallTips', 'idlelib.configHandler', 'idlelib.WindowList', 'idlelib.SimpleDialog', 'os.path', 'idlelib.ScrolledList', 'idlelib.ObjectBrowser', 'idlelib', 'Tkconstants', 'linecache', 'time', 'idlelib.select', 'idlelib.run'] >>> reload(sys) >>> sys.modules.keys() >>> dir() >>> print 'hello world' >>> print 'hi nerds' >>> print 'it just stops here nothing works again' >>> print 'is this a bug or a feature' >>> print 'can some one help' >>> 2 + 4 >>> print 'but when i restart' >>> print 'everything returns' >>> import string >>> string.lowercase >>> string.lowercase() >>> print 'let me see if an exception can be thrown' >>> import nigeria >>> import lagos >>> no exception SyntaxError: invalid syntax >>> print 'still checks for syntax' >>> print 'it checks syntax after the second token has been entered' >>> abracadabra >>> not SyntaxError: invalid syntax >>> print >>> is SyntaxError: invalid syntax >>> print 'syntax check is still working for reserved words' >>> you >>> can >>> check >>> the >>> rest f >>> for SyntaxError: invalid syntax >>> your >>> self >>> print 'i think this IDLE session is self explanatory' This is not part of the above IDLE session please mail me if you have any idea what this means. ogahejini at yahoo.com From paddy3118 at netscape.net Mon May 1 17:19:21 2006 From: paddy3118 at netscape.net (Paddy) Date: 1 May 2006 14:19:21 -0700 Subject: regd efficient methods to manipulate *large* files References: Message-ID: <1146518361.069676.99590@u72g2000cwu.googlegroups.com> I take it that you have a binary file that takes a file name and proceses the file contents. Sometimes Unix binaries are written so that a file name of '-', (just a dash), causes it to take input from stdin so that the piping mentioned in a previous reply could work. On some of our unix systems /tmp is set up as a 'virtual disk' It quacks like a normal disk filesystem but is actually implimented in RAM/virtual memory, and is faster than normal disk access. (Unfortunately we are not allowed to save multi-gigabyte files there as it affects other aspects of the OS). Maybe you can mount a similar filesystem if you have the RAM. -- Pad. From elpX at adsihqX.com Sun May 28 16:56:11 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Sun, 28 May 2006 20:56:11 GMT Subject: Array? Please help. In-Reply-To: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> Message-ID: Many thanks to you all. (Extra thanks to Mr. Daniels.) Dr. Pastor wrote: > I need a row of 127 bytes that I will use as a > circular buffer. Into the bytes (at unspecified times) > a mark (0 After some time the "buffer" will contain the last 127 marks. > (A pointer will point to the next byte to write to.) > What would be the Pythonic way to do the above? > Thanks for any guidance. From email at christoph-haas.de Tue May 9 13:52:08 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 9 May 2006 19:52:08 +0200 Subject: multiline strings and proper indentation/alignment In-Reply-To: References: Message-ID: <20060509175208.GA21047@workaround.org> On Tue, May 09, 2006 at 05:38:52PM +0000, John Salerno wrote: > How do you make a single string span multiple lines, but also allow > yourself to indent the second (third, etc.) lines so that it lines up > where you want it, without causing the newlines and tabs or spaces to be > added to the string as well? > > Example (pretend this is all on one line): > > self.DTD = ' 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n\n' > > I want it to read: > > self.DTD = ''' "http://www.w3.org/TR/html4/strict.dtd">\n\n''' > > Or anything like that, but I don't want the extra newline or tabs to be > a part of the string when it's printed. My favorite way: self.DTD = '''\n\n''' Kindly Christoph From sekhon.hari at googlemail.com Fri May 19 07:37:33 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Fri, 19 May 2006 12:37:33 +0100 Subject: memory error with zipfile module Message-ID: <446DADFD.1040705@gmail.com> I do import zipfile zip=zipfile.ZipFile('d:\somepath\cdimage.zip') zip.namelist() ['someimage.iso'] then either of the two: A) file('someimage.iso','w').write(zip.read('someimage.iso')) or B) content=zip.read('someimage.iso') but both result in the same error: Traceback (most recent call last): File "", line 1, in ? File "D:\u\Python24\lib\zipfile.py", line 357, in read bytes = dc.decompress(bytes) MemoryError I thought python was supposed to handle memory for you? The python zipfile module is obviously broken... Any advise? From ivoras at __-yahoo-__.com_ Sat May 13 16:50:49 2006 From: ivoras at __-yahoo-__.com_ (Ivan Voras) Date: Sat, 13 May 2006 22:50:49 +0200 Subject: Slow network reading? In-Reply-To: References: Message-ID: Andrew MacIntyre wrote: >> That's only because I need the .readline() function. In C, I'm using >> fgets() (with the expectation that iostream will buffer data). > > The readline method of the file object lookalike returned by makefile > implements all of the line splitting logic in Python code, which is very > likely where the extra process CPU time is going. Note that this code is Heh, I didn't know that - you're probably right about this being a possible bottleneck. > in Python for portability reasons, as Windows socket handles cannot be > used as file handles the way socket handles on Unix systems can be. I think they actually can in NT and above... but no, I'm doing it on Unix. > Given your comments above about how much data is actually involved, I'm > a bit surprised that the tweaked version actually produced a measurable > gain. I didn't do statistical analysis of the results so the difference actually could be negligable IRL. Anyway, thanks for the advice - I'll leave it as it is, as the Python client is not used currently. -- Things Mr Welch Cannot Do During An RPG: 274. I cannot commune with the Gods during peak hours. From duncan.booth at invalid.invalid Fri May 26 14:25:54 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 May 2006 18:25:54 GMT Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> <1148650269.190130.209840@i39g2000cwa.googlegroups.com> <1148655313.422226.297700@i40g2000cwc.googlegroups.com> Message-ID: George Sakkis wrote: > Duncan Booth wrote: > >> George Sakkis wrote: >> >> > 2) restricting in a more serious sense: the future addition of >> > optional keyword arguments that affect the dict's behaviour. Google >> > for "default dict" or "dictionary accumulator". >> >> There is nothing to stop dictionaries being created using factory >> functions (e.g. see dict.fromkeys). So one possible way to implement >> defaults would be to extend the dict class with a new classmethod >> 'withdefault' which takes a default value as an argument. >> >> However, given that the default argument isn't actually needed during >> construction, it doesn't seem to me that it fits either as a >> constructor parameter nor a factory method. I don't see why it >> shouldn't just be set on an existing dictionary (or dictionary >> subclass) when you need it. > > Because I would find > > d = dict(default=0) > d['x'] += 3 > > more elegant than > > d = {} > d.withdefault(0) > d['x'] += 3 > Well you could have: d = dict.withdefault(0) but then you may have to start with an empty dictionary. What happens if you need to change default for different uses? Wouldn't wrapping the dictionary in an adaptor be a simpler solution? In many cases the place where you are going to know what default is appropriate will be separated from the place where you create the dictionary. You should be able to write a function which takes a dictionary as parameter and accumulates values into it. From sjmachin at lexicon.net Sun May 28 18:14:07 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 May 2006 08:14:07 +1000 Subject: Serializing / Unserializing datetime In-Reply-To: <1148848054.531695.115160@j55g2000cwa.googlegroups.com> References: <1148751427.204676.238100@g10g2000cwb.googlegroups.com> <4478E634.8060001@lexicon.net> <1148844232.605364.192760@i40g2000cwc.googlegroups.com> <1148848054.531695.115160@j55g2000cwa.googlegroups.com> Message-ID: <447A20AF.7060209@lexicon.net> On 29/05/2006 6:27 AM, Gerard Flanagan wrote: > I don't think it's what you want but I had the following on file - it > uses time.strptime() which I didn't know there was a problem with. In 2.3, time.strptime became a pure-Python routine, thus losing its dependency on the existence and correctness of the strptime in the C library. However, the whole time module has a problem: the range of years it handles -- 1970 to 2038 (maybe). This is documented on the first page of The Fine Manual. Not very useful for customer's date of birth, and (as Brendan indicated), likely to cause Y2.038K problems. Cheers, John From gherron at islandtraining.com Tue May 9 15:57:20 2006 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 09 May 2006 12:57:20 -0700 Subject: multiline strings and proper indentation/alignment In-Reply-To: References: Message-ID: <4460F420.6070203@islandtraining.com> Gary John Salerno wrote: >How do you make a single string span multiple lines, but also allow >yourself to indent the second (third, etc.) lines so that it lines up >where you want it, without causing the newlines and tabs or spaces to be >added to the string as well? > >Example (pretend this is all on one line): > >self.DTD = '4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n\n' > >I want it to read: > >self.DTD = ''' "http://www.w3.org/TR/html4/strict.dtd">\n\n''' > >Or anything like that, but I don't want the extra newline or tabs to be >a part of the string when it's printed. > >Thanks. > > The textwrap module has a function to do just the thing you want. *dedent*( text) Remove any whitespace that can be uniformly removed from the left of every line in text. This is typically used to make triple-quoted strings line up with the left edge of screen/whatever, while still presenting it in the source code in indented form. Gary Herron From per9000 at gmail.com Tue May 30 04:00:57 2006 From: per9000 at gmail.com (per9000) Date: 30 May 2006 01:00:57 -0700 Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> Message-ID: <1148976057.253848.308070@u72g2000cwu.googlegroups.com> Hi, I hope you all know about wikibooks, it's like wikipedia but for books. It is also "some kind of openware" (my favourite expression). I specifically think about http://en.wikibooks.org/wiki/Programming:Python I have thought about adding to it but I am low on time - this randomchoice(["is","could be"]) a great book. Please read and/or add if you are one of the nice guys. Ciao, PER9000 ---- "It is a gift. A gift to the foes of 'the Terrorists'. Why not use this 'terrorism'? Long has my father, 'George Bush', kept the forces of 'the terrorists' at bay. By the blood of our people are your lands kept safe. Give 'the land of the brave' the weapon of the enemy. Let us use it against him." /George W Bush on the topic of Human rights (not really, it's from http://www.imdb.com/title/tt0120737/quotes ) From jdsalt_AT_gotadsl.co.uk Fri May 19 12:57:52 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Fri, 19 May 2006 11:57:52 -0500 Subject: [silly] Does the python mascot have a name ? References: <_s2bg.8867$aa4.296233@news20.bellglobal.com> Message-ID: Mel Wilson wrote in news:_s2bg.8867$aa4.296233 @news20.bellglobal.com: [Snips] > Just reinforces the central truth. The mascot doesn't > *have* a name. Most things don't. Most things don't have names? I'll believe you if you can give me a list of ten things that don't have names. ;-) All the best, John. From bdesth.quelquechose at free.quelquepart.fr Mon May 22 20:37:19 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 May 2006 02:37:19 +0200 Subject: Class probkem - getting msg that self not defined In-Reply-To: <12740frcoaju883@corp.supernews.com> References: <12740frcoaju883@corp.supernews.com> Message-ID: <44722a01$0$17368$636a55ce@news.free.fr> Andrew Robert a ?crit : > Hi Everyone, > > I am having a problem with a class and hope you can help. > > When I try to use the class listed below, I get the statement that self > is not defined. > > test=TriggerMessage(data) > var = test.decode(self.qname) > > I would have thought that self would have carried forward when I grabbed > an instance of TriggerMessage. Hint : what is the name of your TriggerMessage instance in the above code ? I think that what you wannt is more like this : import struct class TriggerMessage(object): def __init__(self,data): """ Unpacks the passed binary data based on the MQTCM2 format dictated in the MQ Application Programming Reference """ self._format = '4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' self._data = data (self.version, self.qname, self.processname, self.triggerdata, self.appltype, self.applid, self.envdata, self.userdata, self.qmgr) = self._decode() def _decode(self): assert len(self._data) == struct.calcsize(self._format) return struct.unpack(self._format, self._data) # test code # data = ??? test=TriggerMessage(data) var = test.qname From fred at adventistcare.org Thu May 4 11:37:35 2006 From: fred at adventistcare.org (Sells, Fred) Date: Thu, 4 May 2006 11:37:35 -0400 Subject: pyuno and oootools with OpenOffice 2.0 Message-ID: <1A4BF05172023E468CB6E867923BC90402B6E09B@accmail2.sunbelt.org> I'm using windows xp and OpenOffice 2.0 and doing my first project with pyuno. I've got the basics to work,. An example I googled at http://blogs.nuxeo.com/sections/aggregators/openoffice_org/blogaggregator_vi ew?b_start:int=0 imported an ootools module. When I try to import it, it does not exist, Does anyone know where this exists, or why I cannot import it. --------------------------------------------------------------------------- The information contained in this message may be privileged and / or confidential and protected from disclosure. If the reader of this message is not the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify the sender immediately by replying to this message and deleting the material from any computer. --------------------------------------------------------------------------- From bpeng at rice.edu Mon May 1 22:35:59 2006 From: bpeng at rice.edu (Bo Peng) Date: Mon, 01 May 2006 21:35:59 -0500 Subject: Python distutil: build libraries before modules In-Reply-To: References: Message-ID: Bo Peng wrote: > How can I let setup.py build these boost libraries separately so that I > can link them to my modules? This will also save some link time because > all my python modules link to the same boost libraries. Although this is nowhere documented, I find that I can use from distutils.ccompiler import * def buildStaticLibrary(sourceFiles, libName, libDir): '''Build libraries to be linked to simuPOP modules''' # get a c compiler comp = new_compiler() objFiles = comp.compile(sourceFiles) comp.create_static_lib(objFiles, libName, libDir) to build the libraries Cheers, Bo From niemand.leermann at thomas-guettler.de Thu May 4 10:11:22 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Thu, 04 May 2006 16:11:22 +0200 Subject: pleac References: <1146740749.200368.173590@g10g2000cwb.googlegroups.com> Message-ID: Am Thu, 04 May 2006 04:05:49 -0700 schrieb jonas: > Hi, > > I'm new to python. > After a search on > http://pleac.sourceforge.net/pleac_python/index.html > why python have a low %? Python has the highest percentage of all languages at pleac. For those who don't know pleac: """Following the great Perl Cookbook (by Tom Christiansen & Nathan Torkington, published by O'Reilly; you can freely browse an excerpt of the book here) which presents a suite of common programming problems solved in the Perl language, this project aims to gather fans of programming, in order to implement the solutions in other programming languages. If successful, this project may become a primary resource for quick, handy and free reference to solve most common programming problems using higher-level programming languages, and for comparison on ease-of-use and power/efficiency of these languages. """ -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From http Mon May 15 14:52:04 2006 From: http (Paul Rubin) Date: 15 May 2006 11:52:04 -0700 Subject: common practice for creating utility functions? References: Message-ID: <7xd5efdstn.fsf@ruckus.brouhaha.com> John Salerno writes: > So my first question is this: should I make a Cryptogram class for > this, or are functions fine? If the latter, then back to my original > point: can I do something like this: > > def convert_quote(quote): > return make_code(quote) It's fine to do that if it expresses your intentions more clearly. It's also normal to write a call for a function you haven't written yet: some_quote = convert_quote(another_quote) where you write convert_quote afterwards. It may not be til you actually write convert_quote that you notice that it simply calls another function. If that happens, it's fine. Also, you don't need to make a class if you don't need to do OOP-like things with the instances. But, sometimes, making a class also clarifies your intentions. For example, making a class means it becomes much simpler to have multiple cryptograms active at the same time, if you want to do that. Programming is not just creating strings of instructions for a computer to execute. It's also "literary" in that you are trying to communicate a program structure to other humans reading the code. Someone once asked the famous bike racing champion Eddy Merckx (he was sort of the Lance Armstrong of the 1970's and then some) how to become a good racer. His answer was "ride a lot". It's the same way with coding. As you get more experienced these questions get easier to answer for yourself. But always, do whatever works, and if your code gets messy or hits technical snags, ask yourself what alternative approaches avoid those snags, and thereby develop a sense of what to do. From reply.in.the.newsgroup at my.address.is.invalid Tue May 9 14:50:59 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 09 May 2006 20:50:59 +0200 Subject: Upgrading Class Instances Automatically on Reload References: <1147196712.192606.75160@g10g2000cwb.googlegroups.com> Message-ID: <24p1625coseqi7imip7f6nssi9feu400j3@4ax.com> malv: >Did anybody get this recipe to work? Did you? -- Ren? Pijlman From cktsoi at school.hk Mon May 15 04:57:44 2006 From: cktsoi at school.hk (Jacky) Date: Mon, 15 May 2006 16:57:44 +0800 Subject: Web framework to recommend In-Reply-To: References: Message-ID: Hi all, Thanks all of you for your recommendations, I'll check them out one by one. Besides, I'd like to say more about what I want to do. Since I'm planning to write something for "backend", I might not focus very much on the layout (HTML template) yet. Instead, I'd like to receive inputs in XML format and then output XML after processing (or maybe I should use web services, perhaps?). Of course, I will write a complete web application in my other projects (such as those I wrote with PRADO and JSF), so all recommendations are welcomed :) Thank you! Best Wishes, Jacky Jacky wrote: > Hi all, > > I just started learning Python and would like to starting writing some > web-based applications with Python. > > I did have pretty much experience with doing so with PHP and Java, but > Python seems a bit different for me. > > Do you guys have some good web framework to recommend? (I don't want to > use CGI mode) > > Thanks a lot. > > -- > Jacky From usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo Sun May 21 14:44:28 2006 From: usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo (KW) Date: Sun, 21 May 2006 20:44:28 +0200 Subject: PEP-xxx: Unification of for statement and list-comp syntax References: Message-ID: On 2006-05-21, Heiko Wundram wrote: > Hi all! > > The following PEP tries to make the case for a slight unification of for > statement and list comprehension syntax. Sounds great! -- Konrad From grante at visi.com Fri May 5 16:55:56 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 05 May 2006 20:55:56 -0000 Subject: NaN handling References: <125hplqmppfeq29@corp.supernews.com> Message-ID: <125neus2mkbgp51@corp.supernews.com> On 2006-05-05, Ivan Vinogradov wrote: > >> >> NaNs are handled. > > Throwing an exception would be nice in regular Python (non-scipy). That would break most of my Python programs (at least most of the ones in which I do floating point). My main problem with NaNs (and Infs) is that there isn't a string represention that is consistent across platforms. > This works to catch NaN on OSX and Linux: > > # assuming x is a number > if x+1==x or x!=x: > #x is NaN > > But is expensive as a precautionary measure. Assert can be > used for testing, if production code can be run with -0 or > -OO. There are those of us that need NaNs in production code, so it would have to be something that could be configured. I find that in my programs the places where I need to do something "exceptional" with a NaN are very limited. The vast majority of the time, I need them to propagate quietly. -- Grant Edwards grante Yow! Thousands of days of at civilians... have produced visi.com a... feeling for the aesthetic modules -- From NOatkinwSPAM at rpi.edu Sun May 7 03:07:37 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 03:07:37 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> Message-ID: <87odyatirq.fsf@rpi.edu> Bill Atkins writes: > Incidentally, is this supposed to be an example of Python's supposed > "aesthetic pleasantness"? I find it a little hideous, even giving you > the benefit of the doubt and pretending there are newlines between > each function. There's nothing like a word wrapped in pairs of > underscores to totally ruin an aesthetic experience. I don't mean to suggest that your code in particular is hideous - sorry if it came off that way. It's just that Python code seems a disappointingly un-pretty after all the discussion about its beauty in this thread. -- This is a song that took me ten years to live and two years to write. - Bob Dylan From kent at kentsjohnson.com Sun May 14 09:54:13 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 14 May 2006 09:54:13 -0400 Subject: any plans to make pprint() a builtin? In-Reply-To: References: <44669e46$0$5337$c3e8da3@news.astraweb.com> Message-ID: <446735ea$1_1@newspeer2.tds.net> Duncan Booth wrote: > Personally I'd just like to see 'python' a builtin shorthand for importing > a name you aren't going to use much > e.g. > > python.pprint.pprint(x) Would you settle for import py py.std.pprint.pprint(x) ? http://codespeak.net/py/current/doc/misc.html#the-py-std-hook Kent From http Fri May 26 00:21:44 2006 From: http (Paul Rubin) Date: 25 May 2006 21:21:44 -0700 Subject: genexp surprise (wart?) Message-ID: <7xpsi14drb.fsf@ruckus.brouhaha.com> I tried to code the Sieve of Erastosthenes with generators: def sieve_all(n = 100): # yield all primes up to n stream = iter(xrange(2, n)) while True: p = stream.next() yield p # filter out all multiples of p from stream stream = (q for q in stream if q%p != 0) # print primes up to 100 print list(sieve_all(100)) but it didn't work. I had to replace stream = (q for q in stream if q%p != 0) with def s1(p): return (q for q in stream if q%p != 0) stream = s1(p) or alternatively stream = (lambda p,stream: \ (q for q in stream if q%p != 0)) (p, stream) I had thought that genexps worked like that automatically, i.e. the stuff inside the genexp was in its own scope. If it's not real obvious what's happening instead, that's a sign that the current behavior is a wart. (The problem is that p in my first genexp comes from the outer scope, and changes as the sieve iterates through the stream) Oh well. From runlevelten at gmail.com Wed May 31 05:17:26 2006 From: runlevelten at gmail.com (Ten) Date: Wed, 31 May 2006 10:17:26 +0100 Subject: saving settings In-Reply-To: References: Message-ID: <200605311017.26280.runlevelten@gmail.com> On Monday 29 May 2006 12:28, SuperHik wrote: > aum wrote: > > On Mon, 29 May 2006 09:05:36 +0200, SuperHik wrote: > >> Hi, > >> > >> I was wondering how to make a single .exe file, say some kind od clock, > >> and be able to save some settings (alarm for example) into the same > >> file? Basically make code rewrite it self... > >> > >> thanks! > > > > Yikes!!! > > > > I'd strongly suggest you read the doco for ConfigParser, and load/save > > your config file to/from os.path.join(os.path.expanduser("~")). > > > > Another option - save your stuff in the Windows Registry > > but if I copy this file on the other computer settings will be lost... A pretty standard behaviour in this context is to have your program create its own config file if it's absent, say on first run, per user, or if it's copied to a new machine. Just do it using whatever defaults are in the python file itself. Regards, Ten. -- There are 10 types of people in this world, those who understand binary, and those who don't. From johnjsal at NOSPAMgmail.com Mon May 1 16:09:07 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 01 May 2006 20:09:07 GMT Subject: using ftplib Message-ID: I'm experimenting with this now and I'm a little confused about transferring commands. This might be more of an FTP question than strictly Python, but it's still related to how to use the ftplib methods. Anyway, if what I want to do is send a command to change the file permission settings of a file (or files), I assume I would use transfercmd() and the command would be something like SITE CHMOD 755 name.py, for example. What I'm confused about is why the documentation says to send a PORT or PASV command as well. Is this just something that must be done before each command? Also, in order to figure out what the FTP commands are to begin with, I did a little testing in FileZilla and I noted what was being displayed at the top (things like PORT xxx, STOR xxx, SITE CHMOD, etc. depending on what I was doing). So I assume these are the 'cmd' parameter. So here are a couple of questions: 1. Are PORT/PASV necessary to start a transfer? 2. Is the cmd parameter some kind of list, or is it just a string and you have to call a separate transfercmd() for each command? 3. My burning question: also during every transfer I made in FileZilla, I see that it sometimes sends a TYPE A or TYPE I command as well. What are these, and are they also necessary when I'm using transfercmd()? Thanks! John From rpdooling at gmail.com Wed May 17 00:26:10 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 16 May 2006 21:26:10 -0700 Subject: common practice for creating utility functions? References: <7xd5efdstn.fsf@ruckus.brouhaha.com> <1147721970.417910.170780@i40g2000cwc.googlegroups.com> Message-ID: <1147839970.101234.32510@i40g2000cwc.googlegroups.com> Hey, thanks. I got the writing thing down: http://dooling.com Now I'm trying to pick up the programming part. Thanks for links. rick From joel.hedlund at gmail.com Fri May 5 06:33:25 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Fri, 05 May 2006 12:33:25 +0200 Subject: Is this a good use of __metaclass__? Message-ID: Hi! I need some input on my use of metaclasses since I'm not sure I'm using them in a pythonic and graceful manner. I'm very grateful for any tips, pointers and RTFMs I can get from you guys. Below, you'll find some background info and an executable code example. In the code example I have two ways of doing the same thing. The problem is that the "Neat" version doesn't work, and the "Ugly" version that works gives me the creeps. The "Neat" version raises a TypeError when I try the multiple inheritance (marked with comment in the code): Traceback (most recent call last): File "/bioinfo/yohell/pybox/gridjs/gridjs-2.0/test.py", line 132, in ? class FullAPI(JobAPI, UserAPI, AdminAPI): File "/bioinfo/yohell/pybox/gridjs/gridjs-2.0/test.py", line 43, in __new__ return type.__new__(cls,classname,bases,classdict) TypeError: Error when calling the metaclass bases metaclass conflict: the metaclass of a derived class must be a (non-strict) subclass of the metaclasses of all its bases In the "Ugly" version, I'm changing the metaclass in the global scope between class definitions, and that gives me bad vibes. What should I do? Is there a way to fix my "Neat" solution? Is my "Ugly" solution in fact not so horrid as I think it is? Or should I rethink the whole idea? Or maybe stick with decorating manually (or in BaseAPI.__init__)? Sincere thanks for your time. Cheers! /Joel Hedlund Background ########## (feel free to skip this if you are in a hurry) I'm writing an XMLRPC server that serves three types of clients (jobs, users and admins). To do this I'm subclassing SimpleXMLRPCServer for all the connection work, and I was planning on putting the entire XMLRPC API as public methods of a class, and expose it to clients using .register_instance(). Each session is initiated by a handshake where a challenge is presented to the client, each method call must then be authenticated using certificates and incremental digest response. Each client type must be authenticated differently, and each type of client will also use a discrete set of methods. At first, I was planning to use method decorators to do the validation, and have a different decorator for each type of client validation, like so: class FullAPI: @valid_job_required def do_routine_stuff(self, clientid, response, ...): pass @valid_user_required def do_mundane_stuff(self, clientid, response, ...): pass @valid_admin_required def do_scary_stuff(self, clientid, response, ...): pass ... There will be a lot of methods for each client type, so this class would become monstrous. Therefore I started wondering if it weren't a better idea to put the different client APIs in different classes and decorate them separately using metaclasses, and finally bring the APIs together using multiple inheritance. This is what I had in mind: class BaseAPI(object): pass class JobApi(BaseAPI): pass class UserApi(BaseAPI): pass class AdminApi(BaseAPI): pass class FullApi(JobAPI, UserAPI, AdminAPI): pass Now, I'm having trouble implementing the metaclass bit in a nice and pythonic way. Code example ############ test.py ======================================================================= # Base metaclass for decorating public methods: from decorator import decorator @decorator def no_change(func, *pargs, **kwargs): return func(*pargs, **kwargs) class DecoratePublicMethods(type): """Equip all public methods with a given decorator. Class data members: decorator = no_change: The decorator that you wish to apply to public methods of the class instances. The default does not change program behavior. do_not_decorate = []: > Names of public methods that should not be decorated. multiple_decoration = False: If set to False, methods will not be decorated if they already have been decorated by a prior metaclass. decoration_tag = '__public_method_decorated__': Decorated public methods will be equipped with an attribute with this name and a value of True. """ decorator = no_change do_not_decorate = [] multiple_decoration = True decoration_tag = '__public_method_decorated__' def __new__(cls,classname,bases,classdict): for attr,item in classdict.items(): if not callable(item): continue if attr in cls.do_not_decorate or attr.startswith('_'): continue if (not cls.multiple_decoration and hasattr(classdict[attr], cls.decoration_tag)): continue classdict[attr] = cls.decorator(item) setattr(classdict[attr], cls.decoration_tag, True) return type.__new__(cls,classname,bases,classdict) ## Authentication stuff: class AuthenticationError(Exception): pass import random @decorator def validate_job(func, self, id, response, *pargs, **kwargs): """Bogus authentiction routine""" if random.randint(0,3) / 3: raise AuthenticationError return func(self, id, response, *pargs, **kwargs) @decorator def validate_user(func, self, id, response, *pargs, **kwargs): """Bogus authentiction routine""" if random.randint(0,4) / 4: raise AuthenticationError return func(self, id, response, *pargs, **kwargs) @decorator def validate_admin(func, self, id, response, *pargs, **kwargs): """Bogus authentiction routine""" if random.randint(0,1): raise AuthenticationError return func(self, id, response, *pargs, **kwargs) ## Ugly (?) way that works: ## ----------------------------------------------------------- #class BaseAPI(object): # __metaclass__ = DecoratePublicMethods # #DecoratePublicMethods.decorator = validate_job # #class JobAPI(BaseAPI): # def do_routine_stuff(self, clientid, response, foo): # print "Routine stuff done." # #DecoratePublicMethods.decorator = validate_user # #class UserAPI(BaseAPI): # def do_mundane_stuff(self, clientid, response, moo): # print "Mundane stuff done." # #DecoratePublicMethods.decorator = validate_admin # #class AdminAPI(BaseAPI): # def do_scary_stuff(self, clientid, response, moose): # print "Scary stuff done." # #class FullAPI(JobAPI, UserAPI, AdminAPI): # pass # #a = FullAPI() ## ----------------------------------------------------------- ## Neat (?) way that doesn't work: ## ----------------------------------------------------------- class RequireJobValidation(DecoratePublicMethods): decorator = validate_job class RequireUserValidation(DecoratePublicMethods): decorator = validate_user class RequireAdminValidation(DecoratePublicMethods): decorator = validate_admin class BaseAPI(object): pass class JobAPI(BaseAPI): __metaclass__ = RequireJobValidation def do_routine_stuff(self, clientid, response, foo): print "Routine stuff done." class UserAPI(BaseAPI): __metaclass__ = RequireUserValidation def do_mundane_stuff(self, clientid, response, moo): print "Mundane stuff done." class AdminAPI(BaseAPI): __metaclass__ = RequireAdminValidation def do_scary_stuff(self, clientid, response, moose): print "Scary stuff done." print "OK up to here." ## FIXME: Illegal multiple inheritance. class FullAPI(JobAPI, UserAPI, AdminAPI): pass b = FullAPI() ## ----------------------------------------------------------- ======================================================================= Oh, and by the way - this example uses Michele Simionato's excellent decorator module, available from here: http://www.phyast.pitt.edu/~micheles/python/decorator.zip If you don't want to donwload it, for this example you can just substitute this: @decorator def foo(func, *pargs, **kwargs): print "Code goes here" return func(*pargs, **kwargs) for this: def foo(func): def caller(*pargs, **kwargs): print "Code goes here" return func(*pargs, **kwargs) return caller The difference is that @decorator preserves function signatures and such for decorated functions. Very neat. Thanks again for your time. /Joel From jerome.decasteau at ksz-bcss.fgov.be Mon May 15 03:42:32 2006 From: jerome.decasteau at ksz-bcss.fgov.be (jdec) Date: 15 May 2006 00:42:32 -0700 Subject: Web framework to recommend References: Message-ID: <1147678952.542396.232560@j73g2000cwa.googlegroups.com> Hi, Jacky Please find below a link to the tool you're looking for : http://karrigell.sourceforge.net/ It's small, easy to install and work with, good documented (In english an in french). The developper is also very reactive on questions / remarks. I'm using it since more than 1 year without trouble Hope you'll enjoy Regards, Jerome From johnjsal at NOSPAMgmail.com Thu May 25 11:05:45 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 25 May 2006 15:05:45 GMT Subject: how to "normalize" indentation sources In-Reply-To: <447525b7$1@news.eftel.com> References: <447525b7$1@news.eftel.com> Message-ID: John Machin wrote: > remove empty lines > at the end of files. Also ensure the last line ends with a newline. don't those two things conflict with one another? or is the newline added after empty lines are removed? From phleum_nospam at chello.se Thu May 11 14:59:12 2006 From: phleum_nospam at chello.se (Carl) Date: Thu, 11 May 2006 20:59:12 +0200 Subject: Calling C/C++ functions in a python script References: <1147299778.630583.83380@q12g2000cwa.googlegroups.com> <1147300511.673435.72630@i39g2000cwa.googlegroups.com> <1147339012.474084.327540@q12g2000cwa.googlegroups.com> Message-ID: chaosquant at tele2.fr wrote: > > Ravi Teja a ?crit : > >> >> For more advanced needs, take a look at some of the extending options >> available. >> http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html > > Thanks for your answer. It is just what I'm trying to do. > Unfortunately, apparently I need a > "pyhton24_d.lib" to link to that does not seem to exists. Do you know a > solution for this? > > Thanks a lot, > > Jean-Claude You can be build it from source! /Carl From http Thu May 11 12:53:33 2006 From: http (Paul Rubin) Date: 11 May 2006 09:53:33 -0700 Subject: find all index positions References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> Message-ID: <7xbqu4ec4y.fsf@ruckus.brouhaha.com> micklee74 at hotmail.com writes: > say i have string like this > astring = 'abcd efgd 1234 fsdf gfds abcde 1234' > if i want to find which postion is 1234, how can i achieve this...? i > want to use index() but it only give me the first occurence. I want to > know the positions of both "1234" Most straightforwardly with re.findall -- see the docs. From onurb at xiludom.gro Thu May 18 05:29:46 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 11:29:46 +0200 Subject: Process forking on Windows In-Reply-To: <126mi8q1t31r9e0@corp.supernews.com> References: <126mgi2j7fl4b4b@corp.supernews.com> <446b45b1$0$7132$636a55ce@news.free.fr> <126mi8q1t31r9e0@corp.supernews.com> Message-ID: <446c3ef2$0$7699$626a54ce@news.free.fr> Andrew Robert wrote: > bruno at modulix wrote: > >>Andrew Robert wrote: >> >>>Hi everyone, >>> >>> >>>I have a python program that will need to interact with an MQSeries >>>trigger monitor. >>> >>>It does this fine but it hogs the trigger monitor while it executes. >>> >>>I'd like to fork the program off and terminate the parent process so >>>that the trigger monitor frees up. >> >> >>Is this really the solution ? >> >> >>>Does anyone how this can be accomplished on a Windows platform? >> >>AFAIK, there's no fork in Windows - you might want to give a try with >>CreateProcess. >>http://www.byte.com/art/9410/sec14/art3.htm >>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/html/UCMGch01.asp >> > Unfortunately there is a real need for this. > The MQSeries trigger monitor is single threaded. > > Because of this, my program would absorb it until it completes. > The way to get around this would be to fork off and terminate the parent. > Unfortunately, Windows appears to be somewhat stubborn about it. > Creating a subprocess does not alleviate the need to get the originating > process out of the trigger monitor. > Have you *really* read the material pointed by the above links ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From claird at lairds.us Mon May 15 11:31:33 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 15 May 2006 15:31:33 +0000 Subject: Test professionalism (was: count items in generator) References: Message-ID: In article , Delaney, Timothy (Tim) wrote: . . . >That's exactly my point. Assuming your test coverage is good, such an >error would be caught by the MemoryError. An infinite loop should also >be caught by timing out the tests, but that's much more dependent on the >test harness. > >Tim Delaney Gulp. OK, you've got me curious: how many people habitually frame their unit tests with resource constraints? I think I take testing seriously, and certainly also am involved with resource limits often, but I confess I've never aimed to write all my tests in terms of bounds on time (and presumably memory and ...). You've got me thinking, Tim. From Serge.Orlov at gmail.com Mon May 1 08:32:57 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 1 May 2006 05:32:57 -0700 Subject: stdin: processing characters References: <2Bd4g.21380$tN3.16246@newssvr27.news.prodigy.net> <1146423801.634307.100970@g10g2000cwb.googlegroups.com> Message-ID: <1146486777.878616.319980@y43g2000cwc.googlegroups.com> Kevin Simmons wrote: > Thanks for your input. I found an answer that suits my needs, not curses > :-), but stty settings and sys.stdin.read(n) : > > import os, sys > > while 1: > os.system("stty -icanon min 1 time 0") > print """ > Radio computer control program. > ------------------------------ > Choose a function: > po) Power toggle > fq) Change frequency > cm) Change mode > vo) Change volume > re) Reset > qu) Quit > -->""", > func = sys.stdin.read(2) > if func == "po": > ... > ... rest of menu actions ... > elif func = "qu": > os.system("stty cooked") > sys.exit() > Looks reasonable if you don't need portability. But you may want to refactor it a little bit to make sure terminal setting are always restored: try: do_all_the_work() finally: os.system("stty cooked") P.S. Maybe its me, but when I see call sys.exit() I always have a gut feeling this function never returns. But in fact my I'm wrong and sys.exit is more reasonable: it raises exception. So you can call sys.exit() inside do_all_the_work and you can still be sure that os.system("stty cooked") is always executed at the end. From mensanator at aol.com Wed May 24 19:23:18 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 May 2006 16:23:18 -0700 Subject: Compiling Python from Sources References: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> <1148509057.542733.217230@i39g2000cwa.googlegroups.com> <1148509487.448417.294690@j33g2000cwa.googlegroups.com> Message-ID: <1148512998.732842.258430@j33g2000cwa.googlegroups.com> rwr wrote: > configure:1687: checking for gcc > configure:1703: found /usr/bin/gcc > configure:1713: result: gcc At this point, configure thinks you have the gcc compiler installed. > configure:1753: checking for C++ compiler default output file name > configure:1756: gcc conftest.cc >&5 Now it's going to invoke the compiler to see what kind of output it creates. > gcc: installation problem, cannot exec 'cc1plus': No such file or > directory The gcc compiler is complaining that it cannot find the file cc1plus. The problem appears to be with the installation of gcc. If gcc was included in your default os setup, you may need to re-install it as the default setup may not include all the options (such as installing the c compiler but not the c++ compiler). I ran into a similar problem with Cygwin. In the setup program you have to specifically tell it which compilers to install. Which it does. But it doesn't include the tools needed by similar configuration programs such as make and m4. Those are in a different section of the setup program and you need to know which ones to install. There's no option for "install everything I need to compile c/c++ programs". In my case, I had to run configure over and over again each time going through the log finding a new missing file, re-install, and repeat until the errors stopped. > configure:1759: $? = 1 > configure: failed program was: > | /* confdefs.h. */ > | > | #define _GNU_SOURCE 1 > | #define _NETBSD_SOURCE 1 > | #define __BSD_VISIBLE 1 > | #define _BSD_TYPES 1 > | #define _XOPEN_SOURCE 600 > | #define _XOPEN_SOURCE_EXTENDED 1 > | #define _POSIX_C_SOURCE 200112L > | /* end confdefs.h. */ > | > | int > | main () > | { > | > | ; > | return 0; > | } > configure:1798: error: C++ compiler cannot create executables > See `config.log' for more details. From larry.bates at websafe.com Mon May 8 09:57:07 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 08 May 2006 08:57:07 -0500 Subject: reading a column from a file In-Reply-To: <87y7xd83rc.fsf@localhost.localdomain> References: <87y7xd83rc.fsf@localhost.localdomain> Message-ID: <445F4E33.4050601@websafe.com> Check out the csv module. -Larry Bates Gary Wessle wrote: > Hi > > I have a file with data like > location pressure temp > str floot floot > > I need to read pressure and temp in 2 different variables so that I > can plot them as lines. is there a package which reads from file with > a given formate and returns desired variables? or I need to open, > while not EOF read, parse, build list, return? > > thanks From me+python at modelnine.org Mon May 22 05:39:22 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Mon, 22 May 2006 11:39:22 +0200 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <447183f8$1_5@news.bluewin.ch> References: <447183f8$1_5@news.bluewin.ch> Message-ID: <200605221139.22948.me+python@modelnine.org> Am Montag 22 Mai 2006 11:27 schrieb Boris Borcic: > Mhhh, your unsugared form remind me of darks hours with primitive BASICS in > my youth - the kind Dijsktra commented on. Why don't you write > > for node in tree: > if node.haschildren(): > As I've replied on python-dev, indentation is not always a good thing, especially if the for-body is longer than a few lines. The "if not: continue" form allows you to keep the indentation at one level, so that it's pretty clear what is part of the loop body, and what is not. If you add an extra indentation, your mind has to keep track of the indentation, and will expect an "else:" somewhere, which in the use case I propose won't happen. At least that's what my mind does, and is majorly confused, if the else doesn't appear. This certainly is personal taste, and AFAICT there are pretty few people who feel like I do. But, basically, I find it easier to have one level of indentation, and to test for the negated condition, than to put the loop body in an enclosing if-statement, which will always add an extra level of indentation. I put forth the proposal, because it allows you to save this level of indentation, which makes the code more readable for me. Anyway, the PEP has already been rejected on python-dev, and I'm currently just rewriting it with the positive and negative things that have so far been said, so basically, it'll just be there so that people can be pointed at it when anybody else'll ask for it. --- Heiko. From rick446 at NOSPAM.usa.net Wed May 17 13:21:15 2006 From: rick446 at NOSPAM.usa.net (Richard Copeland) Date: Wed, 17 May 2006 13:21:15 -0400 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <1147885843.162424.133030@i40g2000cwc.googlegroups.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> <9bKdnakiGs9Cy_bZRVn-qw@comcast.com> <1147885843.162424.133030@i40g2000cwc.googlegroups.com> Message-ID: I tested the exact code I sent you on python 2.4.1. What version of Python are you using? Thanks, Rick Pierre wrote: > Nop I get the same AttributeError when I try to access to the property > "c"... > From mh at pixar.com Wed May 10 19:29:00 2006 From: mh at pixar.com (Mark Harrison) Date: Wed, 10 May 2006 23:29:00 GMT Subject: create a c++ wrapper for python class? Message-ID: <0Hu8g.70548$F_3.61654@newssvr29.news.prodigy.net> Right now I'm using Boost Python to wrap some C++ code so that applications from both languages can use it. This is great, but I'm rapidly coming to the conclusion that a lot of this work is better coded in Python. There's nothing particularly CPU-bound, and the comprehensive Python library is a big help. So, I'm looking for a C++ wrapper generator, so that I can write a class in Python, and then have a .h and .cpp generated that will give me a corresponding C++ class. Of course, the usual restrictions apply: no dynamically added methods, accessing all instance data via getters and setters, etc. It seems a first cut of this is pretty straightforward, using introspection to get the required methods. Something needs to be done to specify the C++ types of the parameters. Is there any work being done in this area? Many TIA, Mark -- Mark Harrison Pixar Animation Studios From notvalid at email.com Wed May 17 01:03:44 2006 From: notvalid at email.com (Ala Qumsieh) Date: Wed, 17 May 2006 05:03:44 GMT Subject: python vs perl lines of code In-Reply-To: References: Message-ID: Edward Elliott wrote: > John Bokma wrote: >> >>Without seeing the actual code this is quite meaningless. > > > Evaluating my experiences yes, relating your own no. Well, quality of code is directly related to its author. Without knowing the author personally, or at least seeing the code, your anecdote doesn't really mean anything. A colleague of mine, who is efficient at programming, and pretty decent at Perl, routinely does something like: if ($var =~ /something and something else/) { $var =~ /(something) and (something else)/; my $match1 = $1; my $match2 = $2; ... } Needless to say, this adds a lot of unnecessary redundancy, which will go towards increasing your character count. Being an avid Perl Golfer (although not one of the best) I can almost guarantee that any python code can be written more succinctly in Perl, although readability will suffer. Plus, the extensibility argument is very subjective, and is closely related to personal coding style. Btw, do you include space chars that go toward indentating Python code in your count? If not, you should since they are required. Not so for Perl. --Ala From tim.peters at gmail.com Thu May 4 13:19:46 2006 From: tim.peters at gmail.com (Tim Peters) Date: Thu, 4 May 2006 13:19:46 -0400 Subject: Multiple Version Install? In-Reply-To: References: Message-ID: <1f7befae0605041019u7abba4cahd567d25c5bee45c6@mail.gmail.com> [David C.Ullrich] > Would there be issues (registry settings, environment > variables, whatever) if a person tried to install > versions 1.x and 2.x simultaneously on one Windows > system? Windows 98, if it matters. > > (I can handle the file associations with no problem.) There are generally no issues beyond file associations. On Windows, Python versions i.j.k and i'.j'.k' coexist happily so long as i != i' or j != j'. For example, I currently have the python.org-released Pythons 2.2.3, 2.3.5, and 2.4.3 installed on my Windows box. It would be a challenge only if I wanted, say, 2.4.2 and 2.4.3 installed simultaneously. Another possible issue is that whenever the major or minor version numbers (i or j) change on Windows, you also need to install matching versions of any 3rd party extensions you want. The major and minor version numbers appear in the _name_ of the core Python DLL (like python23.dll and python24.dll), and extensions with C code must be compiled to link with the correct version of the Python DLL. > If anyone feels like pointing out that there's simply > no reason to want to keep 1.x after installing the > current version: By all means talk me into that! If you've been using extensions with 1.j.k, then as above they have no chance of working with 2.j'.k' bejore you install 2.j' versions of those extensions. That's a good reason to keep an old version. There have been thousands of bugfixes and language enhancements since 1.j.k too, and not all are 100% backward-compatible. In all, best advice is to keep the old version around until you're sure you no longer need it. > The problem is not that I'm concerned about backwards > compatibility of Python code. The problem is that I > use Python embedded in various Delphi programs, > including a "DIDE" that I use really a lot, via > a certain set of Delphi "components". These components > don't seem to work with 2.x. Presumably the PyDelphi > people have new versions of the components that do > work with Python 2.x. These presumably use much > newer versions of Delphi than what I have. A new > version of Delphi is not free... If I could use > Python 2.x when I need to while continuing to > use 1.x the way I have been for things that > don't need 2.x that would be convenient. That should work fine. I don't know about PyDelphi, but found what appears to be a still-active discussion list: http://groups.yahoo.com/group/pythonfordelphi/ The theoretical joy of open source is that if they _don't_ support the Python+Delphi combo you have, you can fix that yourself ;-) From gmc at serveisw3.net Sat May 27 10:10:45 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Sat, 27 May 2006 16:10:45 +0200 Subject: Pyrex speed In-Reply-To: <1148734724.933745.277830@j73g2000cwa.googlegroups.com> References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> <4dqq38F1bi6btU1@uni-berlin.de> <1148728491.640293.298470@38g2000cwa.googlegroups.com> <1148728959.466305.23870@u72g2000cwu.googlegroups.com> <1148729670.982351.132060@j33g2000cwa.googlegroups.com> <1148734724.933745.277830@j73g2000cwa.googlegroups.com> Message-ID: <44785DE5.3060708@serveisw3.net> Hi Jim, It depends a lot on what you're doing. You will get speed up from Pyrex or wrapping C code if you understand how does it work internally, and to speed up you application via coding *only* Pyrex parts (I mean don't using it for wrapping C but implementing in Pyrex), it limits a lot the things that you can expect to get faster -'cause on some kind of things you can even get better performance coding that in straight Python than in Pyrex and converted to C & compiled, I thought you should know how Python works in the C side to understand it fully-. I attach some examples of different code where C is a lot faster, or just a little bit faster (and I compare with C counterparts, not Pyrex ones -Pyrex is only used for wrapping in these examples-). So you can get an idea of why depends a lot on what you're doing. If you plan only using cdefs to speed-up Python code, you're very limited in the things that could be speed-up. Try to do some experiments and examine the C generated code by Pyrex, and you will see why it is -you will see how Pyrex does Python C api function calls for conversion from Python objects to C type values every time you use that var, and that's not a great gain, even in some kind of operations can be worse as Python does a better job than generated C code by Pyrex for some operations or value conversions (i.e. when doing operations on some kind of iterable objects I remember to read on some paper that Pyrex does not traslate to the faster C approach) Some days ago I posted some timing results for a function coded in Python, or coded in C and wrapped by Pyrex. C approach was more than 80 times faster. And I attach below another one, where C isn't much a gain (1 time faster). Example A: This code is more than 80 times faster than a "easy" Python implementation. For every call, it does some bitwise operations and does an array lookup for every string character from argument. Its a lot faster because in Python approach a list lookup is done and it is a lot faster to do a C array lookup -thought that in these C loops no Python type value conversions are needed, if it where the case, C approach would not be so faster than python. I don't know how would perform an array based Python code, but I expect it to be a lot faster than using a list, so Python code can be speed up a lot if you know how to do it. // C code: int CRC16Table[256]; // Filled elsewhere int CalcCRC16(char *str) { int crc; for(crc = 0xFFFF; *str != 0; str++) { crc = CRC16Table [(( crc >> 8 ) & 255 )] ^ ( crc << 8 ) ^ *str; } return crc; } # Python code gCRC16Table = [] # Filled elsewhere def CalcCRC16(astr): crc = 0xFFFFL for c in astr: crc = gCRC16Table[((crc >> 8) & 255)] ^ ((crc & 0xFFFFFF) << 8) ^ ord(c) return crc ------------------------------------------------------------------------- Example B: If we do compare the functions below, Python approach is only a bit slowly than C implementation. I know both aren't the faster approaches for every language, but that's a different issue. C here is only about 1 time faster: // C code. gTS type is struct { int m, int s } gTS gTS_diff(gTS t0, gTS t1) { gTS retval; retval.s = (t1.s-t0.s); if ((t0.m>t1.m)) { retval.m = (t1.m-t0.m); while((retval.m<0)) { retval.s = (retval.s-1); retval.m = (m+1000); } } else { retval.m = (t1.m-t0.m); } while((retval.m>999)) { retval.m = (retval.m-1000); retval.s = (retval.s+1); } return retval; } # Python code (t0 and t1 are tuples) def gts_diff(t0,t1): s = t1[0] - t0[0] if (t0[1] > t1[1]): m = t1[1] - t0[1] while m < 0: s = s - 1 m = m + 1000 else: m = t1[1] - t0[1] while m > 999: m = m - 1000 s = s + 1 return s, m I encourage you to google for some Pyrex papers on the net, they explain the "to do"'s and the "not to do"'s with Pyrex. Sorry but I don't have the urls. Regards, Gonzalo Jim Lewis escribi?: >>I never had an opportunity to do any more sophisticated math than simple adding, >> >> >multiplying, subtracting and dividing. > >Neither is the primes example doing anything more sophisticated than >basic arithmetic but it's 50 times faster. > > > From deets at nospam.web.de Tue May 2 14:17:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 May 2006 20:17:20 +0200 Subject: Polling from keyboard References: <1146593098.744039.89340@u72g2000cwu.googlegroups.com> Message-ID: <4bpm1qF124s7vU1@uni-berlin.de> sturnfie at gmail.com wrote: > I am trying to find a way to poll the keyboard. In my searching, I > have found that Windows users are given the msvcrt module. Is there an > equivilant for Unix systems? > > I am writing a p2p chat application, and would like to ideally approach > user input in a manner similar to the way I am using poll() to moniter > the sockets for events I currently do that under Linux using /dev/input/*. However, that's for a special case where we want several keyboards read simultaneously. I guess what you want is a RAW-mode for your terminal, or alternatively the event-system of your windowing system. Then you can get every keystroke. But we need somewhat more information to be more helpful I fear. diez From Serge.Orlov at gmail.com Thu May 25 01:54:48 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 24 May 2006 22:54:48 -0700 Subject: deploying big python applications References: Message-ID: <1148536488.420620.248840@j55g2000cwa.googlegroups.com> AndyL wrote: > Hi, > > let me describe how I do that today. There is standard python taken from > python.org installed in a c:\python23 with at least dozen different > additional python packages (e.g. SOAPpy, Twisted, wx, many smaller ones > etc) included. Also python23.dll moved from c:\windows to c:\python23. > This is zipped and available as over 100MB file to anyone to manually > unzip on his/her PC. This is a one time step. > > On top of that there is 30K lines of code with over 100 .py files > application laid out within a directory tree. Very specific for the > domain, typical application. This again is zipped and available to > anyone as much smaller file to unzip and use. This step is per software > releases. > > There is one obvious drawback - I can not separate python from standard > libraries easily. True, python releases on windows are forward incompatible with C extensions, so don't even think about that. I'm not even talking about big pure python packages that could probably break because of small subtle changes in python API between releases. > So when upgrade to 2.4 comes, I need to reinstall all > the packages. Yes, but how much time it will *actually* take? I bet it's 1 hour. Seriously, why don't you *time* it with a stopwatch? And then compare that time to the time needed to debug the new release. > In order to address that as well as the Linux port I > project following structure: > -default python.org installation or one time step on Windows > -set of platform dependent libraries in directory A > -set of platform independent libraries in directory B > -application in directory C I would suggest the same structure I described for deploying over LAN: http://groups.google.com/group/comp.lang.python/msg/2482a93eb7115cb6?hl=en& The only problem is that exemaker cannot find python relative to itself, you will have to mash exemaker, python and application launcher in one directory. So the layout is like this: app/ engine/ -- directory with your actual application app.exe -- renamed exemaker.exe app.py -- dispatching module, see below python.exe python24.dll lib -- python stdlib, etc === app.py === from engine import real_application ============ This way file engine/real_application.py is platform independant. On Linux/Unix shell script is an equivalent of exemaker. Or C program like exemaker, but you will have to compile it for all platforms. From mirandacascade at yahoo.com Sat May 6 20:16:18 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 6 May 2006 17:16:18 -0700 Subject: the print statement In-Reply-To: References: <1146950481.610645.39710@j33g2000cwa.googlegroups.com> Message-ID: <1146960978.564533.59730@j73g2000cwa.googlegroups.com> Thank you. Yes, that post answers most of the questions. I now have a bit of an understanding of the \xhh pattern. It's still unclear to me, however, how one can go from the \x92 pattern and arrive at the apostrophe character. Is \x92 theh apostrophe character in another character set? If so, which character set? From grante at visi.com Sat May 6 17:06:00 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 06 May 2006 21:06:00 -0000 Subject: NaN handling References: <125hplqmppfeq29@corp.supernews.com> <01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> <1146929327.30335.5.camel@kenshin.CASA> <445CD5E3.1070600@cs.uoregon.edu> Message-ID: <125q3tortqgsn6b@corp.supernews.com> On 2006-05-06, Terry Reedy wrote: >> That's Python 2.4.1 on Mac OS X. > >>>> float("NaN") > > Traceback (most recent call last): > File "", line 1, in -toplevel- > float("NaN") > ValueError: invalid literal for float(): NaN > > As Tim Peters has said often enough, this sort of thing is specific to the > underlying C library and will remain so until someone cares enough to write > or fund a cross-platform solution. Yea, that's a royal PITA. I had to add my own code into the "pickle" classes to handle NaNs. Having a pickler that only works for a subset of the legal IEEE FP values proved to be sort of useless. -- Grant Edwards grante Yow! Were these parsnips at CORRECTLY MARINATED in visi.com TACO SAUCE? From onurb at xiludom.gro Thu May 18 07:33:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 13:33:18 +0200 Subject: Best active community website In-Reply-To: <1147948251.530565.210690@y43g2000cwc.googlegroups.com> References: <1147948251.530565.210690@y43g2000cwc.googlegroups.com> Message-ID: <446c5be5$0$7700$626a54ce@news.free.fr> martinskou at gmail.com wrote: > Hi > > I have been looking for a active Python community website. Something > like www.codeproject.com (contains code articles and guide, by > developers, for developers) for Python users. > > Does something like this exist? - this newsgroup - which is very active, friendly and helpful -, - the Python Cookbook: http://aspn.activestate.com/ASPN/Python/Cookbook/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From robert.kern at gmail.com Fri May 12 18:07:25 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 12 May 2006 17:07:25 -0500 Subject: which windows python to use? In-Reply-To: References: Message-ID: Don Taylor wrote: > Robert Kern wrote: > >>>Which C compiler will you be using for the Enthought 2.4 Windows release? >> >>Define "using". We build Python with whatever compiler the official build is >>compiled with. In this case, MSVC 7., I think . For this release, we >>will ship the latest available gcc available for mingw. Some of the extension >>modules will be built with this gcc. > > I meant to build Python itself. > > I asked because I was interested in trying your Traits package but could > not use it with Python 2.4. I don't have MSVC 7 and I was intimidated > by the prospect of building the CTraits extension with either the free > MS toolkit or mingw and munging the dlls to conform to the MSVC 7 formats. > > I just wondered if Enthought's distro for Windows was gcc-based. The Python interpreter is not. Most of the extension modules we build are. Building stock-2.4 extension modules using mingw works for the most part. It certainly does for Traits as we build Traits using mingw. Most extension modules compiled this way appear to work. There are still some incompatibilities with C++ modules that use iostream and possibly some C modules that use, IIRC, ischar() and friends. Until someone fully ports mingw to use msvcr71.dll as its C runtime, those incompatibilities will remain. -- 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 bdesth.quelquechose at free.quelquepart.fr Thu May 18 20:08:46 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 19 May 2006 02:08:46 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147980462.464427.323030@u72g2000cwu.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147958226.200557.264850@j33g2000cwa.googlegroups.com> <1147975275.206451.107730@j73g2000cwa.googlegroups.com> <446cc017$0$12808$636a55ce@news.free.fr> <1147980462.464427.323030@u72g2000cwu.googlegroups.com> Message-ID: <446cdd6b$0$7043$636a55ce@news.free.fr> glomde a ?crit : >>We already have this (quite close to) this syntax: >> >>class (super): >> = * >> [class *] >> >>There's also the Zope3 'implements' trick, that allow to modify the >>class namespace without assignement: >> >>class : >> (*args, **kw)* >> >>So what you want is very certainly doable without any syntax change. > > > It's not obvious me how you would do it it with the above syntax. > Could you give me an example? > For example how would you do: > > root = ET.Element("html") > node root: > attr head("head"): > node title("title): > for i in sections: > node section(): > attr Text = section[i] > Your snippet doesn't follow the syntax you described. But FWIW: class Root(Node): class Head(Node): class Title(Node): content="page title" for section in sections: class Section(Node): content=section Ok. Get it. Doh :( Can't work, because we can't neither reuse the same name nor dynamically create it (or if it's possible, I fail to see how without really dirty code). Point taken. We'd need the make: statement, but the BDFL has pronounced against. I'm still -2 against your proposition, but it could make a good use case for the make statement. I gave an eye at the new 'with' statement, but I'm not sure it could be used to solve this. From laurent.pointal at limsi.fr Mon May 22 07:07:38 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 22 May 2006 13:07:38 +0200 Subject: Includeing Python in text files In-Reply-To: References: Message-ID: Paolo Pantaleo a ?crit : > I am working on this: > > I have a text file, containig certain section in the form > python code here > py?> > > I parse the text file and substitute the python code with its result > [redirecting sys.stdin to a StringIO]. It something like php or > embedded perl. > > So my little toy works not bad, but I was wondering if such a feature > already existed, if yes, can you point me out some links? Yes Python Inside HTML, like this example from Karrigell docs ( http://karrigell.sourceforge.net/en/pythoninsidehtml.htm ): The current date is <% import time print time.strftime("%d:%m:%y",time.localtime(time.time())) %> See http://karrigell.sourceforge.net/ A+ Laurent. From NOatkinwSPAM at rpi.edu Sun May 7 06:45:51 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 06:45:51 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <87wtcyy5i0.fsf@rpi.edu> <445dc17a$1$25449$bed64819@news.gradwell.net> <87d5eq6rx1.fsf@rpi.edu> Message-ID: <87mzdu5d0g.fsf@rpi.edu> Bill Atkins writes: > There are still more! _On Lisp_ has a lot of interesting ones, like > an embedded Prolog interpreter and compiler: > > (<-- (father billsr billjr)) > (?- (father billsr ?)) > > ? = billjr Actually, these might not be implemented as macros. -- This is a song that took me ten years to live and two years to write. - Bob Dylan From tomasz.zielonka at gmail.com Sun May 7 00:16:13 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Sun, 7 May 2006 04:16:13 +0000 (UTC) Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> Message-ID: Alex Martelli wrote: > ``An unneeded feature "cannot" be added (elegantly) in future releases > of the language'' is just as trivial and acceptable for the unneded > feature ``allow ( as an ordinary single-character identifier'' as for > the unneded feature ``allow unnamed functions with all the flexibility > of named ones''. You can't be seriously claiming that these two features are equally (un)needed. Anonymous functions come from the foundations of computer science - Lamda Calculus. They are just a natural step on the road to higher level languages. There are useful programming techniques, like monadic programming, that are infeasible without anonymous functions. Anonymous functions really add some power to the language. On the other hand, what do you get by allowing ( as an indentifier? Significant whitespace is a good thing, but the way it is designed in Python it has some costs. Can't you simply acknowledge that? Best regards Tomasz From phddas at yahoo.com Sat May 6 20:05:38 2006 From: phddas at yahoo.com (Gary Wessle) Date: 07 May 2006 10:05:38 +1000 Subject: combined files together References: <87psirslhy.fsf@localhost.localdomain> Message-ID: <87slnmog19.fsf@localhost.localdomain> Gary Herron writes: > Gary Wessle wrote: > > >Hi > > > >is there a module to do things like concatenate all files in a given > >directory into a big file, where all the files have the same data > >formate? > >name address phone_no. > > > >or do I have to open each, read from old/write-or-append to new ... > > > >thanks > > > > > There's hardly enough code here to make a module out of this: > > combined = open('...', 'wb') > for name in os.listdir(path): I need to traverse those files in the order they were created chronologically. listdir() does not do it, is there a way besides build a list then list.sort(), then for element in list_of_files open element? thanks > infile = open(os.path.join(path,name), 'rb') > for line in infile: > combined.write(line) > > It could be more efficient by reading larger chunks than single lines, > and could be more accurate by closing both input and output files when > done, but you get the point I hope. > > On the other hand, if you've got the right OS, you might try something like: > os.system("cat * > combined") > > Gary Herron From johnjsal at NOSPAMgmail.com Sun May 14 14:33:20 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 14 May 2006 14:33:20 -0400 Subject: do/while structure needed In-Reply-To: <1147585422.693953.292480@u72g2000cwu.googlegroups.com> References: <4466bddd$0$18984$c3e8da3@news.astraweb.com> <1147585422.693953.292480@u72g2000cwu.googlegroups.com> Message-ID: <4467786c$0$1956$c3e8da3@news.astraweb.com> George Sakkis wrote: > while True: > random.shuffle(letters) > trans_letters = ''.join(letters)[:len(original_set)] > if some_compatison(original_set,trans_letters): > trans_table = string.maketrans(original_set, trans_letters) > break Thanks, that looks pretty good. Although I have to say, a do/while structure is the much more obvious way. I wonder why it hasn't been added to the language. From heikki at osafoundation.org Fri May 5 19:12:18 2006 From: heikki at osafoundation.org (Heikki Toivonen) Date: Fri, 05 May 2006 16:12:18 -0700 Subject: Building Python (2.4.x) with Visual C++ 2005 Express Edition? Message-ID: I did some searches but did not find any definitive answers as to whether or not it should be possible to build Python 2.4+ with Microsoft Visual C++ 2005 Express Edition. I tried it myself (have VC++ project files that work with Visual Studio 2003 .NET commercial version, just opened and closed them in vcexpress to convert the projects) and the compilation finished without errors (although with a bunch of deprecation warnings). But when I try to run, python crashes on startup. Has anyone gotten this to work? -- Heikki Toivonen From akameswaran at gmail.com Wed May 31 12:14:09 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 31 May 2006 09:14:09 -0700 Subject: Strange behavior with iterables - is this a bug? In-Reply-To: References: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> <1149087772.403131.270480@f6g2000cwb.googlegroups.com> Message-ID: <1149092049.044973.253560@y43g2000cwc.googlegroups.com> My original concern and reason for goint the iterator/generator route was exactly for large large lists :) Unnecessary in this example, but exactly what I was exploring. I wouldn't be using list comprehension for generating the permutiations. Where all this came from was creating a generator/iterator to handle very large permutations. Gary Herron wrote: > akameswaran at gmail.com wrote: > > >Gary Herron wrote: > > > > > >>List comprehension is a great shortcut, but when the shortcut starts > >>causing trouble, better to go with the old ways. You need to reopen each > >>file each time you want to iterate through it. You should be able to > >>understand the difference between these two bits of code. > >> > >>The first bit opens each file but uses (two of them) multiple times. > >>Reading from a file at EOF returns an empty sequence. > >> > >>The second bit opened the file each time you want to reuse it. That > >>works correctly. > >> > >>And that suggest the third bit of correctly working code which uses list > >>comprehension. > >> > >># Fails because files are opened once but reused > >>f1 = open('word1.txt') > >>f2 = open('word2.txt') > >>f3 = open('word3.txt') > >>for i1 in f1: > >> for i2 in f2: > >> for i3 in f3: > >> print (i1.strip(),i2.strip(),i3.strip()) > >> > >>and > >> > >># Works because files are reopened for each reuse: > >>f1 = open('word1.txt') > >>for i1 in f1: > >>f2 = open('word2.txt') > >>for i2 in f2: > >>f3 = open('word3.txt') > >>for i3 in f3: > >>print (i1.strip(),i2.strip(),i3.strip()) > >> > >>and > >> > >># Also works because files are reopened for each use: > >>print [(i1.strip(),i2.strip(),i3.strip()) > >> for i1 in open('word1.txt') > >> for i2 in open('word2.txt') > >> for i3 in open('word3.txt')] > >> > >>Hope that's clear! > >> > >>Gary Herron > >> > >> > > > > > >My original problem was with recursion. I explicitly nested it out to > >try and understand the behavior - and foolishly looked in the wrong > >spot for the problem, namely that file is not reitreable. In truth I > >was never concerned about file objects, the problem was failing with my > >own custom iterators (wich also were not reiterable) and I switched to > >file, to eliminate possible code deficiencies on my own part. I was > >simply chasing down the wrong problem. As was pointed out to me in a > >nother thread - the cleanest implementation which would allow me to use > >one copy of the file (in my example the files are identical) would be > >to use a trivial iterator class that opens the file, uses tell to track > >position and seek to set position, and returns the appropriate line for > >that instance - thus eliminating unnecessary file opens and closes. > > > > > > > I see. > > I wouldn't call "tell" and "seek" clean. Here's another suggestion. Use > l1 = open(...).readlines() > to read the whole file into a (nicely reiterable) list residing in > memory, and then iterate through the list as you wish. Only if your > files are MANY megabytes long would this be a problem with memory > consumption. (But if they were that big, you wouldn't be trying to find > all permutations would you!) > > Gary Herron From tim.golden at viacom-outdoor.co.uk Thu May 18 11:20:54 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Thu, 18 May 2006 16:20:54 +0100 Subject: Windows Registry Dump Message-ID: [Dirk Hagemann] | Does someone know how I can make a Text-Dump-File of a remote | Windows-Computer's Registry (not the whole registry - only a part of | it)? Well, your question doesn't seem to rule out this option so I thought I'd offer it: Use regedit to connect to the remote registry, then do the usual right-click Export stuff Maybe not what you wanted (doesn't use Python at all, unless you do: import os os.system ("regedit") but it certainly works! 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 NOatkinwSPAM at rpi.edu Sat May 6 04:22:02 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 04:22:02 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> Message-ID: <87y7xf8swl.fsf@rpi.edu> aleaxit at yahoo.com (Alex Martelli) writes: > Ken Tilton wrote: > ... >> > Absolutely. That's why firms who are interested in building *seriously* >> > large scale systems, like my employer (and supplier of your free mail > ... >> > Obviously will not scale. Never. >> > >> > Well... hardly ever! >> >> You are talking about being incredibly popular. I was talking about > > Who, me? I'm talking about the deliberate, eyes-wide-open choice by > *ONE* firm -- one which happens to more or less *redefine* what "large > scale" computation *means*, along many axes. That's got nothing to do > with Python being "incredibly popular": it has everything to do with > scalability -- the choice was made in the late '90s (and, incidentally, > by people quite familiar with lisp... no less than the reddit.com guys, > you know, the ones who recently chose to rewrite their side from Lisp to > Python...?), based on scalability issues, definitely not "popularity" > (Python in the late '90s was a very obscure, little-known language). > >> kenny (who is old enough to have seen many a language come and go) > > See your "many a language" and raise you one penny -- besides sundry > Basic dialects, machine languages, and microcode[s], I started out with > Fortran IV and APL, and I have professionally programmed in Pascal (many > dialects), Rexx, Forth, PL/I, Cobol, Lisp before there was a "Common" > one, Prolog, Scheme, Icon, Tcl, Awk, EDL, and several proprietary 3rd > and 4th generation languages -- as well of course as C and its > descendants such as C++ and Java, and Perl. Many other languages I've > studied and played with, I've never programmed _professionally_ (i.e., > been paid for programs in those languages), but I've written enough > "toy" programs to get some feeling for (Ruby, SML, O'CAML, Haskell, > Snobol, FP/1, Applescript, C#, Javascript, Erlang, Mozart, ...). > > Out of all languages I know, I've deliberately chosen to specialize in > Python, *because it scales better* (yes, functional programming is > _conceptually_ perfect, but one can never find sufficiently large teams > of people with the right highly-abstract mathematical mindset and at the > same time with sufficiently down-to-earth pragmaticity -- so, for _real > world_ uses, Python scales better). When I was unable to convince top > management, at the firm at which I was the top programmer, that the firm > should move to Python (beyond the pilot projects which I led and gave > such stellar results), I quit, and for years I made a great living as a > freelance consultant (mostly in Python -- once in a while, a touch of > Pyrex, C or C++ as a vigorish;-). > > That's how come I ended up working at the firm supplying your free mail > (as Uber Tech Lead) -- they reached across an ocean to lure me to move > from my native Italy to California, and my proven excellence in Python > was their prime motive. The terms of their offer were just too > incredible to pass by... so, I rapidly got my O1 visa ("alien of > exceptional skills"), and here I am, happily ubertechleading... and > enjoying Python and its incredibly good scalability every single day! > > > Alex How do you define scalability? -- This is a song that took me ten years to live and two years to write. - Bob Dylan From robert.kern at gmail.com Thu May 11 15:19:48 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 14:19:48 -0500 Subject: segmentation fault in scipy? In-Reply-To: <1147373294.235202.188220@y43g2000cwc.googlegroups.com> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> <1147373294.235202.188220@y43g2000cwc.googlegroups.com> Message-ID: conor.robinson at gmail.com wrote: > This is great advise and much appreciated. It was the answer to my > problem, thank you. However, isn't this faster... > scipy.sum(scipy.array(scipy.matrix(error)*scipy.matrix(error)), axis = > None) > as we you explained in my other posting? No! matrix objects use matrix multiplication for *. You seem to need elementwise multiplication. -- 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 mumia.w.18.spam+fbi.gov at earthlink.net Wed May 24 13:00:47 2006 From: mumia.w.18.spam+fbi.gov at earthlink.net (Mumia W.) Date: Wed, 24 May 2006 17:00:47 GMT Subject: John Bokma harassment In-Reply-To: <447479A1.8050809@hotORgooMAIL.invalid> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <447479A1.8050809@hotORgooMAIL.invalid> Message-ID: <3j0dg.27$u4.11@newsread1.news.pas.earthlink.net> Mitch wrote: > John Bokma wrote: > [...] >> You're mistaken. All you need to do is report it. After some time Xah >> will either walk in line with the rest of the world, or has found >> somewhere else to yell. As long as it's not my back garden and not >> around 4AM, I am ok with it. >> > > Walk in line with the rest of the world? Pah. > > This is no-ones back garden. But it is a place where John Bokma can engage in a little power play. Notice how John Bokma pretends to own these newsgroups. In every analogy, Bokma uses "ownership" concepts to support his harassment of Xah. John Bokma conceptualizes these newsgroups as something that he dominates. Without other people to recognize his power, it's empty, so he bashes and then trashes Xah, and in doing so, proves that he is dominant here. Don't let it happen. Write the abuse address at Dreamhost, and try to help Xah out. From jdsalt_AT_gotadsl.co.uk Wed May 17 14:27:09 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Wed, 17 May 2006 13:27:09 -0500 Subject: [silly] Does the python mascot have a name ? References: Message-ID: Andy Sy wrote in news:mailman.5791.1147860411.27775.python-list at python.org: > http://mail.python.org/pipermail/python-list/2003-September/185612.html "Odi" must be the Dutch for "Monty". All the best, John. From jim.lewis at miclog.com Sat May 27 07:14:51 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 27 May 2006 04:14:51 -0700 Subject: Pyrex speed References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> <4dqq38F1bi6btU1@uni-berlin.de> Message-ID: <1148728491.640293.298470@38g2000cwa.googlegroups.com> I'm not planning to write C functions. My understanding is that by using cdefs in the python code one can gain substantial speed. I'm trying to find a description of how to modify python code in more detail so it runs fast under pyrex. From grante at visi.com Fri May 12 10:30:12 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 12 May 2006 14:30:12 -0000 Subject: Threads References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <1147417744.770080.11490@q12g2000cwa.googlegroups.com> Message-ID: <12696vkcb08a0f5@corp.supernews.com> On 2006-05-12, Sybren Stuvel wrote: > placid enlightened us with: >>> Did you read the documentation for Queue methods? >> >> there is no need to be patronizing about this dude, im just learning >> Python in my spare time, as im a Intern Software Engineer > > There is nothing patronizing about the question, it's merely > an enquiry to a possible fact. If you're going to be a techie, > you should learn stuff like that. It's also valuable information to the maintainers of the documentation. If he _did_ read the documentation and still didn't know that Queue.get() could block, then one might ask how the documentation could be improved. -- Grant Edwards grante Yow! Is this ANYWHERE, at USA? visi.com From hancock at anansispaceworks.com Thu May 4 02:08:34 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 04 May 2006 06:08:34 +0000 Subject: basic python programing In-Reply-To: <1146419329.959290.69870@j73g2000cwa.googlegroups.com> References: <1146376141.767029.17850@j73g2000cwa.googlegroups.com> <1146383327.664894.279250@v46g2000cwv.googlegroups.com> <1146419329.959290.69870@j73g2000cwa.googlegroups.com> Message-ID: <44599A62.9000703@anansispaceworks.com> gregarican wrote: >Ravi Teja wrote: > >>How To Ask Questions The Smart Way >>http://www.catb.org/~esr/faqs/smart-questions.html >> >> > >Actual the parent post on the thread wasn't asking a question. They >were making a somewhat puzzling dangling statement. > >"here we discuss the most basic concepts about python" > >Where is _here__? The comp.lang.python newsgroup? In the poster's head? >These are but a sampling of my own stoopid questions. > > The original poster is using the wrong etiquette. This is fairly common practice in an explicit flat-thread environment like PHP BB. I'm not sure it's particularly smart there either, but that is likely where he learned it. Either that or it's yet another email virus. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From viridia at gmail.com Sat May 20 01:27:25 2006 From: viridia at gmail.com (Talin) Date: 19 May 2006 22:27:25 -0700 Subject: PEP 3102 for review and comment Message-ID: <1148102845.438543.16380@38g2000cwa.googlegroups.com> (Note: PEPs in the 3xxx number range are intended for Python 3000, however this particular PEP may be backported if there is support for it.) PEP: 3102 Title: Keyword-Only Arguments Version: $Revision: 46053 $ Last-Modified: $Date: 2006-05-19 22:23:44 -0700 (Fri, 19 May 2006) $ Author: Talin Status: Draft Type: Standards Content-Type: text/plain Created: 22-Apr-2006 Python-Version: 3.0 Post-History: 28-Apr-2006, May-19-2006 Abstract This PEP proposes a change to the way that function arguments are assigned to named parameter slots. In particular, it enables the declaration of "keyword-only" arguments: arguments that can only be supplied by keyword and which will never be automatically filled in by a positional argument. Rationale The current Python function-calling paradigm allows arguments to be specified either by position or by keyword. An argument can be filled in either explicitly by name, or implicitly by position. There are often cases where it is desirable for a function to take a variable number of arguments. The Python language supports this using the 'varargs' syntax ('*name'), which specifies that any 'left over' arguments be passed into the varargs parameter as a tuple. One limitation on this is that currently, all of the regular argument slots must be filled before the vararg slot can be. This is not always desirable. One can easily envision a function which takes a variable number of arguments, but also takes one or more 'options' in the form of keyword arguments. Currently, the only way to do this is to define both a varargs argument, and a 'keywords' argument (**kwargs), and then manually extract the desired keywords from the dictionary. Specification Syntactically, the proposed changes are fairly simple. The first change is to allow regular arguments to appear after a varargs argument: def sortwords(*wordlist, case_sensitive=False): ... This function accepts any number of positional arguments, and it also accepts a keyword option called 'case_sensitive'. This option will never be filled in by a positional argument, but must be explicitly specified by name. Keyword-only arguments are not required to have a default value. Since Python requires that all arguments be bound to a value, and since the only way to bind a value to a keyword-only argument is via keyword, such arguments are therefore 'required keyword' arguments. Such arguments must be supplied by the caller, and they must be supplied via keyword. The second syntactical change is to allow the argument name to be omitted for a varargs argument. The meaning of this is to allow for keyword-only arguments for functions that would not otherwise take a varargs argument: def compare(a, b, *, key=None): ... The reasoning behind this change is as follows. Imagine for a moment a function which takes several positional arguments, as well as a keyword argument: def compare(a, b, key=None): ... Now, suppose you wanted to have 'key' be a keyword-only argument. Under the above syntax, you could accomplish this by adding a varargs argument immediately before the keyword argument: def compare(a, b, *ignore, key=None): ... Unfortunately, the 'ignore' argument will also suck up any erroneous positional arguments that may have been supplied by the caller. Given that we'd prefer any unwanted arguments to raise an error, we could do this: def compare(a, b, *ignore, key=None): if ignore: # If ignore is not empty raise TypeError As a convenient shortcut, we can simply omit the 'ignore' name, meaning 'don't allow any positional arguments beyond this point'. (Note: After much discussion of alternative syntax proposals, the BDFL has pronounced in favor of this 'single star' syntax for indicating the end of positional parameters.) Function Calling Behavior The previous section describes the difference between the old behavior and the new. However, it is also useful to have a description of the new behavior that stands by itself, without reference to the previous model. So this next section will attempt to provide such a description. When a function is called, the input arguments are assigned to formal parameters as follows: - For each formal parameter, there is a slot which will be used to contain the value of the argument assigned to that parameter. - Slots which have had values assigned to them are marked as 'filled'. Slots which have no value assigned to them yet are considered 'empty'. - Initially, all slots are marked as empty. - Positional arguments are assigned first, followed by keyword arguments. - For each positional argument: o Attempt to bind the argument to the first unfilled parameter slot. If the slot is not a vararg slot, then mark the slot as 'filled'. o If the next unfilled slot is a vararg slot, and it does not have a name, then it is an error. o Otherwise, if the next unfilled slot is a vararg slot then all remaining non-keyword arguments are placed into the vararg slot. - For each keyword argument: o If there is a parameter with the same name as the keyword, then the argument value is assigned to that parameter slot. However, if the parameter slot is already filled, then that is an error. o Otherwise, if there is a 'keyword dictionary' argument, the argument is added to the dictionary using the keyword name as the dictionary key, unless there is already an entry with that key, in which case it is an error. o Otherwise, if there is no keyword dictionary, and no matching named parameter, then it is an error. - Finally: o If the vararg slot is not yet filled, assign an empty tuple as its value. o For each remaining empty slot: if there is a default value for that slot, then fill the slot with the default value. If there is no default value, then it is an error. In accordance with the current Python implementation, any errors encountered will be signaled by raising TypeError. (If you want something different, that's a subject for a different PEP.) Backwards Compatibility The function calling behavior specified in this PEP is a superset of the existing behavior - that is, it is expected that any existing programs will continue to work. Copyright This document has been placed in the public domain. Local Variables: mode: indented-text indent-tabs-mode: nil sentence-end-double-space: t fill-column: 70 coding: utf-8 End: From lrasinen at iki.fi Mon May 15 14:39:13 2006 From: lrasinen at iki.fi (Lasse Rasinen) Date: 15 May 2006 21:39:13 +0300 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <44681F95.9040400@gmail.com> Message-ID: [I trimmed some of the newsgroups away; this mostly concerns Python and Lisp] Ken Tilton writes: > Lasse Rasinen wrote: > > Ken Tilton writes: > > > >>>if any concepts have survived to the Python version. Since Python's object > >>>model is sufficiently different, the system is based on rules being > >>>defined per-class... > >> > >>That will be a total disaster for PyCells, if true. But I do not think it > >>is. You just need a constructor that takes some slot initializers, and > >>initialize the slots to one of: a normal value; an InputCell itself > >>initialized with a starting value, if only nil; or a RuledCell itself > >>initialized with a lambda. > > Hmm, just tried it: > > > > [snip example] > > > > So it does work out-of-the-box ;-) > > So why exactly did you say that the differences in the object model made > it impossible? I was really stunned by that claim. And you sounded so > confident. What went wrong there? It was trivial, right? How did you miss > that? Simple: I didn't think to try that before you asked. I did not say the differences in the object model made it impossible, I said the system is based on rules defined per-class. My goal was to explore the how one would go about defining data flow in Python, which is why I concentrated on class-level definitions first. The situation is similar to functions in classes. Normally you'd define them like this: class X: def function(self, ...): ... However, you can just as well set them, even on per instance basis: x = X() x.another_function = lambda self, x: return x+2 I also think(*) that while one would have the option to define per-instance rules, in a Python implementation one would structure the code so that common rules would be class-related, and the per-instance rules would be used less frequently, used only when you absolutely need them. (*) Unfounded Gut Feeling(TM); if your project is successful, we can revisit this prediction in September ;-) > >>PyCells looks like it will be a project for SoC2006, so you may as well > >>relax. > > You really want to start a SoC project on something that takes about two > > weeks ... > > You sound so confident. :) Indeed. Having reread the post I do think the tone was possibly a tad arrogant. However: > A new test suite, documentation (a first, there is none now), a full port > of Cells in all their ten years of sophisticated evolution and variety > (no, not your stupid pet trick), and as a demo project an entire > cells-driven GUI, probably a port of my new Celtk (+ Cells Tk) work, all > in a language without macros, without special variables, with a more > modest OO system, and limited first class functions... oh, I think we'll > keep him busy. :) I did not know all this. The list above does sound like a full summer of work ;) I assumed that PyCells referred to the core dependency tracking module which (even now) does not sound like a such huge task, especially when one has the reference implementation ;-) As I said above, I was mostly concerned with exploring how the data flow system would work, so I haven't implemented the various different types of cells in Cells. So there would obviously be a bit more work if one is implementing all that, but still, two caffeine and youth powered student weeks can achieve a lot ;-) What "your stupid pet trick" would be referring to? The use of the __getattribute__ method (which is quite close to SLOT-VALUE-USING-CLASS), or the use of @decorator syntax to reduce typing and redundancy? > Now since you are such a genius, maybe you can help with something. Trust > me on this: this is one place where macros would be able to hide a ton of > implementation wiring it does no one any good to look at, and actually > turns into a maintenance nightmare whenever Cells might get revised. I'd probably use decorators a lot, since they let you play around with function objects. If they are suitably chosen and designed, the interface should stay pretty stable even while the wiring is changed. (Decorator background: The regular python Python function definition would be as follows: def foo(x,y,z): ... would be in CL (if CL were Lisp-1 with symbol-function-or-value) more or less: (setf (symbol-function-or-value 'foo) (lambda (x y z) ...) The decorated syntax would be: @magic_decorator def foo(x,y,z): ... and the translation: (setf (symbol-function-or-value 'foo) (funcall magic-decorator #'(lambda (x y z) ...))) ) -- Lasse Rasinen lrasinen at iki.fi From rpdooling at gmail.com Mon May 22 11:36:21 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 22 May 2006 08:36:21 -0700 Subject: Testing for file type In-Reply-To: <1273iims70cu3e6@corp.supernews.com> References: <1273iims70cu3e6@corp.supernews.com> Message-ID: <1148312181.618764.27240@i39g2000cwa.googlegroups.com> In the Python Cookbook, 2ed, page 25, there's a script by Andrew Dalke that uses the same heureistic criteria that Perl does and analyzes a string and deems it binary if it contains any nulls or if more than 30% of its characters have the high bit set or are strange control codes. There's a follow on script that uses the same test on files. rick From Serge.Orlov at gmail.com Fri May 5 23:35:34 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 5 May 2006 20:35:34 -0700 Subject: Elegent solution to replacing ' and " ? References: <1146872815.237738.57590@j73g2000cwa.googlegroups.com> Message-ID: <1146886534.287919.243480@g10g2000cwb.googlegroups.com> fyleow wrote: > I'm trying to replace the ' and " characters in the strings I get from > feedparser so I can enter it in the database without getting errors. > Here's what I have right now. > > self.title = entry.title.encode('utf-8') > self.title = self.title.replace('\"', '\\\"') > self.title = self.title.replace('\'', '\\\'') > > This works just great but is there a more elegent way to do this? It > looks like maybe I could use the translate method but I'm not sure. You should use execute method to construct sql statements. This is wrong: self.title = entry.title.encode('utf-8') self.title = self.title.replace('\"', '\\\"') self.title = self.title.replace('\'', '\\\'') cursor.execute('select foo from bar where baz="%s" ' % self.title) This is right: self.title = entry.title cursor.execute("select foo from bar where baz=%s", (self.title,)) The formatting style differs between db modules, take a look at paramstyle description in PEP 249: http://www.python.org/dev/peps/pep-0249/ From digitalorganics at gmail.com Tue May 23 14:24:44 2006 From: digitalorganics at gmail.com (Cloudthunder) Date: Tue, 23 May 2006 14:24:44 -0400 Subject: Method Delegation To Subinstances In-Reply-To: References: Message-ID: In the example: class Boo: def __init__(self, parent): self.parent = parent print self.parent.testme def run(): print "Yahooooo!" class Foo: testme = "I love you!" def __init__(self): test = Boo(self) A = Foo() How can I set up method delegation so that I can do the following: A.run() and have this call refer to the run() method within the boo instance? Also, what if I have tons of functions like run() within the boo instance and I want all them to be directly accessible as if they were part of their parent (the Foo instance)? -------------- next part -------------- An HTML attachment was scrubbed... URL: From robert.kern at gmail.com Wed May 10 18:12:17 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 10 May 2006 17:12:17 -0500 Subject: installing numpy In-Reply-To: <87y7x9zgdm.fsf@localhost.localdomain> References: <877j4v5ukc.fsf@localhost.localdomain> <6Y%7g.11622$EC.10694@tornado.rdc-kc.rr.com> <8764kfkkhb.fsf@localhost.localdomain> <87vesegvtj.fsf@localhost.localdomain> <87y7x9zgdm.fsf@localhost.localdomain> Message-ID: Gary Wessle wrote: > thanks > I followed your suggestions, it built the package ok, while it was > building, I noticed lots of lines going by the screen in groups of > different colors, white, yellow, red. > the red got my attention: > > **************** > Could not locate executable gfortran > Could not locate executable f95 > **************** Don't worry about those. numpy does not require a Fortran compiler to build. Some projects using numpy.distutils, like scipy, will. The information flow in distutils is not ideal, so the checks are done regardless of whether you need Fortran or not. > is there a way to find out if the built is fine and it is using the > high performance libraries? You can use the ldd(1) program on the extension modules (they're the ones with the .so extension) to see what libraries they link against. To run all of the unit tests: [~]$ python Python 2.4.1 (#2, Mar 31 2005, 00:05:10) [GCC 3.3 20030304 (Apple Computer, Inc. build 1666)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import numpy >>> numpy.test() Found 5 tests for numpy.distutils.misc_util Found 3 tests for numpy.lib.getlimits Found 30 tests for numpy.core.numerictypes Found 13 tests for numpy.core.umath Found 8 tests for numpy.lib.arraysetops Found 42 tests for numpy.lib.type_check Found 93 tests for numpy.core.multiarray Found 3 tests for numpy.dft.helper Found 36 tests for numpy.core.ma Found 9 tests for numpy.lib.twodim_base Found 2 tests for numpy.core.oldnumeric Found 8 tests for numpy.core.defmatrix Found 1 tests for numpy.lib.ufunclike Found 34 tests for numpy.lib.function_base Found 1 tests for numpy.lib.polynomial Found 6 tests for numpy.core.records Found 19 tests for numpy.core.numeric Found 4 tests for numpy.lib.index_tricks Found 46 tests for numpy.lib.shape_base Found 0 tests for __main__ ........................................................................................................................................................................................................................................................................................................................................................................... ---------------------------------------------------------------------- Ran 363 tests in 2.812s OK >>> -- 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 email at christoph-haas.de Tue May 9 15:24:25 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 9 May 2006 21:24:25 +0200 Subject: How to recast integer to a string In-Reply-To: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> References: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> Message-ID: <20060509192425.GD21047@workaround.org> On Tue, May 09, 2006 at 12:17:34PM -0700, James wrote: > How to recast an integer to a string? > > something like > n = 5 > str = str + char(n) str(n) Kindly Christoph From pydecker at gmail.com Wed May 17 10:06:30 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 17 May 2006 10:06:30 -0400 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147873879.818361.10040@i40g2000cwc.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147873879.818361.10040@i40g2000cwc.googlegroups.com> Message-ID: On 17 May 2006 06:51:19 -0700, Bill Pursell wrote: > In my experience, the people who complain about the use > of tabs for indentation are the people who don't know > how to use their editor, and those people tend to use > emacs. In my experience, whenever there is a 'religious' issue like this, one side tends to be quick to pronounce the other as 'evil', and insist that everyone do things their way, while the other tends to feel comfortable with people having their own preferences. If I ever find myself on the side of the former, I always wonder if I'm missing something obvious. -- # p.d. From greg.kujawa at gmail.com Wed May 24 14:12:49 2006 From: greg.kujawa at gmail.com (gregarican) Date: 24 May 2006 11:12:49 -0700 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474604.279491.71090@j55g2000cwa.googlegroups.com> Message-ID: <1148494368.935599.80730@j55g2000cwa.googlegroups.com> I third this opinion. This book gave me a lot of insight and helped me get comfortable using Python. I also recall looking at a document Guido published on how to get started with Python as well as reading the reference docs that come bundled with the language install. Of course I came from a background of already using Ruby so the departure wasn't altogether difficult. The languages are different but to me they seem like cousins :-) Typically when I try to teach myself a new language, such as Python, Ruby, Smalltalk, Scheme, Haskell, etc. I check out my online catalog through my local library system. Usually I can find a couple of books to peruse. If I don't like them I can just drop them back off. Then I check out eBay for used books. This route was especially helpful for teaching myself Smalltalk, since a lot of the books were 10-20 years old so I picked them up for anywhere between $1.00 to $5.00. I digress. "Learning Python" by Mark Lutz is a thorough and complete introduction to what you need to know to get started. Even if you are coming into Python with no prior programming language exposure. John Salerno wrote: > vbgunz wrote: > > Learning Python by Mark Lutz will be the most perfect book to get you > > started! Perhaps there are others aimed at the non-programmer but after > > getting through that book (2 times) I finally left it with wings... It > > is a great book for the n00b in my humble opinion. After that, you'll > > pretty much start flying higher on your own as long as you always keep > > the python docs handy along with the addresses to comp.lang.python and > > it's IRC channel #python on irc.freenode.net... > > > > Good luck, welcome to Python! > > > > I second this opinion completely. Use this book to start with! It is a > wonderful intro to the language and will give you a solid foundation. > > As for waiting for a 3rd edition, don't do it! If you're like me, you'll > want the latest there is, so I was tempted to start with something newer > too (since this book covers up to 2.2), but honestly it covers > everything you need to know. There are maybe two or three new additions > that you can read about elsewhere, but Learning Python is THE book to > start with, IMO. > > Get it now! :) From fredrik at pythonware.com Mon May 1 15:56:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 1 May 2006 21:56:17 +0200 Subject: How do I take a directory name from a given dir? References: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> Message-ID: "Merrigan" wrote: > I am trying to write a script to backup all my company's server configs > weekly. The script will run in a cronjob, on whatever I set it. > > The issue I am currently having isto "extract" the directory name from > a given directory string. For example: from the string > "/home/testuser/projects/" I need to extract the "projects" part. The > problem is that the directory names that needs to be used will never be > the same lenght, so as far as my (very limited) knowledge stretches, > slicing and indicing is out of the question. os.path.split(path) splits a path into directory name and "base name" parts. >>> import os >>> os.path.split("/usr/bin/python") ('/usr/bin', 'python') if you have a trailing slash, split will return an empty string for the base- name part >>> os.path.split("/home/testuser/projects/") ('/home/testuser/projects', '') but you can work around that by doing an extra split: >>> path = "/home/testuser/projects/" >>> path, name = os.path.split(path) >>> if not name: ... path, name = os.path.split(path) ... >>> path '/home/testuser' >>> name 'projects' hope this helps! From ronnyma at math.uio.no Thu May 18 15:42:48 2006 From: ronnyma at math.uio.no (Ronny Mandal) Date: Thu, 18 May 2006 21:42:48 +0200 Subject: Sorting of list containing tuples References: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> <7x1wurcecw.fsf@ruckus.brouhaha.com> Message-ID: Uhm, thanks. (I've used lambda-sort earlier, but quite forgot......) :) On 18 May 2006 12:38:55 -0700, Paul Rubin wrote: >Ronny Mandal writes: >> And now I want to sort l reverse by the second element in the tuple, >> i.e the result should ideally be: >> >> l = [(6,5),(2,3),(3,2)] > >sorted(l, key = lambda a: -a[1]) From roger.miller at nova-sol.com Thu May 18 19:08:31 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 18 May 2006 16:08:31 -0700 Subject: Python trig precision problem References: <1147989418.253313.3650@38g2000cwa.googlegroups.com> Message-ID: <1147993711.347422.210800@j33g2000cwa.googlegroups.com> If I were you I would see if I could get the Perl script referred to on the ERIN web page. You might find that the discrepancy is something as simple as a slightly different value for the Earth's radius. And by the way, math.radians() might be a bit clearer than the pi/180 business. From bugs at almad.net Thu May 11 05:21:08 2006 From: bugs at almad.net (Almad) Date: 11 May 2006 02:21:08 -0700 Subject: PIL thumbnails unreasonably large In-Reply-To: References: <1147272829.719796.150680@y43g2000cwc.googlegroups.com> Message-ID: <1147339268.886432.145930@i39g2000cwa.googlegroups.com> Thank You! That helped. Somehow obvious when you pointed out, but...*phew*. Almad From Kyler at news.Lairds.org Thu May 11 23:45:37 2006 From: Kyler at news.Lairds.org (Kyler Laird) Date: Thu, 11 May 2006 23:45:37 -0400 Subject: Simple DAV server? References: <1fg0i3-7pc.ln1@snout.lairds.com> Message-ID: <10ddj3-qhb.ln1@snout.lairds.com> Ivan Voras writes: >Most of the problems are probably because I didn't mean it to be a >fully-compliant WebDAV server, but to serve my need at the time :) I am *so* close to having a WebDAV solution. Unfortunately when I finally moved to using HTTPS, it all broke in MS Windows. (Konqueror handles it beautifully.) If I make a Web Folder with HTTP, Windows displays it (as "\\hostname\") in Windows Explorer. If I make it with HTTPS, it throws me into Internet Explorer (where WebDAV isn't used - I can't even launch files). WTF?! It looks like other people are using WebDAV over HTTPS. http://www.mydocsonline.com/info_webfolders.html Why is Windows kicking me into IE for HTTPS??? (I'm tired and frustrated. I hate being forced to deal with proprietary software.) --kyler From NA at NA.com Tue May 9 23:16:47 2006 From: NA at NA.com (N/A) Date: Wed, 10 May 2006 11:16:47 +0800 Subject: Matplotlib in Python vs. Matlab, which one has much better graphical pressentation? Message-ID: Hi all, Can I have your opinions on Matlab vs. Matplotlib in Python in terms of 2D and 3D graphical presentation please. Matplotlib in Python vs. Matlab, which one has much better graphical pressentation? From andrew at acooke.org Mon May 22 18:52:56 2006 From: andrew at acooke.org (andrew at acooke.org) Date: 22 May 2006 15:52:56 -0700 Subject: system(...) and unicode References: <1148331460.400964.158420@u72g2000cwu.googlegroups.com> <1148335865.001493.13320@38g2000cwa.googlegroups.com> <44723D8B.8030304@v.loewis.de> Message-ID: <1148338376.930401.316580@i39g2000cwa.googlegroups.com> The impression I got from the link I gave was that exec et al already had the appropriate unicode support; system seems to be the exception. Anyway, thanks for the info - that directory name is coming from a DOM call, and I'm pretty sure it's returning Unicode, so that makes sense. Andrew From 63q2o4i02 at sneakemail.com Tue May 16 02:16:21 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 15 May 2006 23:16:21 -0700 Subject: Why does stack.inspect take so long? In-Reply-To: References: <1147745178.664795.326020@v46g2000cwv.googlegroups.com> Message-ID: <1147760181.369499.317730@j55g2000cwa.googlegroups.com> Tim Peters wrote: > [63q2o4i02 at sneakemail.com] > > Hi, I've written a top-down recursive decent parser for SPICE circuit > > descriptions. For debugging purposes, I wanted each production ... > > Any clues? > > It should go much faster to use a function that doesn't crawl the > entire call stack. For example, > > >>> import sys, inspect > >>> def name_of_caller(): > ... return inspect.getframeinfo(sys._getframe(1), context=0)[2] > >>> def f(): > ... print "my name is", name_of_caller() > >>> f() > my name is f > > name_of_caller() takes time independent of the call-stack depth. > > The "context=0" is to avoid wasting time sucking up and packaging > source-code lines you don't want anyway. Cool, thanks. I'll try that. I didn't realize there were other ways of getting it. ms From robert.kern at gmail.com Tue May 9 15:27:25 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 May 2006 14:27:25 -0500 Subject: installing numpy In-Reply-To: <20060509122303.GC20063@torf.workaround.org> References: <877j4v5ukc.fsf@localhost.localdomain> <873bfj5sp5.fsf@localhost.localdomain> <20060509120715.GB20063@torf.workaround.org> <20060509122303.GC20063@torf.workaround.org> Message-ID: Christoph Haas wrote: > Yes, you are right. "python-numeric" refers to NumPy but contains the > "Numeric" version of it (24-2). It's pretty misleading. It's an unfortunate consequence of letting software packages acquire nicknames. C.f.: http://www.scipy.net/pipermail/scipy-user/2006-May/007847.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From deets at nospam.web.de Tue May 23 07:36:10 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 23 May 2006 13:36:10 +0200 Subject: Valid SQL? References: <1148383118.187847.197700@j33g2000cwa.googlegroups.com> Message-ID: <4dgaelF1a6ljeU1@uni-berlin.de> Harlin Seritt wrote: > I have this string that I am sending via a Cursor.execute() using > MySQLdb: > > insert into table Ping82_eb13__elearn__ihost__com (`dateTime`, > `values`) values( > "Fri May 12 11:39:02 2006", "1") > > Does anyone see anything wrong with this SQL syntax? How about a stacktrace? http://www.catb.org/~esr/faqs/smart-questions.html And you should use the parametrized version of execute, because then the DB-API will take care of escaping the strings properly for you. Which is the problem here, btw: you are using "" for strings, where SQl requires ''. Diez From yairchu at gmail.com Fri May 19 07:32:53 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 19 May 2006 04:32:53 -0700 Subject: Question about exausted iterators In-Reply-To: <446d8971$0$6053$626a54ce@news.free.fr> References: <446b48e2$0$5293$626a54ce@news.free.fr> <446c2dea$0$5306$626a54ce@news.free.fr> <446d8971$0$6053$626a54ce@news.free.fr> Message-ID: <1148038373.801520.200580@i39g2000cwa.googlegroups.com> Consider this example: >>> X = range(5) >>> Y = iter(X) >>> Z = iter(Y) As you can see, X is a container, and Y is an iterator. They are simliar in that "iter" works on them both. Cristoph claims that this causes confusion. Why? Because "iter" doesn't have the same meaning for both of them. For X it always returns an iterator that yields the same set of values. For Y it returns an iterator yielding different values each time. >>> Z = iter(Y) >>> Z.next() 0 >>> Z = iter(Y) >>> Z.next() 1 Most of the uses of iterators iterate all values until exaustion. Given that, the first call to "iter" will mean the same for an iterator and a container, but the second one won't. Allow me to compare it to division in python 2.4 >>> 4./2, 4/2 2.0, 2 >>> 5./2, 5/2 2.5, 2 Division sometimes works the same for integers and reals, and sometimes doesn't. This caused consfusion and bugs, and that's why future Pythons will change that. But changing "iter" to have the same meaning for containers and iterables is impossible. You cannot, conceptually, reiterate an iterator. So what Cristoph is suggesting - is to add an exception for the cases in which iterators and collections behave differently. Somewhat similar to this: >>> 4/2 2 >>> 5/2 Traceback (most recent call last): File "", line 1, in ? IntegerDivisionError: 5 does not divide by 2 From atul.nene at gmail.com Tue May 23 14:16:42 2006 From: atul.nene at gmail.com (Atul) Date: 23 May 2006 11:16:42 -0700 Subject: Announcing WERD (1.0), the Phonetic Transliterator to Indic scripts Message-ID: WERD is a phonetic transliterator that helps users write english text but read the same in the chosen Devanagari (Indic) font. WERD is expected to make it easy for Indians wanting to communicate over chat or email in their native language. Checkout http://werd.sourceforge.net/ WERD is written in Python and Tkinter, is open source software released under GPL, and is hosted by SourceForge (www.sourceforge.net) Thanks and Regards, -- Atul From incall at msn.com Thu May 25 20:24:21 2006 From: incall at msn.com (Pablo) Date: 25 May 2006 17:24:21 -0700 Subject: Use of lambda functions in OOP, any alternative? References: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> <4474bfe9$1@nntp0.pdx.net> Message-ID: <1148603061.733437.97730@j55g2000cwa.googlegroups.com> Oh! Thanx! Great! this is what i was looking for! :) Scott David Daniels ha escrito: > Pablo wrote: > > > Second solution: This is what i want, but... > > > > class Base(object): > > def __init__(self, attr): > > self._attr = attr > > def getattr(self): > > return self._attr > > attr = property(fget=lambda self: self.getattr()) > > > > class Derived(Base): > > def getattr(self): > > return 2*self._attr > > > > Question: Isn't there an *alternative* way to do it without the lambda > > function? > > > > Thanks in advance! > > Simplest: > > class Base(object): > def __init__(self, attr): > self._attr = attr > def getattr(self): > return self._attr > @property # single-arg property is a read-only thing. > def attr(self): > return self.getattr() > > ### Little longer; maybe more explicit (tastes vary): > > class Base(object): > def __init__(self, attr): > self._attr = attr > def getattr(self): > return self._attr > def attr(self): > return self.getattr() > attr = property(fget=attr) > > > --Scott David Daniels > scott.daniels at acm.org From alisonken1 at gmail.com Tue May 2 18:06:20 2006 From: alisonken1 at gmail.com (alisonken1) Date: 2 May 2006 15:06:20 -0700 Subject: ConfigParser and multiple option names In-Reply-To: References: Message-ID: <1146607580.926231.12090@u72g2000cwu.googlegroups.com> Benji York wrote: > > I generally do this: > > dirs = > /home/florian > /home/john > /home/whoever > > ...and then use str.split() in my program. > -- > Benji York The only problem with this would be if you plan on updating the config file later in the program - I don't think ConfigParser would write the new config file with these options setup this way. From peace.is.our.profession at gmx.de Mon May 8 09:24:49 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Mon, 08 May 2006 15:24:49 +0200 Subject: Python's regular expression? In-Reply-To: References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> Message-ID: Hi Duncan > There is no need to compile the regular expression in advance in Python > either: > ... > The only advantage to compiling in advance is a small speed up, and most of > the time that won't be significant. I read 'some' introductions into Python Regexes and got confused in the first place when to use what and why. After some minutes in this NG I start to get the picture. So I narrowed the above regex-question down to a nice equivalence between Perl and Python: Python: import re t = 'blue socks and red shoes' if re.match('blue|white|red', t): print t t = 'blue socks and red shoes' if re.search('blue|white|red', t): print t Perl: use Acme::Pythonic; $t = 'blue socks and red shoes' if $t =~ /blue|white|red/: print $t And Python Regexes eventually lost (for me) some of their (what I believed) 'clunky appearance' ;-) Thanks Mirco From phddas at yahoo.com Sun May 21 20:56:16 2006 From: phddas at yahoo.com (Gary Wessle) Date: 22 May 2006 10:56:16 +1000 Subject: Tk.iconname still there? Message-ID: <87odxqubbj.fsf@localhost.localdomain> Hi I am going through a tutorial on Tkinter http://doctormickey.com/python/pythontutorial_201.html, it referees to Tk.iconname() but I could not locate one after googleing and browsed and searched the Tkinter On-line reference material in the Tkinter reference: a GUI for Python, 84 pp. pdf from here http://infohost.nmt.edu/tcc/help/pubs/lang.html can any one fill us in. thanks From usenet at local.machine Sat May 27 10:54:49 2006 From: usenet at local.machine (=?ISO-8859-2?Q?Dra=BEen_Gemi=E6?=) Date: Sat, 27 May 2006 16:54:49 +0200 Subject: John Bokma harassment In-Reply-To: <87slmwbhx5.fsf@wolfbone.ath.cx> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <447479A1.8050809@hotORgooMAIL.invalid> <3j0dg.27$u4.11@newsread1.news.pas.earthlink.net> <87slmwbhx5.fsf@wolfbone.ath.cx> Message-ID: I can't see the way how Xah Lee could be on topic in comp.lang.java.programmer. He is not a programmer, and does not write about neither programming nor Java. He should stick to philosophy and advocacy groups. DG From tim.golden at viacom-outdoor.co.uk Fri May 26 12:18:41 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 26 May 2006 17:18:41 +0100 Subject: hide python window, cont'd Message-ID: [John Salerno] | | Bell, Kevin wrote: | > Bell, Kevin wrote: | >> Great! And now that it's hiding w/ .pyw, how would I kill it if I | > want? | >> Just log off, or is there a better way? | >> | >> Kevin | >> | >> | > | >>> JOE WROTE: | >>> Close it in the Task Manager? | > | > | > I don't see it in the task manager. | > | > | | You might have to look at running processes instead of | applications. See | if any of the names looks like your program. Just in case you want something marginally more sophisticated, you might take at look at this example: http://timgolden.me.uk/python/win32_how_do_i/catch_system_wide_hotkeys.h tml Depending on just what your own program is doing, it should be more or less easy to incorporate the concepts so that you program runs and checks for a hotkey press at which point it shuts itself down (or shows itself, or reformats your hard drive, or whatever). 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 dadapapa at googlemail.com Tue May 9 09:26:23 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 9 May 2006 06:26:23 -0700 Subject: How can I do this with python ? In-Reply-To: References: <1147078986.624152.14770@u72g2000cwu.googlegroups.com> Message-ID: <1147181183.375780.214520@u72g2000cwu.googlegroups.com> Better go for the subprocess module. It is supposed to replace os.popen and has a much nicer interface. - harold - From grflanagan at yahoo.co.uk Wed May 10 04:33:46 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 10 May 2006 01:33:46 -0700 Subject: Dictionaries -- ahh the fun.. (newbie help) In-Reply-To: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> References: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> Message-ID: <1147250026.664021.26040@j73g2000cwa.googlegroups.com> rh0dium wrote: > Hi all, > > Can someone help me out. I am trying to determing for each run whether > or not the test should pass or fail but I can't seem to access the > results .. > > Alternatively can someone suggest a better structure ( and a lesson as > to the reasoning ) that would be great too!! > > cells={} > > cells["NOR3X1"]= { > 'run' : [ 'lvs', 'drc' ], > 'results' : [{ 'lvs' : 'pass' }, > { 'drc' : 'fail' }] > } > > cells["OR3X1"] = { > 'run' : [ 'lvs' ], > 'results' : [{ 'lvs' : 'pass' }] > } > > cells["AND3X1"] = { > 'run' : [ 'drc' ], > 'results' : [{ 'drc' : 'fail' }] > } > > other suggestions: cells={ "NOR3X1": { 'pass' : ['lvs'], 'fail' : ['drc'] }, "OR3X1" : { 'pass' : ['lvs'], 'fail' : [] }, "AND3X1" : { 'pass' : [], 'fail' : ['drc'] } } cells2={ "NOR3X1": [ ('lvs',1), ('drc', 0) ], "OR3X1" : [ ('lvs', 1) ], "AND3X1" : [ ('drc',0) ] } class cell(object): def __init__(self, id, passes=None, fails=None): self.id = id self.passes = passes or [] self.fails = fails or [] Gerard From __peter__ at web.de Sat May 13 12:04:59 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 May 2006 18:04:59 +0200 Subject: Package that imports with name of dependent package References: Message-ID: David Pratt wrote: > Hi. I have code that currently depends on a particular package of a > framework. I have decided I want to create my own package because I have > made many changes and it is getting too difficult to maintain each time > I retrieve an updated version of the framework from svn. > > The problem is, that there are all sorts of imports to the dependent > package throughout my code and I just want to replace this module with > something that will provide a reference to my own package without > changing the original imports. So it just needs to point to the new > package so that the original imports in my code will continue to work. > > For example, here is a package structure. > > dependentpackage > | > +---- __init__.py > +---- somemodule.py > +---- somefolder > | > +---- __init__.py > +---- somesubmodule.py > +---- someotherfolder > etc .... > > I simply want the dependentpackage to point to the new package leaving > no more than an init file or whatever would have to be minimally > required to make this work > > dependentpackage > | > +---- __init__.py > > mypackage > | > +---- __init__.py > +---- somemodule.py > +---- somefolder > | > +---- __init__.py > +---- somesubmodule.py > +---- someotherfolder > etc .... > > I my code I still need to have this work: > > from dependentpackage.somemodule import something > > - but I want the package to be getting the code from the new module. > > I'd appreciate hearing of what I can do in an __init__ file or what > other strategy could make this work. Many thanks. I think fixing the imports is the better long-term approach. But putting from pkgutil import extend_path import mypackage __path__ = extend_path(mypackage.__path__, __name__) into dependentpackage/__init__.py might work. Peter From sybrenUSE at YOURthirdtower.com.imagination Mon May 8 03:26:19 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 8 May 2006 09:26:19 +0200 Subject: Why list.sort() don't return the list reference instead of None? References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> <1147071499.135783.193610@e56g2000cwe.googlegroups.com> Message-ID: ankyhe at gmail.com enlightened us with: > However, I wonder why L.sort() don't return the reference L, the > performance of return L and None may be the same. It's probably because it would become confusing. Many people don't read the documentation. If L.sort() returns a sorted version of L, they would probably assume it didn't do an in-place sort. The effects of an unexpected in-place sort are much harder to track down and debug than a function returning None. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From edeveaud at pasteur.fr Wed May 3 09:13:17 2006 From: edeveaud at pasteur.fr (Eric Deveaud) Date: Wed, 3 May 2006 13:13:17 +0000 (UTC) Subject: Sorting a list of dictionaries by dictionary key References: Message-ID: Nico Grubert wrote: > Hi there, > > I am looking for a way to sort a list containing dictionaries. > > This is my example list: > [{'Title': 'ABC', 'from_datetime': DateTime('2006/04/25 12:45:00 > GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 > 12:45:00 GMT+2')}, {'Title': 'GHI', 'from_datetime': > DateTime('2006/03/10 12:45:00 GMT+2')}] > > I want to sort the list by dictionary's key 'from_datetime' so the > sorted list should be: > > [{'Title': 'GHI', 'from_datetime': DateTime('2006/03/10 12:45:00 > GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 > 12:45:00 GMT+2')}, {'Title': 'ABC', 'from_datetime': > DateTime('2006/04/25 12:45:00 GMT+2')}] > > Any idea how I can sort this list? sort can take a comparaison function. which specification are takes 2 elements returns a negative value if elem1 is lesser than elem2 returns a positive value if elem1 is grater than elem2 returns zero if elem1 == elem2 you may write such fuction def dictionary_datetime_sorter(d1, d2): date1 = d1['from_datetime'] date2 = d2['from_datetime'] if date1 < date2: return -1 elif date1 > date2: return 1 else: return 0 you'll have to find out how to compare 2 DateTime and then, in order to sort your list your_dictionary_list.sort(dictionary_datetime_sorter) Eric -- ? Voyons-voir : est-ce que ma question est vraiment conne ? Oh oui, vraiment trop conne, je vais poster dans "premiers-pas", je posterai dans "configuration" quand je serai moins con. ? -+-JLC - Guide du Neuneu d'Usenet - Bien configurer sa question -+- From bearophileHUGS at lycos.com Fri May 19 17:21:38 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 May 2006 14:21:38 -0700 Subject: newb: comapring two strings In-Reply-To: <7xhd3lvpng.fsf@ruckus.brouhaha.com> References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <4d4chmF185ohoU1@uni-berlin.de> <1148038726.023455.145900@j73g2000cwa.googlegroups.com> <1148062114.800989.293270@j73g2000cwa.googlegroups.com> <1148062688.445501.30260@y43g2000cwc.googlegroups.com> <7xhd3lvpng.fsf@ruckus.brouhaha.com> Message-ID: <1148073698.476514.140070@j33g2000cwa.googlegroups.com> Paul Rubin>Still terrible. Use a better algorithm!< I agree, it's O(n^2), but if you need to run this program just 1 time, and the program is in C, and you don't want to use much time to think and code a better algorithm (or you aren't able to do it) then maybe that naive solution can be enough, (if the running time is around 30-90 minutes). Total time to solve a one-shot problem is often the sum of thinking time + programming time + running time :-) Paul Rubin>Use this to generate all the variants of all the words in the dictionary, and write those out into a file, each line containing a variant plus the original word. Then use a sorting utility like the unix "sort" program to sort the file. Those programs work efficiently even if the file is too large to fit in memory. Then read the sorted file to find equivalence classes on the variants.< If the words are all 5 character long, then I think you are creating: (len(lowercase)-1) * 5 * 30000 = 3750000 strings of len 5+5 (plus enter if you save it into a file), this means a file of about 37 MB. All those trings may even fit in memory if you have lot of it. Your solution looks nice :-) (It reminds me a little the word signature trick used to find anagrams). Bye, bearophile From defcon8 at gmail.com Wed May 24 13:24:55 2006 From: defcon8 at gmail.com (defcon8) Date: 24 May 2006 10:24:55 -0700 Subject: Python keywords vs. English grammar In-Reply-To: References: Message-ID: <1148491495.794376.26920@38g2000cwa.googlegroups.com> 1. Does it matter? 2. Is it affecting your productivity. 3. Are you not trying to programme? 4. It is open source, change it and stop whining. From rpdooling at gmail.com Tue May 16 21:42:57 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 16 May 2006 18:42:57 -0700 Subject: help with this simple DB script In-Reply-To: <446a7849$0$1901$c3e8da3@news.astraweb.com> References: <446a7849$0$1901$c3e8da3@news.astraweb.com> Message-ID: <1147830177.787319.268940@i40g2000cwc.googlegroups.com> Are you able to connect to the DB using MySQL administrator? From reply.in.the.newsgroup at my.address.is.invalid Mon May 8 02:58:18 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 08 May 2006 08:58:18 +0200 Subject: Getting HTTP responses - a python linkchecking script. References: <1147056628.354150.116120@y43g2000cwc.googlegroups.com> Message-ID: <3vqt52hb9b1k1ddk1pkqu9k1qb0kalcmor@4ax.com> blair.bethwaite at gmail.com: >with urllib2 it doesn't seem possible to get HTTP status codes. except urllib2.HTTPError, e: if e.code == 403: -- Ren? Pijlman From ramen at lackingtalent.com Tue May 16 18:32:06 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 16 May 2006 15:32:06 -0700 Subject: Time to bundle PythonWin In-Reply-To: <4464F4B9.8080603@v.loewis.de> References: <4464F4B9.8080603@v.loewis.de> Message-ID: Martin v. L?wis wrote: > Dave Benjamin wrote: >> Why is PythonWin (win32all) still a separate download from a third >> party? Is it legal, technical, or what? I think it's about time it be >> part of the standard distribution. > > Both legal and technical. The PythonWin author and maintainer (Mark > Hammond) hasn't contributed this package for inclusion into Python. > Without him explicitly saying that he wants that to happen, and prefers > that over maintaining it outside Python himself, there is no way it > could ever get included. This is a basic rule of politeness in open > source software: don't fork, not even if you are legally allowed to. > [of course, forks happen, typically because people don't consider > it important enough to be polite to the original author] Sure. I wasn't proposing that this be done behind Mark's back. I wasn't even proposing a fork; rather, just two installers bundled into one. The user, upon running the .msi file, would simply be asked if they'd like PythonWin also. PythonWin could be automatically combined into the installer by downloading the latest version from SourceForge, perhaps. > Now, if Mark did indeed offer it for inclusion, I would request (and > also work on if I find the time) that the structure of these libraries > is revised. I know that the current structure tries to be "natural" > in some sense, but I find the assignment of API functions to modules > quite arbitrary. I also think that some of the API functions should > be replaced with their *Ex versions that Microsoft added over time. Well, I'm sure the structure could be improved, but there's really nothing else quite like PythonWin out there. And I could think of parts of Python's standard library that evolved organically (os.popen2 thru 12 comes to mind ;-) ) which could stand some reorganization. But anyway, I digress... > Coming back to organizational issues: it would surely help if people > would actively contribute to PythonWin. I believe this still is > primarily a one-man show, and that Mark does an excellent job should > not be an excuse for you to not contribute. If only I had his expertise on the win32 API... >> There are many useful things that you ought to be able to do without >> downloading third-party libraries. Terminating a process, for example. > > You can use subprocess.TerminateProcess for that (in some limited way). Good to know, although this requires Python 2.5. I'm getting rather excited about Python 2.5... looks like a lot of useful new tools are in the pipeline. >> Communicating with other applications via a standard, common protocol >> (COM). We demand these things from our UNIX environments--why do we >> tolerate their omission on the Windows platform? > > We tolerate them because they aren't omitted. They are readily > available, and we are all lazy enough to never do more than just > post to a newsgroup complaining about it. Well, good, at least I'm not the only lazy complainer around here. =) >> It's time to bundle PythonWin. > > So go and work on that. Nah. Sounds like the better option is to wait for ctypes in 2.5... Dave From bdesth.quelquechose at free.quelquepart.fr Tue May 2 23:00:36 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 05:00:36 +0200 Subject: assignment in if In-Reply-To: <87iroodnqz.fsf@localhost.localdomain> References: <87iroodnqz.fsf@localhost.localdomain> Message-ID: <4457ee22$0$31162$636a55ce@news.free.fr> Gary Wessle a ?crit : > Hi > > is there a way to make an assignment in the condition of "if" and use > it later No. >, e.g. > > nx = re.compile('regex') > if nx.search(text): > funCall(text, nx.search(text)) > > nx.search(text) is evaluated twice, I was hoping for something like > > nx = re.compile('regex') > if x = nx.search(text): > funCall(text, x)) x = nx.search(text) if x: funCall(text, x) From reply.in.the.newsgroup at my.address.is.invalid Sun May 28 17:04:40 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Sun, 28 May 2006 23:04:40 +0200 Subject: HTMLParser chokes on bad end tag in comment Message-ID: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> The code below results in an exception (Python 2.4.2): HTMLParser.HTMLParseError: bad end tag: "", at line 4, column 6 Should it? The end tag it chokes on is in comment, isn't it? import HTMLParser HTMLParser.HTMLParser().feed(""" """) -- Ren? Pijlman From andrew.arobert at gmail.com Wed May 24 14:24:55 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 24 May 2006 14:24:55 -0400 Subject: Conversion of perl based regex to python method In-Reply-To: <127923enb2dbh21@corp.supernews.com> References: <127923enb2dbh21@corp.supernews.com> Message-ID: <127998j378v4n3d@corp.supernews.com> Andrew Robert wrote: > I have two Perl expressions > > > If windows: > > perl -ple "s/([^\w\s])/sprintf(q#%%%2X#, ord $1)/ge" somefile.txt > > If posix > > perl -ple 's/([^\w\s])/sprintf("%%%2X", ord $1)/ge' somefile.txt > > > > The [^\w\s] is a negated expression stating that any character > a-zA-Z0-9_, space or tab is ignored. > > The () captures whatever matches and throws it into the $1 for > processing by the sprintf > > In this case, %%%2X which is a three character hex value. > > How would you convert this to a python equivalent using the re or > similar module? > > I've begun reading about using re expressions at > http://www.amk.ca/python/howto/regex/ but I am still hazy on implementation. > > Any help you can provide would be greatly appreciated. > > Thanks, > Andy Okay.. I got part of it.. The code/results below seem to do the first part of the expression. I believe the next part is iterating across each of the characters, evaluate the results and replace with hex as needed. # Import the module import re # Open test file file=open(r'm:\mq\mq\scripts\testme.txt','r') # Read in a sample line line=file.readline() # Compile expression to exclude all characters plus space/tab pattern=re.compile('[^\w\s]') # Look to see if I can find a non-standard character # from test line #! C:\Python24\Python var=pattern.match('!') # gotcha! print var <_sre.SRE_Match object at 0x009DA8E0 # I got print var.group() ! # See if pattern will come back with something it shouldn't var =pattern.match('C') print var #I got None Instead of being so linear, I was thinking that this might be closer. Got to figure out the hex line but then we are golden # Evaluate captured character as hex def ret_hex(ch): return chr((ord(ch) + 1) % ) # Evaluate the value of whatever was matched def eval_match(match): return ret_hex(match.group(0)) # open file file = open(r'm:\mq\mq\scripts\testme.txt','r') # Read each line, pass any matches on line to function for line in file.readlines(): re.sub('[^\w\s]',eval_match, line) From pod at internode.on.net Fri May 19 02:29:29 2006 From: pod at internode.on.net (PoD) Date: Fri, 19 May 2006 15:29:29 +0900 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: On Thu, 18 May 2006 08:30:03 +0000, Duncan Booth wrote: > PoD wrote: >> How many levels of indentation does 12 spaces indicate? >> It could be 1,2,3,4,6 or 12. If you say it's 3 then you are >> _implying_ that each level is represented by 4 spaces. > > By reading the code I can see how many levels of indentation it > represents. > >> How many levels of indentation is 3 tabs? 3 levels in any code that >> you will find in the wild. > > No. That is precisely the problem: there is code in the wild which > contains mixed space and tab indentation, and any time that happens 3 > tabs could mean any number of indentations. I think it is universally accepted that mixed tabs and spaces is indeed **EVIL** I should have said any code using tabs exclusively. From fredrik at pythonware.com Fri May 26 09:06:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 May 2006 15:06:55 +0200 Subject: "Learning Python" 2nd ed. p479 error? In-Reply-To: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> References: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> Message-ID: AbrahamLincolnIllinois at yahoo.com wrote: > On page 479, the 2nd edition of the "Learning Python" book, this code > appears > > class Derived(Base): > def __init__(self, arg, *args, **kw): > self.__init__(self, *args, **kw) > > Surely self.__init__ should be > > Base.__init__ I don't have a copy within reach, but from what you say, it sure looks like a typo. > It doesn't appear in the errata. What am I misunderstanding? nothing, except perhaps what's the best place to report errors in O'Reilly books (I'm quite sure they don't read this newsgroup ;-) there's a "view/submit errata" link on this page: http://www.oreilly.com/catalog/lpython2/ From vinay_sajip at yahoo.co.uk Thu May 25 13:17:21 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 25 May 2006 10:17:21 -0700 Subject: "No handlers could be found for logger xxx" ? References: Message-ID: <1148577441.058078.247410@i40g2000cwc.googlegroups.com> robert wrote: > some packages like paramiko use the logging. I get this messages: > "No handlers could be found for logger xxx" on stderr > > Why is un-initialized logging allowed to chatter at all? You could invoke logging.basicConfig with a level of CRITICAL. This will generally filter out logging messages. Un-initialized logging chatters because in development environments, it's useful to be able to spot misconfigured loggers. For production use, set logging.raiseExceptions to 0 and logging should then be quiet. Regards, Vinay Sajip From knowledge at world.net Thu May 18 22:57:49 2006 From: knowledge at world.net (Knowledge) Date: Fri, 19 May 2006 03:57:49 +0100 Subject: Great! Message-ID: 100% Reliable! http://theproofonline.com/?8a4y We Ship WorldWide! Gurantee 100% Top Quality of All Products Discreet Packaging & Shipping Verisign Secure Site! http://theproofonline.com/?8a4y From nobody at 127.0.0.1 Wed May 17 01:25:52 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 05:25:52 GMT Subject: python vs perl lines of code References: Message-ID: Charles DeRykus wrote: > This subject thread may be of great interest but I think an language > advocacy mailing list would be a better forum. Fair enough, but advocacy isn't at all what I'm after. Anecdotes are fine, after all what is data but a collection of anecdotes? :) Seriously, anecdotes are valuable: they give you another perspective, reflect common wisdom, and can tell you what/where/how to look for hard data. Of course if anyone already has hard data that would be welcome too, but it's hard to even pin down what 'hard data' means in this situation. I'll grant you though, asking for non-value-judgement-laden anecdotes on newsgroups may be asking too much. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From chris.cavalaria at free.fr Fri May 19 04:29:25 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 19 May 2006 10:29:25 +0200 Subject: Complex evaluation bug In-Reply-To: References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> <446d79da$0$7144$626a54ce@news.free.fr> Message-ID: <446d8209$0$7139$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > Christophe wrote: > >>> So, putting them together, you could expect >>> eval(repr(a)) >>> to reproduce a, and in fact it does so. >> >> >> Says who ? >> >> Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] >> on win32 >> Type "help", "copyright", "credits" or "license" for more information. >> >>> repr(1+3j) >> '(1+3j)' >> >>> complex(repr(1+3j)) >> Traceback (most recent call last): >> File "", line 1, in ? >> ValueError: complex() arg is a malformed string >> >>> > > > in what language is "eval" spelled "complex" ? > > > Oups, I was too fast to read what was written. I though you only changed one of the terms ( str -> repr ). You'll note that repr and str produce the exact same result for complex. And also, I'm not sure using eval anywhere is a good idea so it probably doesn't help for what the OP wants to do. From onurb at xiludom.gro Thu May 4 04:45:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 10:45:11 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> <44580270$0$4903$626a54ce@news.free.fr> Message-ID: <4459bf73$0$12430$626a54ce@news.free.fr> Ben Finney wrote: > Bruno Desthuilliers writes: > > >>Ben Finney a ?crit : >> >>>So now you're proposing that this be a special case when a >>>function is declared by that particular syntax, and it should be >>>different to when a function is created outside the class >>>definition and added as a method to the object at run-time. >>> >>>Thus breaking not only "explicit is better than implicit", >> >>This one can be subject to discussion. > > > All the assertions in 'import this' are subject to discussion. Of course - but that was not the point. I meant that having implicit self in methods would not break this assertion much more than the current strange mix of explicit declaration of self + implicit passing of self. > They're > even contradictory. That's the nature of Zen, isn't it ?-) (snip) >>I'm not yet ready to vote for Edward's proposition - as you say, it >>makes 'def statements into a class statement' a special case, and I >>don't like special cases too much (OTOH, there actually *are* >>special cases - __new__() being an example) - *but* it's not that >>silly either IMHO, and I think this should not be dismissed on a >>purely reactional basis. > > > My basis for rejecting the proposal is that it claims to offer net > simplicity, yet it breaks at least two of the admonishments that > simplify Python. One could also claim that the current scheme *actually* breaks explicit-implicit and special-case rules in that the instance is implicitely passed at call time for the bound methods special case - which is ok IMHO since practicallity-beats-purity. Also, FWIW, Edward's proposition can be justified (at least that's Edward's POV) by the first rule : beautiful is better than ugly !-) disclaimer : None of this is to be taken as the expression of my own position on this proposition... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tommy04 at gmail.com Sat May 27 01:29:05 2006 From: tommy04 at gmail.com (Tommy B) Date: 26 May 2006 22:29:05 -0700 Subject: Running External Commands + Seeing when they are Finished Message-ID: <1148707745.744045.77770@g10g2000cwb.googlegroups.com> I'm currently working on a script that I will run when I leave my computer on at night. It runs external commands like Ad-Aware, Spybot, AVG, Avast, and the like. The problem is, I want to know how to make it so that one command starts only after the last one finishes. When I run them, they end up running all at once! Can someone please tell me if this is possible? Judging from what I've seen in Python's versitility, I bet it can... From fredrik at pythonware.com Tue May 2 11:39:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 May 2006 17:39:46 +0200 Subject: stripping blanks References: <1146551010.297649.314610@y43g2000cwc.googlegroups.com><445720fd$1_2@news.estpak.ee> <200605022323.12710.fulvio@pc.jaring.my> Message-ID: Fulvio wrote: > > printLine = line.rstrip("\n") > > I think that nobody considered if the text has (\r) or (\r\n) or (\n) at the > end of the line(s). if it's opened in text mode (the default), and is a text file, it will always have "\n" at the end of the line. From claird at lairds.us Tue May 23 19:29:29 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 23 May 2006 23:29:29 +0000 Subject: real time info to web browser from apache side ? References: <1148408900.176202.281530@g10g2000cwb.googlegroups.com> Message-ID: In article , Ben Finney wrote: >"Joseph" writes: > >> So I am looking more for a push technology than a pull from teh >> browser (user hit Ctrl-R to refresh is a pull). > >Not necessarily; just write the web page so that it instructs the >browser to do the pull automatically, without refreshing the entire >page. > >This has come to be known as AJAX (though, because this is the sort of >thing JavaScript was designed for, some just call it JavaScript). . . . While refresh and AJAX are the standard answers now, there are other possibilities that we can regard as browser-specific that remain use- ful in rare situations . Good luck with your project. Using the Web to monitor plant operations can be a real winner. From pmartin at snakecard.com Sun May 21 14:48:53 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Sun, 21 May 2006 13:48:53 -0500 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: Xah Lee wrote: > Software Needs Philosophers > > by Steve Yegge, 2006-04-15. > > Software needs philosophers. > > This thought has been nagging at me for a year now, and recently it's > been growing like a tumor. One that plenty of folks on the 'net would > love to see kill me. > > People don't put much stock in philosophers these days. The popular > impression of philosophy is that it's just rhetoric, just frivolous > debating about stuff that can never properly be answered. ?Spare me > the philosophy; let's stick to the facts!? > > The funny thing is, it's philosophers who gave us the ability to think > rationally, to stick to the facts. If it weren't for the work of > countless philosophers, facts would still be getting people tortured > and killed for discovering and sharing them. > > Does it ever strike you as just a teeny bit odd that after a brief > period where philosophy flourished, from maybe 400 B.C.E. to ~100 C.E., > we went through a follow-on period of well over one thousand five > hundred years during which the Roman Catholic Church enslaved > everyone's minds and killed anyone who dared think differently? > > What's weirder is that we tend to pretend it didn't really happen. We > like to just skip right over the dominance of religion over our minds > for a hundred generations, and think of religion today as a kindly old > grandpa who's just looking out for us kids. No harm, no foul. Let > bygones be bygones. Sure, there were massacres and crusades and > genocides and torture chambers with teeth grinding and eyes bleeding > and intestines torn out in the name of God. But we were all just kids > then, right? Nobody does that kind of thing today, at least not in > civilized countries. > > We try not to think about the uncivilized ones. > > It was philosophers that got us out of that Dark Ages mess, and no > small number of them lost their lives in doing so. And today, the > philosophy majors are the butts of the most jokes, because after the > philosophers succeeded in opening our minds, we forgot why we needed > them. > > And if we stop to think about it at all, we think that it was other > people, people who are very unlike us, who committed those atrocities > in the name of Faith (regardless of whether it's faith in a god, or in > a political party, or any other form of mind control carried out by > force). > > We like to think we live in an enlightened age, but we don't. Humans > haven't changed significantly in 10,000 years. We're still killing and > torturing each other. It's apparently incredibly easy to decide to kill > someone and then do it. Happens every day, all around the world. > Torture, too. > > But those people are just people. If they had been born down the street > from you, they'd have gone to school with you, been friends with you, > learned to program with you, written blogs and comments, never tortured > or killed anyone in the name of an idea. They'd have been you. Which > means they are you; you just got lucky in where you were born. > > One of the commenters on my last blog entry expressed the fervent wish > that I drop dead. To be sure, they qualified it with ?on the > internet?. But if they really feel that way, especially about > something as hilariously and absurdly unimportant in the Grand Scheme > as whether the Lisp programming language has any acceptable > implementations, then what does it say about us? > > Everyone who commented angrily on that blog entry was caught. I caught > you, anonymous or not, being a religious fanatic. The only > ?negative? commenter who doesn't appear to be a religious zombie > was Paul Costanza (ironic, since he claims to be the opinionated one), > who relegated his comments to pedantic technical corrections. They're > welcome, of course; I'm always looking to correct any technical > misconceptions I harbor. But they're moot, since even if I was wrong > about every single technical point I brought up in that entry, my > overall point ? Lisp is not an acceptable Lisp ? remains largely > uncontested by the commenters. > > Some of them just don't get it, which is fine; no harm in that. If > you've been using Lisp for years and years, and you've written books > and articles and zillions of lines of Lisp code, then you're unlikely > to remember anything about what it's like coming to Lisp for the first > time. They're religious because they've forgotten what it's like to be > a skeptic. > > But make no mistake; a substantial percentage of people who take a side > in any programming language discussion that devolves into a flamewar > know exactly what the other side means, and they want to invoke the > Ultimate Censorship: drop dead! Killing someone, after all, is one of > the best ways to silence them. You also have to burn all their > writings, which is getting harder these days; hence the increased > vehemence on the 'net. > > Those of you who've followed what I've written over the past year or so > know where I'm going. I'm taking a stand, all right, and it's a very > definite one. I'm finding myself drawn inexorably towards a single > goal: stamping out technological religion, because I'm frigging tired > of not being able to stick to the facts. > > FACT: Java has no first-class functions and no macros. This results in > warped code that hacks around the problem, and as the code base grows, > it takes on a definite, ugly shape, one that's utterly unique to Java. > Lisp people can see this clear as day. So can Python folks, so can Ruby > folks. Java people flip out, and say ?macros are too much power?, > or ?what do u mean i dont understand u? or ?fuck you, you jerk, > Lisp will NEVER win?. > > You think I don't hear ALL that, and much more, in the hate mail I get > every day? > > I sure wouldn't want to be alone with a Java fanatic in a medieval > torture chamber, because God only knows what they're capable of. > > Turn the mirror towards Python, and what happens? Funny, but the Java > folks will mail me saying: ?yeah, I've always known I detested > Python, and you really nailed exactly why. Thanks!? Meanwhile, Python > folks are literally frothing at the mouth, looking for the ?Kill That > Bastard? key on their 101-key keyboards. > > I turned the mirror towards Lisp yesterday. Had to go to the bathroom > like nobody's business, and my wife was expecting me home any minute, > so I rushed it out: just a few thoughts here and there. So the Gorgon > only caught the tiniest glimpse of itself, but hell evidently hath no > fury like that of a Lisper scorned, and all that. > > It doesn't matter that I rushed it out. I'm glad I did; spending any > more time on it, trying to get it ?right? by looking up useless > factoids like how you can override length's non-polymorphicness with > some weird setting (when it plainly should just be the default), would > have had the exact same net effect: Lisp zealots would have found some > way to turn it into a flamewar. And I'd have been out 2 or 3 more > hours. > > Let's call it a troll, then, because it was poorly researched; it was > just some months-old recollections of pain I'd gone through last year > trying to commit to Common Lisp, after another year of trying the same > with various flavors of Scheme and finding them all wanting. As far as > I'm concerned, Lisp is unacceptable today; it's my opinion and just > that, but I'll stick with it. > > I still need Lisp; after you learn enough of it, it becomes part of > your soul. I get my fix hacking elisp, and I do a lot of it. The > commenters are quite right; I've never written anything substantial in > Common Lisp, because in each of my serious attempts, there was too much > friction. Risk/reward wasn't high enough, and believe me, I wanted it. > > But after many attempts, I've given up on Common Lisp. They won't let > me use it where I work, and there are probably more Lispers per capita > where I work, including some famous ones, than at any other big company > in the world. If we can't use it where I work, then it's frigging > unacceptable; that's the shortest proof I can offer. > > What I'm far more interested today is the situation that arises if you > consider my post a troll. I'm far more interested in the social > consequences of working in a world filled with religious fanatics of > different religious persuasions. Especially given that it's a world in > which ?natural religion? has, by and large, been marginalized > through the work of philosophers. > [ ? Peter Siebel is the author of the book Practical Common Lisp, > 2005. ( http://gigamonkeys.com/book/).] > > Let's look at this world in a little more detail, starting with Peter > Siebel's comment, which I believe is the most interesting. Peter said: > > I was trying to figure out why on earth you spent so much time > writing about something that you apparently don't like. Then it hit me: > HCGS?. So thanks for your help. > > His first sentence speaks volumes about the sociology. His viewpoint is > exactly what they teach us all as kids: If you don't have anything nice > to say, don't say anything at all. We like to think people have a right > to believe whatever they want, and that it's not nice to say mean > things about other people's beliefs, especially when their livelihoods > are at stake. > > That's where philosophers come in, folks. They pick your beliefs apart > and show you in unforgettable ways the consequences of what you believe > in. I'm no philosopher; I know basically nothing about it, but I can > tell you I wish fervently that some great philosophers would come along > and effect change in our technical society. > > Because if nothing else, I can see the consequences of the way we're > thinking about things. One of many such consequences is that languages > aren't getting any better, and the worst offenders are Lisp and Scheme, > which by rights should be racing along the innovation curve faster than > their supposedly less capable peers. But they've stagnated worse than > any other non-dead language I can think of.[1] > > Programming languages are religions. For a long while now I've been > mildly uncomfortable calling it ?religion?, but I don't feel bad > about it anymore. They're similar enough. At the top of the language > religion is the language itself; it serves as the deity and the object > of worship. > > Like any other organized religion, there's always a Pope (or a > politburo chairman, in countries where the government has brutally set > itself up as what is for all intents the religion of choice): a > spiritual leader that gives the religion the human touch. This person > is almost always the language designer, of course. In Lisp's case it's > complicated, because McCarthy, Sussman and Steele aren't very active as > spiritual leaders for their languages anymore. > > Every major organized religion is a heirarchical government, and > programming languages are no exception. You'll find equivalents of > cardinals, bishops, priests and laity in programming language camps: > the closer you are to the fire, to the spiritual center, the higher > your rank. It's a great way to quantify your perceived self-importance: > a high-score list, in effect. Great for the ego, but it makes you a > piss-poor debater, because you're so emotionally invested in your > status. > > You'd think your rank would be accrued by virtue of your technical > and/or documentation contributions, but in practice it's usually more > of a function of how many converts you've gained, how many followers > you have, how much you've been spreading the Word. > > [? Paul Graham is a lisp dignitary. He is well known for having sold > his ecommerce software written in lisp to Yahoo.com for $49.9 million, > among other things. See Paul Graham? and http://www.paulgraham.com/ ] > > That's why Paul Graham isn't the Pope of Lisp. He's eminently > qualified, but unfortunately he's a heretic. Notice that almost none of > the commenters on my last blog mentioned the PG argument I made. The > only one who did (as of this writing) tried to make it an argument for > Common Lisp. Let's face it: you can't give those heretics too much > press; people might start listening to them! > > Peter, are you beginning to understand why I write so much about > something I apparently don't like? It's because I wanted to like it but > found it fatally flawed, technically and culturally. It's as if I were > a would-be convert to Roman Catholicism, but I can't bring myself to > commit because I've seen too much of their role in creating a history > that ironically we all wish we could rewrite. > > I was born and raised a Roman Catholic, and I renounced it when I was > thirteen years old, after my Uncle Frank (a devout terrorist Catholic > if there ever was one) told me to stop reading the Bible, that it would > ?really screw a person up? to do that, that you needed someone to > interpret it for you. That wasn't the only reason I renounced it, but > it'll suffice for our purposes. > > Technologically I was born and raised an assembly-language programmer; > at least that's what my first real job was, for 5 years after I got my > CS degree. Assembly is just flagellation, though, and damned > uncomfortable at that, so I joined the Church of Java for fully seven > years. And practically at the very moment I'd finally tired of chafing > at Java's limitations, Paul Graham came along and through his early > essays, showed me Lisp. What a great new religion! > > Problem is, each time you switch religions, the next one has less > impact on you. Once a Catholic, always a Catholic, they say. I don't > know what that means for me, since I was raised by the > assembly-language wolf, but it appears to mean that I'm never going to > be enthralled with another programming language. And now that I've > swallowed the red pill, what choice do I have? I need to try to show > people what's out there. > > Interestingly, it was Peter Siebel's most excellent book, Practical > Common Lisp?, that played the role of Uncle Frank and killed my > desired to continue with Common Lisp. Peter was the first person to > show me beast's underbelly. Every other Lisp book had pretended it was > pure and beautiful and uncorrupted, because they left all the nastiness > out as ?implementation-defined?. Once I saw what you really need to > do in order to build something resembling a portable Lisp code base, > and then had a few runs at it myself, I threw in the towel. > > I much prefer Lisp the idea to Lisp the implementation.[2] > > [ ? Fyodor_Dostoyevsky?, David_Hume?, Aristotle?, > Jean-Paul_Sartre?, Ben_Franklin?, Galileo_Galilei?, > Bertrand_Russell?, Albert_Einstein? ] > > I can tell you this: I've tried writing this essay for a year. I've > tried fully a dozen times. I've tackled it from a dozen angles. I've > wanted to say it ? software needs philosophers! ? so many times, in > so many ways. We need great thinkers ? the Fyodor Dostoyevskys and > David Humes and Aristotles and Jean-Paul Sartres and Ben Franklins and > Galileo Galileis and Bertrand Russells and Albert Einsteins to show us > the way through the Software Dark Ages we're in today: a time that will > doubtless be remembered as every bit as mired in darkness and ignorance > as the Dark Ages themselves. > > But I've failed. This isn't the essay I wanted to write, because I'm > neither a great thinker nor a great writer. However, you might be: if > not now, then perhaps someday. So I think it's better to get the idea > out now than to hoard it in the hopes of someday writing a > world-changing essay. > > For those of you who were surprised at the suddenness and vehemence of > the Lisp community's backlash to my little rant, I hope I've helped > shed a little light, helped you see its inevitability. Basically > they've had a lot of practice. Lisp is one of the oldest technology > religions, and they've both experienced and doled out their share of > religious persecution. > > But that's not the lesson you should take away. The lesson is that they > are you. Whenever you hear someone ranting about something you take for > granted as wonderful and praiseworthy, and you're wondering why they > don't leave well enough alone so we can all get back to our incestuous > cheerleading, just remember: we went from the Dark Ages to our > reeeeasonably enlightened society today by questioning our most > cherished beliefs. > > So keep questioning them. > > [ ? R6RS refers to the Scheme Lisp language's upcoming specification. > See Scheme programming language? ] > > [1] Yes, I've read all of R6RS. It's a lukewarm compromise that punts > on most of the important issues. It's not going to make Scheme any more > successful than it is today, which to me feels practically criminal; it > was their one big chance to break out of the rut they're in. But it > doesn't matter. Let's pretend this footnote is just a troll. If your > hackles went up, then you're a techno-religious zombie, and I hope in > my lifetime to find you a cure. Try your best to think about that long > and hard before responding. > > [ ? SLIME is a emacs mode for lisp programing. See > http://common-lisp.net/project/slime/. ] > > [2] For the record, the commenter I agree the most with is the one who > said the problem basically boils down to an IDE issue. SLIME doesn't > cut it, either, as beautiful as SLIME is. Can't use it on Windows to > save your life, for instance. But that's one of a thousand problems > with the Lisp IDE situation; it's pointless to try to discuss them all > in blogger. It's probably pointless to discuss them at all, because > it's just going to make me more miserable that no decent IDE exists for > Lisp, except for Emacs-as-Elisp-IDE. Which is why I get my Lisp fix by > hacking elisp these days. > > ---- > This post is archived at: > http://steve-yegge.blogspot.com/2006/04/software-needs-philosophers.html > > and > http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html > > This essay is reported with permission. > > Xah > xah at xahlee.org > ? http://xahlee.org/ No Xah :-) many of us want you to stay healthy ! Philippe From alanalan at newsgroup.nospam Wed May 31 13:59:57 2006 From: alanalan at newsgroup.nospam (A.M) Date: Wed, 31 May 2006 13:59:57 -0400 Subject: Oracle Data Access in Python References: Message-ID: "Bill Scherer" wrote in message news:mailman.6375.1149096323.27775.python-list at python.org... > A.M wrote: > >> Hi, >> >> >> >> I am familiar with Perl's DBI programming. >> >> >> >> In Python, do we access to Oracle by using DBI? >> > No. > >> Is Oracle DBD driver included with Python distributions? >> > No. > >> What is the most common strategy for accessing to Oracle data through >> Python? >> > cx_Oracle seems to be the leading module for Oracle access today. It works > well. > > http://www.cxtools.net/default.aspx?nav=cxorlb > > > You'll need the apropriate Oracle client installed for it to work, of > course. Oracle's "Instant Client" is probably the easiest way to get what > you need for that. > > > Hope that helps, > > Bill Thanks Bill for help. I also learned about DCOracle2 at this page: http://www.python.org/doc/topics/database/modules/ What do you think about DCOracle2? It seems to be based on Python Database API Specification. Thanks again, Ali From Elric02 at rogers.com Tue May 16 11:27:24 2006 From: Elric02 at rogers.com (Elric02 at rogers.com) Date: 16 May 2006 08:27:24 -0700 Subject: Unable to extract Python source code using Windows Message-ID: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> I'm currently trying to get access to the Python source code, however whenever I try to extract the files using the latest version of WinZip (version 10) I get the following error "error reading header after processing 0 entries" I was under the impression that I could (from reading the various posts on this group) that I could simply extract the tar ball, using WinZip. If this is not the case does anybody know how I can actually get source code on Windows platform. I don't have access to a UNIX box so that's not an option for me thanks in advance for any help you can provide Jeff From sendha_vin at yahoo.com Mon May 29 02:26:08 2006 From: sendha_vin at yahoo.com (sendhil kumar) Date: Sun, 28 May 2006 23:26:08 -0700 (PDT) Subject: deleting item from ListCtrl by pop-up menu Message-ID: <20060529062608.28189.qmail@web33108.mail.mud.yahoo.com> hi all, i need more information on the EVT_LIST_DELETE_ITEM() for a list ctrl! iam not able to delete the selected list item from the popup menu...below i have given the part of the code ... im using popup menu... wher am i wrong.... any suggestions wud b of great help... list.Bind(wx.EVT_LIST_ITEM_RIGHT_CLICK, self.OnRightClick) def OnRightClick(self, event): # Pop Up Menu Initialisation self._menu_popup = wx.Menu() [ self._ID_MENU_POPUP_DELETE, ] = [wx.NewId() for i in range(2)] 'Pop Up Menu' self.Bind(wx.EVT_MENU, self.OnPopupDelete, id = self._ID_MENU_POPUP_DELETE) self._menu_popup.Append(self._ID_MENU_POPUP_DELETE, 'Delete') self.PopupMenu(self._menu_popup) self._menu_popup.Destroy() def OnPopupDelete(self, event): self.Bind(wx.EVT_LIST_DELETE_ITEM, self.OnDelete) def OnDelete(self): print "Del" self.remove() thanx in advance, SendhilKumar B.Tech __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From vaikings at gmail.com Fri May 19 02:24:00 2006 From: vaikings at gmail.com (vaibhav) Date: 18 May 2006 23:24:00 -0700 Subject: import woe In-Reply-To: <1148016083.020020.40660@u72g2000cwu.googlegroups.com> References: <1148016083.020020.40660@u72g2000cwu.googlegroups.com> Message-ID: <1148019840.711270.314650@u72g2000cwu.googlegroups.com> Hi bob, 1. decide the directory which will be your root folder containing foo [/home/ROOT/foo/] 2. work out your directory structure relative to this root folder here it is ->ROOT->foo->car.py ->bar->far.py ->bar->jar.py 3. add __init__.py file inside each folder containing a list variable __all__ with contents as the name of the directories and classes so foo folder should contain a file called __init__.py which has the following contents __all__ = ['bar','car'] and bar folder should contain a file called __init__.py which has the following contents __all__ = ['far','jar'] 4. add the root folder to your sys.path so your jar.py file should have the following entries from sys import path path.append('../../../ROOT') note: i prefer relative paths or make paths using os.getcwd combinations in such situations, which makes the class more flexible. you can also do this step where u configure/initialize 5. then you can import the classes you want in jar.py from foo import car from foo.bar import far pls mail if u dont get it working/any doubts. - vaibhav From garabik-news-2005-05 at kassiopeia.juls.savba.sk Mon May 29 02:44:16 2006 From: garabik-news-2005-05 at kassiopeia.juls.savba.sk (garabik-news-2005-05 at kassiopeia.juls.savba.sk) Date: Mon, 29 May 2006 06:44:16 +0000 (UTC) Subject: html 2 plain text References: <1148840205.741356.209310@i40g2000cwc.googlegroups.com> Message-ID: robin wrote: > hi, > i remember seeing this simple python function which would take raw html > and output the content (body?) of the page as plain text (no <..> tags > etc) > i have been looking at htmllib and htmlparser but this all seems to > complicated for what i'm looking for. i just need the main text in the > body of some arbitrary webbpage to then do some natural-language > processing with it... > thanks for pointing me to some helpful resources! text=re.sub(r'(?s)\<.+?\>', '', html_text) (this will keep html entities, though) -- ----------------------------------------------------------- | Radovan Garab?k http://kassiopeia.juls.savba.sk/~garabik/ | | __..--^^^--..__ garabik @ kassiopeia.juls.savba.sk | ----------------------------------------------------------- Antivirus alert: file .signature infected by signature virus. Hi! I'm a signature virus! Copy me into your signature file to help me spread! From ptmcg at austin.rr._bogus_.com Sat May 13 12:38:42 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 13 May 2006 16:38:42 GMT Subject: Named regexp variables, an extension proposal. References: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> Message-ID: "Paddy" wrote in message news:1147513160.977268.253690 at j33g2000cwa.googlegroups.com... > Proposal: Named RE variables > ====================== > > The problem I have is that I am writing a 'good-enough' verilog tag > extractor as a long regular expression (with the 'x' flag for > readability), and find myself both > 1) Repeating sections of the RE, and > 2) Wanting to add '(?P...) ' around sections > because I know what the section does but don't really want > the group. > > If I could write: > (?P/verilog_name/ [A-Za-z_][A-Za-z_0-9\$\.]* | \\\S+ ) > > ...and have the RE parser extract the section of RE after the second > '/' and store it associated with its name that appears between the > first two '/'. The RE should NOT try and match against anything between > the outer '(' ')' pair at this point, just store. > > Then the following code appearing later in the RE: > (?P=verilog_name) > > ...should retrieve the RE snippet named and insert it into the RE > instead of the '(?P=...)' group before interpreting the RE 'as normal' > > Instead of writing the following to search for event declarations: > vlog_extract = r'''(?smx) > # Verilog event definition extraction > (?: event \s+ [A-Za-z_][A-Za-z_0-9\$\.]* \s* (?: , \s* > [A-Za-z_][A-Za-z_0-9\$\.]*)* ) > ''' > I could write the following RE, which I think is clearer: > vlog_extract = r'''(?smx) > # Verilog identifier definition > (?P/IDENT/ [A-Za-z_][A-Za-z_0-9\$\.]* (?!\.) ) > # Verilog event definition extraction > (?: event \s+ (?P=IDENT) \s* (?: , \s* (?P=IDENT))* ) > ''' > By contrast, the event declaration expression in the pyparsing Verilog parser is: identLead = alphas+"$_" identBody = alphanums+"$_" #~ identifier = Combine( Optional(".") + #~ delimitedList( Word(identLead, identBody), ".", combine=True ) ).setName("baseIdent") # replace pyparsing composition with Regex - improves performance ~10% for this construct identifier = Regex( r"\.?["+identLead+"]["+identBody+"]*(\.["+identLead+"]["+identBody+"]*)*" ). setName("baseIdent") eventDecl = Group( "event" + delimitedList( identifier ) + semi ) But why do you need an update to RE to compose snippets? Especially snippets that you can only use in the same RE? Just do string interp: > I could write the following RE, which I think is clearer: > vlog_extract = r'''(?smx) > # Verilog identifier definition > (?P/IDENT/ [A-Za-z_][A-Za-z_0-9\$\.]* (?!\.) ) > # Verilog event definition extraction > (?: event \s+ (?P=IDENT) \s* (?: , \s* (?P=IDENT))* ) > ''' IDENT = "[A-Za-z_][A-Za-z_0-9\$\.]* (?!\.)" vlog_extract = r'''(?smx) # Verilog event definition extraction (?: event \s+ %(IDENT)s \s* (?: , \s* %(IDENT)s)* ) ''' % locals() Yuk, this is a mess - which '%' signs are part of RE and which are for string interp? Maybe just plain old string concat is better: IDENT = "[A-Za-z_][A-Za-z_0-9\$\.]* (?!\.)" vlog_extract = r'''(?smx) # Verilog event definition extraction (?: event \s+ ''' + IDENT + ''' \s* (?: , \s* ''' + IDENT + ''')* )''' By the way, your IDENT is not totally accurate - it does not permit a leading ".", and it does permit leading digits in identifier elements after the first ".". So ".goForIt" would not be matched as a valid identifier when it should, and "go.4it" would be matched as valid when it shouldn't (at least as far as I read the Verilog grammar). (Pyparsing (http://sourceforge.net/projects/pyparsing/) is open source under the MIT license. The Verilog grammar is not distributed with pyparsing, and is only available free for noncommercial use.) -- Paul From nobody at 127.0.0.1 Sun May 21 17:43:31 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 21:43:31 GMT Subject: Programming language productivity References: Message-ID: <7a5cg.20466$Lm5.19755@newssvr12.news.prodigy.com> Peter Maas wrote: > I think that a LOC comparison between a language that enforces line breaks > and another language that enables putting an lots of code in one line > doesn't make much sense. I wonder why comparisons aren't made in terms of > word count. Word count would include literals, constants, variables, > keywords, operators, bracket- and block delimiter pairs. Python > indent/unindent would of course also count as block delimiters. I think > this would be a more precise measure for software size. I don't disagree, but "word" counts aren't so simple, either to define or to implement. What counts as a word? Parser tokens? That counts a.b (or a::b, or a->b, depending on language) as 3 words. Block delimiters? After a month, you don't even notice them in properly formatted code, which is why python doesn't have them in the first place. Operators? Then e.g. a = b + c + d + e counts more than a = add (b, c, d, e). The complexity of expressions seems determined by the numbers of operands; using operators as well arguably overcounts. Regardless of the above choices, you still need a parser (or at least a lexer) to count anything. Whitespace separation won't cut it - what happens with 'for (i=0;i<5;i++)' or 's = "foo bar baz"'? If you toss out operators, you could almost get away with regular expressions for counting the identifiers, keywords, and literals. But there's still the problem of overcounting string literals. Line counts are simple to compute and it's easier to agree on which lines to count. Thus their popularity. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From duncan.booth at invalid.invalid Mon May 22 11:29:36 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 22 May 2006 15:29:36 GMT Subject: XML/HTML Encoding problem References: Message-ID: Dale Strickland-Clark wrote: > from xml.dom.minidom import parseString > output = parseString(strHTML).toxml() > > The output is: > > > > > ><meta content="text/html; charset=iso-8859-1" >http-equiv="Content-Type"/> </head> ><body> > ??? ></body> ></html> > > So it encodes the entity reference to ??? (Euro sign). ??I need it to > remain as € so that the resulting HTML can render properly in a > browser. ??Is there a way to make the parser not convert the entity > references? ??Or is there a convenient post processing function that > will do the conversion? First up, when I repeat what you did I don't get the same output. toxml() without an encoding argument produces a unicode string, and no encoding attribute in the <?xml ...?> toxml() only takes a single encoding argument, so unfortunately there isn't any way to tell it what to do for unicode characters which are not supported in the encoding you are using. However, if you then encode the unicode output to ascii with entity escapes, I think you should be alright (unless I've missed something): >>> from xml.dom.minidom import parseString >>> strHTML = '''<?xml version="1.0" encoding="ISO-8859-1"?> <html> <head> <title> € ''' >>> print parseString(strHTML).toxml().encode('ascii', 'xmlcharrefreplace') <meta content="text/html; charset=iso-8859-1" http-equiv="Content-Type"/> </head> <body> € </body> </html> >>> You lose the encoding at the top of the output, but since the output is entirely ascii I don't think that matters. From durumdara at gmail.com Sun May 7 10:13:36 2006 From: durumdara at gmail.com (Dara Durum) Date: Sun, 7 May 2006 16:13:36 +0200 Subject: Why I get wrong filetime values with win32 api (FindFilesW) ? Message-ID: <9e384ef60605070713r9a2072ck@mail.gmail.com> Hi ! I need to get filelists from many HDD-s with more props. of files. I used FindFilesW to get these informations. But I have a problems with it. When I used Find_Data tuple, and it's atime,ctime,mtime props, I get wrong result. I have hungarian Windows (XP), so little time diff. I have. These method I use to get local time: timeval=localtime(int(pytime)) pv=strftime('%Y.%m.%d %H:%M:%S',timeval) pytime is a PyTime object that I get from the tuple. When I use it, it is shows 2 hours lesser than normal file time (Total Commander, File explorer). Example: it shows 18:54, but I have 20:54. When I modify the getting proc the time informations to: pytime=localtime(os.path.getctime(afile)) I get good result. What I do wrong ? Please help me: dd -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060507/569f6dac/attachment.html> From aurelioNOSPAMmartin at tele2.es Thu May 25 20:03:12 2006 From: aurelioNOSPAMmartin at tele2.es (Aurelio Martin) Date: Fri, 26 May 2006 02:03:12 +0200 Subject: Anyone compiling Python 2.3 on an SCO OpenServer 5 box? In-Reply-To: <1148577884.528595.157910@j33g2000cwa.googlegroups.com> References: <1148577884.528595.157910@j33g2000cwa.googlegroups.com> Message-ID: <4Brdg.278$%U1.166@nntpserver.swip.net> Mike Kent wrote: > If anyone is successfully compiling Pyton 2.3 on an SCO OpenServer 5 > box, I'd appreciate hearing from you on how you managed to do it. So > far, I'm unable to get a python that doesn't coredump. > Hey, I remember trying to compile Python 1.5 on an SCO OpenServer 5 box back in 1997 ! It was a mess so I downloaded an SCO binary instead (I think, my memory is not what it used to be, or is it?). Why do you want to compile it ? You can download a binary Python 2.3.4 from SCO Skunkware website, at http://www.caldera.com/skunkware/ Your URL: ftp://ftp2.sco.com/pub/skunkware/osr5/vols/python-2.3.4-VOLS.cpio Regards Aurelio From kentilton at gmail.com Mon May 15 02:28:37 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 15 May 2006 02:28:37 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <d6lu07r7u0u.fsf@vipunen.hut.fi> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> <d6lu07r7u0u.fsf@vipunen.hut.fi> Message-ID: <44681F95.9040400@gmail.com> Lasse Rasinen wrote: > Ken Tilton <kentilton at gmail.com> writes: > > >>>if any concepts have survived to the Python version. Since Python's object >>>model is sufficiently different, the system is based on rules being >>>defined per-class... >> >>That will be a total disaster for PyCells, if true. But I do not think it >>is. You just need a constructor that takes some slot initializers, and >>initialize the slots to one of: a normal value; an InputCell itself >>initialized with a starting value, if only nil; or a RuledCell itself >>initialized with a lambda. > > > Hmm, just tried it: > > >>>>class A(cells.cellular): > > ... def __init__(self): > ... self.a = cells.InputCell(10) > ... self.b = cells.RuleCell(lambda self: self.a+1, self, None) > > >>>>a = A() >>>>a.a > > 10 > >>>>a.b > > 11 > > So it does work out-of-the-box ;-) So why exactly did you say that the differences in the object model made it impossible? I was really stunned by that claim. And you sounded so confident. What went wrong there? It was trivial, right? How did you miss that? > > >>PyCells looks like it will be a project for SoC2006, so you may as well >>relax. > > > You really want to start a SoC project on something that takes about two > weeks ... You sound so confident. :) Do you know the deliverables? I know you do not know Cells. You say you looked at the code -- it does not show. I can also tell you have not done much serious programming, or you would know that twelve weeks is more like twelve minutes than three months. A new test suite, documentation (a first, there is none now), a full port of Cells in all their ten years of sophisticated evolution and variety (no, not your stupid pet trick), and as a demo project an entire cells-driven GUI, probably a port of my new Celtk (+ Cells Tk) work, all in a language without macros, without special variables, with a more modest OO system, and limited first class functions... oh, I think we'll keep him busy. :) Now since you are such a genius, maybe you can help with something. Trust me on this: this is one place where macros would be able to hide a ton of implementation wiring it does no one any good to look at, and actually turns into a maintenance nightmare whenever Cells might get revised. Is there any experiemntal macro package out there for Python? Maybe a preprocessor, at least? Or are there ways to actually hack Python to extend the syntax? My honest guess is that Cells will port readily to Python but leave everyone very interested in finding some way to hide implementation boilerplate. Got anything on that? kenny From larry.bates at websafe.com Fri May 5 10:12:14 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 05 May 2006 09:12:14 -0500 Subject: how to remove 50000 elements from a 100000 list? In-Reply-To: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> Message-ID: <OdudnV46Vu6-wMbZRVn-qg@comcast.com> Ju Hui wrote: > I want to remove about 50000 elements from a list,which has 100000 > elements. > sample code like below: > >>>> a=range(10) >>>> b=range(4) >>>> for x in b: > ... a.remove(x) > ... >>>> a > [4, 5, 6, 7, 8, 9] > > when a and b is small size, it will finished quickly, but when a and b > have many elements. > such as: >>>> a=range(100000) >>>> b=range(50000) >>>> for x in b: > ... a.remove(x) > ... > it will very slowly. Shall I change to another data structure and choos > a better arithmetic? > any suggestion is welcome. > thanks a lot! > A list isn't going to respond very well to random removals of large numbers of elements like this. Remember that it must do linear search to find the value to be removed and then basically build a completely new list with the remaining values. Depending on the data in question, you might be able to leverage things. Are the two lists sorted? If so you can iterate over both of them and build a third list with the results. This is not particularly 'elegant' but it is fast for sorted lists: import time a=range(100000) b=range(50000) start_time=time.time() for x in b: a.remove(x) stop_time=time.time() print "brute force elapsed time=%.2f seconds" % (stop_time-start_time) start_time=time.time() n=[] i1=0 i2=0 while 1: try: v1=a[i1] except IndexError: break try: v2=b[i2] except IndexError: n.extend(a[i1:]) break if v1 < v2: n.append(v1) i1+=1 continue elif v1 > v2: i2+=1 continue else: i1+=1 i2+=1 continue stop_time=time.time() print "new elapsed time=%.2f seconds" % (stop_time-start_time) start_time=time.time() a=set(a) b=set(b) a.symmetric_difference(b) stop_time=time.time() print "sets elapsed time=%.2f seconds" % (stop_time-start_time) brute force elapsed time=4.13 seconds new elapsed time=0.05 seconds sets elapsed time=0.03 seconds There may be other ways using bisect or some other module. If data is random, unsorted or has duplicates, I would look at in-memory database like SQLlite instead. If the values are unique you can do something like: a=set(range(100000)) b=set(range(50000)) a.symmetric_difference(b) Which is the fastest way. It all depends on the "real" data which we can't tell from your test using range(). -Larry Bates From john at castleamber.com Thu May 18 19:29:01 2006 From: john at castleamber.com (John Bokma) Date: 18 May 2006 23:29:01 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <Qg6bg.28899$4L1.16796@newssvr11.news.prodigy.com> Message-ID: <Xns97C7BC06AE240castleamber@130.133.1.4> Edward Elliott <nobody at 127.0.0.1> wrote: > John Bokma wrote: > >> "akameswaran at gmail.com" <akameswaran at gmail.com> wrote: >>> It seems to me the discussion could actually be beneficial. If >>> several different coders gave similar responses, ie code >>> line/character count comparisons, we might be able to see if there >>> is a trend of any sort - the more "anecdotes" given and we start to >>> have trends - or maybe we don't. >> >> What's the point? So you can say: Perl code has on average 1.727 more >> lines compared to Python? > > That's more than we know right now. You never know what data will > reveal until you collect and analyze it. 1.727 is meaningless. It says nothing about your code, nor mine. > BTW I'm not limiting this discussion to lines of code. That was > simply the most convenient metric available. If people have other > metrics to consider, by all means post them. The number $ characters per square furlong. > More knowledge = more choice = better tools. When all you have is a > hammer, everything looks like a nail. It's as simple as that. If > you're happy playing with your hammers, fine. Go away and post in > some other thread. At least I am not as silly to claim that hammer A is better then hammer B because the handle of hammer A came from an oak tree that had a owl hooting 13 times at the full moon 7 times a year. >> People who just know either Perl or Python don't care much about such >> figures, or so I hope. > > I don't know Ruby, but if you could show me it produced significantly > shorter code with comparable readability to Python, I'd certainly look > into it. Yeah, I could have guessed that. [ .. ] > Code can always be improved, it's a question of resources. The point > is not what could be done better in my code, but what was done with my > skill and my time committment, and what others have done with their > skill and their time committment. If we have no way to see your skills, there is not really a point. > At some point I may post small snippets of each so others can gauge my > style and experience, but I'm afraid it will devolve into a code > crtitiquing fest. At least people can learn from that. If you don't understand that everbody has his/her own coding style, you have a lot to learn. >>> Ok I'm going to end with a flamebait - but I would posit, ALL OTHER >>> THINGS BEING EQUAL - that a smaller number of characters and lines >>> in code is more maintainable than larger number of characters and >>> lines in the code. >> >> And I think that's why a lot of people posted very negative, in the >> hope that people would not be tempted to make the above very dumb >> statement. > > That's not a dumb statement, it's a sensible and testable hypothesis. So you *do* still have a lot to learn. Isn't one Xah Lee enough? > step, etc, etc. Didn't your mother ever tell you how science works? > It's not all bunsen burners and test tubes. Nor is it: I have have examined some random samples of which I give only a vague description. Now get your own random samples, and lets talk science. > To everyone who thinks this thread is pointless or a bad idea: please > just go away. Your objections have been noted, at this point you're > not contributing anything to the discussion. Welcome to Usenet. How it really works can be seen by having a peek at the archives. Since you love science, you'll will find the answer very fast. -- 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 michele.simionato at gmail.com Fri May 26 04:46:15 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 26 May 2006 01:46:15 -0700 Subject: genexp surprise (wart?) In-Reply-To: <7xpsi14drb.fsf@ruckus.brouhaha.com> References: <7xpsi14drb.fsf@ruckus.brouhaha.com> Message-ID: <1148633175.419682.54830@38g2000cwa.googlegroups.com> Paul Rubin wrote: > I tried to code the Sieve of Erastosthenes with generators: > > def sieve_all(n = 100): > # yield all primes up to n > stream = iter(xrange(2, n)) > while True: > p = stream.next() > yield p > # filter out all multiples of p from stream > stream = (q for q in stream if q%p != 0) > > # print primes up to 100 > print list(sieve_all(100)) > > but it didn't work. This is a known issue with the scope rules in loops which has bitten many (including myself; there is a long thread involving me and Jacek Generowitz debating this at death, you may find it if you google the newsgroup). I would be curious to know if your code would work the way you expect in Haskell (I know it would for 'for' loop, dunno about 'while' loops, I am completely ignorant in Haskell). Michele Simionato From ask at me Thu May 11 19:10:59 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 19:10:59 -0400 Subject: python equivalent of the following program In-Reply-To: <t1O8g.85795$dW3.66367@newssvr21.news.prodigy.com> References: <FbWdnZazBY8Aqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> <J-CdnRbdnJzNBP7ZnZ2dnUVZ_s-dnZ2d@comcast.com> <t1O8g.85795$dW3.66367@newssvr21.news.prodigy.com> Message-ID: <24-dnWcg5IQETf7ZnZ2dnUVZ_tKdnZ2d@comcast.com> Edward Elliott wrote: > Steven Bethard wrote: > >>import subprocess >> >>file1 = open('file1', 'w') >>prog1 = subprocess.Popen(['prog1'], stdout=file1) > > > And if the script runs somewhere that stderr is likely to disappear: > > prog1 = subprocess.Popen(['prog1'], stdout=file1, stderr=subprocess.STDOUT) > Forgot to mention before that the main motivation is to have the same code on bot Linux and M$ platforms. Does subprocess work well on both? Also how to find out that the 'prog1' e.g. has exited and it is done? Thx, A. From onurb at xiludom.gro Wed May 3 12:41:19 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 18:41:19 +0200 Subject: __getattr__ on non-instantiated class In-Reply-To: <4458D4F9.8010900@websafe.com> References: <1146671588.529743.249570@v46g2000cwv.googlegroups.com> <4458D4F9.8010900@websafe.com> Message-ID: <4458dd8a$0$22761$626a54ce@news.free.fr> Larry Bates wrote: > Fredp wrote: > >>Hi >>I was wondering if it is possible to have the various magic methods, >>mainly __getattr__ and __setattr__, and @property attributes called >>when accessing the attribute of a non-intantiated class. >> >>Imagin something like this: >>##### >>class MyClass: >> @property >> def prop(self): >> print "Accessed" >> return "ABCD" >> >>print MyClass.prop >>##### >>having it printing: >>##### >>Accessed >>ABCD >>##### >> >>Thanks very much >> > > Looks like you want Python to execute a method on an uninstantiated > class. s/uninstantiated// Python's classes are objects, and as such can have attributes and methods (read about staticmethod or classmethod). > I can't imagine how you would use such a thing. I do - that's something I do quite frequently. > > This produces the output you want: > > m=MyClass() > print m.prop() But this is not what the OP asked for !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From andrew.arobert at gmail.com Tue May 16 18:44:21 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 16 May 2006 18:44:21 -0400 Subject: Option parser question - reading options from file as well as command line In-Reply-To: <mailman.5768.1147811830.27775.python-list@python.org> References: <126k3273j7kb28f@corp.supernews.com> <mailman.5760.1147803481.27775.python-list@python.org> <126k6ed517nf73e@corp.supernews.com> <mailman.5768.1147811830.27775.python-list@python.org> Message-ID: <126klekfbcnkdaa@corp.supernews.com> Max Erickson wrote: > I don't know much about optparse, but since I was bored: > >>>> help(o.parse_args) > Help on method parse_args in module optparse: > > parse_args(self, args=None, values=None) method of > optparse.OptionParser instance > parse_args(args : [string] = sys.argv[1:], > values : Values = None) > -> (values : Values, args : [string]) > > Parse the command-line options found in 'args' (default: > sys.argv[1:]). Any errors result in a call to 'error()', which > by default prints the usage message to stderr and calls > sys.exit() with an error message. On success returns a pair > (values, args) where 'values' is an Values instance (with all > your option values) and 'args' is the list of arguments left > over after parsing options. > >>>> o.parse_args('seven') > Traceback (most recent call last): > File "<pyshell#15>", line 1, in ? > o.parse_args('seven') > File "C:\bin\Python24\lib\optparse.py", line 1275, in parse_args > stop = self._process_args(largs, rargs, values) > File "C:\bin\Python24\lib\optparse.py", line 1322, in _process_args > del rargs[0] > TypeError: object doesn't support item deletion > > That's the result of poking an optionParser instance in Idle. > parse_args is expecting something that looks like sys.argv[1:], which > is a list. You are passing it a string. > > max > Yup.. the code now works as: parser = OptionParser() if len(sys.argv) == 2: lines = open(sys.argv[1],"rb").readlines() for line in lines: line=line.strip() if not line: continue short, long, dest, help, default = line.split(";") help = "\t\t" + help # Prepend tabs to help message parser.add_option(short, long, dest=dest, help=help, default=default) else: parser.add_option("-m","--qmanager", dest="qmanager", help="\t\tQueue Manager to inquire against"), parser.add_option("-q","--queue", dest="queue", help="\t\tQueue the message will be sent to"), parser.add_option("-d","--dest", dest="dest", help="\t\tDestination File Name"), parser.add_option("-f", "--file", action="store", type="string", dest="filename", help="File to be transmitted", metavar="FILE") (options, args) = parser.parse_args() thanks all for the insight From a.schmolck at gmail.com Fri May 12 13:15:29 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 12 May 2006 18:15:29 +0100 Subject: New tail recursion decorator References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <Xns97BF8E839A8D1duncanbooth@127.0.0.1> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> <1147437656.779139.54840@d71g2000cwd.googlegroups.com> <1147441799.331677.88460@d71g2000cwd.googlegroups.com> <Xns97C19C18C76A4duncanbooth@127.0.0.1> Message-ID: <yfsy7x7tb9q.fsf@oc.ex.ac.uk> Duncan Booth <duncan.booth at invalid.invalid> writes: > Tim N. van der Leeuw wrote: > > > The other thing I do not understand, due to my limited understanding of > > what is tail-recursion: factorial2 (Duncan's definition) is not proper > > tail-recursion. Why not? How does it differ from 'real' tail recursion? > > Tail recursion is when a function calls itself and then immediately returns > the result of that call as its own result. I think the definition is broader than that so that these two functions would also be tail-recursive (i.e. the tail call doesn't have to be a self-tail call; I might be mistaken, don't have a good reference at hand; however "properly tail recursive" certainly refers to being able to do the below without exhausting the stack even for large n, not just transforming self-tail calls to a loop, which is sort of limited usefulness anyway): def even(n): return n == 0 or not odd(n-1) def odd(n): return n == 1 or not even(n-1) 'as From No.Spam at Spam.none Wed May 3 19:49:31 2006 From: No.Spam at Spam.none (I. Myself) Date: Wed, 03 May 2006 23:49:31 GMT Subject: Can Python kill a child process that keeps on running? In-Reply-To: <qakg5255b9jkff1cmpa6h22t09u7csavgm@4ax.com> References: <g0x5g.104639$7a.102977@pd7tw1no> <1146532884.872505.154370@i40g2000cwc.googlegroups.com> <MTy5g.104796$7a.25459@pd7tw1no> <mailman.5200.1146536105.27775.python-list@python.org> <_eM5g.106190$P01.81874@pd7tw3no> <qakg5255b9jkff1cmpa6h22t09u7csavgm@4ax.com> Message-ID: <fkb6g.115157$P01.29733@pd7tw3no> Dennis Lee Bieber wrote: > On Tue, 02 May 2006 17:00:42 GMT, "I. Myself" <No.Spam at Spam.none> > declaimed the following in comp.lang.python: > > >> I'm an intermediate Python programmer. Can you explain to me how ctypes >> will let me kill a child process? >> >> > ctypes allows you to call functions within pretty much any DLL file > (whereas the ActiveState win32api module only calls some core functions) > Ok, I don't know which function to call in which .dll file, but perhaps I can find out. Will ctypes will be a module in Python 2.5? Thanks Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From tjreedy at udel.edu Thu May 11 13:44:50 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 11 May 2006 13:44:50 -0400 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com><445fe772$1@nntp0.pdx.net><1147248164.805219.295970@y43g2000cwc.googlegroups.com><slrne63ahp.dac.apardon@rcpc42.vub.ac.be><1147283519.066005.134470@i40g2000cwc.googlegroups.com><1147333696.789718.189050@v46g2000cwv.googlegroups.com><Xns97C066238ECA4duncanbooth@127.0.0.1> <1147366331.637492.129980@i39g2000cwa.googlegroups.com> Message-ID: <e3vt6i$jq1$1@sea.gmane.org> "Kaz Kylheku" <kkylheku at gmail.com> wrote in message news:1147366331.637492.129980 at i39g2000cwa.googlegroups.com... > Let me make the observation that name of an inner function is, alone, > insufficient to identify that function in a debugging scenario. If you > have some inner function called I, defined within function F, you need > to know that it's the I inside F, and not some other I. > > Look at what happens with: > >>>> def err(): > ... def inner(): > ... return nonexistent > ... return inner > ... >>>> err() > <function inner at 0x8177304> >>>> err()() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "<stdin>", line 3, in inner > NameError: global name 'nonexistent' is not defined So name it err_inner. Or _err. tjr From tomasz.zielonka at gmail.com Mon May 8 00:52:35 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Mon, 8 May 2006 04:52:35 +0000 (UTC) Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <pan.2006.05.07.08.35.04.362248@gmail.com> Message-ID: <slrne5tjeo.b7l.tomasz.zielonka@tomekz.gem.lan> I V wrote: > Monads are one of those parts of functional programming I've never really > got my head around, but as I understand them, they're a way of > transforming what looks like a sequence of imperative programming > statements that operate on a global state into a sequence of function > calls that pass the state between them. This is a description of only one particular kind of monad - a state monad. A generalisation of your statement would be something like this: "they're a way of writing what looks like a sequence of imperative programming statements that, depending on the monad, can have certain computational side-effects (like operating on a global state) in a purely functional way". But this doesn't explain much. If you want to know more, there are some pretty good tutorials on http://www.haskell.org/. > So, what would be a statement in an imperative language is an anonymous > function that gets added to the monad, and then, when the monad is run, > these functions get executed. A monad is a type, it isn't run. The thing you run can be called a monadic action. You don't add functions to a monad (in this sense), you build a monadic action from smaller monadic actions, gluing them with functions - here's where anonymous functions are natural. > The point being, that you have a lot of small functions (one for each > statement) which are likely not to be used anywhere else, so defining > them as named functions would be a bit of a pain in the arse. Exactly! > Actually, defining them as unnamed functions via lambdas would be annoying > too, although not as annoying as using named functions - what you really > want is macros, so that what looks like a statement can be interpreted is > a piece of code to be executed later. Haskell has one such "macro" - this is the do-notation syntax. But it's translation to ordinary lambdas is very straightforward, and the choice between using the do-notation or lambdas with >>= is a matter of style. Best regards Tomasz From kentilton at gmail.com Mon May 8 11:48:00 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 08 May 2006 11:48:00 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> References: <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> Message-ID: <1LJ7g.17$u17.10@fe08.lga> David C. Ullrich wrote: > On Sun, 07 May 2006 10:36:00 -0400, Ken Tilton <kentilton at gmail.com> > wrote: > > >>[...] >> >>Your spreadsheet does not have slots ruled by functions, it has one slot >>for a dictionary where you store names and values/formulas. >> >>Go back to your example and arrange it so a and b are actual slots (data >>members? fields?) of the spreadsheet class. You can just stuff numbers in a: >> >> sheet1.a = 42 >> >>but b should be somehow associated with a rule when sheet1 is created. >>As I said in the other post, also associate an on-change callback with >>slots a and b. > > > I must be missing something - seems this should be easy using > __setattr__ and __getattr__. Then _literally_ there's just a > dict containing names and functions, but when you _use_ the > class it looks just like the above: Ah, but looks like is not enough. Suppose you have a GUI class from Tkinter. After a little more playing and fixing the huge gap described in the next paragraph you decide, Cripes! Kenny was right! This is very powerful. So now you want to subclass a Tkinter button and control whether it is enabled with a rule (the huge gap, btw). But the enabled flag of the super class is a native Python class slot. How would you handle that with your faux object system? Had you truly extended the Python class system you could just give the inherited slot a rule. Speaking of which... btw, You claimed "no lambda" but I did not see you doing a ruled value anywhere, and that is where you want the lambda. And in case you thinking your callbacks do that. No, you do not want on-change handlers propagating data to other slots, though that is a sound albeit primitive way of improving self-consistency of data in big apps. The productivity win with VisiCalc was that one simply writes rules that use other cells, and the system keeps track of what to update as any cell changes for you. You have that exactly backwards: every slot has to know what other slots to update. Ick. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From Mark.Geyzer at gmail.com Thu May 18 06:51:09 2006 From: Mark.Geyzer at gmail.com (volcano) Date: 18 May 2006 03:51:09 -0700 Subject: How to couple pyunit with GUI? In-Reply-To: <1147939937.192370.293530@g10g2000cwb.googlegroups.com> References: <1147879480.640335.252950@y43g2000cwc.googlegroups.com> <1147939937.192370.293530@g10g2000cwb.googlegroups.com> Message-ID: <1147949469.502158.299080@j73g2000cwa.googlegroups.com> Miki, toda, but it did not work for me. BTW, I have forgotten to mention - the implementation I develop should be multi-platform.If anything else comes to you mind - I'll be more than gateful to hear. Regards, Mark From diffuser78 at gmail.com Tue May 9 00:55:46 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 8 May 2006 21:55:46 -0700 Subject: Memory leak in Python In-Reply-To: <1147141448.837348.115470@y43g2000cwc.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <1147141448.837348.115470@y43g2000cwc.googlegroups.com> Message-ID: <1147150546.224299.284980@i40g2000cwc.googlegroups.com> Its kinda 65o lines of code...not the best idea to paste the code. compromise at gmail.com wrote: > Can you paste an example of the code you're using? From kkylheku at gmail.com Mon May 8 17:27:28 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 8 May 2006 14:27:28 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <pan.2006.05.06.03.54.17.404055@hastings.org> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> Message-ID: <1147123648.914726.212680@i39g2000cwa.googlegroups.com> Steve R. Hastings wrote: > On Fri, 05 May 2006 21:16:50 -0400, Ken Tilton wrote: > > The upshot of > > what he wrote is that it would be really hard to make semantically > > meaningful indentation work with lambda. > > Pretty much correct. The complete thought was that it would be painful > all out of proportion to the benefit. > > See, you don't need multi-line lambda, because you can do this: > > > def make_adder(x): > def adder_func(y): > sum = x + y > return sum > return adder_func Now imagine you had to do this with every object. def add_five(x) # return x + 5 <-- anonymous integer literal, not allowed!!! five = 5 # define it first return x + five Think about the ramifications of every object having to have a name in some environment, so that at the leaves of all expressions, only names appear, and literals can only be used in definitions of names. Also, what happens in the caller who invokes make_adder? Something like this: adder = make_adder(42) Or perhaps even something like this make_adder(2)(3) --> 5 Look, here the function has no name. Why is that allowed? If anonymous functions are undesireable, shouldn't there be a requirement that the result of make_adder has to be bound to a name, and then the name must be used? > Note that make_adder() doesn't use lambda, and yet it makes a custom > function with more than one line. Indented, even. That function is not exactly custom. What is custom are the environment bindings that it captures. The code body comes from the program itself. What about actually creating the source code of a function at run-time and compiling it? (let ((source-code (list 'lambda (list 'x 'y) ...))) (compile nil source-code)) Here, we are applying the compiler (available at run-time) to syntax which represents a function. The compiler analyzes the syntax and compiles the function for us, giving us an object that can be called. Without that syntax which can represent a function, what do you pass to the compiler? If we didn't have lambda in Lisp, we could still take advantage of the fact that the compiler can also take an interpreted function object and compile that, rather than source code. So we could put together an expression which looks like this: (flet ((some-name (x y) ...)) #'some-name) We could EVAL this expression, which would give us a function object, which can then be passed to COMPILE. So we have to involve the evaluator in addition to the compiler, and it only works because the compiler is flexible enough to accept function objects in addition to source code. > No; lambda is a bit more convenient. But this doesn't seem like a very > big issue worth a flame war. If GvR says multi-line lambda would make > the lexer more complicated and he doesn't think it's worth all the effort, > I don't see any need to argue about it. I.e. GvR is the supreme authority. If GvR rationalizes something as being good for himself, that's good enough for me and everyone else. > I won't say more, since Alex Martelli already pointed out that Google is > doing big things with Python and it seems to scale well for them. That's pretty amazing for something that doesn't even have a native compiler, and big mutexes in its intepreter core. Look at "docs.python.org" in section 8.1 en titled "Thread State and the Global Interpreter Lock": "The Python interpreter is not fully thread safe. In order to support multi-threaded Python programs, there's a global lock that must be held by the current thread before it can safely access Python objects. Without the lock, even the simplest operations could cause problems in a multi-threaded program: for example, when two threads simultaneously increment the reference count of the same object, the reference count could end up being incremented only once instead of twice. Therefore, the rule exists that only the thread that has acquired the global interpreter lock may operate on Python objects or call Python/C API functions. In order to support multi-threaded Python programs, the interpreter regularly releases and reacquires the lock -- by default, every 100 bytecode instructions (this can be changed with sys.setcheckinterval())." That doesn't mean you can't develop scalable solutions to all kinds of problems using Python. But it does mean that the scalability of the overall solution comes from architectural details that are not related to Python itself. Like, say, having lots of machines linked by a fast network, working on problems that decompose along those lines quite nicely. From fredrik at pythonware.com Thu May 18 10:31:45 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 16:31:45 +0200 Subject: Strange error In-Reply-To: <1147962206.900840.19130@38g2000cwa.googlegroups.com> References: <1147962206.900840.19130@38g2000cwa.googlegroups.com> Message-ID: <e4i0gh$gug$1@sea.gmane.org> WSobczuk at gmail.com wrote: > I have encountered a very strange error and I'm hoping that some Python > hackers here could give me insight on this. > > searchview.py file contains two functions: > def mysearch(indexname, request, c, page = 0, searchdburl = INDEX_URL, > query_add = {}, queries = [], form = True, limit = DEFAULT_LIMIT, tags > = {}, order = ''): > and > def search(findquery, path = None, page=0, tags = {}, order='', limit = > DEFAULT_LIMIT, queries=[], searchdburl = INDEX_URL): default values are evaluated once, when the function object is created. this is explained in the tutorial, in the language reference, and in the FAQ: http://pyfaq.infogami.com/why-are-default-values-shared-between-objects </F> From aleax at mac.com Sun May 14 01:27:39 2006 From: aleax at mac.com (Alex Martelli) Date: Sat, 13 May 2006 22:27:39 -0700 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> Message-ID: <1hfarom.1lfetjc18leddeN%aleax@mac.com> BartlebyScrivener <rpdooling at gmail.com> wrote: > Still new. I am trying to make a simple word count script. > > I found this in the great Python Cookbook, which allows me to process > every word in a file. But how do I use it to count the items generated? > > def words_of_file(thefilepath, line_to_words=str.split): > the_file = open(thefilepath) > for line in the_file: > for word in line_to_words(line): > yield word > the_file.close() > for word in words_of_file(thefilepath): > dosomethingwith(word) > > The best I could come up with: > > def words_of_file(thefilepath, line_to_words=str.split): > the_file = open(thefilepath) > for line in the_file: > for word in line_to_words(line): > yield word > the_file.close() > len(list(words_of_file(thefilepath))) > > But that seems clunky. My preference would be (with the original definition for words_of_the_file) to code numwords = sum(1 for w in words_of_the_file(thefilepath)) Alex From johnjsal at NOSPAMgmail.com Tue May 23 16:21:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 20:21:10 GMT Subject: how to change sys.path? In-Reply-To: <e4vn3u$brc$1@atlantis.news.tpi.pl> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <5aGcg.2150$No6.46806@news.tufts.edu> <e4vn3u$brc$1@atlantis.news.tpi.pl> Message-ID: <W8Kcg.2156$No6.46787@news.tufts.edu> Jarek Zgoda wrote: > John Salerno napisa?(a): > >>> yes, I mean I want change the sys.path value and save it for next >>> using. >>> I can change the value of sys.path, but I can't "save" it permanently. >>> There is no python_path environment on my pc, what the relationship >>> between it and the sys.path? >> In Windows, at least, you can create the PYTHONPATH variable and assign >> to it the paths of the directories you want Python to check for when >> running a script. > > Setting Windows envvar by changing os.environ dict will work only for > processes running in the same environment (i.e. in the same shell session). > I meant actually adding the PYTHONPATH variable to the environment variables list. From alanmk at hotmail.com Thu May 18 05:24:28 2006 From: alanmk at hotmail.com (Alan Kennedy) Date: 18 May 2006 02:24:28 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <1147944268.262819.13450@u72g2000cwu.googlegroups.com> [glomde] > i I would like to extend python so that you could create hiercical > tree structures (XML, HTML etc) easier and that resulting code would be > more readable than how you write today with packages like elementtree > and xist. > Any comments? Yes: it's ugly and unnecessary. Why would you want to change the language syntax just to make it easier to express markup directly in program code? Javascript just made that mistake with E4X: IMHO, it makes for some of the ugliest code. E4X reminds me of that Microsoft b*stardisation, XML Data Islands. http://www.w3schools.com/e4x/e4x_howto.asp http://en.wikipedia.org/wiki/E4X For a nice pythonic solution to representing markup directly in python code, you should check out stan. http://divmod.org/users/exarkun/nevow-api/public/nevow.stan-module.html Here's a nice stan example, taken from Kieran Holland's tutorial http://www.kieranholland.com/code/documentation/nevow-stan/ aDocument = tags.html[ tags.head[ tags.title["Hello, world!"] ], tags.body[ tags.h1[ "This is a complete XHTML document modeled in Stan." ], tags.p[ "This text is inside a paragraph tag." ], tags.div(style="color: blue; width: 200px; background-color: yellow;") [ "And this is a coloured div." ] ] ] That looks nice and simple, and no need to destroy the elegance of python to do it. regards, -- alan kennedy ------------------------------------------------------ email alan: http://xhaus.com/contact/alan From g.horvath at gmx.at Thu May 11 07:11:59 2006 From: g.horvath at gmx.at (Gregor Horvath) Date: Thu, 11 May 2006 13:11:59 +0200 Subject: Install libraries only without the program itself Message-ID: <e3v660$jqt$1@newsreader1.utanet.at> Hi, My application is a client/server in a LAN. I want to keep my programs .py files on a central File Server serving all clients. The clients should load those over the LAN every time they start the program since I expect that they are rapidly changing and I dont want to update each client seperatly. On the clients there should only be python and the necessary libraries and third party modules (sqlobject etc.) installed. How do I make a setup script that only installs the necessary things, without the program itself. Is there a tool for that? -- Servus, Gregor http://www.gregor-horvath.com From carol.chisholm at gmail.com Fri May 26 07:44:09 2006 From: carol.chisholm at gmail.com (carol.chisholm at gmail.com) Date: 26 May 2006 04:44:09 -0700 Subject: Python for my mum Message-ID: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> Someone has give my 78 year old mother a tool for learning French vocabulary written in Python. She has a plain vanilla Windows XP system and does not know what a compiler is. What can I tell her to do: - forget the helpful friend, and use more traditional means to do her home work - go to this asy to understand website (need some help here) and follow the instructions Many thanks From vinay_sajip at yahoo.co.uk Tue May 23 19:13:38 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 23 May 2006 16:13:38 -0700 Subject: logging In-Reply-To: <mailman.6101.1148366215.27775.python-list@python.org> References: <mailman.6101.1148366215.27775.python-list@python.org> Message-ID: <1148426018.334087.124160@i40g2000cwc.googlegroups.com> Baurzhan Ismagulov wrote: > Hello all, > > I want that each module has its own logger. I've defined the following > config file: > > [logger_root] > level=CRITICAL > handlers=console > > [logger_l01] > level=DEBUG > qualname=l01 > handlers=console > > I want logger_root to go to /dev/null, so I've configured it with level > CRITICAL. My understanding is that in this way debug messages are not > printed on logger_root's handler. However, running the program results > in the message being printed twice. What is the problem? You've defined the handler against both the root logger and l01. You only need it configured for the root logger - events passed to l01 will be passed to all handlers up the hierarchy. So remove the "handlers=console" line from [logger_l01] and it should print the message just once. Vinay Sajip From jjl at pobox.com Tue May 2 21:53:35 2006 From: jjl at pobox.com (John J. Lee) Date: 03 May 2006 01:53:35 +0000 Subject: urllib2 not support proxy on SSL connection? References: <1146604944.658622.119860@u72g2000cwu.googlegroups.com> <200605022336.13609.me+python@modelnine.org> Message-ID: <87wtd3ri00.fsf@pobox.com> Heiko Wundram <me+python at modelnine.org> writes: > Am Dienstag 02 Mai 2006 23:22 schrieb itay_k: > > Is it possible that urllib2 doesnt support for proxy over https > > connections? > > Are you sure this a proxy which is accessed by https, or rather a proxy that > supports CONNECT, and thus allows you to access https-sites? I'd guess the > latter, which I haven't gotten to work with urllib2 so far. [...] There's a patch on SF that implements this (CONNECT), but it's fairly nasty and would need rewriting to get into the stdlib. John From scott.daniels at acm.org Mon May 8 14:23:19 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 11:23:19 -0700 Subject: Getting HTTP responses - a python linkchecking script. In-Reply-To: <1147072270.475178.321030@v46g2000cwv.googlegroups.com> References: <1147056628.354150.116120@y43g2000cwc.googlegroups.com> <3vqt52hb9b1k1ddk1pkqu9k1qb0kalcmor@4ax.com> <1147072270.475178.321030@v46g2000cwv.googlegroups.com> Message-ID: <445f88df@nntp0.pdx.net> blair.bethwaite at gmail.com wrote: > Rene Pijlman wrote: >> blair.bethwaite at gmail.com: >>> with urllib2 it doesn't seem possible to get HTTP status codes. >> except urllib2.HTTPError, e: >> if e.code == 403: > > Thanks. Is there documentation for this available somewhere online, I > can't see it to obviously in the library reference? You can help by mentioning where you'd most expect to find it in a Python documentation bug (or enhancement) report. Then you to can be a Python contributor. --Scott David Daniels scott.daniels at acm.org From ronnyma at math.uio.no Mon May 15 14:41:27 2006 From: ronnyma at math.uio.no (Ronny Mandal) Date: Mon, 15 May 2006 20:41:27 +0200 Subject: OOP and Tkinter Message-ID: <7gih62p25k5krj9c5l9ot6tpt01c45e723@4ax.com> Hello. I am stuck; provided is the code and error-msg: file front_ui.py: class Front(object): _images = [] # Holds image refs to prevent GC def __init__(self, root): # Widget Initialization self._listbox_1 = Tkinter.Listbox(root, height = 0, width = 0, ... ) other file: from Front_ui import Front class CustomFront(Front): Front._listbox_1.insert( 0, 'foo' ) ... ... File "H:\My Documents\Komodo\Front.py", line 63, in CustomFront Front._listbox_1.insert( 0, foo' ) AttributeError: type object 'Front' has no attribute '_listbox_1' i.e., it cannot find the listbox! Strange, both files is in the same folder. What is wrong here? Thanks, Ronny Mandal From george.sakkis at gmail.com Wed May 24 10:12:14 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 24 May 2006 07:12:14 -0700 Subject: John Bokma harassment In-Reply-To: <1148466919.006694.191310@u72g2000cwu.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148466919.006694.191310@u72g2000cwu.googlegroups.com> Message-ID: <1148479934.506633.303710@g10g2000cwb.googlegroups.com> Alan wrote: > With apologies to Voltaire: > If Xah Lee did not exist, it would be necessary for John Bokma to > invent him. > > Xah and Bokma are both idiots, they truly deserve each other. The > sooner you killfile these two clowns, the happier you'll be. Well said, I couldn't put it better. From roy at panix.com Mon May 8 22:37:16 2006 From: roy at panix.com (Roy Smith) Date: Mon, 08 May 2006 22:37:16 -0400 Subject: which is better, string concatentation or substitution? References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <roy-A5FC8E.09284008052006@reader1.panix.com> <IWH7g.2053$No6.45672@news.tufts.edu> <e3nnv0$jbm$1@reader1.panix.com> <envv521lhcir4i9bpg2affcu2kg7gje41v@4ax.com> Message-ID: <roy-3BB5E8.22371608052006@reader1.panix.com> In article <envv521lhcir4i9bpg2affcu2kg7gje41v at 4ax.com>, Casey Hawthorne <caseyhHAMMER_TIME at istar.ca> wrote: > roy at panix.com (Roy Smith) wrote: > > >O(n^0), which is almost always written as O(1). This is a "constant > >time" algorithm, one which takes the same amount of steps to execute > >no matter how big the input is. For example, in python, you can > >write, "x = 'foo'". That assignment statement takes the same amount > >of time no matter how long the string is. All of these execute in the > >same number of steps: > > > > x = '' > > x = 'foo' > > x = 'a very long string with lots and lots of characters' > > > >We can say that "assignment is constant time", or "assignment is > >O(1)". > > Constant time if converted to byte code or compiled? > > O(n) in string length if being interpreted? Compiled, byte-code, or interpreted has nothing to do with it. Assignment would be O(n) if it involved copying the string (as it might in C++ using std:string, for example), but in Python, assignnment simply involves binding a new name to an existing object. From aleaxit at yahoo.com Sun May 7 14:57:55 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 11:57:55 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1146990071.634244.83380@i39g2000cwa.googlegroups.com> <871wv6b3y0.fsf@rpi.edu> <1146996240.867564.139490@u72g2000cwu.googlegroups.com> Message-ID: <1heyqxs.4dbeogv9o591N%aleaxit@yahoo.com> <brian at sweetapp.com> wrote: ... > >> 2. There has to be a mechanism where an organization can add > >> developers - even if it is only for new projects. Python advocates > > > > Obviously. > > It's good that you agree. I think that the ability to add new > productive developers to a project/team/organization is at least part > of what Alex means by "scaleability". I'm sure that he will correct me > if I am wrong. I agree with your formulation, just not with your spelling of "scalability";-). > [1] I'm considering introducing bugs or misdesigns that have to be > fixed > as part of training for the purposes of this discussion. Also the Actually, doing it _deliberately_ (on "training projects" for new people just coming onboard) might be a good training technique; what you learn by finding and fixing bugs nicely complements what you learn by studying "good" example code. I do not know of this technique being widely used in real-life training, either by firms or universities, but I'd love to learn about counterexamples. > time needed to learn to coordinate with the rest of the team. Pair programming can help a lot with this (in any language, I believe) if the pairing is carefully chosen and rotated for the purpose. Alex From vedranf at riteh.hr Tue May 2 10:28:03 2006 From: vedranf at riteh.hr (=?UTF-8?B?VmVkcmFuIEZ1cmHEjQ==?=) Date: Tue, 02 May 2006 16:28:03 +0200 Subject: Strange result with math.atan2() In-Reply-To: <44575f1d$0$16971$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <chuji3xd2m.ln2@pollux.home> <44575f1d$0$16971$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <ks6ki3xefk.ln2@pollux.home> Ben Caradoc-Davies wrote: > Vedran Fura? wrote: >> I think that this results must be the same: >> In [3]: math.atan2(-0.0,-1) >> Out[3]: -3.1415926535897931 >> In [4]: math.atan2(-0,-1) >> Out[4]: 3.1415926535897931 > > -0 is converted to 0, then to 0.0 for calculation, losing the sign. You > might as well write 0.0 instead of -0 > > The behaviour of atan2 conforms to the ISO C99 standard (Python is > implemented in C). Changing the sign of the first argument changes the > sign of the output, with no special treatment for zero. > > http://www.ugcs.caltech.edu/manuals/libs/mpfr-2.2.0/mpfr_22.html Well, here I can read: Special values are currently handled as described in the ISO C99 standard for the atan2 function (note this may change in future versions): * atan2(+0, -0) returns +Pi. * atan2(-0, -0) returns -Pi. /* wrong too */ * atan2(+0, +0) returns +0. * atan2(-0, +0) returns -0. /* wrong too */ * atan2(+0, x) returns +Pi for x < 0. * atan2(-0, x) returns -Pi for x < 0 ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ And the formula (also from that site): if x < 0, atan2(y, x) = sign(y)*(PI - atan (abs(y/x))) ^^^^^^^ So, you can convert -0 to 0, but you must multiply the result with sign of y, which is '-' (minus). Also, octave: octave2.9:1> atan2(-0,-1) ans = -3.1416 or matlab: >> atan2(-0,-5) ans = -3.1416 From robert.kern at gmail.com Fri May 5 18:57:21 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 05 May 2006 17:57:21 -0500 Subject: NaN handling In-Reply-To: <125nlbgm8l1fi17@corp.supernews.com> References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> <mailman.5402.1146867973.27775.python-list@python.org> <125nlbgm8l1fi17@corp.supernews.com> Message-ID: <e3gl8i$9rk$1@sea.gmane.org> Grant Edwards wrote: > On 2006-05-05, Robert Kern <robert.kern at gmail.com> wrote: >>Pure Python has a similar, but somewhat less flexible method, on UNIX platforms. >> >> http://docs.python.org/dev/lib/module-fpectl.html > > For which "Unix" platforms? It's not there under Linux: > > Python 2.4.2 (#1, Feb 14 2006, 07:55:13) > [GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>>>import fpectl > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > ImportError: No module named fpectl You might have to enable it during the Python build process. -- 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 tjreedy at udel.edu Sat May 27 01:55:54 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 May 2006 01:55:54 -0400 Subject: iterator? way of generating all possible combinations? References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> Message-ID: <e58pla$cn$1@sea.gmane.org> <akameswaran at gmail.com> wrote in message news:1148705122.317512.294540 at i40g2000cwc.googlegroups.com... > Ok, this is really irritating me. I'm sure there are different ways of > doing this - I'm interested in the algo, not the practical solution, > I'm more trying to play with iterators and recursion. I want to create > a program that generates every possible combination of a set of a n > dice, with s sides. Are the dice identical or distinguishable (marked). In other words, with 2 dice, is 1,2 the same as 2,1 or different? Note that in most dice games, such as craps, the dice are not distinguished, but probability calculations must treast them as if they were to get the elementary events. Terry Jan Reedy From robert.kern at gmail.com Fri May 26 18:49:13 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 26 May 2006 17:49:13 -0500 Subject: Thread vs. generator problem In-Reply-To: <7xodxkmmzl.fsf_-_@ruckus.brouhaha.com> References: <7xodxkmmzl.fsf_-_@ruckus.brouhaha.com> Message-ID: <e580l7$1ig$1@sea.gmane.org> Paul Rubin wrote: > As I understand it, generators are supposed to run til they hit a > yield statement: > > import time > def f(): > print 1 > time.sleep(3) > for i in range(2,5): > yield i > > for k in f(): > print k > > prints "1" immediately, sleeps for 3 seconds, then prints 2, 3, and 4 > without pausing, as expected. When I try to do it in a separate thread: > > import time, itertools > def remote_iterate(iterator, cachesize=5): > # run iterator in a separate thread and yield its values > q = Queue.Queue(cachesize) > def f(): > print 'thread started' > for x in iterator: > q.put(x) > threading.Thread(target=f).start() > while True: > yield q.get() > > g = remote_iterate(itertools.count) > print 'zzz...' > time.sleep(3) > print 'hi' > for i in range(5): > print g.next() > > I'd expect to see 'thread started' immediately, then 'zzz...', then a 3 > second pause, then 'hi', then the numbers 0..4. Instead, the thread > doesn't start until the 3 second pause has ended. My 10-second analysis is that *none* the body of a generator runs until a value is requested from it. In [3]: def f(): ...: print 'Starting f' ...: for i in range(3): ...: yield i ...: ...: In [4]: g = f() In [5]: for i in g: ...: print i ...: ...: Starting f 0 1 2 In your first example, you instantiate the generator and then iterate over it immediately; in your second, you separate the two things. I don't think threads have anything to do with it. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From john at castleamber.com Wed May 24 11:00:06 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:00:06 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <Xns97CD65BDCF177castleamber@130.133.1.4> fup to poster "Xah Lee" <xah at xahlee.org> wrote: > I'm sorry to trouble everyone. But as you might know, due to my > controversial writings and style, You're mistaken. Not that I or many other people with some brains had expected anything else. The problem is that you crosspost to 5 groups (5, which I am sure is a limitation Google Groups set to you, and has nothing to do with you respecting Usenet a bit) for the sole purpose of spamvertizing your website. > recently John Bokma lobbied people to > complaint to my web hosting provider. After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. Which shows that your actions are frowned upon by others, for good reasons. Of course you are going in cry baby mode now. > I'm not sure I will be able to keep using their service, but I do hope > so. I do not like to post off-topic messages, Liar. > but this is newsgroup > incidence is getting out of hand, and I wish people to know about it. > > I wrote some full detail here: > http://xahlee.org/Periodic_dosage_dir/t2/harassment.html You mean your brain farted again some bullshit. > If you believe this lobbying to my webhosting provider is unjust, > please write to my web hosting provider abuse at dreamhost.com dreamhost has made a decission, a right one IMO. And now you ask people to harass them more? You really are just a pathetic little shit now aren't you? Not even the balls nor the guts to fix the issue that you are. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From nobody at 127.0.0.1 Tue May 2 22:30:12 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 02:30:12 GMT Subject: assignment in if References: <87iroodnqz.fsf@localhost.localdomain> <roy-746AEB.19412402052006@reader1.panix.com> <lgT5g.66665$F_3.13831@newssvr29.news.prodigy.net> <hQT5g.979$fb2.319@newssvr27.news.prodigy.net> Message-ID: <UAU5g.72044$H71.32831@newssvr13.news.prodigy.com> Edward Elliott wrote: > Edward Elliott wrote: >> <nitpick> assignemnt is actually an expression in those languages, not a >> statement. </nitpick> > > s/statement/operator/ <shakes head> it was probably clearer the first time, but let me rephrase: in C/Java, assignment is neither a statement not an operator. it is an expression involving a certain operator. that operator (not so) coincidentally happens to be the assignment operator, or one of its variants. ah forget it, replying to your reply to yourself is probably illegal... From bnblazer at gmail.com Mon May 22 17:15:45 2006 From: bnblazer at gmail.com (Brian) Date: 22 May 2006 14:15:45 -0700 Subject: problem with my regex? Message-ID: <1148332545.563949.102290@38g2000cwa.googlegroups.com> I have a simple script below that is causing me some problems and I am having a hard time tracking them down. Here is the code: import urllib import re def getPicLinks(): found = [] try: page = urllib.urlopen("http://continuouswave.com/whaler/cetacea/") except: print "ERROR RREADING PAGE." sys.exit() page1 = page.read() cetLinks = re.compile("cetaceaPage..\.html", page1) for line in page1: found.append(cetLinks.findall(line)) print found This is the error message: "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre_parse.py", line 396, in _parse if state.flags & SRE_FLAG_VERBOSE: TypeError: unsupported operand type(s) for &: 'str' and 'int' I am trying to extract the links on a web page that have a similar pattern. Here is an example of the html source: <HR> <P><SMALL><A HREF="photoLog.html">PHOTO-LOG</A><br> <A HREF="guide.html">How-To-Submit</A><BR><A HREF="cetaceaPage01.html">01</A> | <A HREF="cetaceaPage02.html">02</A> | <A HREF="cetaceaPage03.html">03</A> | <A HREF="cetaceaPage04.html">04</A> | <A HREF="cetaceaPage05.html">05</A> | <A HREF="cetaceaPage06.html">06</A> | <A HREF="cetaceaPage07.html">07</A> | <A HREF="cetaceaPage08.html">08</A> | <A HREF="cetaceaPage09.html">09</A> | <A HREF="cetaceaPage10.html">10</A> <BR><A> My problem is that I can't seem to be able to figure out what is going wrong here. Mostly because I am a bit confused by the error message as it points to a file (presumable part of re) that I am unfamiliar with, and I am a bit new with python. Any help is greatly appreciated, as is your patience. Brian From danb_83 at yahoo.com Sat May 6 04:30:24 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 6 May 2006 01:30:24 -0700 Subject: NaN handling References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> Message-ID: <1146904224.359966.195340@j73g2000cwa.googlegroups.com> Ivan Vinogradov wrote: > > <snip> > > NaNs are handled. > > Throwing an exception would be nice in regular Python (non-scipy). > > This works to catch NaN on OSX and Linux: > > # assuming x is a number > if x+1==x or x!=x: > #x is NaN x != x works, but: >>> x = 1e100 >>> x + 1 == x True From hancock at anansispaceworks.com Fri May 19 10:27:48 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 19 May 2006 14:27:48 +0000 Subject: number of different lines in a file In-Reply-To: <e4jnbd$vmg$1@sea.gmane.org> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <mailman.5913.1147991572.27775.python-list@python.org> <iY7bg.3778$x4.261@newsread3.news.pas.earthlink.net> <e4jnbd$vmg$1@sea.gmane.org> Message-ID: <446DD5E4.5090701@anansispaceworks.com> Fredrik Lundh wrote: >a for loop inside square brackets is a "list comprehension", and the >result is a list. if you use a list comprehension inside a function >call, the full list is built *before* the function is called. in this >case, this would mean that the entire file would be read into memory >before the set was constructed. > >if you change the square brackets to ordinary parentheses, you get a >generator expression instead: > > http://pyref.infogami.com/generator-expressions > >the generator expression results in an iterator object that calculates >the values one by one. if you pass it to a function that expects an >iterator, that function will end up "running the for loop itself", and >no extra storage is needed. (in this case, you still need memory to >hold the set, of course, so the difference between a list comprehension >and a generator expression will only matter if you have lots of duplicates). > > This is interesting. I wonder how this compares to uniq in performance? I actually had this problem a couple of weeks ago when I discovered that my son's .Xsession file was 26 GB and had filled the disk partition (!). Apparently some games he was playing were spewing out a lot of errors, and I wanted to find out which ones were at fault. Basically, uniq died on this task (well, it probably was working, but not completed after over 10 hours). I was using it something like this: cat Xsession.errors | uniq > Xsession.uniq It never occured to me to use the Python dict/set approach. Now I wonder if it would've worked better somehow. Of course my file was 26,000 X larger than the one in this problem, and definitely would not fit in memory. I suspect that there were as many as a million duplicates for some messages in that file. Would the generator version above have helped me out, I wonder? Unfortunately, I deleted the file, so I can't really try it out. I suppose I could create synthetic data with the logging module to try it out. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From percivall at gmail.com Sat May 27 07:22:39 2006 From: percivall at gmail.com (Simon Percivall) Date: 27 May 2006 04:22:39 -0700 Subject: Pyrex speed References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> <4dqq38F1bi6btU1@uni-berlin.de> <1148728491.640293.298470@38g2000cwa.googlegroups.com> Message-ID: <1148728959.466305.23870@u72g2000cwu.googlegroups.com> You can gain substantial speed-ups in very certain cases, but the main point of Pyrex is ease of wrapping, not of speeding-up. Depending on what you're doing, rewriting in Pyrex or even in C, using the Python/C API directly, might not gain you much. From fredrik at pythonware.com Thu May 4 03:30:29 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 09:30:29 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com><4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com><mailman.5248.1146637412.27775.python-list@python.org> <445880e8$0$27057$626a54ce@news.free.fr> Message-ID: <e3caip$3c0$1@sea.gmane.org> Christophe wrote: > That's easy, since A is a symbolic constant know at compile time, and > since it's a known mutable objet, the code once compiled will be > equivalent to: > > >>> b = [[]] > > >>> # much later > >>> b|0].append('1') the OP talked about constants as names for immutable objects, not pre- processor macros. but alright, using the "symbolic constant" approach, what would this print ? >>> def foo(var): ... var.append('1') ... print var ... >>> b = [] >>> foo(b) >>> foo(b) and this ? >>> constant A = [] >>> print A is A </F> From timo.stamm at arcor.de Wed May 24 11:36:22 2006 From: timo.stamm at arcor.de (Timo Stamm) Date: Wed, 24 May 2006 17:36:22 +0200 Subject: John Bokma harassment In-Reply-To: <Xns97CD68305314Ccastleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> Message-ID: <44747d86$0$11075$9b4e6d93@newsread4.arcor-online.net> John Bokma schrieb: > Timo Stamm <timo.stamm at arcor.de> wrote: > >> Tim N. van der Leeuw schrieb: > [...] >>> but since I've stopped following threads originated by him >> That's all you need to do if you are not interested in his posts. > > You're mistaken. All you need to do is report it. Why the hell should I do that? I find his postings interesting. Of course I am just a pathetic, egocentric sock puppet with a dent in my ego and not using my brains, according to your logic. Thank you. > After some time Xah will either walk in line with the rest of the world > [...] You sound like a villain from a James Bond movie. Timo From fulvio at pc.jaring.my Tue May 2 11:23:12 2006 From: fulvio at pc.jaring.my (Fulvio) Date: Tue, 2 May 2006 23:23:12 +0800 Subject: stripping blanks In-Reply-To: <445720fd$1_2@news.estpak.ee> References: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> <445720fd$1_2@news.estpak.ee> Message-ID: <200605022323.12710.fulvio@pc.jaring.my> Alle 17:06, marted? 02 maggio 2006, seeker ha scritto: > ? ? ?printLine = line.rstrip("\n") I think that nobody considered if the text has (\r) or (\r\n) or (\n) at the end of the line(s). From m.yanowitz at kearfott.com Thu May 18 11:52:54 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 18 May 2006 11:52:54 -0400 Subject: Tkinter Dialog Management problems: In-Reply-To: <ops9q43zmcrqur0o@eb.pragmadev> Message-ID: <HGEOKIAPAMCIFPPBDALKAEJNCAAA.m.yanowitz@kearfott.com> > Hello: > > Below I have included a stripped down version of the GUI I am working > on. > It contains 2 dialog boxes - one main and one settings. It has the > following > problems, probably all related, that I am hoping someone knows what I am > doing wrong: > > 1) Pressing the Settings.. Button multiple times, brings up many > instances > of the Settings Panel. I just want it to bring up one. Is there an > easy > way to do that? In fact, the two windows you created are not dialogs; they're just windows. To turn a window into an actual "dialog", i.e basically to make it modal, you have to do the following operations (supposing your dialog window is named dlg and your main window in named root): ## Ensure only window can receive user events dlg.grab_set() ## Force Dialog to stay on top of main window dlg.transient(root) ## Wait for dialog to be destroyed root.wait_window(dlg) > 2) Pressing the Done button in the Settings Panel, just erases the Done > button > (and any other widgets in the Panel). It does not dismiss the Panel. > Pressing > the X button does work. What callback is that? Can I make the Done > button > call > that instead? How? This is not the way it works. In fact, what you did wrong is something that has been around for years in some Tkinter tutorial(s): you made your classes inherit from Frame. This is a Bad Idea: a Frame is not a window, but only a generic container. There are 2 classes for windows: Tk for the main window and Toplevel for all others. They both also act as containers, so you can do in them everything you do in Frames. So make your ScriptDialog inherit from Tk, your SettingsDialog inherit from Toplevel, remove all explicit creations of Tkinter.Tk or Tkinter.Toplevel and instantiate your classes instead. Then calling destroy on either on the dialogs will actually close the window. > 3) Pressing the Done button from the Main Panel has no effect? Why not? > It > used > to work (self.quit()). Again, I would like to call whatever is called > when the > X button (top Right corner) is pressed. This should work. BTW, your "done" method is not needed: creating the Button with command=self.quit works without problem. Thanks. That helped alot. However it leaves a couple very minor problems which I think I can live with. 1) It brings up an empty additional 'main window'. I have tried using the Tkinter.NoDefaultRoot() option, but run into other problems with other things not defined. NameError: global name '_default_root' is not defined Exception exceptions.AttributeError: "IntVar instance has no attribute '_tk'" in <bound method IntVar.__del__ of <Tkinter.IntVar instance at 0x009C7990>> ignored 2) By deriving the 'dialog' from Tk, existing calls to self.pack() no longer are valid, but they don't appear to be necessary. My only 'Tkinter tutorial' is what is included in Orielly's "Programming Python". Still looking for a good tutorial. I am not clear what the difference between Tk() and Toplevel() are. They seem totally interchangeable. From xah at xahlee.org Sun May 14 22:04:40 2006 From: xah at xahlee.org (Xah Lee) Date: 14 May 2006 19:04:40 -0700 Subject: Tabs versus Spaces in Source Code Message-ID: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Tabs versus Spaces in Source Code Xah Lee, 2006-05-13 In coding a computer program, there's often the choices of tabs or spaces for code indentation. There is a large amount of confusion about which is better. It has become what's known as ?religious war? ? a heated fight over trivia. In this essay, i like to explain what is the situation behind it, and which is proper. Simply put, tabs is proper, and spaces are improper. Why? This may seem ridiculously simple given the de facto ball of confusion: the semantics of tabs is what indenting is about, while, using spaces to align code is a hack. Now, tech geekers may object this simple conclusion because they itch to drivel about different editors and so on. The alleged problem created by tabs as seen by the industry coders are caused by two things: (1) tech geeker's sloppiness and lack of critical thinking which lead them to not understanding the semantic purposes of tab and space characters. (2) Due to the first reason, they have created and propagated a massive none-understanding and mis-use, to the degree that many tools (e.g. vi) does not deal with tabs well and using spaces to align code has become widely practiced, so that in the end spaces seem to be actually better by popularity and seeming simplicity. In short, this is a phenomenon of misunderstanding begetting a snowball of misunderstanding, such that it created a cultural milieu to embrace this malpractice and kick what is true or proper. Situations like this happens a lot in unix. For one non-unix example, is the file name's suffix known as ?extension?, where the code of file's type became part of the file name. (e.g. ?.txt?, ?.html?, ?.jpg?). Another well-known example is HTML practices in the industry, where badly designed tags from corporation's competitive greed, and stupid coding and misunderstanding by coders and their tools are so wide-spread such that they force the correct way to the side by the eventual standardization caused by sheer quantity of inproper but set practice. Now, tech geekers may still object, that using tabs requires the editors to set their positions, and plain files don't carry that information. This is a good question, and the solution is to advance the sciences such that your source code in some way embed such information. This would be progress. However, this is never thought of because the ?unix philosophies? already conditioned people to hack and be shallow. In this case, many will simply use the character intended to separate words for the purpose of indentation or alignment, and spread the practice with militant drivels. Now, given the already messed up situation of the tabs vs spaces by the unixers and unix brain-washing of the coders in the industry... Which should we use today? I do not have a good proposition, other than just use whichever that works for you but put more critical thinking into things to prevent mishaps like this. Tabs vs Spaces can be thought of as parameters vs hard-coded values, or HTML vs ascii format, or XML/CSS vs HTML 4, or structural vs visual, or semantic vs format. In these, it is always easy to convert from the former to the latter, but near impossible from the latter to the former. And, that is because the former encodes information that is lost in the latter. If we look at the issue of tabs vs spaces, indeed, it is easy to convert tabs to spaces in a source code, but more difficult to convert from spaces to tabs. Because, tabs as indentation actually contains the semantic information about indentation. With spaces, this critical information is lost in space. This issue is intimately related to another issue in source code: soft-wrapped lines versus physical, hard-wrapped lines by EOL (end of line character). This issue has far more consequences than tabs vs spaces, and the unixer's unthinking has made far-reaching damages in the computing industry. Due to unix's EOL ways of thinking, it has created languages based on EOL (just about ALL languages except the Lisp family and Mathematica) and tools based on EOL (cvs, diff, grep, and basically every tool in unix), thoughts based on EOL (software value estimation by counting EOL, hard-coded email quoting system by ?>? prefix, and silent line-truncations in many unix tools), such that any progress or development towards a ?algorithmic code unit? concept or language syntaxes are suppressed. I have not written a full account on this issue, but i've touched it in this essay: ?The Harm of hard-wrapping Lines?, at http://xahlee.org/UnixResource_dir/writ/hard-wrap.html ---- This post is archived at: http://xahlee.org/UnixResource_dir/writ/tabs_vs_spaces.html Xah xah at xahlee.org ? http://xahlee.org/ From xah at xahlee.org Wed May 31 09:51:14 2006 From: xah at xahlee.org (Xah Lee) Date: 31 May 2006 06:51:14 -0700 Subject: John Bokma harassment In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <1149083474.097849.262460@i40g2000cwc.googlegroups.com> Thanks to the great many people who has written to my ISP in support of me. I'm sorry to say, it looks like they will be killing my account anyhow. I have exchanged a couple letters with the guy at my web host and he is not changing the decision. Of this thread, i think 2/3 or 3/4 supported my view that this constitutes a harassment and the canceling of my account is not right, even if some disliked my writings. However, there are a few who has made accusations because of my alleged ?spam? or ?abuse? of newsgroups. I've been considering of writing a single essay to reply or explain these wrongful accusations. Or, perhaps these people prefer me to write short replies at quantity as they do, so that i'm ?in the community? or ?not using newsgroups as a blog?. In my opinion, making multiple short, fast replies is one problem that plagues and perpetuates the newsgroups nature of drivels and brainlessness. Most people who have problem with me simply because i sound cocky and do not bow to them. Another point i'd like to make, is about cross-posting. Tech geekers, due to their pissing male nature, often turns a cross-posted messages to a flamewar if the message contained any slight possibility of being perceived as sensitive. (students in fact constitute a significant portion, if not majority, of the newsgroup demograph) The problem isn't cross-posting itself, but the tech geekers themselves. As Steve Yegge has pointed out in his essay ?Software Needs Philosophers?, that languages and its people are full of religious hot-air. And, computing languages and its people, are forever ignorant and blindly fanatical of their own and attack outsiders. When i learned Python in 2005, i thought it is a great language that remedies the problems created by the Perl cult. But as i realized, the Python people are as militant, poor in knowledge, and in fact ignorant of computer languages and constantly propagandize their own and attack others. The point i want to make here, is that the taboo of cross-posting is in fact a contributor to this problem. Most languages stay blindly in their own community, oblivious to the nature or facts of computing languages outside of their world. If there are more relevant cross-posting, then this problem can be lessened. I have in fact already composed 7 replies to some the accusers of my alleged abuse of newsgroups. If people like me to post them as a remedy of me ?using newsgroups like a personal blog?, i'd be happy to. As to dreamhost my webhosting company canceling my account, i will try to reason with them, and see what is the final outcome. They have the legal right to kick me because in the contract that allowed them to do so with 30 days advanced noticed and without cause. However, it is my interest and my right, if they actually do kick me in the end, i'll try to contact Electronic Frontier Foundation and Better Business bureau for whatever advice or action i can solicit. Meanwhile, if you do know a web hosting company that can take some 80 G of bandwidth/month for less than $25 a month, please let me know! (i do hope if someone here runs a hosting business and can host my site. I will certainly return the favor.) Thanks. Xah xah at xahlee.org ? http://xahlee.org/ Xah Lee wrote: > I'm sorry to trouble everyone. But as you might know, due to my > controversial writings and style, recently John Bokma lobbied people to > complaint to my web hosting provider. After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. > > I'm not sure I will be able to keep using their service, but I do hope > so. I do not like to post off-topic messages, but this is newsgroup > incidence is getting out of hand, and I wish people to know about it. > > I wrote some full detail here: > http://xahlee.org/Periodic_dosage_dir/t2/harassment.html > > If you believe this lobbying to my webhosting provider is unjust, > please write to my web hosting provider abuse at dreamhost.com > > Your help is appreciated. Thank you. From junk.rubbish at alma-services.abel.co.uk Wed May 3 16:38:21 2006 From: junk.rubbish at alma-services.abel.co.uk (Sandy) Date: Wed, 3 May 2006 21:38:21 +0100 Subject: SciTE: Printing in Black & White References: <0DcfmOAcMoVENwUq@alma-services.abel.co.uk> Message-ID: <qq3IcMA9SRWENwcC@alma-services.abel.co.uk> Alexander Anderson: > ...I like to study large files of (hobby) code on paper. I have a > black and white bubble-jet printer. However, my (Win NT4) screen > syntax-highlighting setup has a couple of problems when it comes to > doing print-outs. > > The _chief_ problem is that my on-screen background colour is not > bright white -- it's an off-white cream, which is so much easier on my > eyes: There are several properties that tweak printing listed in the documentation. Perhaps you want print.colour.mode=2. Neil [ copied from the SciTE-interest mailing list, http://mailman.lyra.org/mailman/listinfo/scite-interest ] From fredrik at pythonware.com Fri May 19 11:40:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 17:40:16 +0200 Subject: Exception style (was: calling python functions using variables) References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com><mailman.5934.1148032680.27775.python-list@python.org><446da180$0$10184$636a55ce@news.free.fr><126rjus43k450df@corp.supernews.com> <9121k3-hjm.ln1@lairds.us> Message-ID: <e4kot0$lbn$1@sea.gmane.org> Cameron Laird wrote: > Guys, I try--I try *hard*--to accept the BetterToAskForgiveness > gospel, but this situation illustrates the discomfort I consistently > feel: how do I know that the NameError means VARIABLE didn't resolve, > rather than that it did, but that evaluation of commands.VARIABLE() > itself didn't throw a NameError? My usual answer: umm, unless I go > to efforts to prevent it, I *don't* know that didn't happen. two notes: 1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError. 2) as you point out, doing too much inside a single try/except often results in hard- to-find errors and confusing error messages. the try-except-else pattern comes in handy in cases like this: try: f = getattr(commands, name) except AttributeError: print "command", name, "not known" else: f() </F> From jordan.taylor2 at gmail.com Wed May 24 09:58:31 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 24 May 2006 06:58:31 -0700 Subject: Access C++, Java APIs from Python.. In-Reply-To: <mailman.6138.1148451960.27775.python-list@python.org> References: <mailman.23185.1148370303.27774.python-list@python.org> <mailman.6138.1148451960.27775.python-list@python.org> Message-ID: <1148479111.673828.285160@i40g2000cwc.googlegroups.com> check out the pywin32 extension by Mark Hammond From nospam at nospam.nospam Mon May 1 06:22:59 2006 From: nospam at nospam.nospam (Giandomenico Sica) Date: Mon, 1 May 2006 12:22:59 +0200 Subject: An Atlas of Graphs with Python Message-ID: <4455e186$0$14794$4fafbaef@reader4.news.tin.it> Call for Cooperation An Atlas of Linguistic Graphs I'm a researcher in graph theory and networks. I'm working about a project connected with the theory and the applications of linguistic graphs, which are mathematical structures useful to represent languages and consequently to manage the organization of data in different kinds of scientific fields. At the present I'm developing an application of these graphs to medicine, specifically related to the ontology of clinical diseases. And now to the purpose of this message, which is to ask if someone in this list can be interested in collaborating with me about the construction of an open source software useful to represent, to analyse and to compare linguistic graphs. I've developed the project but don't have the necessary programming skills to proceed with the creation of the code. The software would be distributed in public domain and the collaboration is free and voluntary. I really hope that someone can be interested. In the case, please feel free to contact me by using my private e-mail address. I'll be pleased to send the complete documentation related to the project. Really many thanks. All the best, Giandomenico Sica Faculty of Philosophy Leiden University giandomenico.sica at polimetrica.com Publications http://www.polimetrica.com/polimetrica/view/people/Sica,_Giandomenico.html 1st World Congress and School on Universal Logic http://www.uni-log.org From nospam at nospam.com Fri May 19 15:32:53 2006 From: nospam at nospam.com (3c273) Date: Fri, 19 May 2006 12:32:53 -0700 Subject: Why does the _winreg module start with an underscore References: <e4l19e02mm9@enews3.newsguy.com> <K5GdnVSKDaAwhPPZnZ2dnUVZ_vydnZ2d@speakeasy.net> Message-ID: <e4l6h50hcj@enews1.newsguy.com> "Erik Max Francis" <max at alcyone.com> wrote in message news:K5GdnVSKDaAwhPPZnZ2dnUVZ_vydnZ2d at speakeasy.net... > 3c273 wrote: > > > Does it signify something? Just curious. > > Dear quasar, > > Typically an identifier starting with an underscore signifies something > that is not intended to be exposed as part of a public API. In other > words, it's an implementation detail in whatever you're using and as > such you probably shouldn't use it or rely on it, unless you know the > internal details very well. An identifier starting with _two_ > underscores is automatically mangled in a way that makes it more > difficult (but not impossible) for external clients to accidentally use > them. > Thanks for the explanation. (Fellow astronomer?) Louis From heikki at osafoundation.org Mon May 22 13:30:25 2006 From: heikki at osafoundation.org (heikki at osafoundation.org) Date: 22 May 2006 10:30:25 -0700 Subject: PHP's openssl_sign() using M2Crypto? References: <slrne6v5vk.f2c.usenet2@localhost.localdomain> Message-ID: <1148319025.745324.171890@i40g2000cwc.googlegroups.com> KW wrote: > The openssl module in PHP basicly does this (C code): > EVP_SignInit(&md_ctx, EVP_sha1()); > EVP_SignUpdate(&md_ctx, data, data_len); > EVP_SignFinal(&md_ctx, sigbuf, &siglen, pkey); > > Looks like some magic is used to get pkey, I think that's what I'm missing. > See php_openssl_evp_from_zval() in PHP's ext/openssl/openssl.c. > > I've tried the following: > key = M2Crypto.EVP.load_key(keyfile, lambda x: passphr) > hmac = M2Crypto.EVP.HMAC(key, 'sha1') > hmac.update(message) > hmac.final() Does this work?: key = M2Crypto.EVP.load_key(keyfile, lambda x: passphr) key.sign_init() key.sign_update(message) signature = key.final() > Unfortunately M2Crypto documentation is practically nonexistent.. A lot of the OpenSSL documentation works fine, the names are usually straight mapping. From maha.murali at gmail.com Wed May 10 10:52:42 2006 From: maha.murali at gmail.com (Murali) Date: 10 May 2006 07:52:42 -0700 Subject: reusing parts of a string in RE matches? In-Reply-To: <YMm8g.2077$No6.45935@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> Message-ID: <1147272762.242351.49860@u72g2000cwu.googlegroups.com> John Salerno wrote: > So my question is, how can find all occurrences of a pattern in a > string, including overlapping matches? I figure it has something to do > with look-ahead and look-behind, but I've only gotten this far: > > import re > string = 'abababababababab' > pattern = re.compile(r'ab(?=a)') > m = pattern.findall(string) > Why not something like import re string = 'abababababababab' pattern = re.compile(r"^aba") ans = [] for x in xrange(len(string)): m = pattern.match(string[x:]) if m: ans.append( (x+m.start(),x+m.end())) # now ans is a list of pairs (p,q) where the substring string[p:q] matches pattern - Murali From steve at holdenweb.com Thu May 25 17:05:12 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 25 May 2006 22:05:12 +0100 Subject: John Bokma harassment In-Reply-To: <e9e3813b0605240847g6e21dcdeyc3c8d50cc093b3f7@mail.gmail.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148484597.410529.219960@j33g2000cwa.googlegroups.com> <e9e3813b0605240847g6e21dcdeyc3c8d50cc093b3f7@mail.gmail.com> Message-ID: <e55660$r9q$1@sea.gmane.org> Robert Boyd wrote: > On 24 May 2006 08:29:57 -0700, Rune Strand <rune.strand at gmail.com> wrote: > > >>I can just declare my support. Reading Mr. Bokmas comments below [*] >>certainly makes my suport stronger. >> > > > I sent an email in support of Xah, which I wouldn't have bothered to > do had I not read the rapid-fire posts from Bokma which were abusive, > insulting, and arrogant. Xah's posts often make me roll my eyes, or I > skip them, but sometimes (and more so lately) they have been > intriguing and foster thought-provoking replies. I'd prefer debate and > discussion be fostered, rather than squelched. But what does this > clueless sock-puppet know? ;) I too wrote to XL's hosting company pointing out that while he might be an irritant he wasn't particularly abusive. Bokma, on the other hand, can be. I don't like either of them much, but at least Xah Lee insults everyone while Bokma appears to resort to ad hominem attacks frequently. -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From shejo284 at gmail.com Wed May 24 03:14:57 2006 From: shejo284 at gmail.com (Sheldon) Date: 24 May 2006 00:14:57 -0700 Subject: ftputil.py Message-ID: <1148454897.089654.46130@j33g2000cwa.googlegroups.com> Hi Everyone, I recently installed a module called ftputil and I am trying to understand how it works. I created a simple program to download about 1500 files from my ftp and the program looks like this: ************************************************************************** #! /usr/bin/env python #-*- coding: UTF-8 -*- def ftp_fetch(newdir): import sys import ftputil # download some files from the login directory host = ftputil.FTPHost('ftp.xxxx.xx', 'xxxxxx', 'xxxxxxx') names = host.listdir(host.curdir) print "There are %d files on the FTP server to be downloaded" % len(names) for name in names: if host.path.isfile(name): host.download(name, name, 'b') # remote, local, binary mode #make a new directory and copy a remote file into it host.mkdir('newdir') source = host.file('index.html', 'r') # file-like object target = host.file('newdir/index.html', 'w') # file-like object host.copyfileobj(source, target) # similar to shutil.copyfileobj source.close() target.close() return 0 #-------------------------------- if __name__== "__main__": import os import sys newdir = os.getcwd() print "Downloading files from FTP into directory: %s" % newdir #sys.exit(0) stat = ftp_fetch(newdir) ********************************************************************************** Now I also need to write another function to upload files and I haven't the faintest idea yet. Here is the part of the program that I need explained: host.download(name, name, 'b') # remote, local, binary mode source = host.file('index.html', 'r') # file-like object target = host.file('newdir/index.html', 'w') # file-like object host.copyfileobj(source, target) # similar to shutil.copyfileobj Any help would be greatly appreciated! Sincerely, Sheldon From rpdooling at gmail.com Wed May 10 15:07:20 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 May 2006 12:07:20 -0700 Subject: reusing parts of a string in RE matches? In-Reply-To: <whq8g.2082$No6.45965@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> Message-ID: <1147288040.290425.49520@u72g2000cwu.googlegroups.com> >> otherwise i might as well just use string >> methods I think you're supposed to use string methods if you can, to avoid the old adage about having two problems instead of one when using regex. rd From dacut at kanga.org Thu May 18 04:19:13 2006 From: dacut at kanga.org (David Cuthbert) Date: Thu, 18 May 2006 01:19:13 -0700 Subject: Using python for a CAD program In-Reply-To: <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> Message-ID: <e4ham3$1td$1@sea.gmane.org> baalbek wrote: > CAD systems available today (Autocad, Archicad, Architectural Desktop, > etc) have one huge flaw: they don't store data to a SQL database, but to > binary files. There's a reason for this. Most CAD data is not in a form (First Normal Form) suitable for a relational database. In addition, the sheer number of objects involved in each operation brings performance to its knees. Finally, most RDBMS provide (and are optimized for) transactional semantics -- for a CAD system, this is wasted overhead. People dabbled in this years back but quickly discovered just how different they are. If you have access to it, you should take a peek at the source for the OpenAccess database. Although this is for chips, I suspect some of the same design principles would go into designing a CAD database. From levub137 at wi.rr.com Sat May 20 12:25:33 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 20 May 2006 16:25:33 GMT Subject: Decimal and Exponentiation In-Reply-To: <mailman.6011.1148138808.27775.python-list@python.org> References: <1148060287.088387.41150@j55g2000cwa.googlegroups.com> <mailman.5981.1148073533.27775.python-list@python.org> <zLCbg.3265$8T4.567@tornado.rdc-kc.rr.com> <mailman.6011.1148138808.27775.python-list@python.org> Message-ID: <1qHbg.4012$8T4.2045@tornado.rdc-kc.rr.com> Tim Peters wrote: > [Raymond L. Buvel, on > http://calcrpnpy.sourceforge.net/clnumManual.html > ] > >> The clnum module handles this calculation very quickly: >> >> >>> from clnum import mpf >> >>> mpf("1e10000") ** mpf("3.01") >> mpf('9.9999999999999999999999932861e30099',26) > > > That's probably good enough for the OP's needs -- thanks! > > OTOH, it's not good enough for the decimal module: > > (10**10000)**3.01 = > 10**(10000*3.01) = > 10**30100 > > exactly, and the proposed IBM standard for decimal arithmetic requires > error < 1 ULP (which implies that if the mathematical ("infinite > precision") result is exactly representable, then that's the result > you have to get). It would take some analysis to figure out how much > of clnum's error is due to using binary floats instead of decimal, and > how much due to its pow implementation. Indeed, it is not clear where the error is comming from especially since you can increase the precision of the intermediate calculation and get the exact result. >>> mpf(mpf("1e10000",30) ** mpf("3.01",30), 20) mpf('1.0e30100',26) Is this the kind of thing you will need to do in the Decimal module to meet the specification? From robin.meier at gmail.com Thu May 18 10:21:33 2006 From: robin.meier at gmail.com (robin) Date: 18 May 2006 07:21:33 -0700 Subject: module webbrowser - open link in same window - osx Message-ID: <1147962093.872808.10800@38g2000cwa.googlegroups.com> hi, i'm using the webbrowser module to open url's in safari or firefox. specifically i'm using the webbrowser.open('http://...', new=0) command. however, even though i say new=0 my url is always opened in a new browser window. what can i do, so my link is opened in an already open browser window? thank you for your help, robin From michele.simionato at gmail.com Wed May 3 06:24:37 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 3 May 2006 03:24:37 -0700 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <1146644904.906523.255970@j73g2000cwa.googlegroups.com> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> <mailman.5253.1146643043.27775.python-list@python.org> <1146644904.906523.255970@j73g2000cwa.googlegroups.com> Message-ID: <1146651877.687428.294320@v46g2000cwv.googlegroups.com> tsaar2003 at yahoo.com wrote: > As stated in my first post, I am quite newbie in > Python and miss a simple and intuitive mechanism that would allow to > declare something as constant and that would protect these "constant" > objects from accidental modifications. > > T.S. Python solution is to rely on the intelligence of programmers. If they see an all caps name and then they try to change it without knowing what they are doing, then they are stupid. If you have stupid programmers there is no way the language can stop them for making disasters. For true constants, this is the end of the story. OTOH, sometimes you want read-only attributes which should not be accidentally overwritten but that are not really constants. In this case, the solution is to use properties. Just google the newsgroup for "properties" and you will find many examples of usage. Michele Simionato From nobody at 127.0.0.1 Thu May 4 14:29:59 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 04 May 2006 18:29:59 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <pan.2006.05.03.20.57.05.32060@gmx.net> <Sda6g.67189$F_3.50022@newssvr29.news.prodigy.net> <mailman.5289.1146697051.27775.python-list@python.org> <k_a6g.21491$4L1.14831@newssvr11.news.prodigy.com> <4459c050$0$3552$626a54ce@news.free.fr> Message-ID: <HKr6g.81687$dW3.22405@newssvr21.news.prodigy.com> bruno at modulix wrote: > Edward Elliott wrote: >> Ah, well then, there's no need for a full-blown parser. It should >> suffice to recognize a class definition and modify the parameter list of >> every def indented one level further than that. > > won't do : > > class CounterExample(object): > if compute_some_const_according_to_phase_of_moon(): > def meth(...): > do_something(self, 42) Uuuhhhhnn, you got me pardner. (cough, cough) my hands, they're so cold. bruno? where'd you go, bruno? i can't see you anymore. are we back on the farm? tell ma i love her. (clunk) From sjmachin at lexicon.net Sun May 28 18:43:08 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 May 2006 08:43:08 +1000 Subject: (mostly-)POSIX regular expressions In-Reply-To: <1148852793.028851.102920@i39g2000cwa.googlegroups.com> References: <1148764193.962418.192750@j73g2000cwa.googlegroups.com> <1148838196.463101.210180@i39g2000cwa.googlegroups.com> <1148852793.028851.102920@i39g2000cwa.googlegroups.com> Message-ID: <447A277C.6060302@lexicon.net> On 29/05/2006 7:46 AM, S?bastien Boisg?rault wrote: > Paddy a ?crit : > >> maybe this: http://www.pcre.org/pcre.txt and ctypes might work for you? > > Well finally, it doesn't fit. What I need is a "longest match" policy > in > patterns like "(a)|(b)|(c)" and NOT a "left-to-right" policy. > Additionaly, > I need to be able to obtain the matched ("captured") substring and > the PCRE does not allow this in DFA mode. > Perhaps you might like to be somewhat more precise with your requirements. "POSIX-compliant" made me think of yuckies like [:fubar:] in character classes :-) The operands of | are such that the length is not fixed and so you can't write them in descending length order? Care to tell us some more detail about those operands? If those operands are simple strings (LOGICAL|LOGIC|LOG) and you've got more than a handful of them, try Danny Yoo's ahocorasick module. HTH, John From songyi012133 at gmail.com Thu May 18 04:38:57 2006 From: songyi012133 at gmail.com (hankssong) Date: 18 May 2006 01:38:57 -0700 Subject: how to make the program notify me explicitly In-Reply-To: <1147939268.619806.147550@j73g2000cwa.googlegroups.com> References: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> <1147939268.619806.147550@j73g2000cwa.googlegroups.com> Message-ID: <1147941537.039418.316340@j73g2000cwa.googlegroups.com> Ben Finney , Miki ,thanks a lot! may be message dialog is the best way to let me be informed! From nobody at 127.0.0.1 Sat May 20 19:06:56 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 20 May 2006 23:06:56 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <446F9BA8.4040204@websafe.com> Message-ID: <kiNbg.19897$Lm5.3619@newssvr12.news.prodigy.com> Larry Bates wrote: > Sorry, I don't buy this. I can write REALLY short programs that don't > handle exceptions, don't provide for logging for debugging purposes, don't > allow > for future growth, etc. I find that 60% of my code has nothing to do with > the actual algorithm or function I'm trying to accomplish. It has more to > do with handling user's bad input, exceptions, recovering from hardware or > communications failures, etc. Wow, only 60%, I'm surprised it's that low :). When I say the algorithms are roughly equivalent, I'm including the amount of input verification and error checking that they do. To me, that's part of the algorithm. > Inexperienced programmers can write some > pretty short programs that get the job done, but can't handle the real > world. Tell me about it. I've taught intro comp sci, things can get real ugly real quick. :) > Also, many years ago I wrote a number of applications in APL. We often > referred to programs written in APL as "write only code" because going > back > to read what you had written after-the-fact was very hard. You could > write in one line of APL what takes 1000's of lines of C or even Python > and it was pretty efficient also (for applications that needed to > manipulate vectors or matrices). Of course. Comparing line counts between assembly and Prolog is pretty useless given the vast discrepancy in their expressive power. Perl and Python are roughly comparable in expressiveness, so it doesn't seem unreasonable to compare their line counts. It might not tell you much, there are undoubtedly better comparisons to make, but I don't think it's grossly unfair the way you suggest. I'm all ears if you have another metric I can test as easily. > I understand what you are trying to say, but I can't support your > conclusions as presented. What would those be? I tried hard not draw any conclusions. I just want to see how other people's data compares to mine. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From kentilton at gmail.com Mon May 15 00:05:34 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 15 May 2006 00:05:34 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <d6l3bfc8nmr.fsf@vipunen.hut.fi> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> Message-ID: <i6T9g.228$qU1.90@fe08.lga> Lasse Rasinen wrote: > Ken Tilton <kentilton at gmail.com> writes: > > >>ps. flaming aside, PyCells really would be amazingly good for Python. And >>so Google. (Now your job is on the line. <g>) k > > > Here's something I wrote this week, mostly as a mental exercise ;-) It's fun, right? But what you have is a complete wreck. :) > The whole code is available at <http://www.iki.fi/~lrasinen/cells.py>, > I'll include a test example below. Feel free to flame away ;-) > > (As for background: I like CL better as a language, but I also like Python > a lot. However, I was employed for 3 years as a developer and maintainer > in a Python data mining application, so I'm more fluent in Python than CL.) > > The code is mostly based on Kenny's descriptions of Cells in the following > messages: > <0mp7g.600$4q2.70 at fe12.lga> > <NUP7g.17$G22.12 at fe11.lga> > <xcn8g.11$FO5.5 at fe08.lga> > > In addition, I have looked at the CL source code briefly, but I'm not sure > if any concepts have survived to the Python version. Since Python's object > model is sufficiently different, the system is based on rules being > defined per-class... That will be a total disaster for PyCells, if true. But I do not think it is. You just need a constructor that takes some slot initializers, and initialize the slots to one of: a normal value; an InputCell itself initialized with a starting value, if only nil; or a RuledCell itself initialized with a lambda. Trust me, you lose a vast amount of power unless different instances of the same class can have different rules for the same slot. >... (however, if you define a rule by hand in the __init__ > function, it'll work also. I think; haven't tested). > > I can possibly be persuaded to fix bugs in the code and/or to implement > new features ;-) PyCells looks like it will be a project for SoC2006, so you may as well relax. But I understand if you want to keep going, it is great fun. btw, I have met more than a few people who had done something like Cells independently, and there are many full-blown similar implementations around. Mine is just the best. <g> Kidding, i do not really know, there are so many. > > Features: > - Tracks changes to input cells dynamically (normal attributes are not tracked) Ha! All your rules depend on the input cell itself! How about A depends on B depends on C? :) > - Callbacks for changes (see caveats) > - Requires Python 2.4 for the decorator syntax (@stuff) > - Should calculate a cell only once per change (haven't tested ;-) Quite hard to test deliberately, but it happens "in nature". But it will not happen until you do A->B->C. Once you have /that/ working, make A the input, then have B and C both use A. But also have B use C, and jiggle things around until A happens to think it should update B first, then C. What happens is that B runs and uses C, but C has not been updated yet. C is inconsistent with A, but is being used to calculate a new value for B which does see the new value of A. Mismatch! B will get sorted out in a moment when C gets recalculated and tells B to calculate a second time, but meanwhile after the first recalculation of B the on-change callback for that got invoked, missiles were launched, and Moscow has been destroyed. > > Caveats: > - The input cell callbacks are not called with the class instance > as the first argument, while the rule cell callback are. This > is mostly due to laziness. And unacceptable! have fun. :) kenny ps. In the getattr for any Cell-mediated slot, look to see if "parent" is non-nil. If so, set up a dependency. k -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From aleax at mac.com Mon May 29 12:10:22 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 29 May 2006 09:10:22 -0700 Subject: itertools.count() as built-in References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> <1148860241.048549.269330@j73g2000cwa.googlegroups.com> <1hg24o2.18odi4uzoiraoN%aleax@mac.com> <1148893017.099404.39750@38g2000cwa.googlegroups.com> <447b1721.0@entanet> Message-ID: <1hg3dfy.mhrnrcw45b2eN%aleax@mac.com> Duncan Smith <buzzard at urubu.freeserve.co.uk> wrote: > jantod at gmail.com wrote: > > Zipping an xrange? I'm having trouble visualizing how you do that to > > avoid x*i+y. > > > > -Janto > > > > Something like, > > >>> lis = ['a', 'b', 'c', 'd'] > >>> y = 3 > >>> i = 7 > >>> for n, item in zip(xrange(y, len(lis)*i+y, i), lis): > print n, item Actually I tend to use sys.maxint as the xrange's middle arg, but, yes, this IS the general idea!-) Alex From sjmachin at lexicon.net Wed May 24 23:34:14 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 May 2006 13:34:14 +1000 Subject: how to "normalize" indentation sources In-Reply-To: <PKqdndjnUPVbgOjZRVn-hA@comcast.com> References: <PKqdndjnUPVbgOjZRVn-hA@comcast.com> Message-ID: <447525b7$1@news.eftel.com> On 25/05/2006 12:00 PM, AndyL wrote: > Hi, > > I have a lot of sources with mixed indentation typically 2 or 4 or 8 > spaces. Is there any way to automatically convert them in let's say 4 > spaces? > Yup. Right under your nose: C:\junk>\python24\tools\scripts\reindent.py --help reindent [-d][-r][-v] [ path ... ] -d (--dryrun) Dry run. Analyze, but don't make any changes to, files. -r (--recurse) Recurse. Search for all .py files in subdirectories too. -v (--verbose) Verbose. Print informative msgs; else no output. -h (--help) Help. Print this usage information and exit. Change Python (.py) files to use 4-space indents and no hard tab characters. Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files. Also ensure the last line ends with a newline. [snip] From pydecker at gmail.com Wed May 17 10:31:46 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 17 May 2006 10:31:46 -0400 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <e4fas7$hlk$1@sea.gmane.org> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <e4f8nr$8q9$1@sea.gmane.org> <ca55a9900605170639re1ad32co4164913a78d8f228@mail.gmail.com> <e4fas7$hlk$1@sea.gmane.org> Message-ID: <ca55a9900605170731mab99520id4ce4ae664bccb32@mail.gmail.com> On 5/17/06, Andy Sy <andy at neotitans.com> wrote: > Peter Decker wrote: > > On 5/17/06, Andy Sy <andy at neotitans.com> wrote: > > > >> If tabs are easily misunderstood, then they are a MISfeature > >> and they need to be removed. > > > > I don't seem to understand your point in acting as a dictator. > > Therefore, you are a MISfeature and need to be removed. > > Is the above an example of how a tab-user exercises 'logic'...? Uh, I should know better than to try to educate, but FYI: using the same argument construction and having it reach an invalid conclusion suffices to show that the original construction is invalid, and thus the original conclusion is suspect. -- # p.d. From ed at leafe.com Thu May 11 16:02:05 2006 From: ed at leafe.com (Ed Leafe) Date: Thu, 11 May 2006 16:02:05 -0400 Subject: 2 books for me In-Reply-To: <1147375933.114803.40870@q12g2000cwa.googlegroups.com> References: <87lkt9ytxx.fsf@localhost.localdomain> <4462f24d$0$311$636a55ce@news.free.fr> <1147375933.114803.40870@q12g2000cwa.googlegroups.com> Message-ID: <3CF9B7C9-AE70-4724-938D-07F851EBCFAC@leafe.com> On May 11, 2006, at 3:32 PM, Robert Hicks wrote: > Wouldn't portability go with Tkinter since that is installed with > every > Python? Dunno about other platforms, but it's not on my Mac. -- Ed Leafe -- http://leafe.com -- http://dabodev.com From email at christoph-haas.de Thu May 18 15:52:39 2006 From: email at christoph-haas.de (Christoph Haas) Date: Thu, 18 May 2006 21:52:39 +0200 Subject: Sorting of list containing tuples In-Reply-To: <7x1wurcecw.fsf@ruckus.brouhaha.com> References: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> <7x1wurcecw.fsf@ruckus.brouhaha.com> Message-ID: <20060518195239.GC5309@workaround.org> On Thu, May 18, 2006 at 12:38:55PM -0700, Paul Rubin wrote: > Ronny Mandal <ronnyma at math.uio.no> writes: > > And now I want to sort l reverse by the second element in the tuple, > > i.e the result should ideally be: > > > > l = [(6,5),(2,3),(3,2)] > > sorted(l, key = lambda a: -a[1]) Or in Python <2.4: l.sort(lambda x,y: x[1]-y[1]) (Although that's not technically perfect. Sort expect a function that returns -1, 0 or 1. Here we get positive integers and negative integers. YMMV.) Kindly Christoph From hancock at anansispaceworks.com Fri May 19 10:33:11 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 19 May 2006 14:33:11 +0000 Subject: import woe In-Reply-To: <1148019840.711270.314650@u72g2000cwu.googlegroups.com> References: <1148016083.020020.40660@u72g2000cwu.googlegroups.com> <1148019840.711270.314650@u72g2000cwu.googlegroups.com> Message-ID: <446DD727.4060802@anansispaceworks.com> vaibhav wrote: >4. add the root folder to your sys.path >so your jar.py file should have the following entries >from sys import path >path.append('../../../ROOT') > >note: i prefer relative paths > > Interesting that that works. I guess you could create a limited form of Zope acquisition type behavior: sys.path = ['.', '../', '../../', '../../../'] + sys.path I'm looking forward to the introduction of relative imports in 2.5, though. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From herraotic at googlemail.com Wed May 24 08:50:29 2006 From: herraotic at googlemail.com (herraotic at googlemail.com) Date: 24 May 2006 05:50:29 -0700 Subject: Python Programming Books? In-Reply-To: <1148474604.279491.71090@j55g2000cwa.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474604.279491.71090@j55g2000cwa.googlegroups.com> Message-ID: <1148475029.108300.250810@i40g2000cwc.googlegroups.com> Thanks vbgunz that was the reply I was looking for! Do you think it is wise to hold back for a 3rd edition? My 1:47 pm message was a reply to Rony Steelandt. From sam at nuevageorgia.com Tue May 23 12:51:43 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 23 May 2006 09:51:43 -0700 Subject: Software Needs Philosophers In-Reply-To: <WOadnW-sRKmdoe7Z4p2dnA@speakeasy.net> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <Xns97CC91CC89166BaldHeadedJohn@216.196.109.145> <WOadnW-sRKmdoe7Z4p2dnA@speakeasy.net> Message-ID: <1148403103.843248.99000@g10g2000cwb.googlegroups.com> Good question on new ideas vs old ideas. Seems to me the computer industry needs some young brains, raised around the internet, to generate some major new theoretical ideas for computers. Seems to me it must already be occuring below the radar. When it happens, it shouldn't be too hard to spot. It will make cool new things possible, and won't make sense to most people over 25. From diffuser78 at gmail.com Fri May 5 11:00:36 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 5 May 2006 08:00:36 -0700 Subject: cross platform libraries In-Reply-To: <mailman.5375.1146840269.27775.python-list@python.org> References: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> <tsml52pij438mt1goq071663t1r415nljl@4ax.com> <1146836899.678804.168000@g10g2000cwb.googlegroups.com> <mailman.5375.1146840269.27775.python-list@python.org> Message-ID: <1146841236.864198.272950@i40g2000cwc.googlegroups.com> Can we have some program in Linux which shuts down the windows computer remotely. Every help is appreciated. Max Erickson wrote: > diffuser78 at gmail.com wrote in > news:1146836899.678804.168000 at g10g2000cwb.googlegroups.com: > > > I went to this webpage > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 > > > > Isn't it supposed to run on the network and close the connected > > machine. > > That code uses the windows libraries on the machine it is run on to > generate a request to the networked machine to shutdown. The code > executes locally and sends the request over the network. > > > Every help is appreciate, > > > > If you have some way of remotely running programs on the windows > machine(ssh, telnet, etc.), you might try pstools: > > http://www.sysinternals.com/Utilities/PsTools.html > > specifically, psshutdown. > > max From tjreedy at udel.edu Fri May 5 14:19:09 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 5 May 2006 14:19:09 -0400 Subject: 4 little Python programs References: <1146833949.544241.88330@y43g2000cwc.googlegroups.com> Message-ID: <e3g4ur$p82$1@sea.gmane.org> "RM" <ny_r_marquez at yahoo.com> wrote in message news:1146833949.544241.88330 at y43g2000cwc.googlegroups.com... > I had been thinking of releasing some of my little personal apps for a > while. So, this finally motivated me to clean them up enough for > release. The website is not yet finished, but I couldn't wait to share > with you these little Python programs. I have packaged them nicely for > Windows using py2exe and InnoSetup. Unfortunately, I haven't had the > time to do the same for Linux. I plan to that soon. You can get them > here. > > http://rmcorrespond.googlepages.com/customsoftware > > I have been using them for several years, but never got around to > releasing them. Any way, I hope you like them. Oh, they are all > licensed with the GPL, but for now, since I don't yet have a way to > track downloads, I am only making the source available upon request. If > you have any questions or suggestions let me know. Since you asked: delete the .exes and release the source and give a link to python.org for anyone who does not have it already installed. Since I already have at least two versions of Python installed, I don't need four more copies. Since I have no reason to trust that you are not distributing malware, I would not touch your .exes anyway. Python is really meant for source distribution. Terry Jan Reedy From blair.bethwaite at gmail.com Sun May 7 23:58:33 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 7 May 2006 20:58:33 -0700 Subject: utility functions within a class? In-Reply-To: <445ebacc$0$5345$c3e8da3@news.astraweb.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> Message-ID: <1147060713.875377.104640@y43g2000cwc.googlegroups.com> John Salerno wrote: > Ugh, sorry about another post, but let me clarify: In these utility > functions, I need to refer to an attribute of an instance, but these > functions will be called from another method in the class, not from the > instance itself. Is this even possible, or would 'self' have no meaning > when used this way? I'm having trouble deciphering what this bit means - "but these functions will be called from another method in the class, not from the instance itself", I don't think it makes sense. If you're calling something in a class method then there must be an instance of that class, instantiated as an object, in order to make the call in the first place. 'self' does have meaning inside a class, you use it when you want to call another method within the same class. Python can then fill in the self reference in the arguments to the callee for you as it does when you call a method from outside of the class by qualifying with the instance name. inside class A: self.blah(args) outside class A: a_A = A() a_A.blah(args) Cheers, -B (Hope I've got this one right) From grante at visi.com Sat May 27 15:31:48 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 19:31:48 -0000 Subject: How to control color of contour lines? References: <127h41neuk81408@corp.supernews.com> <127h46hotumkl6c@corp.supernews.com> Message-ID: <127ha94g2pfra4e@corp.supernews.com> On 2006-05-27, Grant Edwards <grante at visi.com> wrote: > On 2006-05-27, Grant Edwards <grante at visi.com> wrote: >> How do I get contour lines drawn in just one color (e.g. black)? >> >> Multicolored contour lines on top of a pm3d surface can be very >> hard to look at... > > Of course I found it right after I posted the question: > > "unset clabel" And then I realized I posted it to the wrong group. I shouldn't be workign on a Saturday.... -- Grant Edwards grante Yow! My FAVORITE group at is "QUESTION MARK & THE visi.com MYSTERIANS"... From scott.daniels at acm.org Tue May 2 16:05:20 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 02 May 2006 13:05:20 -0700 Subject: stripping blanks In-Reply-To: <445720fd$1_2@news.estpak.ee> References: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> <445720fd$1_2@news.estpak.ee> Message-ID: <4457b7f3$1@nntp0.pdx.net> seeker wrote: > Last suggestion I made was bad. Here is the new one. Hopefully thats > correct. > > f = open("test.dat") > for line in f: > printLine = line.rstrip("\n") > if not printLine: > continue > print printLine A little better: f = open("test.dat") for line in f: printLine = line.rstrip("\n") if printLine: print printLine --Scott David Daniels scott.daniels at acm.org From me at privacy.net Sun May 7 18:54:07 2006 From: me at privacy.net (Dan Sommers) Date: Sun, 07 May 2006 18:54:07 -0400 Subject: printing list References: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> <mailman.5452.1147019753.27775.python-list@python.org> <unu7g.3512$M31.19937@news20.bellglobal.com> Message-ID: <m23bflwink.fsf@unique.fqdn> On Sun, 07 May 2006 18:16:22 -0400, Mel Wilson <mwilson-to at sympatico.ca> wrote: > Tim Chase wrote: >> compboy wrote: >> >>> How do you print elements of the list in one line? >>> >>> alist = [1, 2, 5, 10, 15] >>> >>> so it will be like this: >>> 1, 2, 5, 10, 15 >> >> >> >>> print ', '.join(alist) >> 1, 2, 5, 10, 15 > ??? > Python 2.4.2 (#1, Jan 23 2006, 21:24:54) > [GCC 3.3.4] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> a=[1,2,3,4,5] >>>> print ', '.join (a) > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: sequence item 0: expected string, int found >>>> print ', '.join ('%d'%x for x in a) > 1, 2, 3, 4, 5 Or one of: print ', '.join(str(x) for x in a) print ', '.join(map(str, a)) both of which work if the list contains non-integer elements. Regards, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From Ericzhao82 at gmail.com Thu May 11 08:24:38 2006 From: Ericzhao82 at gmail.com (Eric.zhao.82) Date: 11 May 2006 05:24:38 -0700 Subject: Python editor recommendation. In-Reply-To: <mailman.5585.1147348514.27775.python-list@python.org> References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <RW08g.19915$D61.2897@fe58.usenetserver.com> <pan.2006.05.09.15.03.47.433646@thomas-guettler.de> <mailman.5585.1147348514.27775.python-list@python.org> Message-ID: <1147350278.386171.204920@u72g2000cwu.googlegroups.com> HI I use VIM in FreeBSD or M$'s Windows From LittlePython at lost.com Sun May 28 18:46:18 2006 From: LittlePython at lost.com (LittlePython) Date: Sun, 28 May 2006 22:46:18 GMT Subject: Using a package like PyInstaller References: <FyYdg.2216$As2.860@trnddc02> <e5ab5l$tkm$1@daisy.noc.ucla.edu> <DD4eg.2432$As2.2216@trnddc02> <e5amec$64m$1@daisy.noc.ucla.edu> <ZX5eg.287$xO5.197@trnddc03> <e5bf4k$of9$1@daisy.noc.ucla.edu> <0rieg.1829$hv1.972@trnddc01> <e5d593$v4p$1@daisy.noc.ucla.edu> Message-ID: <_Kpeg.1222$ho6.11@trnddc07> Thx for the tip ... I'll give it a go "James Stroud" <jstroud at ucla.edu> wrote in message news:e5d593$v4p$1 at daisy.noc.ucla.edu... > LittlePython wrote: > > "Im 99.999% confident that this will not happen from the .exe file > > generated by pyinstaller (unless you specify--see link above)." > > > > Well I guess that's about as close as any one can get in this business. I > > have been trying to introduce py into our environment, and have opened a few > > eyes, however I have been given one restriction. I can not install anything, > > leave behind anything or alter anything on a systems ...... period, > > > You can always hard-code external resources. For example, first write a > script that makes a module out of one or several jpegs (assuming jpeg > extension is consitently 'jpg': > > import binascii > > def append_to_jpeg_module(modulename, jpegs): > myjpegs = open('%s.py' % modulename, 'wa') > for jpegname in jpegs: > afile = open('%s.jpg' % jpegname, 'rb') > ajpeg = afile.read() > afile.close() > jpegascii = binascii.b2a_base64(ajpeg) > print jpegascii > myjpegs.write('%s = """%s"""\n\n' % (jpegname, jpegascii)) > myjpegs.close() > > append_to_jpeg_module('myjpegs', ['logo_sm']) > > #heres how you use it > append_to_jpeg_module('myjpegs', ['coolpik1', 'coolpik2', 'anotherpik']) > > Now, in your file that needs the jpegs, you can pretend these strings > are files with the cStringIO module, e.g. (pretending 'modulename' above > is 'myjpegs'): > > import binascii > import myjpegs > import cStringIO > > def get_jpeg_as_opened_file(jpegname, module): > jpegascii = module.__dict__[jpegname] > jpegbin = binascii.a2b_base64(jpegascii) > return cStringIO.StringIO(jpegbin) > > # getting that pik > get_jpeg_as_opened_file('coolpik1', myjpegs) > > > And your company can go on making widgets feeling secure in the fact > that you have not required any extra entries in their file allocation > tables. > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From bill.scherer at verizonwireless.com Wed May 31 14:55:05 2006 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Wed, 31 May 2006 14:55:05 -0400 Subject: Oracle Data Access in Python In-Reply-To: <NYOBGCEXSMTP21Cf9q4001b5b4a@nyobgcexsmtp21.uswin.ad.vzwcorp.com> References: <NYOBGCEXSMTP20oghBe002072bb@nyobgcexsmtp20.uswin.ad.vzwcorp.com><mailman.6375.1149096323.27775.python-list@python.org> <NYOBGCEXSMTP21Cf9q4001b5b4a@nyobgcexsmtp21.uswin.ad.vzwcorp.com> Message-ID: <447DE689.1060409@verizonwireless.com> A.M wrote: > > "Bill Scherer" <bill.scherer at verizonwireless.com> wrote in message > news:mailman.6375.1149096323.27775.python-list at python.org... > > A.M wrote: > > > >> Hi, > >> > >> > >> > >> I am familiar with Perl's DBI programming. > >> > >> > >> > >> In Python, do we access to Oracle by using DBI? > >> > > No. > > > >> Is Oracle DBD driver included with Python distributions? > >> > > No. > > > >> What is the most common strategy for accessing to Oracle data through > >> Python? > >> > > cx_Oracle seems to be the leading module for Oracle access today. It > works > > well. > > > > http://www.cxtools.net/default.aspx?nav=cxorlb > > > > > > You'll need the apropriate Oracle client installed for it to work, of > > course. Oracle's "Instant Client" is probably the easiest way to get > what > > you need for that. > > > > > > Hope that helps, > > > > Bill > > Thanks Bill for help. > I also learned about DCOracle2 at this page: > http://www.python.org/doc/topics/database/modules/ > > What do you think about DCOracle2? It seems to be based on Python Database > API Specification. > DCOracle was the first on the block. Back in the day it was the only way to speak with the Oracle. From what I can tell, development of DCOracle has lagged of late. Try them both and see which works better for you. PS. Both cx_Oracle and DCOracle, as well as, oh I guess 99% of other Python database modules, are DB API 2.0 compliant. > > Thanks again, > Ali > > > > -- > http://mail.python.org/mailman/listinfo/python-list > From hannu at skype.net Mon May 15 16:33:10 2006 From: hannu at skype.net (Hannu Krosing) Date: Mon, 15 May 2006 23:33:10 +0300 Subject: Iterating generator from C (PostgreSQL's pl/python RETUN SETOF/RECORD iterator support broken on RedHat buggy libs) Message-ID: <1147725190.3790.37.camel@localhost.localdomain> Sorry for cross-posting, but this IS a cross-platform issue. Christian Tismer tismer at stackless.com wrote: > Sven Suursoho wrote: > > >>> Is there any way to rewrite following program to handle returned > >>> generator without hitting this bug? > > The only way I can think of getting around this is to make > sure that there is always a running python frame. > This would be possible if you can control how the > extension is called. What would be the easiest way to hold a "always running" python frame ? The actual calls to iterator come through a pl/python framework, which can hold some state - like some inter-call dictionaries - so keeping also a simple outer frame there may be possible. What danger (apart from general uglyness) may lurk there in keeping this frame ? > > Unfortunately, this is not an option because I can't control used > > environment: I'm trying to improve PostgreSQL's stored procedure > > language PL/Python and this software can be used everywhere. > > Then there is no other way than to report the bug, get the > fix back-ported and nagging the PL/Python maintainers > to update things after the fix. Unfortunately there is no 'after the fix', as the fix must happen outside postgresql/plpython development and should also run on oldish systems. The reason we want to get some workaround for that bug is the need to overcome resistance from core postgreSQL developers to inclusion of our plpython enchancements to postgreSQLs bundled plpython due to one specific use of our generic enchancement (using a built-in generator, usually a function with yield) on buggy RedHat's bundled plpython.so causing crashes. Also, PL/Python has been in minimal maintenance mode for many years, with basically only immediate bugfixing going on. We at Skype (that is currently Sven Suursoho) are the first ones doing active development on it after Andrew Bosma dropped development many years ago once he got just the very basic stuff working. > Also a test should be added which is probably missing since a while. Test where ? In python.so build process, so that RedHat will spot it and fix their RPM builds ? As for testing in actual pl/python build environment, we had objections from leading postgresql Tom Lane that even if we do test it at build time, a determined DBA may substitute a buggy python.so later and still crash her DB instance. Do you have any ideas, how to test for buggy asserts in python runtime environment without actually triggering the assert ? Then we could introduce some (uglish) special handling for generators in pl/pythons iterator. > I'd put a warning somewhere that generators are broken in > debug mode, file an issue as well, but avoid trying to hack > around this. It would make the bug even more resistent :-) We have been trying to advocate such approach, but so far with modest results :( -- ---------------- Hannu Krosing Database Architect Skype Technologies O? Akadeemia tee 21 F, Tallinn, 12618, Estonia Skype me: callto:hkrosing Get Skype for free: http://www.skype.com From phddas at yahoo.com Wed May 17 23:05:52 2006 From: phddas at yahoo.com (Gary Wessle) Date: 18 May 2006 13:05:52 +1000 Subject: getting the value of an attribute from pdb Message-ID: <87odxwt4kv.fsf@localhost.localdomain> Hi how can I "using pdb" get a value of an attribute?, read the docs and played around with pdb 'p' for no avail. thanks class main: def __init__(self, master): self.master = master self.master.title('parent') self.master.geometry('200x150+300+225') ... root = Tk() **************** **************** ignore the following if you are not interested on how I tried **************** **************** (Pdb) n > /home/fred/python/practic/window_08.py(12)__init__() -> self.master.geometry('200x150+300+225') (Pdb) p root.title <bound method Tk.wm_title of <Tkinter.Tk instance at 0xb717c16c>> (Pdb) p root.title[Tk.wm_title] *** TypeError: <exceptions.TypeError instance at 0xb717c3cc> (Pdb) p root.title[wm_title] *** NameError: <exceptions.NameError instance at 0xb717c3cc> (Pdb) p root[wm_title] *** NameError: <exceptions.NameError instance at 0xb717c3cc> (Pdb) p root['wm_title'] *** TclError: <_tkinter.TclError instance at 0xb717c3cc> (Pdb) p self.master[title] *** NameError: <exceptions.NameError instance at 0xb717c3cc> (Pdb) p self.master['title'] *** TclError: <_tkinter.TclError instance at 0xb717c40c> (Pdb) p self.master["title"] *** TclError: <_tkinter.TclError instance at 0xb717c42c> (Pdb) p self.master[wm_title] *** NameError: <exceptions.NameError instance at 0xb717c42c> (Pdb) p self.master['wm_title'] *** TclError: <_tkinter.TclError instance at 0xb717c3cc> (Pdb) p self.master["wm_title'] *** SyntaxError: <exceptions.SyntaxError instance at 0xb717c3cc> (Pdb) p self.master["wm_title"] *** TclError: <_tkinter.TclError instance at 0xb717c40c> (Pdb) q Traceback (most recent call last): File "./window_08.py", line 65, in ? main(root) File "./window_08.py", line 12, in __init__ self.master.geometry('200x150+300+225') File "./window_08.py", line 12, in __init__ self.master.geometry('200x150+300+225') File "/usr/lib/python2.4/bdb.py", line 48, in trace_dispatch return self.dispatch_line(frame) File "/usr/lib/python2.4/bdb.py", line 67, in dispatch_line if self.quitting: raise BdbQuit bdb.BdbQuit **************** **************** From yairchu at gmail.com Fri May 26 08:48:36 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 26 May 2006 05:48:36 -0700 Subject: Request for comments on python distributed technologies In-Reply-To: <mailman.5972.1148064796.27775.python-list@python.org> References: <mailman.5972.1148064796.27775.python-list@python.org> Message-ID: <1148647716.053276.302880@i39g2000cwa.googlegroups.com> Carl J. Van Arsdall wrote: > Hey everyone, another question for the list. In particular i'm looking > for comments on some of the distributed technologies supported in > python. Specifically, I'm looking at XML-RPC, RPyC, CORBA, and Twisted. > > Before you offer any comments let me talk about what i'm doing a little > bit. Right now I'm creating an execution framework. The framework aims > to allow users to create a modular system by which engineers can > mitigate some of the issues seen in large complex systems. By using > modules the system hopes to allow the system to change but allow > engineers to re-use as much code as possible. By using the modules in a > framework we hope to encapsulate the entire system to that it is > controllable in the sense that we can generate and catch errors anywhere > in the system and exit gracefully, things like that. There's a lot more > to it but the motivation spawn from our system where the system kept > needing to adapt to support changes in our company. These changes over > time have resulted in a large number of "hacks". The hope of the > modules is to make the code a lot cleaner and organized so that the > system can operate in whatever way it needs to without having so many > hacks. This system I use also operates in a primitive distributed > environment. Currently, these are ssh calls to other nodes that then > execute other python scripts and shell commands. This is the next piece > I'm interested in moving away from. > > With all that being said, I've come across those four technologies so > far and I've been looking into them. I was wondering if anyone had any > comments, pros/cons, or suggestions of other distributed technologies to > take a look at. I intend to integrate the distributed technology > directly into the framework making it easy for developers to distribute > tasks. Anyhow, any comments would be greatly appreciated! I also hope > to release this framework as an open-source project when its finished, > so again I community input is important. > > Thanks! > > .c > > > -- > > Carl J. Van Arsdall > cvanarsdall at mvista.com > Build and Release > MontaVista Software RPyC ! I personnaly used it (and its predecessor, pyinvoke) for: * a testing system that controls several computers * drawing graphs with matplotlib while avoiding its memory leaks * distributed calculation * controlling embedded python applications from my favorite python shell (not the embedded one), also allowing me to control several instances of the application. it's so easy to use that there's was no effort require to do any of those! it's pretty self-explanatory, so I'll only say this: it's Transparent. you run remote code and access remote objects just as you would locally. it's minimal, and complete. I highly recommend it! From fredrik at pythonware.com Fri May 19 10:55:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 16:55:16 +0200 Subject: open file with whitespaces References: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> Message-ID: <e4km8k$ags$1@sea.gmane.org> "mardif" wrote: > Now, I MUST open this file with os.spawn(os.P_WAIT ...., because I must > wait the user cancel the explorer window, ok? note that backslashes in string literals have special meaning in Python; to make sure a backslash in the string literal really ends up as a backslash in the resulting string, you must either double each backslash, or use "raw" strings: program = r"c:\programmi\internet explorer\iexplorer.exe" file = r"c:\documents and settings\username\desktop\cicciobello.html" also, getting the quoting/escaping right with os.exec/os.spawn is quite messy. I recommend using the subprocess module instead: import subprocess print subprocess.call([program, file]) </F> From grflanagan at yahoo.co.uk Sat May 20 04:45:59 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 20 May 2006 01:45:59 -0700 Subject: combining a C# GUI with Python code? In-Reply-To: <3Dnbg.2135$No6.46516@news.tufts.edu> References: <3Dnbg.2135$No6.46516@news.tufts.edu> Message-ID: <1148114759.852381.99010@j33g2000cwa.googlegroups.com> John Salerno wrote: > Is it possible to construct a C# form (using Visual Studio) but write > only Python code for the events? Is there some way to tell your program > to run Python whenever code is run, since it will be all Python code > (e.g. for button presses, etc.)? > > I know it's sort of silly, and it makes your program depend on .NET, but > it would be a nice and easy way to create a GUI while still writing in > Python, if it's possible. code here any use: http://gflanagan.net/site/dotnet/05/RunPythonScriptFromWord.html ? Gerard From tdw at tdw.net Thu May 4 09:04:18 2006 From: tdw at tdw.net (Tim Williams) Date: Thu, 4 May 2006 14:04:18 +0100 Subject: Swaying A Coder Away From Python In-Reply-To: <G40843809.903.44387.1@mx-extra.net> References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <W40839200.311.1532.1@mx-extra.net> <9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> <G40843809.903.44387.1@mx-extra.net> Message-ID: <9afea2ac0605040604h6e72a41bm10f50d703644238b@mail.gmail.com> On 04/05/06, Fredrik Lundh <fredrik at pythonware.com> wrote: > nope, but if we were to post to the list every time some random blogger says > something about Python, we wouldn't have room for much other stuff. > It wasn't from a random blogger, it was from an email newsletter for this site: http://www.devwebpro.co.uk/ I am not a member or in anyway related to the site :) and have no idea how large its user-base is. As I said, the email was forwarded to someone who thought I would be interested. :) From petr at tpc.cz Tue May 9 05:11:49 2006 From: petr at tpc.cz (Petr Jakes) Date: 9 May 2006 02:11:49 -0700 Subject: do "some action" once a minute In-Reply-To: <tjl062lu3m6d96d8e67ve2h1m7kleijakh@4ax.com> References: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> <tjl062lu3m6d96d8e67ve2h1m7kleijakh@4ax.com> Message-ID: <1147165909.579147.216030@g10g2000cwb.googlegroups.com> Thanks for your comment. It is mainly English issue (I am not native English speaker). OK, to be more specific, I would like to run the code, when the value of seconds in the timestamp become say "00". The whole code will run in the infinitive loop and other actions will be executed as well, so it can not "sleep" for 60 seconds :). Regards Petr From mhellwig at xs4all.nl Sat May 6 10:55:23 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 06 May 2006 16:55:23 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <7xhd43qkxq.fsf@ruckus.brouhaha.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> <445c8812$0$31639$e4fe514c@news.xs4all.nl> <7xhd43qkxq.fsf@ruckus.brouhaha.com> Message-ID: <445cb8e6$0$31641$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > "Martin P. Hellwig" <mhellwig at xs4all.nl> writes: >> and clients make it quite scalable. For example, I'm creating a >> xmlrpcserver that returns a randomized cardlist, but I because of >> fail-over I needed some form of scalability , my solution was to first >> randomize the deck then marshal it and dump the file on a ZFS >> partition, giving back the client a ticket number, the client can then >> connect with the ticket number to receive the cardlist (read the file >> - unmarshal it). > > This is a weird approach. Why not let the "ticket" by the (maybe > encrypted) PRNG seed that generates the permutation? Because the server that handles the generate request doesn't need to be the same as the one that handles the request to give the client that deck. Even more, the server that handles the request calls the crypto servers to actually do the shuffling. So when the server fails before it has given the client the ticket, it could be possible that a deck is already created but not used, no biggie there. But if the ticket is given to the client, than any other server can serve back that ticket to give the shuffled deck, unless the ZFS dies of course but then again thats why I use ZFS so I can mirror them om 4 different machines in 2 different locations. > >> While this is overkill for 1 server, I needed multiple because of >> fail-over and load-balancing, in this case I have 3 'crypto' boxes >> (with hardware crypto engines using OpenBSD) doing only the >> randomizing and 4 solaris machines doing the zfs and distribution of >> the list. > > I don't know what good that hardware crypto is doing you, if you're > then writing out the shuffled deck to disk in the clear. It's not about access security it's more about the best possible randomness to shuffle the deck. -- mph From jzgoda at o2.usun.pl Sat May 27 07:50:00 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Sat, 27 May 2006 13:50:00 +0200 Subject: Pyrex speed In-Reply-To: <1148729670.982351.132060@j33g2000cwa.googlegroups.com> References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> <4dqq38F1bi6btU1@uni-berlin.de> <1148728491.640293.298470@38g2000cwa.googlegroups.com> <1148728959.466305.23870@u72g2000cwu.googlegroups.com> <1148729670.982351.132060@j33g2000cwa.googlegroups.com> Message-ID: <e59eh9$hlk$1@nemesis.news.tpi.pl> Jim Lewis napisal: >>main point of Pyrex is ease of wrapping, not of speeding-up. > > Supposedly the primes example is 50 times faster. How often you perform primes calculations in your programs? In my >10 years of professional career in writing business software I never had an opportunity to do any more sophisticated math than simple adding, multiplying, subtracting and dividing. -- Jarek Zgoda http://jpa.berlios.de/ From fredrik at pythonware.com Wed May 31 02:40:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 31 May 2006 08:40:25 +0200 Subject: genexp performance problem? In-Reply-To: <SC5fg.18764$jP5.469405@twister1.libero.it> References: <SC5fg.18764$jP5.469405@twister1.libero.it> Message-ID: <e5jdoo$kj4$2@sea.gmane.org> Giovanni Bajo wrote: > I found this strange: > > python -mtimeit "sum(int(L) for L in xrange(3000))" > 100 loops, best of 3: 5.04 msec per loop > > python -mtimeit "import itertools; sum(itertools.imap(int, xrange(3000)))" > 100 loops, best of 3: 3.6 msec per loop > > I thought the two constructs could achieve the same speed. hint: how many times to the interpreter have to look up the names "int" and "L" in the two examples ? </F> From bnblazer at gmail.com Mon May 22 18:49:00 2006 From: bnblazer at gmail.com (Brian) Date: 22 May 2006 15:49:00 -0700 Subject: problem with my regex? In-Reply-To: <44722f53$0$2546$636a55ce@news.free.fr> References: <1148332545.563949.102290@38g2000cwa.googlegroups.com> <44722f53$0$2546$636a55ce@news.free.fr> Message-ID: <1148338140.550227.18880@i40g2000cwc.googlegroups.com> I sincerely appreciate your reply and the time you took to explain it. Thank you, Brian From conor.robinson at gmail.com Thu May 11 15:25:47 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 11 May 2006 12:25:47 -0700 Subject: Nested loops confusion In-Reply-To: <W8GdnaVYdtMnX__ZRVny1A@giganews.com> References: <W8GdnaVYdtMnX__ZRVny1A@giganews.com> Message-ID: <1147375547.892792.186830@g10g2000cwb.googlegroups.com> >I'm still not sure what was stopping the inner >loop from working earlier - but removing the redundancy in "j=0" and so >on seems to have solved it. Call me crazy, but be careful when programming python in different text editors and in general, ie cutting and pasting, tabing and spacing. Loops can look fine and not work (try moving around test print statements for iterators), in this case try re-tabing your indents so that everything is uniform in the editor you are using. From ptmcg at austin.rr._bogus_.com Wed May 3 09:12:23 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 03 May 2006 13:12:23 GMT Subject: Recommended data structure for newbie References: <1146626916.066395.206540@y43g2000cwc.googlegroups.com> <7Z16g.1536$CH2.1053@tornado.texas.rr.com> Message-ID: <X_16g.1544$CH2.1242@tornado.texas.rr.com> > You asked about data structures specifically. The core collections in > python are lists, dicts, and more recently, sets. (oops, also forgot tuples - very much like lists, but immutable) From deets at nospam.web.de Mon May 29 04:56:35 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 May 2006 10:56:35 +0200 Subject: dynamically loaded libraries References: <mailman.6300.1148878851.27775.python-list@python.org> Message-ID: <4dvrd2F1cabbdU1@uni-berlin.de> mhearne808 wrote: > I have a question about how dynamically loaded C++ modules work, which > I will phrase as a hypothetical scenario involving the Numeric module. > Please understand that I don't really care about Numeric per se, it's > just a useful example of a module that defines a generally useful data > type. > > Let's say I want to create a C++ Python extension module that has > methods accepting the Numeric array type as input, and also create > these arrays as output. > > In order to make this work, do I have to statically link against the > Numeric source, or do I only have to include the headers, under the > assumption (??) that the Numeric functionality will be available > because the Python executable has dynamically loaded it? You'll only need the dynamic libs. Of course they must be available on link- as well as run-time. Diez From grflanagan at yahoo.co.uk Tue May 16 05:41:33 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 16 May 2006 02:41:33 -0700 Subject: Python and Combinatorics References: <44697b5c$0$14794$4fafbaef@reader4.news.tin.it> Message-ID: <1147772493.232440.28230@i39g2000cwa.googlegroups.com> Nic wrote: > Hello, > I've a problem in defining a good Python code useful to articulate the > following algorithm. > Can you help me please? > Thanks a bunch, > Nic > > 1. Insert a number "n". > Example: 3 > > 2. List all the numbers < or = to n. > Example: 1,2,3. > > 3. Combine the listed numbers each other. > Example: > 12 > 13 > 23 > > 4. For each combination associate two letters a and b. > Example: > 12a > 12b > 13a > 13b > 23a > 23b > > 5. Combine the new combinations each other, provided that combinations > including the same couple of numbers (e.g. 12a and 12b) cannot be combined. > Example: > 12a 13a 23a > 12a 13b 23a > 12a 13b 23b > 12b 13a 23a > 12b 13b 23a > 12b 13b 23b > > PS > 12a 13a 23a and13a 23a 12a are the same thing. This might get you some of the way: def nkRange(n,k): m = n - k + 1 indexer = range(0, k) vector = range(1, k+1) last = range(m, n+1) yield vector while vector != last: high_value = -1 high_index = -1 for i in indexer: val = vector[i] if val > high_value and val < m + i: high_value = val high_index = i for j in range(k - high_index): vector[j+high_index] = high_value + j + 1 yield vector X = [ ''.join(map(str,x)) + y for x in nkRange(3,2) for y in ['a','b'] ] print X def kSubsets( alist, k ): n = len(alist) for vector in nkRange(n, k): ret = [] for i in vector: ret.append( alist[i-1] ) yield ret Y = [ ''.join(x) + y for x in kSubsets( '123', 2 ) for y in ['a','b']] print Y ['12a', '12b', '13a', '13b', '23a', '23b'] (a 'cross product' function may also help you - search this Group) Gerard From robert.kern at gmail.com Thu May 4 01:03:05 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 04 May 2006 00:03:05 -0500 Subject: Newbie question on code vetting In-Reply-To: <yvT5g.132$yh.117@trnddc04> References: <yvT5g.132$yh.117@trnddc04> Message-ID: <e3c1ud$d8o$1@sea.gmane.org> william.boquist at gte.net wrote: > Hi. > > I have visited the Python web site and read some information on who the > commiters are and how to go about submitting code to them, but I have not > been able to locate any information regarding the process for vetting the > code to identify any possible IP infringement before it is committed. How do > the committers ascertain the originality of the code before it becomes part > of the base? They tell themselves very sternly not to commit code that isn't appropriately licensed. > Is there any use of tools like BlackDuck ProtexIP or the > competing Palamida product to scan for matches to code that is already > licensed elsewhere? No. > Also, is the same or a different standard of IP assurance practiced for the > Cheese Shop? There is no vetting for the Cheese Shop. Anyone can post packages there. If some illegal-to-redistribute code is discovered, it will probably be removed by the administrators. This hasn't come up, yet, I don't think. If you want the code to be vetted, you have to do it yourself. Besides, if you don't trust the commiters and the package authors not to infringe on other peoples' IP, why do you trust them to report infringement? -- 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 andrew.arobert at gmail.com Mon May 22 14:56:05 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 22 May 2006 14:56:05 -0400 Subject: Class probkem - getting msg that self not defined In-Reply-To: <mFncg.420$Sf2.95@newsread1.news.pas.earthlink.net> References: <12740frcoaju883@corp.supernews.com> <mFncg.420$Sf2.95@newsread1.news.pas.earthlink.net> Message-ID: <12742avhp3vmac8@corp.supernews.com> wes weston wrote: > Andrew Robert wrote: >> Hi Everyone, >> >> I am having a problem with a class and hope you can help. >> >> When I try to use the class listed below, I get the statement that self >> is not defined. >> >> test=TriggerMessage(data) > > self is not known here; only inside the class. > >> var = test.decode(self.qname) >> <snip> I guess I was barking up the wrong tree on that one. How would I go about getting the required values out of the class? Return self? From M.Waack at gmx.de Fri May 19 10:32:34 2006 From: M.Waack at gmx.de (Mathias Waack) Date: Fri, 19 May 2006 14:32:34 GMT Subject: SIGILL importing random Message-ID: <6Gkbg.612$RG3.10453@se2-cb104-9.zrh1.ch.colt.net> Hi all, I've embedded python into an older application and created some extensions to interact with the old data structures. Everythings works like a charm - beside a simple "import random". During import the whole process crashes with a SIGILL. I've found some older mails describing just the same problem: http://mail.python.org/pipermail/python-dev/2003-May/035386.html Unfortunately I'm not able to read x86 assembler code:( I'm using gcc version 4.0.3 (Debian 4.0.3-1) and python: Python 2.3.5 (#2, Mar 6 2006, 10:12:24) [GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2 Everything out of the box from Debian unstable. Anybody with any idea about this? Mathias From mariano.difelice at gmail.com Thu May 11 07:06:47 2006 From: mariano.difelice at gmail.com (mariano.difelice at gmail.com) Date: 11 May 2006 04:06:47 -0700 Subject: Python memory deallocate Message-ID: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> Hi, I've a big memory problem with my application. First, an example: If I write: a = range(500*1024) I see that python process allocate approximately 80Mb of memory. What can i do for DEALLOCATE this memory, or good part of this? My really problem is that my program work with more photos, which I open with PIL package. When I start it, my program allocate approximately 200Mb memory. If I want abort actual work and restart without restarting python process, the memory usage will go up approximately 380-400 Mb. I would like find something that DEallocate the memory not used. I've tried with gc python module, but don't work fine (it deallocate approximately 20-30 Mb) I've tried with Destroy, del command, but the memory don't show down. Thx I'm very desperate From michele.simionato at gmail.com Thu May 11 02:54:09 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 May 2006 23:54:09 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <m3irodpxt9.fsf@rigel.goldenthreadtech.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> Message-ID: <1147330449.102694.317200@i40g2000cwc.googlegroups.com> jayessay wrote: > I was saying that you are mistaken in that pep-0343 could be used to > implement dynamically scoped variables. That stands. Proof by counter example: from __future__ import with_statement import threading special = threading.local() def getvar(name): return getattr(special, name) def setvar(name, value): return setattr(special, name, value) class dynamically_scoped(object): def __init__(self, name, value): self.name = name self.value = value def __context__(self): return self def __enter__(self): self.orig_value = getvar(self.name) setvar(self.name, self.value) def __exit__(self, Exc, msg, tb): setvar(self.name, self.orig_value) if __name__ == '__main__': # test setvar("*x*", 1) print getvar("*x*") # => 1 with dynamically_scoped("*x*", 2): print getvar("*x*") # => 2 print getvar("*x*") # => 1 If you are not happy with this implementation, please clarify. Michele Simionato From tim.leeuwvander at nl.unisys.com Wed May 17 03:45:56 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 17 May 2006 00:45:56 -0700 Subject: Option parser question - reading options from file as well as command line In-Reply-To: <126k3273j7kb28f@corp.supernews.com> References: <126k3273j7kb28f@corp.supernews.com> Message-ID: <1147851955.954641.180880@38g2000cwa.googlegroups.com> Andrew Robert wrote: > Hi Everyone. > > > I tried the following to get input into optionparser from either a file > or command line. > > > The code below detects the passed file argument and prints the file > contents but the individual swithces do not get passed to option parser. > After reading your post I decided to play around with optparse a bit, to get acquainted with it. Experimenting with IDLE I found that the Values object returned by parse_args has a method 'readfile', and this 'readfile' method allows you to add options to the Values object. The syntax should be in the form: <option>=<value> <option> should not include the hyphens -- if your option is added as '-x', then you should write: x=3 not: -x=3 If you have options with both long names and short names, then you should use the long name -- if your option is added as '-f', '--file', then you should write: file=foo.txt not: f=foo.txt Also, you need the assignment-operator in your file. I didn't find any documentation on this, and I didn't try this with any actions; only with options added to the parser like op.add_option('-x', dest='x') Using this 2-step approach allows you to use optparse itself to get to the command-line option with your command-line settings... Out of pure personal interest, what queuing-system are you writing to from Python? What libraries do you have for that? And is it commercial software, or freely downloadable? (I'd love to be able to write messages to IBM MQ Series from Python) Cheers, --Tim From brian at sweetapp.com Mon May 15 13:25:42 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 15 May 2006 19:25:42 +0200 Subject: Tabs versus Spaces in Source Code In-Reply-To: <qz2ag.6572$fb2.2976@newssvr27.news.prodigy.net> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <qz2ag.6572$fb2.2976@newssvr27.news.prodigy.net> Message-ID: <4468B996.5000407@sweetapp.com> Edward Elliott wrote: > Tab is not 4 spaces. Tab is 1 level of indentation. The confusion that > tabs equals some fixed width, or can/should be set to some fixed width, is > the entire problem hampering their use. It implies that conversion between > tabs and spaces is straightforward when it is not. They are not comparable > entities. The problem with tabs is that people use tabs for alignment e.g. def foo(): ->query = """SELECT * -> -> -> FROM sometable -> -> -> WHERE condition""" Now I change my editor to use 8-space tabs and the code is all messed up. Of course, a very disciplined group of people could be trained to never use tabs except to align with the current block level but, in practice, that doesn't work. Therefore tabs are bad. Cheers, Brian From m.yanowitz at kearfott.com Thu May 4 08:00:47 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 4 May 2006 08:00:47 -0400 Subject: Python function returns: In-Reply-To: <4459e6b8@127.0.0.1> Message-ID: <HGEOKIAPAMCIFPPBDALKIEIDCAAA.m.yanowitz@kearfott.com> I am still new to Python but have used it for the last 2+ months. One thing I'm still not used to is that functions parameters can't change as expected. For example in C, I can have status = get_network_info (strIpAddress, &strHostname, &nPortNumber) where this fictitious function returns a status, but also returns modified values for a hostname and a port number. In Python, there does not seem to be an easy way to have functions return multiple values except it can return a list such as: strHostname, nPortNumber, status = get_network_info (strIpAddress, strHostname, nPortNumber) Am I missing something obvious? Is there a better, or more standard way to return values from functions? Thanks in advance: Michael Yanowitz From johnjsal at NOSPAMgmail.com Tue May 2 21:52:29 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 21:52:29 -0400 Subject: simultaneous assignment In-Reply-To: <mailman.5224.1146604977.27775.python-list@python.org> References: <8dM5g.2031$No6.43874@news.tufts.edu> <RAN5g.2037$No6.43926@news.tufts.edu> <e38ghu$he1$1@avnika.corp.mot.com> <mailman.5224.1146604977.27775.python-list@python.org> Message-ID: <44580dd5$0$5389$c3e8da3@news.astraweb.com> Heiko Wundram wrote: > Hummm... Isn't it easier and faster to solve this problem by hand than to code > a Python program for it? I had proofs for what has to be on both papers in > about 30 seconds... ;-) Yeah, I had actually already figured it out in my head fairly quickly. > If you're looking for things to code in Python, I'd rather suggest you look at > number theory than at logic problems. Basically, every logic problem can be > solved by exhaustive search (which is always the same algorithm), whereas a > number theory problem requires that you implement a certain algorithm from > scratch for each problem you're trying to tackle. Thanks for the suggestion. Do you know where I might find number theory problems that aren't too complicated? (No math degree here, in fact, just the opposite: English!) :) From Serge.Orlov at gmail.com Thu May 11 17:46:39 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 May 2006 14:46:39 -0700 Subject: FTP filename escaping References: <1147375459.332757.212570@u72g2000cwu.googlegroups.com> <1147377391.521967.26730@j33g2000cwa.googlegroups.com> Message-ID: <1147383999.022322.80060@q12g2000cwa.googlegroups.com> Almad wrote: > OK, after some investigation...problem is in non-latin characters in > filenames on ftp. > > Yes, users should be killed for this, It's futile, users will always find a way to crash you program :) And you can't kill them all, there are too many of them. > but I would like to handle it > somehow... It depends on what you're actually doing. Did you write the ftp server? Or do you have any information about server (OS etc...)? Is your client the only client who can upload? Do you care how file names actually look interally in the server? > I can't figure out how it's handled by protocol, ftplib seems to just > strip those characters... I believe filename == sequence of bytes terminated by newline byte. I doubt ftplib strips bytes over 127. Even if it does, copy it to your private module collection as ftplibng.py, fix it and import ftplibng as ftplib From t.buehler at codeforge.ch Thu May 11 14:10:52 2006 From: t.buehler at codeforge.ch (t.buehler) Date: Thu, 11 May 2006 18:10:52 -0000 Subject: multi-threaded c++ callback problem Message-ID: <200604112004068288996@codeforge.ch> hi all, i'm building a wrapper for a multi-threaded c++ library to use it in python. everything works fine except the callback. the c++ code to call the python function: //-----------------------------------------------------------// void pyCallEventCallback( CALL hCall, LINE hLine, CALLSTATE_MAJOR eMajor, CALLSTATE_MINOR eMinor, PyObject* def ) { if( !PyCallable_Check( def ) ) { PyErr_SetString( PyExc_TypeError, "Need a callable object!" ); return; } printf( "EventCallback hCall: %i, hLine: %i, eMajor: %i, eMinor: %i\n", hCall, hLine, eMajor, eMinor); PyObject* arglist = Py_BuildValue("(iiii)", hCall, hLine, eMajor, eMinor); // if i comment out next line it works! PyEval_CallObject( def, arglist ); Py_XDECREF(arglist); } //-----------------------------------------------------------// the python callback function looks like this: //-----------------------------------------------------------// def callback( *args ): print "callback:", args //-----------------------------------------------------------// the soutput i get looks like this: EventCallback hCall: 1, hLine: 1, eMajor: 2000, eMinor: 2001 callback: ( 1, 1, 2000, 2001 ) EventCallback hCall: 1, hLine: 1, eMajor: 2500, eMinor: 2501 callback: ( 1, 1, 2500, 2501 ) EventCallback hCall: 1, hLine: 1, eMajor: 8000, eMinor: 8001 an then instead of: callback: ( 1, 1, 8000, 8001) it crashes there are no other python interactions between the callback calls. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060511/b4341fa7/attachment.html> From patrick.d.hull at gmail.com Thu May 11 12:01:15 2006 From: patrick.d.hull at gmail.com (patrick.d.hull at gmail.com) Date: 11 May 2006 09:01:15 -0700 Subject: pythoncode in matlab References: <4cgogmF15ljumU1@news.dfncis.de> Message-ID: <1147363274.990265.163990@i39g2000cwa.googlegroups.com> check out PyMat: http://claymore.engineer.gvsu.edu/~steriana/Python/pymat.html I've never used it but I believe it should work for your needs. However, I highly recommend taking a look at SAGE: http://modular.math.washington.edu/sage/ which has an interface to octave. -ph From defcon8 at gmail.com Sun May 14 05:01:03 2006 From: defcon8 at gmail.com (defcon8) Date: 14 May 2006 02:01:03 -0700 Subject: Cellular automata and image manipulation In-Reply-To: <1147596765.468995.292560@v46g2000cwv.googlegroups.com> References: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> <i4OdnQZa45PQ7_vZUSdV9g@ptd.net> <1147595982.184878.25800@d71g2000cwd.googlegroups.com> <1147596298.106352.245420@j33g2000cwa.googlegroups.com> <1147596765.468995.292560@v46g2000cwv.googlegroups.com> Message-ID: <1147597263.803555.243660@i39g2000cwa.googlegroups.com> Actually never mind either. I guessed I needed to append all values after eachother in one row list: x = [] for y in buff: for z in y: x.append(z) thanks for the help From scott.daniels at acm.org Mon May 8 12:52:48 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 09:52:48 -0700 Subject: Python Graphics Library In-Reply-To: <1147099026.983602.148160@v46g2000cwv.googlegroups.com> References: <1147099026.983602.148160@v46g2000cwv.googlegroups.com> Message-ID: <445f73a8$1@nntp0.pdx.net> utab wrote: > Dear all, > > Could you please recommend me a graphics library for python. I saw PYX > which has nice screenshots on the webpage. > > My first ambition is to be able to draw 2D or 3D graphs for my > mathematical results. Maybe later, I can handle other types of > graphical operations. PIL (Python Imaging Library) is the "standard" Python graphics library. It is used to create images in the form of pictures and saving as .png, .jpg, or whatever. http://www.pythonware.com/products/pil/ Also check out ReportLab and my constant recommendation, VPython. http://www.reportlab.org -- generate PDFs. http://www.vpython.org -- 3(or 2)-D as interactive display graphics. It gives real 3-D graphics (mouse can roll & zoom). VPython can also put out POV-Ray source ( http://www.povray.org ). --Scott David Daniels scott.daniels at acm.org From sjmachin at lexicon.net Fri May 26 16:46:30 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 27 May 2006 06:46:30 +1000 Subject: Speed up this code? In-Reply-To: <1148649951.816182.134210@g10g2000cwb.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <4476d3ac_2@newspeer2.tds.net> <1148647447.804097.228580@j33g2000cwa.googlegroups.com> <1148649951.816182.134210@g10g2000cwb.googlegroups.com> Message-ID: <44776926.3020305@lexicon.net> On 26/05/2006 11:25 PM, Frank Millman wrote: > bearophileHUGS at lycos.com wrote: >> If you are interested in such programs, you can take a look at this one >> too: >> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178 >> >> It requires more memory, but it's quite fast. >> >> Bye, >> bearophile > > I compared the speed of this one (A) with the speed of Paul Rubin's > above (B). > > Primes from 1 to 100 - > A - 0.000118 > B - 0.000007 > > Primes from 1 to 200 - > A - 0.000224 > B - 0.000008 > > Primes from 1 to 300 - > A - 0.000278 > B - 0.000008 > > Nice one, Paul. > > Frank Millman > Nice one, Frank. Go back and read Paul's code. Read what he wrote at the bottom: """It's cute, but horrendous once you realize what it's doing ;-) """ Pax Heisenberg, it is innately horrendous, whether observers realise it or not :-) From bearophileHUGS at lycos.com Wed May 10 16:13:13 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 10 May 2006 13:13:13 -0700 Subject: data entry tool In-Reply-To: <446236d5@news.maxnet.co.nz> References: <445f038f@news.maxnet.co.nz><4461a499@news.maxnet.co.nz> <1147267750.833367.234180@v46g2000cwv.googlegroups.com> <446236d5@news.maxnet.co.nz> Message-ID: <1147291993.831470.156300@y43g2000cwc.googlegroups.com> Peter wrote>Wow - why so big for such a simple tool? 2MB sounds like a LOT of coding.< Yes, it's a lot of code, but it's code written by other people (Python, Tkinter). Using Tkinter your program will probably be quite short, even if you use some dbase. If the data to be entered is simple and textual you can even think about using a text only interface. The resulting program will be really simple, and probably good enough. 2+ MB is the size of the executable package you need to give people to install Python + some libs + your program. Bye, bearophile From doug.bromley at gmail.com Fri May 5 09:13:40 2006 From: doug.bromley at gmail.com (Doug Bromley) Date: Fri, 5 May 2006 14:13:40 +0100 Subject: Can I use python for this .. ?? In-Reply-To: <1146831346.298953.144110@e56g2000cwe.googlegroups.com> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146831346.298953.144110@e56g2000cwe.googlegroups.com> Message-ID: <288425520605050613g130d0f8eu40d70b52debb386c@mail.gmail.com> Careful of using the wrong tool for the job. Don't use Python for the sake of it unless its as a learning experience. All of the things you ask for can be done by simply using the Windows start menu to launch a shortcut with various command line options. Voila - problem solved. On 5 May 2006 05:15:46 -0700, nikie <n.estner at gmx.de> wrote: > > san wrote: > > > Hi > > > > I am using windows xp and have installed python and win32. I am > > familiar with basic Python. I wanted to control some of the > > applications via python script. > > > > I would like to write a python script to say: > > 1. Open firefox and log on to gmail > > 2. Another firefox window to visit slickdeals > > 3. Open winamp and tune in to a shoutcast station > > 4. Open groupwise ... > > etc .. > > > > These are the task I do every day whenever I log on my computer .. it > > just seems repetitive and hence probably can be coded in python. > > > > Can I do this in python? Where do I find the COM objects/interfaces for > > all these different programs? Are there any sample codes ? > > I just googled for "iTunes com python", there are lots of samples. If > you can't find any, or want to find out about an applications > interfaces yourself, you can sill use MakePy to find out what com > interfaces are installed on your computer, and simply use the "dir" and > "help" commands in the interactive console on those interfaces to find > out what they do. (There are other tools to explore COM interfaces, > like OleView, but if you're familiar with Python already, using > dir/help is probably going to be easier) > Reading Mark Hammond's excellent book (or at least the sample chapter > on automation) wouldn't hurt either ;-) > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060505/d2606e6f/attachment.html> From ognjen at mailshack.com Sun May 14 16:23:52 2006 From: ognjen at mailshack.com (Ognjen Bezanov) Date: Sun, 14 May 2006 21:23:52 +0100 Subject: Converting String to int In-Reply-To: <44678C99.5020003@tim.thechases.com> References: <mailman.3510.1143024593.27775.python-list@python.org> <200605141933.57679.ognjen@mailshack.com> <44678C99.5020003@tim.thechases.com> Message-ID: <200605142123.52846.ognjen@mailshack.com> Hi all, Another problem, with the same error (error: "invalid literal for int()") code: mynums = "423.523.674.324.342.122.943.421.762.158.830" mynumArray = string.split(mynums,".") x = 0 for nums in mynumArray: if nums.isalnum() == true: x = x + int(nums) else: print "Error, element contains some non-numeric characters" break /end code This seemed like a simple thing, and I have done it before with no issues. have I missed something obvious? taking into account my previous hex question, I tried changing int(nums) to int(nums,10) but it still gives me the error From S.Jerzembeck at itm.rwth-aachen.de Thu May 11 08:20:37 2006 From: S.Jerzembeck at itm.rwth-aachen.de (Sven Jerzembeck) Date: Thu, 11 May 2006 13:20:37 +0100 Subject: pythoncode in matlab Message-ID: <4cgogmF15ljumU1@news.dfncis.de> Hello guys, is there any possibiliy using Phython code in Matlab. I couldnt find any helpful stuff. Its not graphical stuff I am doing just calculations with arrays and strings. Thanks for answering in advance Sven From andre.roberge at gmail.com Fri May 5 07:19:49 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 5 May 2006 04:19:49 -0700 Subject: ANN: Crunchy Frog 0.2.5 Message-ID: <1146827989.367164.157060@j33g2000cwa.googlegroups.com> Crunchy Frog is a "desktop web application" that transforms a traditional Python web-based tutorial into an interactive session within a browser. At present it is limited to tutorials (html files) that are contained within a single directory on the computer where it is run. You can download from https://sourceforge.net/project/showfiles.php?group_id=125834 It consists of 3 python files, 5 sample html files in a single 10kB zipped file. Crunchy Frog is based on CherryPy (www.cherrypy.org) and requires Elementtree. Further instructions are provided in the file readme_first.html. From rpdooling at gmail.com Wed May 10 13:48:54 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 May 2006 10:48:54 -0700 Subject: reusing parts of a string in RE matches? In-Reply-To: <M2o8g.2080$No6.45875@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> Message-ID: <1147283334.610613.220770@j33g2000cwa.googlegroups.com> I have to at least try :) s = "abababababababab" for x in range(len(s)): ... try: ... s.index("aba", x, x + 3) ... except ValueError: ... pass rd From robert.kern at gmail.com Fri May 19 14:12:18 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 19 May 2006 13:12:18 -0500 Subject: WTF? Printing unicode strings In-Reply-To: <17517.64871.44237.790358@montanaro.dyndns.org> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <RFkbg.2124$No6.46433@news.tufts.edu> <e4kruq$19o$1@sea.gmane.org> <17517.64871.44237.790358@montanaro.dyndns.org> Message-ID: <e4l1q1$m9i$1@sea.gmane.org> skip at pobox.com wrote: > Robert> Because sys.stdout.encoding isn't determined by your Python > Robert> configuration, but your terminal's. > > Learn something every day. I take it "646" is an alias for "ascii" (or vice > versa)? > > % python > Python 2.4.2 (#1, Feb 23 2006, 12:48:31) > [GCC 3.4.1] on sunos5 > Type "help", "copyright", "credits" or "license" for more information. > >>> import sys > >>> sys.stdout.encoding > '646' > >>> import codecs > >>> codecs.lookup("646") > (<built-in function ascii_encode>, <built-in function ascii_decode>, <class encodings.ascii.StreamReader at 0x819aa4c>, <class encodings.ascii.StreamWriter at 0x819aa1c>) Yes. In encodings/aliases.py in the standard library: """ aliases = { # Please keep this list sorted alphabetically by value ! # ascii codec '646' : 'ascii', """ -- 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 ryan at cs.uoregon.edu Wed May 3 18:36:53 2006 From: ryan at cs.uoregon.edu (Ryan Forsythe) Date: Wed, 03 May 2006 15:36:53 -0700 Subject: scope of variables In-Reply-To: <87zmhyagqq.fsf@localhost.localdomain> References: <874q06bz4c.fsf@localhost.localdomain> <pan.2006.05.03.21.37.01.804277@hastings.org> <87zmhyagqq.fsf@localhost.localdomain> Message-ID: <44593085.8080409@cs.uoregon.edu> Gary Wessle wrote: > the example was an in-accuretlly representation of a the problem I am > having. my apologies. > > a = [] > def prnt(): > print len(a) > >>>> prnt > <function prnt at 0xb7dc21b4> > > I expect to get 0 "the length of list a" You want prnt(), not prnt: >>> a = [] >>> def prnt(): ... print len(a) ... >>> prnt <function prnt at 0x43c70> >>> prnt() 0 --Ryan From pydecker at gmail.com Wed May 31 19:35:37 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 31 May 2006 19:35:37 -0400 Subject: using import * with GUIs? In-Reply-To: <bsmfg.2202$No6.47400@news.tufts.edu> References: <R2mfg.2200$No6.47332@news.tufts.edu> <mailman.6381.1149104575.27775.python-list@python.org> <bsmfg.2202$No6.47400@news.tufts.edu> Message-ID: <ca55a9900605311635q6876dcffj196db2463c8fd50c@mail.gmail.com> On 5/31/06, John Salerno <johnjsal at nospamgmail.com> wrote: > I guess if I'm going to learn a GUI, I might as well jump right into > wxPython from the beginning. May I recommend that you take a look at the Dabo project? While they have a full application framework for creating database applications, you can easily just use the dabo.ui module, which wraps wxPython. This eliminates most of the C++ cruft that wxPython inherited from wxWidgets, and makes for a much more Pythonic experience. I worked with wxPython for a couple of years, and looked at Dabo based on a recommendation on the wxPython list. Since then, I haven't written a single app using raw wxPython; I use the dabo.ui module for all my GUI applications. It gives you all the advantages of wxPython, but it just works better. -- # p.d. From jes at nl.demon.net Sat May 20 19:09:21 2006 From: jes at nl.demon.net (Jim Segrave) Date: Sat, 20 May 2006 23:09:21 -0000 Subject: buffers readlines and general popen2 confusion... References: <1148162219.463249.155680@j33g2000cwa.googlegroups.com> Message-ID: <126v8d1cpk0ci8a@corp.supernews.com> In article <1148162219.463249.155680 at j33g2000cwa.googlegroups.com>, aristotelian at onet.eu <aristotelian at onet.eu> wrote: >I'm interested in taking the output of a daemonized shell script that >greps for patterns which would act as an argument to a script. Is it >better to write this stuff to file and visit the file every few seconds >or can this be done a better way. I'm hoping for a more elegant >solution. So far I've seen some troubling info about buffer overflows >with popen2 but it looks like the low-hanging fruit. I'm not a unixpro >so I want to make sure anything I tackle is best practice. Suggestions >welcomed. I'm puzzled - a daemonised program normally closes stdin/stdout/stderr and disconnects from its controlling terminal, so where is its output going? -- Jim Segrave (jes at jes-2.demon.nl) From zacherates at gmail.com Tue May 16 16:36:03 2006 From: zacherates at gmail.com (zacherates at gmail.com) Date: 16 May 2006 13:36:03 -0700 Subject: How to log only one level to a FileHandler using python logging module. References: <1147803042.198679.236260@j73g2000cwa.googlegroups.com> Message-ID: <1147811763.306366.89640@j73g2000cwa.googlegroups.com> Try looking into logging.Filters: http://docs.python.org/lib/node358.html An example: import logging class InfoFilter(logging.Filter): def filter(self, record): return record.levelno == 20 if __name__ == "__main__": logger = logging.getLogger() hdlr = logging.FileHandler("blah.log") hdlr.addFilter(InfoFilter()) logger.addHandler(hdlr) logger.exception("ERROR WILL ROBINSON") Cheers, Aaron fuzzylollipop wrote: > I want a FileHandler to only log a single level say for example > logging.INFO, and nothing else. > do I need to create a custom Handler for this or is this doable with > some magic that is not documeneted somewhere? From spam at me.please Tue May 2 08:51:37 2006 From: spam at me.please (Skink) Date: Tue, 02 May 2006 14:51:37 +0200 Subject: pyqt v3.* and v4.* In-Reply-To: <mailman.5211.1146571881.27775.python-list@python.org> References: <e37hnm$51k$1@news2.ipartners.pl> <mailman.5211.1146571881.27775.python-list@python.org> Message-ID: <e37kkn$6kk$1@news2.ipartners.pl> Phil Thompson wrote: > > > Install the latest versions of PyQt3 and SIP. Thanks Phil! v4.0 & v3.16 work with sip 4.4.3 ;) skink From duncan.booth at invalid.invalid Tue May 9 05:47:58 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 9 May 2006 09:47:58 GMT Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> <e3ndsm$rfa$1@mlucom4.urz.uni-halle.de> <Xns97BD8F2E0EE6Eduncanbooth@127.0.0.1> <e3nh1h$saa$1@mlucom4.urz.uni-halle.de> <slrne5ukoj.4ob.nick@irishsea.home.craig-wood.com> <Xns97BDA5543F8B1duncanbooth@127.0.0.1> <e3pih1$hsb$1@mlucom4.urz.uni-halle.de> Message-ID: <Xns97BE6DD44B4D7duncanbooth@127.0.0.1> Mirco Wahab wrote: > If you wouldn't need dictionary lookup and > get away with associated categories, all > you'd have to do would be this: > > $PATTERN = qr/ > (blue |white |red )(?{'Colour'}) > | (socks|tights )(?{'Garment'}) > | (boot |shoe |trainer)(?{'Footwear'}) > /x; > > $t = 'blue socks and red shoes'; > print "$^R: $^N\n" while( $t=~/$PATTERN/g ); > > What's the point of all that? IMHO, Python's > Regex support is quite good and useful, but > won't give you an edge over Perl's in the end. If you are desperate to collapse the code down to a single print statement you can do that easily in Python as well: >>> PATTERN = ''' (?P<Colour>blue |white |red) | (?P<Garment>socks|tights) | (?P<Footwear>boot |shoe |trainer) ''' >>> t = 'blue socks and red shoes' >>> print '\n'.join("%s:%s" % (match.lastgroup, match.group(match.lastgroup)) for match in re.finditer(PATTERN, t, re.VERBOSE)) Colour:blue Garment:socks Colour:red Footwear:shoe From me at privacy.net Tue May 9 06:31:38 2006 From: me at privacy.net (Dan Sommers) Date: Tue, 09 May 2006 06:31:38 -0400 Subject: advanced number recognition in strings? References: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> <e3nud4$lib$1@reader1.panix.com> Message-ID: <m264kfebg5.fsf@unique.fqdn> On Mon, 8 May 2006 17:16:20 +0000 (UTC), roy at panix.com (Roy Smith) wrote: > s.schmeier at gmail.com <s.schmeier at gmail.com> wrote: >> we want extract numbers from strings and wonder if there is already a >> module around for doing this. An example in our case would look like >> this: >> >> 0.032 +/- 0.5 x 10(-4) >> >> it would even be helpful to have a routine which does not recognise the >> +/- , but at least the 10(-4). [ ... ] > That being said, e-notation does not represent uncertainty, but then > again, neither does an IEEE float. To keep the uncertainty, you need > to create a new numeric class which stores the mantissa, the > uncertainty, and the exponent. Perhaps you could get away with > storing the mantissa and exponent as a standard float, but you'd still > need to store the uncertainty. Then you'd (presumably) need to define > a whole set of math operators which did something useful with these > numbers. For example, what should: For a physics course I took a couple of years ago, I developed a number-like class that kept track of uncertainties through various calculations. I used a float for both the value and the uncertainty, and wrote my own __str__ method to make the output look nice. I didn't have to parse anything at run-time, though. I half-implemented the code to track units as well (IOW, I implemented just enough to meet my own requirements). I can post the code somewhere if anyone is interested. > x = 0.032 +/- 0.5 x 10(-4) > y = 0.032 +/- 1.0 x 10(-4) > print x == y > print out? Regards, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From jcb at iteris.com Tue May 9 17:58:07 2006 From: jcb at iteris.com (Metalone) Date: 9 May 2006 14:58:07 -0700 Subject: interactive shell -- reload definitions? Message-ID: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> I have a question about the interactive Python shell. Is it possible to reload a file and get the new definitions. For example, if I do import xyz Then I find a bug in some function in xyz. So, I edit xyz.py I would like to reload the definitions in xyz.py without leaving my current shell session. Is this possible? Also, is there any way to save definitions created in the interactive shell to a file? Sometimes I write a simple function in the shell, and this wish I had that function in an external file. Thanks. From invalidemail at aerojockey.com Sat May 20 05:02:14 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 20 May 2006 02:02:14 -0700 Subject: noob import question In-Reply-To: <mailman.5949.1148047024.27775.python-list@python.org> References: <mailman.5945.1148045097.27775.python-list@python.org> <4d5vqaF18i4l1U1@uni-berlin.de> <mailman.5949.1148047024.27775.python-list@python.org> Message-ID: <1148115734.344359.95490@i39g2000cwa.googlegroups.com> PA wrote: > On May 19, 2006, at 15:33, Diez B. Roggisch wrote: > > > And it seems as if you have some JAVA-background, putting one class in > > one > > file called the same as the class. Don't do that, it's a stupid > > restriction > > in JAVA and should be avoided in PYTHON. > > Restrictive or not, what's so fundamentally devious in putting a class > declaration in a separate file whose name is that of the declared class > (class Queue -> Queue.py)? > > Sounds like a handy way of organizing your code, no? Handy for a lazy programmer, maybe. Confusing for the reader, though (do you mean Queue module, or Queue class? I must scroll up...). And highly tacky. I recommend avoiding it. For modules, I recommend "act of" words (words ending in -ing and -ion) because such words aren't common identitiers. So queuing instead of Queue. Unfortunately, the Python library isn't setting a good example here. Too much glob.glob, time.time, socket.socket, and Queue.Queue. I hope all these go away in Python 3000. Carl Banks From pink at odahoda.de Tue May 23 17:56:57 2006 From: pink at odahoda.de (Benjamin Niemann) Date: Tue, 23 May 2006 23:56:57 +0200 Subject: GUI viewer for profiler output? References: <44731f6c$1_1@newspeer2.tds.net> Message-ID: <e500f9$mnb$1@online.de> Kent Johnson wrote: > Can anyone point me to a GUI program that allows viewing and browsing > the output of the profiler? I know I have used one in the past but I > can't seem to find it... If you use KDE, then you can convert the output of the hotshot profiler to into a format that KCachegrind can read (using a script called hotshot2calltree, which is part of KCachegrind). If anyone has a more direct solution, I'd be interested, too :) -- Benjamin Niemann Email: pink at odahoda dot de WWW: http://pink.odahoda.de/ From etu.suku at iki.fi.invalid Mon May 15 09:39:37 2006 From: etu.suku at iki.fi.invalid (Ilkka Poutanen) Date: Mon, 15 May 2006 13:39:37 +0000 (UTC) Subject: Web development with python. References: <1147699600.770756.123120@v46g2000cwv.googlegroups.com> Message-ID: <slrne6h14q.7r4.etu.suku@korppi.cs.tut.fi> On 2006-05-15, j.paston.cooper at gmail.com <j.paston.cooper at gmail.com> wrote: > Is Plone analoguous to ASP.NET? Is it a python web developing platform? Plone is analoguous to something line Kentico CMS[1]. Plone runs on Zope which is an application server, being to Python sort of what IIS is to ASP.NET, I think. Don't take my word for it. You might want to read the introductory documentation[1][2] for Zope and Plone. 1. http://www.kentico.com/ 2. http://plone.org/about/plone/ 3. http://www.zope.org/WhatIsZope -- Ilkka Poutanen [http://ipo.iki.fi/] And unto this, Conan; From Serge.Orlov at gmail.com Fri May 19 07:28:49 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 May 2006 04:28:49 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> <1147998139.268318.315250@y43g2000cwc.googlegroups.com> <rNOSPAMon-AC0C9B.18040918052006@news.gha.chartermi.net> <1148001708.183506.296240@g10g2000cwb.googlegroups.com> <rNOSPAMon-96A79F.00032619052006@news.gha.chartermi.net> <1148029074.083644.112370@i40g2000cwc.googlegroups.com> Message-ID: <1148038129.231027.118010@g10g2000cwb.googlegroups.com> Serge Orlov wrote: > Ron Garret wrote: > > In article <1148001708.183506.296240 at g10g2000cwb.googlegroups.com>, > > "Serge Orlov" <Serge.Orlov at gmail.com> wrote: > > > > > Ron Garret wrote: > > > > > > I'm using an OS X terminal to ssh to a Linux machine. > > > > > > > > > > In theory it should work out of the box. OS X terminal should set > > > > > enviromental variable LANG=en_US.utf-8, then ssh should transfer this > > > > > variable to Linux and python will know that your terminal is utf-8. > > > > > Unfortunately AFAIK OS X terminal doesn't set that variable and most > > > > > (all?) ssh clients don't transfer it between machines. As a workaround > > > > > you can set that variable on linux yourself . This should work in the > > > > > command line right away: > > > > > > > > > > LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > > > > > > > Or put the following line in ~/.bashrc and logout/login > > > > > > > > > > export LANG=en_US.utf-8 > > > > > > > > No joy. > > > > > > > > ron at www01:~$ LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > Traceback (most recent call last): > > > > File "<string>", line 1, in ? > > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > > > > position 0: ordinal not in range(128) > > > > ron at www01:~$ > > > > > > What version of python and what shell do you run? What the following > > > commands print: > > > > > > python -V > > > echo $SHELL > > > $SHELL --version > > > > ron at www01:~$ python -V > > Python 2.3.4 > > ron at www01:~$ echo $SHELL > > /bin/bash > > ron at www01:~$ $SHELL --version > > GNU bash, version 2.05b.0(1)-release (i386-pc-linux-gnu) > > Copyright (C) 2002 Free Software Foundation, Inc. > > ron at www01:~$ > > That's recent enough. I guess the distribution you're using set LC_* > variables for no good reason. Either unset all enviromental variables > starting with LC_ and set LANG variable or overide LC_CTYPE variable: > > LC_CTYPE=en_US.utf-8 python -c "print unichr(0xbd)" > > Should be working now :) I've pulled myself together and installed linux in vwware player. Apparently there is another way linux distributors can screw up. I chose debian 3.1 minimal network install and after answering all installation questions I found that only ascii and latin-1 english locales were installed: $ locale -a C en_US en_US.iso88591 POSIX In 2006, I would expect utf-8 english locale to be present even in minimal install. I had to edit /etc/locale.gen and run locale-gen as root. After that python started to print unicode characters. From nick at craig-wood.com Mon May 8 10:30:12 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Mon, 08 May 2006 09:30:12 -0500 Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> <e3ndsm$rfa$1@mlucom4.urz.uni-halle.de> <Xns97BD8F2E0EE6Eduncanbooth@127.0.0.1> <e3nh1h$saa$1@mlucom4.urz.uni-halle.de> Message-ID: <slrne5ukoj.4ob.nick@irishsea.home.craig-wood.com> Mirco Wahab <peace.is.our.profession at gmx.de> wrote: > After some minutes in this NG I start to get > the picture. So I narrowed the above regex-question > down to a nice equivalence between Perl and Python: > > Python: > > import re > > t = 'blue socks and red shoes' > if re.match('blue|white|red', t): > print t > > t = 'blue socks and red shoes' > if re.search('blue|white|red', t): > print t > > Perl: > > use Acme::Pythonic; > > $t = 'blue socks and red shoes' > if $t =~ /blue|white|red/: > print $t > > And Python Regexes eventually lost (for me) some of > their (what I believed) 'clunky appearance' ;-) If you are used to perl regexes there is one clunkiness of python regexpes which you'll notice eventually... Let's make the above example a bit more "real world", ie use the matched item in some way... Perl: $t = 'blue socks and red shoes'; if ( $t =~ /(blue|white|red)/ ) { print "Colour: $1\n"; } Which prints Colour: blue In python you have to express this like import re t = 'blue socks and red shoes' match = re.search('(blue|white|red)', t) if match: print "Colour:", match.group(1) Note the extra variable "match". You can't do assignment in an expression in python which makes for the extra verbiosity, and you need a variable to store the result of the match in (since python doesn't have the magic $1..$9 variables). This becomes particularly frustrating when you have to do a series of regexp matches, eg if ( $t =~ /(blue|white|red)/ ) { print "Colour: $1\n"; } elsif ( $t =~ /(socks|tights)/) { print "Garment: $1\n"; } elsif ( $t =~ /(boot|shoe|trainer)/) { print "Footwear: $1\n"; } Which translates to match = re.search('(blue|white|red)', t) if match: print "Colour:", match.group(1) else: match = re.search('(socks|tights)', t) if match: print "Garment:", match.group(1) else: match = re.search('(boot|shoe|trainer)', t) if match: print "Footwear:", match.group(1) # indented ad infinitum! You can use a helper class to get over this frustration like this import re class Matcher: def search(self, r,s): self.value = re.search(r,s) return self.value def __getitem__(self, i): return self.value.group(i) m = Matcher() t = 'blue socks and red shoes' if m.search(r'(blue|white|red)', t): print "Colour:", m[1] elif m.search(r'(socks|tights)', t): print "Garment:", m[1] elif m.search(r'(boot|shoe|trainer)', t): print "Footwear:", m[1] Having made the transition from perl to python a couple of years ago, I find myself using regexpes much less. In perl everything looks like it needs a regexp, but python has a much richer set of string methods, eg .startswith, .endswith, good subscripting and the nice "in" operator for strings. -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From grante at visi.com Sat May 27 13:45:27 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 17:45:27 -0000 Subject: How to control color of contour lines? Message-ID: <127h41neuk81408@corp.supernews.com> How do I get contour lines drawn in just one color (e.g. black)? Multicolored contour lines on top of a pm3d surface can be very hard to look at... -- Grant Edwards grante Yow! Is it 1974? What's at for SUPPER? Can I spend my visi.com COLLEGE FUND in one wild afternoon?? From tjreedy at udel.edu Fri May 12 21:58:05 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 12 May 2006 21:58:05 -0400 Subject: getting rid of pass References: <4ckrmbF16kr2bU1@news.dfncis.de> Message-ID: <e43efd$n9g$1@sea.gmane.org> "David Murmann" <david.murmann at rwth-aachen.de> wrote in message news:4ckrmbF16kr2bU1 at news.dfncis.de... > i just had this crazy idea: Agreed ;-) > instead of > while cond(): > pass > write > while cond(). Viewing statememts as functions of the program state, pass is the identity function/statement. Many languages have the equivalent. Being explicit is Python's style. Getting rid of it would gratuitously break code for no reason other than your esthetic preference. > i don't know whether this is syntactically unambiguous or replaces all > uses of pass, but i find it quite nice to read. while x/3. would become somewhat ambiguous. Terry Jan Reedy From johnjsal at NOSPAMgmail.com Wed May 10 09:52:30 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 13:52:30 GMT Subject: regular expressions, substituting and adding in one step? In-Reply-To: <4461d885$1_3@newspeer2.tds.net> References: <yEI7g.2056$No6.45379@news.tufts.edu> <4460e0d7$1_1@newspeer2.tds.net> <AY58g.2072$No6.45671@news.tufts.edu> <4461d885$1_3@newspeer2.tds.net> Message-ID: <yem8g.2074$No6.45664@news.tufts.edu> Kent Johnson wrote: > They're just not the right tool for > every job! Thank god for that! As easy as they've become to me (after seeming utterly cryptic and impenetrable), they are still a little unwieldy. Next step: learn how to write look-ahead and look-behind REs! :) From diffuser78 at gmail.com Wed May 10 19:02:44 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 10 May 2006 16:02:44 -0700 Subject: Memory leak in Python References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <ccl062h5tc24b4qe3d66b7hvh7ujgrklcp@4ax.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> <slrne63ae3.96g.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1147302164.557634.177170@v46g2000cwv.googlegroups.com> Sure, are there any available simulators...since i am modifying some stuff i thought of creating one of my own. But if you know some exisiting simlators , those can be of great help to me. Thanks From llosee at gmail.com Thu May 4 09:50:01 2006 From: llosee at gmail.com (Lou Losee) Date: Thu, 4 May 2006 09:50:01 -0400 Subject: Gettings subdirectories In-Reply-To: <5Fm6g.10137$9c6.6757@dukeread11> References: <e3au5u$drm$1@news.in.tum.de> <5Fm6g.10137$9c6.6757@dukeread11> Message-ID: <a6a837f50605040650g48e8f8b3yec9b2bb0b04d4e68@mail.gmail.com> import os.path os.path.isdir(file) Lou On 5/4/06, Philippe Martin <pmartin at snakecard.com> wrote: > > Hi, > > The second edition of "Programming Python - O'REILLY - Mark Lutz" shows > how > to do that using "os.path.walk" > > Philippe > > > > > > Florian Lindner wrote: > > > Hello, > > how can I get all subdirectories of a given directories? os.listdir() > > gives me all entries and I've found no way to tell if an object is a > file > > or a directory. > > > > Thanks, > > > > Florian > > -- > http://mail.python.org/mailman/listinfo/python-list > -- Artificial Intelligence is no match for Natural Stupidity -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060504/246b8733/attachment.html> From vbgunz at gmail.com Tue May 23 03:26:54 2006 From: vbgunz at gmail.com (vbgunz) Date: 23 May 2006 00:26:54 -0700 Subject: Don't wish to give up on a Tkinter GUI Builder :( Message-ID: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> Hello world, I tried looking everywhere for a decent Tkinter GUI builder and the closest I got to finding one before being horrified from looking at the source was vtcl @ http://vtcl.sourceforge.net. The next closest thing was page @ http://page.sourceforge.net/ Page just didn't cut it for me and I got several errors from it whereas vtcl was almost a dream come true. it was not only perfect but I had a full fledged gui design up and running at the click of a file in less than ten minutes with so many widgets neatly placed... When I looked at the source, it was in Tcl... It was huge at about 477 lines for a nice and complete interface... problem is I don't know Tcl from chinese... I assume it is Tcl because the extension on the generated file was Tcl... Man, what a let down... The following sites had nothing helpful on the subject at all... http://www.awaretek.com/toolkits.html http://wiki.python.org/moin/GuiProgramming http://groups.google.com/group/comp.lang.python http://google.com Yup, I searched it all.. Maybe I am searching with the wrong keywords or maybe not a single good gui designer for tkinter even exist? Chances are extremely high at this point the only robust GUI builder for Tkinter is probably Vim . please do not recommend Komodo... I am aware of wxPython, GTK, QT and several others but Tkinter strikes me as perfect... I am not at all worried about the looks of it just the idea of one gui on all platforms strikes me as nice! if at this point you're a veteran at Tkinter Gui design and you know for a fact no Tkinter Gui builder exist now and no plans on making one exist and you know everthing about Tkinter, please advise. Ok, even if you don't know everything do you have a suggestion? My main concern is one Gui builder for an interface for all platforms, no special editing per platform. Just one edit and its game over, hello world. Is this too much to ask for? Thank you for your time! From andyrsmith at googlemail.com Mon May 15 12:15:29 2006 From: andyrsmith at googlemail.com (andyrsmith at googlemail.com) Date: 15 May 2006 09:15:29 -0700 Subject: Finding yesterday's date with datetime In-Reply-To: <1147709343.491705.276360@v46g2000cwv.googlegroups.com> References: <1147709343.491705.276360@v46g2000cwv.googlegroups.com> Message-ID: <1147709729.561144.169540@j55g2000cwa.googlegroups.com> Try something like this... HTH. A. from datetime import * d1 = datetime( year=2006, month=5, day=15) d2 = datetime.now() for d in [d1,d2]: yest = d - timedelta(days =1 ) print "%s -> %s" % (d, yest) From nvasiliev at whiteriversoft.com Wed May 10 15:56:03 2006 From: nvasiliev at whiteriversoft.com (Nicolay A. Vasiliev) Date: Wed, 10 May 2006 23:56:03 +0400 Subject: MySQLdb trouble In-Reply-To: <Xnm8g.2076$No6.45677@news.tufts.edu> References: <mailman.5547.1147249433.27775.python-list@python.org> <Xnm8g.2076$No6.45677@news.tufts.edu> Message-ID: <44624553.3080502@whiteriversoft.com> An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060510/3b0fca96/attachment.html> From sjmachin at lexicon.net Tue May 16 21:43:51 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 May 2006 18:43:51 -0700 Subject: help with this simple DB script In-Reply-To: <446a7849$0$1901$c3e8da3@news.astraweb.com> References: <446a7849$0$1901$c3e8da3@news.astraweb.com> Message-ID: <1147830231.632551.296170@j73g2000cwa.googlegroups.com> Please learn to provide needed information when asking questions. 1. What does "run it directly with my URL" mean?? 2. Show the traceback that you got. From bucodi at yahoo.fr.invalid Wed May 31 09:24:19 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Wed, 31 May 2006 15:24:19 +0200 Subject: os.popen3() - how to close cmd window automatically? References: <mailman.6368.1149079174.27775.python-list@python.org> Message-ID: <mn.fb9c7d65fbc34ccd.43626@yahoo.fr.invalid> > Dear Python developers, > > I use a short python script in order to run an external application plus to > open a browser displaying a default page. > > My Setup: Python 2.4.3. / Windows2000 > > # ---------------------------------------------------------------------- > # Script "shortcut.py" > import os > import webbrowser > import win32api > > # open default web browser and display webbpage > page = 'C:\\Temp\\Welcome.html' > webbrowser.open(page) > > # path to application that is opened > path = "C:\\Program Files\\ExternalApplication.exe" > > # get short name > shortpath = win32api.GetShortPathName(path) > > # open external application > stdin, stdout, stderr = os.popen3(shortpath) > output = stdout.read() > errors = stderr.read() > stdin.close() > stdout.close() > stderr.close() > print output > print errors > # ---------------------------------------------------------------------- > > > In order to make this Script available on other Windows2000 machines where no > Python installation is present, I made this script executable using "py2exe" > (http://www.py2exe.org/). This creates a "shortcut.exe" file. > If I run "shortcut.exe" everything works fine but a black empty cmd window > opens and its kept open until I close the application > "ExternalApplication.exe". > How can I close that black empty window automatically? > > Thanks in advance, > Nico replace console=[... by windows=[... in your setup.py -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From agostino.russo at gmail.com Thu May 25 05:22:12 2006 From: agostino.russo at gmail.com (ago) Date: 25 May 2006 02:22:12 -0700 Subject: Scipy: vectorized function does not take scalars as arguments In-Reply-To: <mailman.6158.1148495146.27775.python-list@python.org> References: <1148480844.817338.69230@u72g2000cwu.googlegroups.com> <mailman.6158.1148495146.27775.python-list@python.org> Message-ID: <1148548932.883584.103850@i39g2000cwa.googlegroups.com> I have installed numpy-0.9.6 I haven't tried 0.9.8. From johnjsal at NOSPAMgmail.com Fri May 19 23:11:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 23:11:09 -0400 Subject: DO NOT USE file() (was Re: altering an object as you iterate over it?) In-Reply-To: <e4m0jg$o3t$1@panix3.panix.com> References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <e4la8j$od9$1@daisy.noc.ucla.edu> <e4m0jg$o3t$1@panix3.panix.com> Message-ID: <446e8a54$0$5326$c3e8da3@news.astraweb.com> Aahz wrote: > Python 2.5a2 (trunk:46052, May 19 2006, 19:54:46) > [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu9)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. >>>> open is file > False > > Per the other comments in this thread, Guido agreed that making open() a > synonym of file() was a mistake, and my patch to split them was accepted. > Still need to do more doc update (per Uncle Timmy complaint), but that > shouldn't be too hard. Interesting. What is the difference between them now? From invalidemail at aerojockey.com Tue May 2 16:20:39 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 2 May 2006 13:20:39 -0700 Subject: unable to resize mmap object In-Reply-To: <mailman.5159.1146398546.27775.python-list@python.org> References: <mailman.5159.1146398546.27775.python-list@python.org> Message-ID: <1146601239.702098.156640@j33g2000cwa.googlegroups.com> Fabiano Sidler wrote: > Hi folks! > > I created an mmap object like so: > --- snip --- > from mmap import mmap,MAP_ANONYMOUS,MAP_PRIVATE > fl = file('/dev/zero','rw') > mm = mmap(fl.fileno(), 1, MAP_PRIVATE|MAP_ANONYMOUS) > --- snap --- > > Now, when I try to resize mm to 10 byte > --- snip --- > mm.resize(10) > --- snap --- > I get an EnvironmentError:[Errno 22] Invalid argument. > > How can I implement a resizeable anonymous memory mapping? > Thanks for your reply! Bug in Python. Here's the reason (from the changelog): - Bug #728515: mmap.resize() now resizes the file on Unix as it did on Windows. The mmap module resizes the file in question by calling ftruncate. Only problem is, you can't truncate /dev/zero. I'm going to file this as a bug; probably on Unix mmap should only resize the file if it's a regular file (so fstat it first). Frankly, I'm not so sure matching Windows behavior is a great idea. mmap module seems to be having an identity crisis. Is it a low-level system call, or a high-level, OS-independent way to access files as blocks of memory? The modules is moving towards the latter (what with Unix mmap accepting ACCESS-style flags, and now this file-resizing behavior). I actually favor a two-level approach similar to file I/O: there would low-level system calls in the os module, and high-level mmap object. (The high-level object would go all the way. It would accept a filename rather than a file descriptor, anonymous blocks would be handled OS-independently, rather than mapping /dev/zero, and so on.) Carl Banks From abrahamson.j at gmail.com Sun May 21 13:26:32 2006 From: abrahamson.j at gmail.com (Tel A.) Date: 21 May 2006 10:26:32 -0700 Subject: Software Needs Philosophers In-Reply-To: <874pzjb9rq.fsf@thalassa.informatimago.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <1148225181.251089.261160@j55g2000cwa.googlegroups.com> <874pzjb9rq.fsf@thalassa.informatimago.com> Message-ID: <1148232392.379772.287730@u72g2000cwu.googlegroups.com> Xah, I agree with the thrust of your thread here, though I don't think it's anything special: people invest their values in what they invest their time in. To top it off, you're taking an anti-CL viewpoint in a group predominantly focused around CL (despite being named for just lisp). You're fighting against group polarization even as you fuel it. Nevertheless, I agree with your point. Unfortunately, I think you need to look closer into the philosophy of your own writing. Rhetoric might not produce definitive answers, but it has a purpose. If you're looking for a place to openly criticize lisp, to search for ways to improve it or to craft an alternative then, simply and without malevolence, look somewhere else. That is the frustrated plea of those who respond violently to your posts. C.l.l. isn't so versatile; however, I'm sure the people here are if you approach the problem from the right angle, with the right rhetoric. Good luck. From foxtree at gmail.com Sun May 21 02:35:34 2006 From: foxtree at gmail.com (foxtree at gmail.com) Date: 20 May 2006 23:35:34 -0700 Subject: Python - Web Display Technology In-Reply-To: <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1148193333.987704.16600@j33g2000cwa.googlegroups.com> None of you seem to know what you are talking about. Flash should be used where one needs to use Flash, and HTML/JS/CSS (+XML+XSLT) likewise. Flash can play video. That is not possible w/ HTML/CSS/JS. Flash also behaves consistently cross-browser, cross/platform -- and most features cannot be disabled by the user. (compare that to a user being able to turn off JS, or Java -- something often mandated in a corporate environment.) It's either "all on" or "all off." Flash has such a large install base, that it could be argued it is the most widely available platform for delivering media-rich "applications" over the web. (And code does not involve anywhere near the same level of attention to kludges and workarounds that one would have to use to replicate similar feature -- where possible -- in different browsers and browser *versions.*) -- Not to sound like I work for MM/Adobe, but, here's what the Flash Player can do at *run time*: Flash can load and play external MP3 audio. Flash can render text -- w/ custom-defined and packaged fonts. (not possible in a browser!) It can apply a limited set of CSS to the rendered text, BTW. Flash can load/parse/serialize/send XML. Flash can POST and GET a variety of data (true, it may access browser controls to manage this.) Flash can access you webcam, allowing you to create your own video chat/IM app. Flash can programatically-build vector shapes, gradients, and fills. Flash can load and render jpegs, gifs(v8), and pngs(v8) -- and in version 8, composite all that w/ vector graphics (+video?) -- *and,* sample the resulting display pixel by pixel. (passing that data back to a server would allow dynamic creation of a jpeg or gif.) Flash 8 has a new "file upload" ability that goes beyond what a browser is capable of: You can *multi-select* files, filter files by type or size, and have programatic access to the state of the upload. It accesses an Operating System GUI control to do this -- and I have tested that these features work in MSIE, Moz FF, and Safari on OSX. *** Flash can #animate# stuff!!! Flash is like a 2 MB download that works in almost *every* browser out there. ...it's pretty phenomenal that all those features could have been crammed into it. (like: a built-in interpreter for a late-version-EcmaScript-compliant scripting language -- that, in many ways, is far more capable than what is available w/ JavaScript in most browsers!) *** This feature can be used for a web-based CMS! It would blow-away anything (non-Java) now available for managing and uploading assets. - Show quoted text - From sam at nuevageorgia.com Sun May 21 11:26:21 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 21 May 2006 08:26:21 -0700 Subject: Software Needs Philosophers In-Reply-To: <4dbartF19cb9rU1@uni-berlin.de> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> Message-ID: <1148225181.251089.261160@j55g2000cwa.googlegroups.com> Religious Fanaticism is a very strong in the Computer community. But, is it really a surprise that when a bunch of hairless apes created a new mental world, they created it with a complicated Quilt of religions and nationalities, and many became fanatical? I am confidant the responces Xah will recieve will validate his observation on religious fanaticism. It is funny, Xah always questions people's Sacred Cow's, I have often noted that the reponces often read like the writings of religious fanatics. As a Georgian (US), the responces often remind me of the Dark Side (there is a Light) of the Southern Baptist Church, translated into Computer Speak. Software needs philosophers is an interesting point, perhaps the most important function of Philosophers is exposing Sacred Cows as just Cattle. --- Sam the Gardener http://SamFeltus.com http://SonomaSunshine.com From siona at chiark.greenend.org.uk Thu May 4 11:20:32 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 May 2006 16:20:32 +0100 (BST) Subject: Swaying A Coder Away From Python References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <mailman.5315.1146743831.27775.python-list@python.org> <R40843717.445.3845.1@mx-extra.net> <mailman.5329.1146749986.27775.python-list@python.org> Message-ID: <C-l*WBOfr@news.chiark.greenend.org.uk> >On 4 May 2006 05:24:40 -0700, BartlebyScrivener <rpdooling at gmail.com> wrote: >> I'm picking this up via clp on Google Groups. I can't tell what Mr. >> Lundh is referring to. The first line of his post is: "Tim Williams >> wrote" but there's nothing that comes before. Similarly, I'm reading this via comp.lang.python and the original article hasn't shown up at this site. Tim Williams <tdw at tdw.net> wrote: >I found the web version at. > >http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html Wherein we find: He also listed a few reasons why C# appeals to him over Python or Java: * anonymous functions (delegates) * a python-like yield statement * a nice type system with generics * interfaces * properties (Yay!!) So that's two of the five Python has, one explicitly acknowledged, plus the combination of lambda and functions-as-first-class-objects is as good as (or better than) "anonymous functions (delegates)". And then we get onto personal preferences as to how to do type systems. That's not a great deal with which to sway someone. -- \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 belred at gmail.com Thu May 4 01:52:22 2006 From: belred at gmail.com (Bryan) Date: Wed, 03 May 2006 22:52:22 -0700 Subject: stripping unwanted chars from string In-Reply-To: <44598a93$1@news.eftel.com> References: <tFe6g.21715$4L1.10250@newssvr11.news.prodigy.com> <44598a93$1@news.eftel.com> Message-ID: <e3c4ug$jkm$1@sea.gmane.org> > >>> keepchars = set(alphabet + alphabet.upper() + '1234567890-.') or >>> keepchars = set(string.letters + string.digits + '-.') bryan From fyleow at gmail.com Sat May 6 16:24:44 2006 From: fyleow at gmail.com (fyleow) Date: 6 May 2006 13:24:44 -0700 Subject: Elegent solution to replacing ' and " ? In-Reply-To: <1146886534.287919.243480@g10g2000cwb.googlegroups.com> References: <1146872815.237738.57590@j73g2000cwa.googlegroups.com> <1146886534.287919.243480@g10g2000cwb.googlegroups.com> Message-ID: <1146947084.402821.239790@y43g2000cwc.googlegroups.com> I'm using PyGreSQL on a PostgreSQL db. I didn't even include my SQL but Serge guessed right and that's what I had. I changed it and it works now. Thanks for the help! :) From aylwyn at cantab.net Wed May 17 08:18:29 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 05:18:29 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <Xns97C65986E948Dduncanbooth@127.0.0.1> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> <1147862865.142339.117610@j55g2000cwa.googlegroups.com> <Xns97C683D60F53Fduncanbooth@127.0.0.1> Message-ID: <1147868309.125766.112550@u72g2000cwu.googlegroups.com> >Hitting the spacebar like a madman? If you have a sensible editor then at >the start of a line you press tab once True! but normally if I'm editing someone else's code then I'm only making small changes and so can't be bothered to temporarily cripple my editor. If I'm merging my code with someone else's space-indented code then piping through sed 's/TAB/SPACES' does the trick. From scott.daniels at acm.org Mon May 8 16:13:46 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 13:13:46 -0700 Subject: utility functions within a class? In-Reply-To: <uQM7g.2060$No6.45697@news.tufts.edu> References: <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <USH7g.2052$No6.45672@news.tufts.edu> <SdI7g.2055$No6.45780@news.tufts.edu> <98uu52hiic72dtt9ibu0e7anfgndv6o8qb@4ax.com> <uQM7g.2060$No6.45697@news.tufts.edu> Message-ID: <445fa2c1$1@nntp0.pdx.net> John Salerno wrote: > Dennis Lee Bieber wrote: >> ... Single underscores are a convention/signal to the programmer that >> "this method/attribute" is considered "private" and should only be used >> by other methods within the class that defined it. The language does no >> enforcement of usage.... > > I see. But isn't there something about a single leading underscore that > doesn't import when you use from X import *? Or am I thinking of > something else? Is that also the double underscore? That has to do with module contents, and is a completely separate issue. If you define a module with a variable name '__all__' which is a list (or tuple) of strings, only module elements with those names will be imported with a "from module import *". If you fail to define the '__all__' element, all names which do not start with an underscore will be imported. --Scott David Daniels scott.daniels at acm.org From nospam at nospam.net Thu May 11 00:51:05 2006 From: nospam at nospam.net (Matthew Graham) Date: Thu, 11 May 2006 05:51:05 +0100 Subject: Nested loops confusion Message-ID: <W8GdnaVYdtMnX__ZRVny1A@giganews.com> Hi, I expect this is very obvious for anyone who knows what they're doing - but I don't understand what's the problem with the following code. I was intending that the program cycle through all i and j (ie. all possible (i,j) coordinates, but the output when I run the program shows me up to "1 99 plot 3 1 100 plot 2 done j" and doesn't perform the print functions for any i > 1. Help much appreciated! :) Matt corna = int(raw_input("CornA? ")) cornb = int(raw_input("CornB? ")) side = int(raw_input("Side? ")) i = 0 j = 0 for i in range(100): for j in range(100): x = corna + i * side / 100 y = cornb + j * side / 100 c = int(x^2 + y^2) if c%3 == 1: print i print j print "plot 1" elif c%3 == 2: print i print j print "plot 2" elif c%3 == 0: print i print j print "plot 3" print "done j" print "Done i" From struggleyb at gmail.com Wed May 31 02:58:39 2006 From: struggleyb at gmail.com (Bo Yang) Date: Wed, 31 May 2006 14:58:39 +0800 Subject: An algorithm problem Message-ID: <447D3E9F.4010008@gmail.com> Hi , I have writen a python program to slove a problem described as below: (Forgive my poor English !) Put the 2^n 0 or 1 to form a ring , and we can select any continuous n ones from the ring to constitute a binary number . And obviously we can get 2^n selections , so the question is : Given a number n and you must Povide an algorithm by which the 0-1 ring is produced , and the 2^n number we get are just from 0 to 2^n-1 uniquely and entirely . So I write the following program to slove the question , and it works well for the n below 10 flag = 0 input = 10 number = 2**input set = set() list = [] def list2int(l , n ): ret = 0 for x in l : if( n == 0 ): break if x : ret = ( ret << 1 ) | 1 else : ret = ( ret << 1 ) | 0 n = n - 1 return ret def ring( index , number ): global list , set temp = [] if( number < index ): #the range overflow #detect whether the remain of the list is ok ? for x in xrange(1,input): begin = number - input + 1 + x l = list[begin:] + list[0:x] i = list2int(l , input ) if i in set: for i in temp: set.remove(i) return else: set.add(i) temp.append(i) #index = index + 1 global flag flag = 1 return list.append(1) if len(list) < input or list2int(list[index-input+1:index+2],input) not in set: if(len(list) >= input ): set.add(list2int(list[index-input+1:index+2],input)) ring(index+1,number) if(flag == 1): return if(len(list) >= input ): set.remove(list2int(list[index-input+1:index+2],input)) list = list[:index] list.append(0) if len(list) < input or list2int(list[index-input+1:index+2],input) not in set: if(len(list) >= input ): set.add(list2int(list[index-input+1:index+2],input)) ring(index+1,number) if(flag == 1): return if(len(list) >= input ): set.remove(list2int(list[index-input+1:index+2],input)) list = list[:index] ring(0,number-1) print list But when the n reach 10 , Python report the stack is exhausted : RuntimeError: maximum recursion depth exceeded And my question is , where can I put some optimization to make the code can work more smoothly with more greater n ? Thanks in advance ! From jared at hpalace.com Wed May 10 02:20:57 2006 From: jared at hpalace.com (M Jared Finder) Date: Tue, 09 May 2006 23:20:57 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hf26zk.1uqniari93h7fN%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <joadnUiUIdmNsP3ZnZ2dnUVZ_tKdnZ2d@speakeasy.net> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> <87ac9r1tem.fsf@snobis.de> <1hf26zk.1uqniari93h7fN%aleax@mac.com> Message-ID: <1ZadnfwKY5_XG_zZRVn-sg@speakeasy.net> Alex Martelli wrote: > Stefan Nobis <snobis at gmx.de> wrote: > >> aleax at mac.com (Alex Martelli) writes: >> >>> if anonymous functions are available, they're used in even more >>> cases where naming would help >> Yes, you're right. But don't stop here. What about expressions? Many >> people write very complex expression, that are hard to understand. A >> good language should forbid these abuse and don't allow expressions >> with more than 2 or maybe 3 operators! > > That would _complicate_ the language (by adding a rule). I repeat what > I've already stated repeatedly: a good criterion for deciding which good > practices a language should enforce and which ones it should just > facilitate is _language simplicity_. If the enforcement is done by > adding rules or constructs it's probably not worth it; if the > "enforcements" is done by NOT adding extra constructs it's a double win > (keep the language simpler AND push good practices). Your reasoning, taken to the extreme, implies that an assembly language, by virtue of having the fewest constructs, is the best designed language ever. But we know that not to be the case -- rarely do even embedded developers program in assembly language any more. Why? Because assembly language is so simple that it's very tedious to write. There's no function call primitive -- you have to manually generate a function call pattern yourself. There's no looping primitive -- you have to manually generate a looping pattern yourself. I feel sorry for the person who's debugging an assembly program using manually generated code that implements a vtable-based dynamic dispatch. Any feature that allows me to write less code to do the same thing has a huge positive -- the reduction of human generated, and therefore error prone, code. I think the advantages of anonymous functions: a) explicitly documenting that the function is used in only one place b) enabling generic iteration and looping routines c) not having to maintain a unique name for the function d) making the language more elegant e) making the language simpler to implement greatly outweigh the small disadvantage of adding one additional construct to the language. -- MJF From larry.bates at websafe.com Mon May 15 13:25:02 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 15 May 2006 12:25:02 -0500 Subject: saving file permission denied on windows In-Reply-To: <1147708797.746442.19220@j73g2000cwa.googlegroups.com> References: <1147708797.746442.19220@j73g2000cwa.googlegroups.com> Message-ID: <4468B96E.8080101@websafe.com> zombek at gmail.com wrote: > I'm making a small program which takes a folder with images and > generates optimized normal-sized images and thumbnails using Python > Imaging Lbrary (PIL). The problem is here: > .... > os.mkdir(self.output) > .... > img = Image.open(os.path.join(self.dir,file)) > img = img.resize(self.imgSize) > # and here comes the error > img.save(self.output, "JPEG", optimize=1) > > IOError: [Errno 13] Permission Denied > "D:\\Szymek\\python\\pythumb\\images\\proba" > > I don't know what's going on, I didn't have any problems with it in the > past. I tried to save it to a pre-made directory but the effect is the > same, so I don't think it's connected with os.mkdir. > I think you have a logic problem. You can't save to a folder name, you must save to a file. Note that O/S is saying that permission is denied to the folder name stored in self.output: "D:\\Szymek\\python\\pythumb\\images\\proba" You most likely meant: img.save(os.path.join(self.output, file), "JPEG", optimize=1) -Larry Bates From nobody at 127.0.0.1 Tue May 16 22:50:24 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 02:50:24 GMT Subject: common practice for creating utility functions? References: <ZI3ag.2095$No6.46239@news.tufts.edu> <7xd5efdstn.fsf@ruckus.brouhaha.com> <4468e3af$0$7129$626a54ce@news.free.fr> Message-ID: <Qbwag.88565$dW3.27773@newssvr21.news.prodigy.com> Bruno Desthuilliers wrote: > Then it would be better to just alias it: > > # def convert_quote(quote): > # return make_code(quote) > convert_quote = make_code The former makes sense if you're planning to do more with the calling function later. > About the "fine to do" part, remember that Python's function calls are > rather expansive... Indeed, their expansiveness makes them great. Unfortunately they're somewhat expensive too. ;) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From fuzzyman at gmail.com Tue May 2 05:27:09 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 2 May 2006 02:27:09 -0700 Subject: Non-web-based templating system In-Reply-To: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> References: <1146221757.653214.115090@g10g2000cwb.googlegroups.com> Message-ID: <1146562029.124021.272490@j33g2000cwa.googlegroups.com> qscomputing at gmail.com wrote: > Hi, > > I'm creating a small application in Python that uses lists and > dictionaries to create a rudimentary database. I'd like to create some > "fill-in-the-blanks" reports from this data, ideally by taking an RTF > or plaintext file as a template and replacing placeholder tags with my > data. > Are there any good pre-written systems that would allow me to do this? > Another option is the 'embedded_code.py' module used by `Firedrop2 <http://www.voidspace.org.uk/python/firedrop2/>`_ and `rest2web <http://www.voidspace.org.uk/python/rest2web/>`_. It takes a text string as input and a namespace (dictionary) as input and returns a text string. It replaces single placeholders of the form : <% name %> It also executes chunks of embedded code in the namespace, and replaces them with whatever the code prints to stdout. These are of the form : <# print name if name2.startswith('something'): print name2 #> This is very useful for simple templating. All the best, Fuzzyman http://www.voidspace.org.uk/python/shareware.shtml > Thanks, > - QS Computing. From johnjsal at NOSPAMgmail.com Wed May 17 16:11:23 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 20:11:23 GMT Subject: creating a new database with mysqldb In-Reply-To: <1147895089.060039.77660@y43g2000cwc.googlegroups.com> References: <gcKag.2113$No6.46302@news.tufts.edu> <1147893204.503850.225770@j73g2000cwa.googlegroups.com> <wKKag.2114$No6.46328@news.tufts.edu> <1147895089.060039.77660@y43g2000cwc.googlegroups.com> Message-ID: <LrLag.2116$No6.46357@news.tufts.edu> BartlebyScrivener wrote: > I would learn basic, commandline SQL first and get comfortable creating > tables, querying your dbs etc. THEN, add Python. Otherwise you spin > your wheels not knowing whether it's your use of the Python modules or > your bad SQL commands that are fouling things up. > > http://sqlcourse.com/intro.html > > or I recommend Chris Fehily's SQL 2nd Ed. Great book, and cheap. > I did that tutorial yesterday. It was great and I learned a lot about the basics of working with tables. After learning the queries, then I moved on to using them with Python. I plan to get the pocket reference later today, so that might help as well. From deusfaber at gmail.com Tue May 9 11:44:47 2006 From: deusfaber at gmail.com (dfaber) Date: 9 May 2006 08:44:47 -0700 Subject: Python editor recommendation. In-Reply-To: <1147187398.410726.111770@y43g2000cwc.googlegroups.com> References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1147186782.792802.227170@g10g2000cwb.googlegroups.com> <1147187398.410726.111770@y43g2000cwc.googlegroups.com> Message-ID: <1147189487.673488.273210@e56g2000cwe.googlegroups.com> I use Eclipse with the Pydev plugin. It's great way to start familiarizing yourself with Python. The editor has got great features and the debugger will be a great help too. Vim is great too but may be not a good idea if you are new to Python. Good luck! From johnjsal at NOSPAMgmail.com Tue May 2 21:53:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 21:53:47 -0400 Subject: simultaneous assignment In-Reply-To: <4457dadd$0$9654$636a55ce@news.free.fr> References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <RAN5g.2037$No6.43926@news.tufts.edu> <4457dadd$0$9654$636a55ce@news.free.fr> Message-ID: <44580e23$0$5389$c3e8da3@news.astraweb.com> Bruno Desthuilliers wrote: > But my question (sorry, it may not have been clear) was more along the > line of : "why do you worry about identity in the given snippet ?". Actually, I kind of thought that maybe it *didn't* matter in this particular example anyway, so my question was meant to be more general than I might have written it. It seems like the identity issue can be a problem in certain cases, although I can't think of a case right now! :) From rpdooling at gmail.com Sun May 14 14:40:15 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 14 May 2006 11:40:15 -0700 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1147584805.462908.201300@g10g2000cwb.googlegroups.com> <7x7j4pjgtt.fsf@ruckus.brouhaha.com> <1hfatt2.1tx1pof1srrn1dN%aleax@mac.com> Message-ID: <1147632015.301932.65670@v46g2000cwv.googlegroups.com> >> True. Changing the except clause here to >> except: return sum(1 for x in iterable) >> keeps George's optimization (O(1), not O(N), for containers) and is a >> bit faster (while still O(N)) for non-container iterables. Every thing was going just great. Now I have to think again. Thank you all. rick From lialie at 126.com Fri May 19 13:19:01 2006 From: lialie at 126.com (Lialie) Date: Sat, 20 May 2006 01:19:01 +0800 Subject: how to read a list from python in C? Message-ID: <446DFE05.6070605@126.com> Thanks for your reply. yes, I pass a list as an argument to the function in C. The list has a random length. Do you mean to do it in this way? use PyTuple_Size(args), in a loop use PyTuple_GetItem(args, i) or use PyArg_VaParse? Best Regards From softwindow at gmail.com Fri May 19 01:50:24 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 22:50:24 -0700 Subject: who can give me the detailed introduction of re modle? Message-ID: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> the re module is too large and difficult to study i need a detaild introduction. From gmnation at gmail.com Wed May 10 02:00:28 2006 From: gmnation at gmail.com (=?iso-8859-1?B?Ry4gTW9uevNu?=) Date: 9 May 2006 23:00:28 -0700 Subject: Incrementally converting a C app to Python In-Reply-To: <mailman.5535.1147211877.27775.python-list@python.org> References: <mailman.5535.1147211877.27775.python-list@python.org> Message-ID: <1147240828.777953.245810@v46g2000cwv.googlegroups.com> Hi Bjorn, I think the best approach is highly-dependent to your current C application design and "way of doing things". For a type of application you would take the opposite path than for other I thought. Yes I did that one time, but I re-coded all from scratch... and since that I usually do in reverse: code in Python, then optimize if needed in C via pyrex coded extensions and glue. If you don't know well the current application internals, both approaches can be harder: to convert step by step to python or re-implement from scratch. You need to know well what is doing there that pretty hard to read code for being sure for success and good starting guidelines. I thought If your app doesn't have very critical parts, and if you really know what the application is doing "inside", I would bet for a complete reimplementation from scratch. More if you say current C code has a lots of bugs! And all the code you need to be in C, can be easily done via pyrex, ctypes, etc. Have in mind I don't know your application! Swig is harder, is more suited to export whole libraries to between languages. Anyway, I'm no expert with Swig! :-) Regards, Gonzalo Monz?n. From mizipzor at gmail.com Mon May 15 09:37:10 2006 From: mizipzor at gmail.com (Alex) Date: Mon, 15 May 2006 15:37:10 +0200 Subject: How to organise classes and modules In-Reply-To: <44686c81$0$6834$626a54ce@news.free.fr> References: <mailman.5703.1147691931.27775.python-list@python.org> <44686c81$0$6834$626a54ce@news.free.fr> Message-ID: <fad9f1a90605150637x560d5e34t26b842b296e577f8@mail.gmail.com> On 5/15/06, bruno at modulix <onurb at xiludom.gro> wrote: > Alex wrote: > > Hi, this is my first mail to the list so please correct me if Ive done > > anything wrong. > > > > What Im trying to figure out is a good way to organise my code. One > > class per .py file is a system I like, keeps stuff apart. If I do > > that, I usually name the .py file to the same as the class in it. > > First point is that Python doesn't force you to put everything in > classes - if you just need a function, well, make it a function !-) > > Also, the common pattern is to put closely related > classes/functions/constants in a same module, and closely related > modules in the same package. Since Python uses a "one file == one > module" scheme, the Javaish "one class per file" idiom leads to overly > complicated imports. And the most common naming scheme for modules is > 'alllowercase'. > > > > > File: Foo.py > > *********************** > > class Foo: > > def __init__(self): > > pass > > def bar(self): > > print 'hello world' > > > > ************************ > > > > Now, in my other module, I want to include this class. I tried these two > > ways: > > > >>>> import Foo > >>>> Foo.Foo.bar() > > > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > TypeError: unbound method bar() must be called with Foo instance as > > first argument (got nothing instead) > > > > Some unbound method error. Have I missunderstood something > > Yes: > 1/ you usually need to instanciate the class to call an instance method > 1/ in this case, bar doesn't need to be a method, since it doesn't > depend on the instance it's called on - a plain old function would be a > better fit. > > > or am I on > > the right track here? > > > > I did this to, almost the same thing: > > > >>>> from Foo import Foo > >>>> Foo.bar() > > > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > TypeError: unbound method bar() must be called with Foo instance as > > first argument (got nothing instead) > > > > One thing that I tried that worked ok was this: > > > >>>> import Foo > >>>> instance=Foo.Foo() > >>>> instance.bar() > > > > hello world > > > > But in my opinion, this is very ugly. > > Nope, it's just OO at work. > > > Especially if the class names > > are long, like my module/class TileDataBaseManager. But is this the > > "right" way in python? > > If you want to import a class from a module and create an instance of > that class, yes. > > > Another (ugly) way that Ive considered is the following. Break it out > > of the class, > > Which would be a sensible thing to do given the current implementation > of bar(). > > > save the functions in a file alone, > > Nothing prevent you from putting many functions in a same module, you > know... > > > import the file > > s/file/module/ > > > and > > treat it like a class: > > ??? > > > File: Foo2.py > > *********************** > > def bar(self): > > print 'hello world' > > > > ************************ > > > >>>> import Foo2 > >>>> Foo2.bar() > > > > hello world > > You don't "treat it like a class", you're just using the normal > namespace resolution mechanism. Modules are namespaces, classes are > namespaces, objects (class instances) are namespaces, and the dot is the > lookup operator (ie : somenamespacename.somename means 'retrieve what's > actually bound to name 'somename' in namespace 'somenamespacename'). > > > Very clean from the outside. I would like something like this. But, > > here, I loose the __init__ function. > > Which in the given implementation is just doing nothing. > > Ok, I understand that this is just example code. The rule here is: > - if you need per-instance state management, use a class (that you of > course need to instanciate - else you can't have per-instance state !-) > - if you don't need per-instance state management, use a plain function. > > > I have to call it manually that > > is, which s not good. Also, maybe the biggest drawback, its no longer > > in a class. > > def MyFunc(): > pass > > print MyFunc.__class__.__name__ > > Python function's are instances of the function class. > > > Maybe its not that important in python but from what Ive > > learned (in c++) object orientation is something to strive for. > > print "object orientation".find("class") > > Being OO doesn't mean using classes. <troll>And FWIW, there quite enough > procedural Java code around to prove that using classes doesn't mean > doing OO !-) </troll> > > > So, to sum it up, I have one class in one file, both with the same > > name. How do I store/import/handle it in a nice, clean and python-like > > manner? > > Quit the Javaish "one-class-per-file" idiom, don't bother using classes > when plain old function will do, and you'll be on track... > > FWIW, Python's standard lib is open-source, so why not have a look at > the source code to see how it is organized ? > > HTH > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" > -- > http://mail.python.org/mailman/listinfo/python-list > Thanks for taking your time to help me out. :) You have cleared out many of my doubts. BTW, should I post "thank you" stuff here or does it just clutter? I tried sending an email to your personal email listed (the one from which you send that mail to the list), but I got this error: PERM_FAILURE: DNS Error: Domain name not found So I guess the entire list will have to be thanked for the help. :) From nobody at 127.0.0.1 Tue May 16 22:47:15 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 02:47:15 GMT Subject: common practice for creating utility functions? References: <ZI3ag.2095$No6.46239@news.tufts.edu> <7xd5efdstn.fsf@ruckus.brouhaha.com> <1147721970.417910.170780@i40g2000cwc.googlegroups.com> Message-ID: <T8wag.88537$dW3.76983@newssvr21.news.prodigy.com> BartlebyScrivener wrote: > QOTW > > "Programming is not just creating strings of instructions for a > computer to execute. It's also 'literary' in that you are trying to > communicate a program structure to other humans reading the code." Paul > Rubin I take it you've never heard of Donald Knuth or literate programming: "The main idea is to regard a program as a communication to human beings rather than as a set of instructions to a computer." "So you need somebody who's not afraid to write an essay, as well as not afraid to write a computer program. They work together perfectly, but you have to be able to communicate to the computer, and you have to be able to communicate to the human being, and if you don't do both, then you can't expect your program to be as successful. Literate programming is just the best way I know to do both at the same time." "My schtick is to promote the idea that humans, not computers, read programs.... I ask programmers to think of themselves as writers, teachers, expositors. When you're programming, the very act of trying to explain it to another human being forces you to get more clarity. And then later on, you can maintain, modify, and port your programs to other platforms much more easily. Even if your only audience is yourself, everything gets better." http://www-cs-faculty.stanford.edu/~knuth/ http://www-cs-faculty.stanford.edu/~uno/lp.html -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From pommereau at univ-paris12.fr Thu May 18 11:41:14 2006 From: pommereau at univ-paris12.fr (Franck Pommereau) Date: Thu, 18 May 2006 17:41:14 +0200 Subject: how to traverse network devices in our system? In-Reply-To: <1147863730.559574.181720@i39g2000cwa.googlegroups.com> References: <mailman.5797.1147863138.27775.python-list@python.org> <1147863730.559574.181720@i39g2000cwa.googlegroups.com> Message-ID: <446c959a$0$15535$79c14f64@nan-newsreader-06.noos.net> > Yes, it is Linux. I was just googling and found that there are kudzu > bindings for python. From that i can query kudzu for any configured and > unconfigured device (i hope so). is there any other method available > other kudzu python bindings ? I do it using DBus/Hal, for instance: ############### import dbus system_bus = dbus.SystemBus() hal_manager_obj = system_bus.get_object('org.freedesktop.Hal', '/org/freedesktop/Hal/Manager') hal_manager = dbus.Interface(hal_manager_obj, 'org.freedesktop.Hal.Manager') for udi in hal_manager.FindDeviceByCapability("net") : obj = system_bus.get_object("org.freedesktop.Hal", udi) dev = dbus.Interface(obj, 'org.freedesktop.Hal.Device') print dev.GetProperty("net.interface"), print dev.GetProperty("net.address") ############### Cheers, Franck From gandalf at designaproduct.biz Fri May 26 05:17:26 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Fri, 26 May 2006 11:17:26 +0200 Subject: urllib2 and HTTP 302 Message-ID: <4476C7A6.5040506@designaproduct.biz> Hello, The code below uses urllib2 and build_opener. Having this code fragment, how can I return the redirection URL? I tried to get this information from the exception but I could not. Is it possible to read it from the openerdirector? Any suggestions? try: self.post_multipart( url, [('uploadType','Inventory')], [('uploadFileName','inv.txt',fdata)] ) except urllib2.HTTPError, e: if e.code == 302: return "I would like to get the URL to be redirected to...." else: raise Thanks, Laszlo From onurb at xiludom.gro Tue May 9 05:01:49 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 11:01:49 +0200 Subject: utility functions within a class? In-Reply-To: <SdI7g.2055$No6.45780@news.tufts.edu> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <USH7g.2052$No6.45672@news.tufts.edu> <SdI7g.2055$No6.45780@news.tufts.edu> Message-ID: <44605add$0$2693$636a55ce@news.free.fr> John Salerno wrote: > John Salerno wrote: > >> blair.bethwaite at gmail.com wrote: >> >>> John Salerno wrote: >>> >>>> What I originally meant was that they would not be called from an >>>> instance *outside* the class itself, i.e. they won't be used when >>>> writing another script, they are only used by the class itself. >>> >>> >>> Yep, so you want to encapsulate the functionality that those methods >>> provide, which is the whole point of building them in a class in the >>> first place. And you want them to be private to the class so that they >>> do not form part of the classes public/external interface. >> >> >> But it's right that they should still be regular instance methods? So >> from within the class I still call them as self._generate_head(), etc.? > > > I tried the underscore method, but I was still able to call it as a > regular instance method in the interpreter. Is that what's supposed to > happen? Yes. Language-inforced access restriction is totally useless (and is quite easy to defeat in C++ and Java FWIW). Python's philosophy is that programmers are not braindead monkey-coders that must be protected (pardon the pun) from their own stupidity. There's no way to idiot-proof a code anyway, so why bother ? The single-underscore prefix means 'implementation, don't touch or else', and this is quite enough. Most python programmers won't touch it - unless they have perfectly valid reasons to do so (yes, it happens), and then they will implicitely accept the consequences. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From webraviteja at gmail.com Wed May 10 01:21:06 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 9 May 2006 22:21:06 -0700 Subject: Can Python installation be as clean as PHP? In-Reply-To: <1147238063.235221.13120@j73g2000cwa.googlegroups.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> <1147238063.235221.13120@j73g2000cwa.googlegroups.com> Message-ID: <1147238466.485259.325310@i39g2000cwa.googlegroups.com> Addendum: Python has zip imports (similar to Java's jar files). You can put all your *.py files in a zip file and access them from it if this means so much to you. From __peter__ at web.de Tue May 9 11:26:23 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 May 2006 17:26:23 +0200 Subject: Deferred Evaluation in Recursive Expressions? References: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> Message-ID: <e3qc7h$ats$01$1@news.t-online.com> birchb at ozemail.com.au wrote: > While working on type expressions I am rather stuck for a > way to express recursive types. A simple example of this is a > singly-linked list of integers. In some languages you have compiler > syntax > which suspends evaluation so you can have recursive types. e.g. > > typedef Linked_List := int, Linked_List > > In LISP I would use a macro. > > I have tried using classes: > > class Linked_List(object): > typedef = (int, Linked_List) > > The closest I have got in Python is the following: > > Linked_List = (int, lambda: Linked_List) # linked list of int > > this is OK, because lambda makes closure which is not executed. However > it required the user of the type expression to call any lfunctions > found whilst traversing the tree. > > To make this a little more OO, I could use a constructor to wrap the > function: > > Linked_List = (int, recursive(lambda: Linked_List)) # linked > list of int > > but I am not satisfied with the "look". > > Any suggestions? (1) Wait until the class is defined: class LinkedList: pass LinkedList.typedef = int, LinkedList or (2) Use a marker object as a placeholder for the class yet to be defined. Fancy example: SELF = object() def fix_typedef(td, cls): for item in td: if item is SELF: yield cls else: yield item class Type(type): def __new__(*args): cls = type.__new__(*args) try: typedef = cls.typedef except AttributeError: pass else: cls.typedef = tuple(fix_typedef(typedef, cls)) return cls class TypeDef: __metaclass__ = Type class LinkedList(TypeDef): typedef = (int, SELF) print LinkedList.typedef # (<type 'int'>, <class '__main__.LinkedList'>) From tbrkic at yahoo.com Thu May 18 09:17:06 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 06:17:06 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <mailman.5873.1147952119.27775.python-list@python.org> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147947048.303912.109150@38g2000cwa.googlegroups.com> <446c5a80$0$7024$636a55ce@news.free.fr> <mailman.5873.1147952119.27775.python-list@python.org> Message-ID: <1147958226.200557.264850@j33g2000cwa.googlegroups.com> > What about writing a mini-language that gets translated to Python? Think of > Cheetah, which does exactly this (albeit not being limited to templating HTML > data). I have implemented my proposal as preprocessor. And it works fine. But my proposal in not only for HTML it can be used for all hieracical data. Example: myList = [] *+* myList: *+* []: for i in range(10): *+* i *+* {}: for i in range(10): *=* i = i Which should create myList = [[0..9], {0:0, ... 9:9}] So it adds the power of for loops etc when creating data structures. ANY datastructure. > nothing general the OP is trying to achieve here Define general :-). I do think I solve something and make it more readable. You could also argue that list comprehension doesnt solve anything general. > By the way: the language you (the OP) are trying to implement here goes > strictly against the MVC model of application programming. You know that, > right? ???. I cant see how this breaks MVC. MVC depends on how you parition your application this doesnt put any constraint on how you should do your application. From steve at holdenweb.com Thu May 18 01:39:29 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 May 2006 06:39:29 +0100 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <1147686809.145019.306180@i40g2000cwc.googlegroups.com> References: <jz09g.2091$No6.46071@news.tufts.edu> <1147497059.393293.182010@j73g2000cwa.googlegroups.com> <1147686809.145019.306180@i40g2000cwc.googlegroups.com> Message-ID: <e4h1ae$5uk$1@sea.gmane.org> NoNickName wrote: > Gerard Flanagan wrote: > > >>Interactive SQL tutorial: http://www.sqlcourse.com/ ; >>http://sqlcourse2.com/ >> >>Indirectly helpful maybe: >>http://initd.org/tracker/pysqlite/wiki/basicintro >> >>HTH >> >>Gerard > > > There's also the TechBookReport SQL tutorial - which is geared to MySQL > (and, shudder, Access). Take a look at > http://www.techbookreport.com/sql-tut1.html > I maintain a few useful relational database links for my students at http://www.holdenweb.com/students/database.html They may not help, but they may. Also I just discovered a shareware application called galaxql that uses a database to describe a galaxy that the program alos visualizes. This cam help with SQL manipulations, as the galactic visualisation changes as you update the data in the SQL database (sqlite, I believe). regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From tdelaney at avaya.com Sun May 14 19:28:00 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 15 May 2006 09:28:00 +1000 Subject: count items in generator Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6ED@au3010avexu1.global.avaya.com> Paul Rubin wrote: > That's only because itertools.count itself uses a C int instead of a > long. True. In either case, the effect is the same in terms of whether len(itertools.count()) will ever terminate. Tim Delaney From aleaxit at yahoo.com Sat May 6 19:57:12 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 16:57:12 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> Message-ID: <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> Bill Atkins <NOatkinwSPAM at rpi.edu> wrote: ... > > ``allow ( as an ordinary single-character identifier'' as for the > > unneded feature ``allow unnamed functions with all the flexibility of > > named ones''. > > Not so infeasible: > > (let ((|bizarrely(named()symbol| 3)) > (+ |bizarrely(named()symbol| 4)) > > ;; => 7 Read again what I wrote: I very specifically said "ordinary *single-character* identifier" (as opposed to "one of many characters inside a multi-character identifier"). Why do you think I said otherwise, when you just quoted what I had written? (Even just a _leading_ ( at the start of an identifier may be problematic -- and just as trivial as having to give names to functions, of course, see below). > And in any case, enforced indentation is a policy with vastly more > serious consequences than the naming of identifiers. So far, what was being discussed here isn't -- having to use an identifier for an object, rather than keeping it anonymous -- trivial. Python practically enforces names for several kinds of objects, such as classes and modules as well as functions ("practically" because you CAN call new.function(...), type(...), etc, where the name is still there but might e.g. be empty -- not a very practical alternative, though) -- so what? Can you have an unnamed macro in Lisp? Is being "forced" to name it a "serious consequence"? Pah. Anyway, I repeat: *any* design choice (in a language, or for that matter any other artefact) has consequences. As Paul Graham quotes and supports his unnamed friend as saying, Python lets you easily write code that *looks* good, and, as Graham argues, that's an important issue -- and, please note, a crucial consequence of using significant indentation. Alien whitespace eating nanoviruses are no more of a worry than alien parentheses eating nanoviruses, after all. Alex From steve at holdenweb.com Fri May 26 09:02:38 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 26 May 2006 14:02:38 +0100 Subject: how to clear up a List in python? In-Reply-To: <1148640472.914547.11640@j55g2000cwa.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <mailman.6221.1148634413.27775.python-list@python.org> <1148636521.026385.171410@y43g2000cwc.googlegroups.com> <e56iu7$g9j$1@news.albasani.net> <1148638555.440810.277540@i40g2000cwc.googlegroups.com> <mailman.6228.1148639629.27775.python-list@python.org> <1148640472.914547.11640@j55g2000cwa.googlegroups.com> Message-ID: <e56u96$3c9$1@sea.gmane.org> vbgunz wrote: > I read the ten commandments. I enjoyed the link. I see my mistakes. > Thank you. > A genuine pleasure. Welcome to comp.lang.python. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From arv.nntp at gmail.com Mon May 1 06:27:33 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Mon, 01 May 2006 12:27:33 +0200 Subject: critique this little script, if you like In-Reply-To: <44554a32$0$11750$c3e8da3@news.astraweb.com> References: <44554a32$0$11750$c3e8da3@news.astraweb.com> Message-ID: <e34npu$ql2$1@nsnmpen2-gest.nuria.telefonica-data.net> John Salerno escribi?: > 2. Between the if block or the try block, which is more Pythonic? Since the command line argument is optional I don't think it should be considered and exceptional condition if it's missing, so the "if" block looks better to me. No idea if this is more pythonic. > The > try block seems nicer because it doesn't have such an ugly-looking check > to make. Ok, so you should do: try: x = 1/i except ZeroDivisionError : do_something_if_zero() instead of if (i == 0) : do_something_if_zero() HTH From sam at nuevageorgia.com Sun May 21 18:37:50 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 21 May 2006 15:37:50 -0700 Subject: Python - Web Display Technology In-Reply-To: <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> Message-ID: <1148251070.320923.65710@38g2000cwa.googlegroups.com> Hmmm... It is interesting how something is terrible to one person, and great to another, and vice versa. I keep trying to understand why people like HTML/JS, I don't think I am gonna understand. I guess for better or worse, Flash is a very different mindset and approach to the web. Oh well, I love the simplicity of Python on the server. I just won't hold my breath waiting for anything cool and Flash-content related to arise in the Python world. :) From sybrenUSE at YOURthirdtower.com.imagination Fri May 19 04:35:05 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 19 May 2006 10:35:05 +0200 Subject: Newbie append() question References: <mailman.5922.1148004495.27775.python-list@python.org> Message-ID: <slrne6r0pp.m6t.sybrenUSE@schuimige.stuvel.eu> Brian Blazer enlightened us with: > def getCurrentClasses(): > classes = [] > print 'Please enter the class name. When finished enter D.' > while (c != "D"): No need for the parentheses, and 'c' doesn't have a value yet. If you add 'c=""' before the while-loop, it should be fine. > c = raw_input("Enter class name") > if (c != "D"): Here there is also no need for parentheses. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From keith.b.perry at gmail.com Tue May 30 08:24:56 2006 From: keith.b.perry at gmail.com (kbperry) Date: 30 May 2006 05:24:56 -0700 Subject: Way to get an array of latitude/longitude points (tuples) from a trip Message-ID: <1148991896.430571.33700@j55g2000cwa.googlegroups.com> I am not sure if this is the right place for this, but I thought it was worth a shot. What I want: Enter a From: street address and a To: street address, and then specify an interval (say every half mile). Then, I click a submit button, and it gives me latitude and longitude points (in order) from the beginning of my trip to the end of my trip in 1/2 mile increments. I can't seem to find anything to simulate this, and I am not sure how to go about coding this either. BTW - I have used Yahoo geocoding service (to my delight), and while it is a good service, I don't see a way to do this unless we knew every street address in 1/2 mile increments. Are there any Python modules that would assist with dealing with latitude and longitude? Can anyone out there help? From __peter__ at web.de Fri May 5 12:15:59 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 05 May 2006 18:15:59 +0200 Subject: how to remove 50000 elements from a 100000 list? References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> <4c13mdF13esivU1@uni-berlin.de> <4c14snF13tbobU1@uni-berlin.de> <1146844567.717687.228160@j33g2000cwa.googlegroups.com> Message-ID: <e3ftkp$qe7$03$1@news.t-online.com> Ju Hui wrote: > cool! > thanks you all! > I choose > a=set(range(100000)) > b=set(range(50000)) > a.symmetric_difference(b) > certainly,the real data not range(), I am satisfied the performance of > set.difference > > thank you all again! Be warned that this may /add/ items to a: >>> set("abc").symmetric_difference("bcd") set(['a', 'd']) If your subject is correct you want difference(), not symmetric_difference(). Peter From danmcleran at yahoo.com Sun May 7 11:00:43 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 7 May 2006 08:00:43 -0700 Subject: Splice two lists In-Reply-To: <1146978308.297369.319930@j73g2000cwa.googlegroups.com> References: <1146961724.195038.18680@u72g2000cwu.googlegroups.com> <1146965920.842441.168920@i40g2000cwc.googlegroups.com> <1146973630.629933.323210@y43g2000cwc.googlegroups.com> <1146978308.297369.319930@j73g2000cwa.googlegroups.com> Message-ID: <1147014043.175075.252730@g10g2000cwb.googlegroups.com> >When used in a function call (as opposed to a function definition), * >is the "unpacking" operator. Basically, it "flattens" an iterable into >arguments. The docs mention it... Cool, looks like I didn't read carefully enough. Thanks again. From pjb at informatimago.com Tue May 23 14:49:57 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Tue, 23 May 2006 20:49:57 +0200 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <Xns97CC91CC89166BaldHeadedJohn@216.196.109.145> Message-ID: <87k68c7ezu.fsf@thalassa.informatimago.com> John D Salt <jdsalt_AT_gotadsl.co.uk> writes: > <corff at zedat.fu-berlin.de> wrote in news:4dbartF19cb9rU1 at uni-berlin.de: > > [Snips] >> Wrong. We live in a paradise of ideas and possibilities well beyond the >> wildest dreams of only 20 years ago. > > What exciting new ideas exist in software that are both important and > cannot be traced back to 1986 or earlier? Well, I would have thought of Genetic Programming but it dates back at least 1980: The first experiments with GP were reported by Stephen F. Smith (1980) and Nichael L. Cramer (1985), as described in the famous book Genetic Programming: On the Programming of Computers by Means of Natural Selection by John Koza (1992). > I'd like to believe that there are some, but I can't think of any at the > moment. I think we're just in a Matrix loop... -- __Pascal Bourguignon__ http://www.informatimago.com/ COMPONENT EQUIVALENCY NOTICE: The subatomic particles (electrons, protons, etc.) comprising this product are exactly the same in every measurable respect as those used in the products of other manufacturers, and no claim to the contrary may legitimately be expressed or implied. From olsongt at verizon.net Tue May 16 13:38:21 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 16 May 2006 10:38:21 -0700 Subject: Did anyone get audio/video from PyCon 2006? Message-ID: <1147801101.498983.60720@i40g2000cwc.googlegroups.com> The obvious link from google seems to indicate that no audio or video got captured. Is this true, or am I looking in the wrong place? http://tinyurl.com/zu9lo Thanks, Grant From rupole at hotmail.com Wed May 31 23:37:55 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 31 May 2006 23:37:55 -0400 Subject: WinPops References: <mailman.6230.1148640634.27775.python-list@python.org> Message-ID: <1149132789_5889@sp6iad.superfeed.net> "Hari Sekhon" <sekhon.hari at googlemail.com> wrote in message news:mailman.6230.1148640634.27775.python-list at python.org... > Hi, > Is there a way of sending winpops (Windows Pop-Up / Net Send messages) in python? > > Perhaps some library or something that I can use under both Windows and Linux? > > Hari On Windows, you can use win32net.NetMessageBufferSend. 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 ilias at lazaridis.com Sun May 21 13:20:05 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sun, 21 May 2006 20:20:05 +0300 Subject: Software Needs Philosophers In-Reply-To: <5lZbg.6992$KB.1650@fed1read08> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <5lZbg.6992$KB.1650@fed1read08> Message-ID: <e4q7g3$agm$1@mouse.otenet.gr> Mark Shelor wrote: > Xah Lee wrote: > >> Programming languages are religions. For a long while now I've been ... ... > Is there really something new out there? I would argue that software > needs innovation more than it needs philosophers. software needs innovation. innovation needs philosophy. philosophy needs openness. - For readers which like a more compact overview of LISP (and its surrounding community): "Showcase for: how the "human factor" can negate, eliminate and even reverse the evolution of a Programming Language System." http://lazaridis.com/core/eval/lisp.html - Note: the results of this reviews are currently moved into several projects: http://lazaridis.com/pj http://case.lazaridis.com/multi . -- http://lazaridis.com From michele.simionato at gmail.com Tue May 9 03:37:21 2006 From: michele.simionato at gmail.com (michele.simionato at gmail.com) Date: 9 May 2006 00:37:21 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <uHa7g.509$SV1.289@fe10.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> Message-ID: <1147160240.954015.181480@j73g2000cwa.googlegroups.com> Ken Tilton wrote: > Python has a weak lambda, statements do not always > return values, it does not have macros, and I do not know if it has > special variables. I am pretty much ignorant of Common Lisp, but I have the impression they are the same as Scheme parameters, i.e. thread-local dynamically scoped variables (feel free to correct me if I am mistaken). If I am right, here is how you would emulate them in recent versions of Python: import threading, time special = threading.local() special.x = 0 def getx(): return special.x def set_x(value): special.x = value time.sleep(3-value) # thread-2 completes after thread-1 print "%s is setting x to %s" % (threading.currentThread(), getx()) if __name__ == '__main__': print getx() # => 0 threading.Thread(None, lambda : set_x(1)).start() # => 1 threading.Thread(None, lambda : set_x(2)).start() # => 2 time.sleep(3) print getx() # => 0 Michele Simionato From reply.in.the.newsgroup at my.address.is.invalid Mon May 8 10:22:17 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 08 May 2006 16:22:17 +0200 Subject: PYTHONPATH vs PATH? References: <445BA18C.3080600@kearfott.com> <HGEOKIAPAMCIFPPBDALKMEIGCAAA.m.yanowitz@kearfott.com> <mailman.5475.1147096312.27775.python-list@python.org> Message-ID: <arku52hqfmjhljj02r010d39hskqhvvnha@4ax.com> Fredrik Lundh: >PATH is used by the operating system to find executables, and PYTHONPATH >is used by Python to find Python modules. Yes, but Python also finds modules in its own installation. So changing PATH may cause another installation of Python to be run, which may have some other set of installed modules. "When a module named spam is imported, the interpreter searches for a file named spam.py in the current directory, and then in the list of directories specified by the environment variable PYTHONPATH. This has the same syntax as the shell variable PATH, that is, a list of directory names. When PYTHONPATH is not set, or when the file is not found there, the search continues in an installation-dependent default path; on Unix, this is usually .:/usr/local/lib/python." http://docs.python.org/tut/node8.html -- Ren? Pijlman From python at rcn.com Mon May 29 15:15:32 2006 From: python at rcn.com (Raymond Hettinger) Date: 29 May 2006 12:15:32 -0700 Subject: itertools.count() as built-in References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> Message-ID: <1148930132.621573.326720@u72g2000cwu.googlegroups.com> jantod at gmail.com wrote: > Is there any chance of itertools.count() ever becoming one of the > built-in functions? That's unlikely. The goal is to have fewer builtins rather than more. Utility and frequency are not the only considerations; otherwise glob.glob, sys.stderr, print.pprint, copy.copy, and many others would also be candidates. > It's a wonderful little function and I find myself > importing it in every module I write. I'm glad you find it so useful. Raymond From andy at neotitans.com Wed May 17 06:09:17 2006 From: andy at neotitans.com (Andy Sy) Date: Wed, 17 May 2006 18:09:17 +0800 Subject: [silly] Does the python mascot have a name ? In-Reply-To: <e4c59e$tqg$1@emma.aioe.org> References: <e4c59e$tqg$1@emma.aioe.org> Message-ID: <e4esht$rmi$1@sea.gmane.org> Steve wrote: > umm, was just wondering, does the python mascot have a name ? We are naming the > conference rooms in our office you see :o). > > Also, is there a place I could get some neat, good quality pics of the python ? > > - steve The Python mascot is called Odi. http://mail.python.org/pipermail/python-list/2003-September/185612.html -- It's called DOM+XHR and it's *NOT* a detergent! From No.Spam at Spam.none Mon May 1 21:48:28 2006 From: No.Spam at Spam.none (I. Myself) Date: Tue, 02 May 2006 01:48:28 GMT Subject: Can Python kill a child process that keeps on running? In-Reply-To: <1146532884.872505.154370@i40g2000cwc.googlegroups.com> References: <g0x5g.104639$7a.102977@pd7tw1no> <1146532884.872505.154370@i40g2000cwc.googlegroups.com> Message-ID: <MTy5g.104796$7a.25459@pd7tw1no> Serge Orlov wrote: > I. Myself wrote: > >> Suppose we spawn a child process with Popen. I'm thinking of an >> executable file, like a compiled C program. >> Suppose it is supposed to run for one minute, but it just keeps going >> and going. Does Python have any way to kill it? >> >> This is not hypothetical; I'm doing it now, and it's working pretty >> well, but I would like to be able to handle this run-on condition. I'm >> using Windows 2000, but I want my program to be portable to linux. >> > > On linux it's pretty easy to do, just setup alarm signal. On windows > it's not so trivial to the point you cannot do it using python.org > distribution, you will need to poke in low level C API using win32 > extensions or ctypes. AFAIK twisted package <http://twistedmatrix.com> > has some code to help you. Also take a look at buildbot sources > <http://buildbot.sf.net> that uses twisted. Buildbot has the same > problem as you have, it needs to kill run away or non-responding > processes. > That is bad news. Thanks anyway; bad news is better than no news. Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From bucodi at yahoo.fr.invalid Wed May 3 09:10:17 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Wed, 03 May 2006 15:10:17 +0200 Subject: We finally have a complete Python project Message-ID: <mn.1b8e7d65822744e3.43626@yahoo.fr.invalid> It is finally a fact, our new software project will be completely developed in Python ! Why is this so special , Well, we are using Python, for internal tools and some internal company software since years So why Python now ? Well, we are talking about a new project for us, so we can start from scratch. All tools that we use are open source tools. Since our project is a commercial project we can not develop it in open source, but we wanted to give back something to the community. We will contribute in 2 ways : - All standard functions & widget that we develop, we will publish here ! Anyone has an idea fort he license to use ? - We hope to interact with other python developers about the development of a commercial project with Python and if we have enough To make this happen we have created a blog : http://360.yahoo.com/bucodi Please visit us, comment, contribute, whatever :) feedback and interaction we will publish this as a free open source book (case study) Rony -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From http Fri May 19 01:18:23 2006 From: http (Paul Rubin) Date: 18 May 2006 22:18:23 -0700 Subject: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <IKbbg.44583$CH2.28892@tornado.texas.rr.com> Message-ID: <7xwtcipp7k.fsf@ruckus.brouhaha.com> "Paul McGuire" <ptmcg at austin.rr._bogus_.com> writes: > >>> def offByNoMoreThanOneCharacter(a,b): > ... return len(a)==len(b) and sum(map(lambda (x,y): x==y, zip(a,b))) >= > len(a)-1 Yikes! How about (untested): def offByNoMoreThanOneCharacter(a,b): return len(a)==len(b) and \ len([i for i in xrange(len(a)) if a[i] != b[i]]) <= 1 which seems more direct. I'm not sure it's correct since I'd consider "apple" and "apples" to be one character apart even though their lengths are unequal. But I think this type of function is useless for the problem at hand, since there are around N=300,000 words, comparing every pair of them is O(N**2) which is a bit painful. I'd use a decorate-sort-undecorate approach like: # generate all the ways to def generate_all_variants(word): wlower = word.lower() yield (wlower, word) for i in xrange(len(word)): yield (wlower[:i] + wlower[i+1:], word) Use this to generate all the variants of all the words in the dictionary, and write those out into a file, each line containing a variant plus the original word. Then use a sorting utility like the unix "sort" program to sort the file. Those programs work efficiently even if the file is too large to fit in memory. Then read the sorted file to find equivalence classes on the variants. From wesbrooks at gmail.com Mon May 22 10:42:14 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Mon, 22 May 2006 15:42:14 +0100 Subject: XP64 64 Bit Linux and Programming Best Practice Guide Message-ID: <eec9f8ee0605220742h62e2b204q4308f2fc362c0057@mail.gmail.com> Dear Users, Is there a version of python that will make full use of the 64 bit processing capabilities on XP64 or a 64 bit version of linux? Is there a particular version of linux best suited to coding in python and c++? Finally is there any references for programming best practice, for python or c++? I would like to know which features are best to use and which are best to avoid when optimising for speed and or memory usage. Thanks in advance of any advice. Yours Faithfully, Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060522/6671b008/attachment.html> From antroy at gmail.com Fri May 26 04:13:35 2006 From: antroy at gmail.com (Ant) Date: 26 May 2006 01:13:35 -0700 Subject: Parsing python dictionary in Java using JPython In-Reply-To: <mailman.6219.1148629589.27775.python-list@python.org> References: <mailman.6219.1148629589.27775.python-list@python.org> Message-ID: <1148631215.548568.296910@g10g2000cwb.googlegroups.com> It really depends on how you are trying to pass the dictionary across to Java, what sort of objects are in the dictionary etc. Could you provide some more background? BTW the Java implementation of Python is now called Jython (and has been for some years!). From nobody at 127.0.0.1 Sat May 13 15:27:16 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 13 May 2006 19:27:16 GMT Subject: compiling module from string and put into namespace References: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> <4464754a$0$306$626a54ce@news.free.fr> <1147474282.618115.60590@u72g2000cwu.googlegroups.com> <UW89g.5100$fb2.3962@newssvr27.news.prodigy.net> <1147545932.917599.217970@j73g2000cwa.googlegroups.com> Message-ID: <oqq9g.71892$F_3.25018@newssvr29.news.prodigy.net> glomde wrote: > I didnt mean that __import__ isnt a function, but that I want to > make a function called ImoprtFile that actually does something > very similar that what __import__. > > So to rephrsase the questin how does __import__ load a module > into the callers namespace. Ok got it now. I'm sure it's doable but it sounds tricky. Wouldn't it be easier to just have your function return a list of modules to the caller and have the caller import them? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From fredrik at pythonware.com Fri May 19 09:45:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 15:45:44 +0200 Subject: about py2exe, I installed it, but can't find py2exe.exe in my computer. References: <1148045399.833782.106910@g10g2000cwb.googlegroups.com> Message-ID: <e4ki68$q87$1@sea.gmane.org> "python" wrote: > I installed it, but can't find py2exe.exe in my computer. why? why are you looking for an EXE file? py2exe is a Python module, not an application. > And , when I execute "python setup.py py2exe" under command line, it > prompt error:wrong command "py2exe" . you're supposed to import py2exe into your setup file. if you don't do that, you'll get the above error message. have you read the "using py2exe" section on this page: http://www.py2exe.org/ ? </F> From Bulkan at gmail.com Wed May 31 23:47:32 2006 From: Bulkan at gmail.com (placid) Date: 31 May 2006 20:47:32 -0700 Subject: How to access the content of notepad with Python? In-Reply-To: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> References: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Message-ID: <1149133652.024007.220150@i39g2000cwa.googlegroups.com> kepioo wrote: > Hi, > > I have a software running on my computer that really looks like notepad > ( same interface, different name). I need to write a script that will > capture the content of this software --> the text written inside. > Dont know about win32, but if you want an easy solution then save the text you want to capture and then read it via Python! From me+python at modelnine.org Sun May 21 13:17:49 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 21 May 2006 19:17:49 +0200 Subject: Feature request: sorting a list slice In-Reply-To: <1148230551.278945.220130@i39g2000cwa.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <mailman.5983.1148077882.27775.python-list@python.org> <1148230551.278945.220130@i39g2000cwa.googlegroups.com> Message-ID: <200605211917.50219.me+python@modelnine.org> Am Sonntag 21 Mai 2006 18:55 schrieb Raymond Hettinger: > If the perf gain is small and the use cases are infrequent, the > addition is likely unwarranted. There is an entire class of feature > requests that are more appropriate as recipes than for inclusion in the > language. The thing is: having an explicit start/stop argument to reverse() and sort() doesn't slow down method call much (it's just one if() whose body is skipped when the parameters aren't passed, I'd say that the time that's lost here is pretty insignificant, in the order of 10^-6 seconds, on _any_ modern machine), and on the other hand warrants huge memory gains (if not performance gains by saving a memcpy) when you do need to sort or reverse slices of large lists. I've had use cases of the latter (reversing large parts of even larger lists in memory) in several data archiving and evaluation programs I wrote, but I can also understand the use case that was made by George for having these arguments for sort(), so that groupBy() can be extended easily to work on subgroups without requiring slicing. Anyway: having these "extensions" as a recipe won't work here: the main idea is saving the slicing by having sort() and reverse() do the "slicing" internally (rather, they just add a constant to the lower and upper bound, and the user specifies these constants, the internal functions they call already work on slices, and the current listobject.c gives them the whole list as the slice by default). The user can't patch this as an extension on the fly, because it requires changes to the underlying listobject.c source. That's why George is asking for inclusion of this patch. I just wrote the patch because I had the time to do so, and I won't battle for it's inclusion, but again, I see the use cases clearly, at the very least for slice support in list.reverse() and array.reverse() (which the patch also implements). --- Heiko. From spudtheimpaler at hotORgooMAIL.invalid Wed May 24 10:34:23 2006 From: spudtheimpaler at hotORgooMAIL.invalid (Mitch) Date: Wed, 24 May 2006 15:34:23 +0100 Subject: John Bokma harassment In-Reply-To: <1148463588.566212.36300@i39g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> Message-ID: <44746EEF.1090103@hotORgooMAIL.invalid> ilitzroth at gmail.com wrote: > Xah Lee schreef: > [...] >> >> If you believe this lobbying to my webhosting provider is unjust, >> please write to my web hosting provider abuse at dreamhost.com >> >> Your help is appreciated. Thank you. >> >> Xah >> xah at xahlee.org >> ? http://xahlee.org/ > > We seem to have strayed a long way from Voltaire's > "I do not agree with what you say, but I will defend to the death your > right to say it.", > but that was of course the age of enlightenment. > Immanuel > I would have to say +1 for Voltaire. Xah has as much right to post to the newsgroups as I do to skip over them. One of the reasons I enjoy lurking on newsgroups is the passion with which a lot of you speak; however, I do think there are a lot of short tempers flying around. Perhaps its because you've been putting up with this guy a lot longer than I have, but I can't imagine it takes that much effort to skip/block/kill file his posts. It's his as much as anyone else's, and all the while this is an unmoderated medium he has the *right* to say as he pleases. That said, if the ISP is kicking you off, it should be because you have broken a TOC. IF you don't think that that is the case, then that is your beef with them. Secondarily, all these essays end up on your site anyway, so why post the whole thing /again/ on the newsgroups when you could just link to the page, perhaps with a brief summary. Will that not A) still allow you to advertise the essays B) Save resources rather than copying everything twice and C) Piss less people off? I'm sure you aren't worried about pissing people off, but when it results in you getting kicked from your ISP, this just seems so much more sensible an answer. My 2 cents. P.S. The Universal Declaration of Human Rights (Summary) says: <quote> Article 19. Everyone has the right to freedom of opinion and expression; this right includes freedom to hold opinions without interference and to seek, receive and impart information and ideas through any media and regardless of frontiers. </quote> http://www.un.org/Overview/rights.html This debate boils down to whether or not he has broken the ISP's TOCs, nothing more. From nobody at 127.0.0.1 Mon May 29 14:05:47 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 29 May 2006 18:05:47 GMT Subject: send an email with picture/rich text format in the body References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <mailman.6297.1148858516.27775.python-list@python.org> <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> <mailman.6315.1148923456.27775.python-list@python.org> Message-ID: <%JGeg.103047$F_3.82622@newssvr29.news.prodigy.net> Ten wrote: > Sorry for the rant, good luck to the guy if he's solved his problem, > but damn, that "90% so let's not bother doing things properly" stuff makes > my blood boil. You must really hate browsing the web then. :) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From onurb at xiludom.gro Tue May 9 05:08:15 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 11:08:15 +0200 Subject: Python's regular expression? In-Reply-To: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> Message-ID: <44605c5f$0$7085$626a54ce@news.free.fr> Davy wrote: > Hi all, > (snip) > Does Python support robust regular expression like Perl? Yes. > And Python and Perl's File content manipulation, which is better? >From a raw perf and write-only POV, Perl clearly beats Python (regarding I/O, Perl is faster than C - or it least it was the last time I benched it on a Linux box). >From a readability/maintenance POV, Perl is a perfect nightmare. > Any suggestions will be appreciated! http://pythonology.org/success&story=esr -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mhellwig at xs4all.nl Wed May 3 19:11:17 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 04 May 2006 01:11:17 +0200 Subject: This coding style bad practise? In-Reply-To: <1146690808.394459.278670@g10g2000cwb.googlegroups.com> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> <1146690808.394459.278670@g10g2000cwb.googlegroups.com> Message-ID: <44593897$0$31654$e4fe514c@news.xs4all.nl> keirr wrote: > Martin P. Hellwig wrote: >> Hi all, >> >> I created a class which creates a relative unique id string, now my >> program just works fine and as expected but somehow I get the feeling >> that I misused the __repr__ since I guess people expect to 'execute' a >> function in an instance instead of using it's representation string of >> the instance itself, could you elaborate whether you find this bad >> practice and if yes what would have been a better way to do it? >> >> TIA >> > > Rather than comment on the style of using a class, I'll just suggest an > alternative. > You can use a generator function, which yields the next id when called; > at least that's > how I'd implement an IDgenerator. > > Cheers, > > Keir. > Thanks for your comment, I do use a generator in my class because I wanted to wrap my subversion when its on its end I had a choice of looping in with an if check or using a generator with try except, this time I choose a generator, though mostly I directly use a generator for these type of functions. -- mph From hancock at anansispaceworks.com Thu May 18 20:28:34 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Fri, 19 May 2006 00:28:34 +0000 Subject: python vs perl lines of code In-Reply-To: <1147993108.475434.177030@j55g2000cwa.googlegroups.com> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> Message-ID: <446D1132.10603@anansispaceworks.com> Michael Tobis wrote: >John Bokma wrote: >>"akameswaran at gmail.com" <akameswaran at gmail.com> wrote: >>>Ok I'm going to end with a flamebait - but I would posit, ALL OTHER >>>THINGS BEING EQUAL - that a smaller number of characters and lines in >>>code is more maintainable than larger number of characters and lines in >>>the code. >>> >>And I think that's why a lot of people posted very negative, in the hope >>that people would not be tempted to make the above very dumb statement. >Since it's too late to avoid such temptation, could you explain why you >are willing to go so far as to call that statement "very dumb"? The problem with the idea is that "simplicity" is not quite equal to "a smaller number of characters". For example, of each of the following pairs, which is "clearer": ls list cp copy mv move Or to ask it another way, "Which is easier to *read*?" Although I have long since come to take the former spellings for granted, and they are undeniably shorter, the latter would've actually been easier for people to remember. The insistence of using the longer, more mnemonic form is a major characteristic of Python. The wisdom behind this is that Python's design takes into account the observation that source code is read many times more than it is written. To do this, it sacrifices some brevity compared to other languages (the classic example being Perl which uses lots of arcane symbols and tends to use shorter, more Unix-like naming). However, this turns out to be a big win, in that you don't waste so much time trying to remember abbreviated names. There are, for example several ways of abbreviating a word like "quantity": q Q quant qtty quanty qnty Qtty QNT etc. But there's only one "standard spelling". If I only have to remember that "Python prefers to use the standard spelling" as a rule of thumb, then I will usually get the right answer (there are still significant exceptions such as "dict" instead of "dictionary" and "def" instead of "define" -- but they are fewer than in most languages). Anyway, since humans tend to parse whole words as symbols when reading, rather than individual characters, the choice between using symbols or abbreviations versus whole standard-form words is not believed to matter (I think it would be a strong claim to say that this is proven, but it does seem likely to me). Frankly, even when typing, I find it slightly easier to type "unmount" than "umount" -- I always pause after the "u" to remember the funky Unix spelling. It's only a split-second delay, but those things add up, and each one represents a possible bug, if the output is source code. Even "dictionary" is hardly different from "dict" -- I've already learned to type common English morphemes without thinking about the process, so it just doesn't make any difference from my PoV. That's why I always find the hoops people will jump through to avoid typing a couple of extra keystrokes to be silly (are they typing with their noses?* ;-) ). It would frankly be harder for me to remember the extra mechanics than to just type the extra letters. The claim is ironic -- even counter-intuitive -- considering this conventional lore. But the real point is that no one here can make any reasonably objective assessment of whether your "data" is meaningful unless you post examples. That's what creates the hostility, I think. Cheers, Terry *With apologies to anyone who's actually using assistive tech to type their code -- but I'm sure you already know how to use macros to get what you want typed. -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From http Tue May 23 14:39:07 2006 From: http (Paul Rubin) Date: 23 May 2006 11:39:07 -0700 Subject: real time info to web browser from apache side ? References: <1148408900.176202.281530@g10g2000cwb.googlegroups.com> Message-ID: <7xac98vb5g.fsf@ruckus.brouhaha.com> "Joseph" <spmok2 at canada.com> writes: > What are the current technology that allows for this. I know its > possible because I can use my browser sometimes to chat with people > online, and I swear that I don't have to do a Control-R everytime to > see that the other person's typing is updating constantly on my > browser. The trendy way these days is with AJAX, which I guess is legitimate in an environment where you control both the browser and the server. From malvert at telenet.be Tue May 9 15:34:20 2006 From: malvert at telenet.be (malv) Date: 9 May 2006 12:34:20 -0700 Subject: Upgrading Class Instances Automatically on Reload References: <1147196712.192606.75160@g10g2000cwb.googlegroups.com> <24p1625coseqi7imip7f6nssi9feu400j3@4ax.com> Message-ID: <1147203260.211710.14890@v46g2000cwv.googlegroups.com> Rene, No, I couldn't get it to work. Sorry, I should have included that information. At the statement b = Bar(), the following error occurs: The debugged program raised the exception unhandled AttributeError "type object 'Bar' has no attribute '__instance_refs__'" malv From malvert at telenet.be Tue May 9 16:18:29 2006 From: malvert at telenet.be (malv) Date: 9 May 2006 13:18:29 -0700 Subject: Upgrading Class Instances Automatically on Reload References: <1147196712.192606.75160@g10g2000cwb.googlegroups.com> <24p1625coseqi7imip7f6nssi9feu400j3@4ax.com> <1147203260.211710.14890@v46g2000cwv.googlegroups.com> <49t1625fkhhkrca8l2u015tums1b0r8c9j@4ax.com> Message-ID: <1147205909.744808.284100@u72g2000cwu.googlegroups.com> Indeed, as I indicated the old recipe/160164 by Michael Hudson works flawlessly for me. I am referring here to the latest edition: cookbook #2 which features an upgraded version. You find the examples in: http://examples.oreilly.com/pythoncook2/cb2_examples.zip The files are named cb2_6_21_*.py, but the book has the recipe in chapter 20.15. malv From john at castleamber.com Thu May 18 22:13:41 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 02:13:41 GMT Subject: Quoting relevant material for response (was: Re: python vs perl lines of code) References: <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <Xns97C7BC8549BA0castleamber@130.133.1.4> <1147996169.818933.252420@u72g2000cwu.googlegroups.com> <Xns97C7C31D1A937castleamber@130.133.1.4> <1148002073.419819.295180@38g2000cwa.googlegroups.com> <mailman.5921.1148002657.27775.python-list@python.org> <1148003186.350496.67670@g10g2000cwb.googlegroups.com> Message-ID: <Xns97C7D7F1646FFcastleamber@130.133.1.4> "akameswaran at gmail.com" <akameswaran at gmail.com> wrote: > quoting mechanism is available on the web interface and I haven't found > it - I'd love to know how to use it. http://groups.google.com/support/bin/answer.py?answer=14213 > Also i use the threaded view on > the web client, so I have little trouble figuring out what is being > referenced. I mark messages as read when I have read them, so without a context I have no idea what "Joh, I disagree" (for example) is about, especially since I don't just post one message a day. Also, due to how Usenet works, not everybody sees the messages in the same order as you do, or might even miss out a message or two (or several). Finally, since Google provides a search engine for Usenet, it might be perfectly possible that your reply without a quote is the first result in such a search. I always recommend to write your reply in such a way that when you print it, and read it 3 months later you're able to understand the message when you read it top down. > My comment about John being funny in fact was a generic comment, and > while the remainder of my response was on topic - it still was not in > response to 1 specific statement or another. Quoting previous comments > is useful, but not required to be in thread - IMHO. True, but if it's not a reply to the previous person, then you might want to start a new thread, or you're replying to the wrong person. -- 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 roger.miller at nova-sol.com Wed May 24 16:11:35 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 24 May 2006 13:11:35 -0700 Subject: Looking for help with Regular Expression References: <1148428798.529016.319100@y43g2000cwc.googlegroups.com> Message-ID: <1148501495.012786.99080@g10g2000cwb.googlegroups.com> Seem to be a lot of regular expression questions lately. There is a neat little RE demonstrator buried down in Python24/Tools/Scripts/redemo.py, which makes it easy to experiment with regular expressions and immediately see the effect of changes. It would be helpful if it were mentioned in the RE documentation, although I can understand why one might not want a language reference to deal with informally-supported tools. From ruv at enomaly.com Tue May 23 08:40:51 2006 From: ruv at enomaly.com (ruv at enomaly.com) Date: 23 May 2006 05:40:51 -0700 Subject: Seeking Contract Python Developer Message-ID: <1148388051.192366.3870@j73g2000cwa.googlegroups.com> Enomaly, a dynamic open source development firm located in Toronto, Ontario is looking for a TurboGears / Python Developer for a 2 month (offsite or on) contract-to-hire opportunity. Responsibilities include reporting on test progress, status, and coverage, as well as meeting test completion and delivery milestones. The contract is for on-going development of the Enomalism Xen management system, see > http://enomalism.com/Jobs.312.0.html to learn more about the application. Experience Development of Python applications from scratch from high level requirements documents. Good working knowledge of LDAP, both the protocol, and the APIs which support it. Proficient with AJAX/JSON, javascript programming, and the HTTP protocol. Proficient with SOAP, XML-RPC, and other HTTP based data interchange methods. Development of Unix scripts required to support execution of applications etc. Development of Web based front ends of tools using HTML, JSP, PHP etc.. Development of applications that use MySQL databases (Oracle, SQL etc..) In-depth knowledge of Linux development environment. Strong debugging skills Responsibilities: Contribute to the development of Enomalism - an OSS administrative console for Xen Hypervisor. Develop and execute test plans and test cases. Contribute to setting and evaluating milestone criteria such that product is released on schedule with high quality. Design and implement quality processes for a small team of senior software developers. Work closely with the core development team during all phases of the product life cycle. Continually research new technologies and incorporate that new knowledge into your ongoing QA process. Requirements: Abilty to succeed in a fast paced/flexible environment. Good team player. Strong verbal and written communications skills. Entrepreneurial spirit, comfortable in a start-up environment. BS degree in computer related field. If you are qualified & interested, please contact: Contact: George Bazos Phone: (212) 203-4734 Email: gb at enomaly.com ------ Reuven Cohen Chief Technologist, Enomaly Inc. www.enomaly.com :: 212 203 4734 x 1 skype: ruv.net // aol: ruv6 - Get Linked in> http://linkedin.com/pub/0/b72/7b4 From jjl at pobox.com Sat May 27 10:37:20 2006 From: jjl at pobox.com (John J Lee) Date: Sat, 27 May 2006 14:37:20 +0000 (UTC) Subject: HTTPS client certificates (was Re: Twill question) (fwd) Message-ID: <Pine.LNX.4.64.0605271433200.8533@localhost> Just forwarding this in case anybody here can shed light on this -- urllib's support for SSL client certificates didn't work for me, and I'm wondering if it works for anybody else... John ---------- Forwarded message ---------- Date: Sat, 27 May 2006 14:33:03 +0000 (UTC) From: John J Lee <jjl at pobox.com> To: Wayne Wang <ytwgq at sbcglobal.net>, twill at lists.idyll.org Subject: HTTPS client certificates (was Re: Twill question) On Fri, 26 May 2006, Wayne Wang wrote: [...wants https client auth...] OK, I added the necessary boilerplate to mechanize (haven't committed yet), but the basic support for this that comes with Python didn't work for me on a local test server I set up, so I couldn't get it working with mechanize either. Wayne, and anybody else who uses client certificates and is inclined to help out: could you try running this script, after replacing HTTPS_URL with a URL on the secure site you're trying to access, and KEY_FILE and CERT_FILE with the full filenames where you keep those? I'm afraid you have to convert the p12 file into separate PEM-format key and cert files using e.g. OpenSSL: openssl pkcs12 -clcerts -nokeys -in cert.p12 -out cert.pem openssl pkcs12 -nocerts -in cert.p12 -out key.pem HTTPS_URL = "https://example.com:443/restricted/foo.html" KEY_FILE = r"c:\blah\blah\key.pem" CERT_FILE = r"c:\blah\blah\cert.pem" import urllib urllib.URLopener(key_file=KEY_FILE, cert_file=CERT_FILE, ) r = urllib.urlopen() print r.read() John From OlafMeding at gmail.com Thu May 4 23:02:39 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 4 May 2006 20:02:39 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <pan.2006.05.04.21.14.29.135773@gmx.net> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <mailman.5282.1146692801.27775.python-list@python.org> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> <125ir8gpofq3i1c@corp.supernews.com> <pan.2006.05.04.21.14.29.135773@gmx.net> Message-ID: <1146798159.209695.4190@j33g2000cwa.googlegroups.com> Marc > IIRC it was something like an NTP daemon that caused the clock to "jump" a little and (Window's) sleep was confused. The problem is not a "jump" but a permanet lockup of the sleep statement. To all others, is there nobody out there that could run the test code at the beginning of this post on a hyper-threading CPU? Olaf From bnblazer at gmail.com Mon May 22 21:46:20 2006 From: bnblazer at gmail.com (Brian) Date: 22 May 2006 18:46:20 -0700 Subject: Too big of a list? and other problems In-Reply-To: <mailman.6092.1148347725.27775.python-list@python.org> References: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> <mailman.6092.1148347725.27775.python-list@python.org> Message-ID: <1148348780.222047.92470@u72g2000cwu.googlegroups.com> Tim Chase wrote: > While I'm not sure if this is the issue, you might be having some > trouble with the greediness of the "*" repeater here. HTML like > > <img src="images/1.jpeg"><img src="hello.jpeg"> > > will yield a result of > > "images/1.jpeg"><img src="hello.jpeg" > > rather than the expected > > "images/1.jpeg" > > You can make it "stingy" (rather than greedy) by appending a > question-mark: > > r"images/.*?\.jpeg" > > I also don't know if they all are coming back as "jpeg", or if > some come back as "jpg", in which case you might want to use > > r"images/.*?\.jpe?g" > Thanks Tim! That modification to the regex helped a lot, and believe it or not, my pic count went up! Thank you, Brian From nobody at 127.0.0.1 Thu May 11 18:44:38 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 11 May 2006 22:44:38 GMT Subject: FTP filename escaping References: <1147375459.332757.212570@u72g2000cwu.googlegroups.com> <1147377391.521967.26730@j33g2000cwa.googlegroups.com> <1147383999.022322.80060@q12g2000cwa.googlegroups.com> Message-ID: <q7P8g.69872$_S7.34344@newssvr14.news.prodigy.com> Serge Orlov wrote: > Almad wrote: >> OK, after some investigation...problem is in non-latin characters in >> filenames on ftp. >> >> Yes, users should be killed for this, > > It's futile, users will always find a way to crash you program :) And > you can't kill them all, there are too many of them. Yes but you can take their toys away. :) From aylwyn at cantab.net Wed May 17 15:18:54 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 12:18:54 -0700 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <slrne6mkt5.hoa.sybrenUSE@schuimige.stuvel.eu> <_2Jag.88816$dW3.57801@newssvr21.news.prodigy.com> <kurm62ph2d18bcal7jkm08q0dohmlg6nll@4ax.com> Message-ID: <1147893534.877297.259030@j73g2000cwa.googlegroups.com> Dave Hansen wrote: >That will work. As long as the creator of file used four-space TABs, >anyway... That sentence has no meaning. There is no such thing as a four-space tab. From bignose+hates-spam at benfinney.id.au Wed May 17 18:40:05 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 08:40:05 +1000 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <87iro4num2.fsf@benfinney.id.au> "glomde" <tbrkic at yahoo.com> writes: > With element tree package. > > # build a tree structure > root = ET.Element("html") > head = ET.SubElement(root, "head") > title = ET.SubElement(head, "title") > title.text = "Page Title" > body = ET.SubElement(root, "body") > body.set("bgcolor", "#ffffff") > body.text = "Hello, World!" > > > > With syntactical sugar: > > # build a tree structure > root = ET.Element("html") > *!*root: > *!*head("head"): > *!*title("title): > *=*text = "Page Title" > *!*body("body"): > *=*bgcolor = "#ffffff" > *=*text = "Hello, World!" We already have syntax for building hierarchical data structures: lists and/or tuples. If you want to define Node and Attribute classes, you can already do so without adding new syntax. > I think that with the added syntax you get better view of the html > page. I think indenting our existing data type syntax can do the same thing: root = Node("html", children=[ Node("head", children=[ Node("title", children=[ "Page Title", ]) ]), Node("body", children=[ Attribute("bgcolor", "white"), "Hello, World!", ]), ]) Set up the __init__ for those classes to do whatever you would have done with the syntax you proposed. > Repeating things dissapears and you get indentation that corresponds > to the tree. Indeed. > I think it is very pythonic IMHO. Adding new punctuation to deal with a particular type is extremely un-Pythonic. -- \ "The cost of a thing is the amount of what I call life which is | `\ required to be exchanged for it, immediately or in the long | _o__) run." -- Henry David Thoreau | Ben Finney From andrew.arobert at gmail.com Thu May 25 10:00:54 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 25 May 2006 10:00:54 -0400 Subject: regex/lambda black magic Message-ID: <127be5or10v59e9@corp.supernews.com> Hi everyone, I have two test scripts, an encoder and a decoder. The encoder, listed below, works perfectly. import re,sys output = open(r'e:\pycode\out_test.txt','wb') for line in open(r'e:\pycode\sigh.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: '%%%2X' % ord(s.group()), line)) The decoder, well, I have hopes. import re,sys output = open(r'e:\pycode\new_test.txt','wb') for line in open(r'e:\pycode\out_test.txt','rb') : output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16)) % ord(s.group()), line)) The decoder generates the following traceback: Traceback (most recent call last): File "E:\pycode\sample_decode_file_specials_from_hex.py", line 9, in ? output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16)) % ord(s.group()), line)) File "C:\Python24\lib\sre.py", line 142, in sub return _compile(pattern, 0).sub(repl, string, count) File "E:\pycode\sample_decode_file_specials_from_hex.py", line 9, in <lambda> output.write( re.sub(r'([^\w\s])', lambda s: chr(int(s.group(), 16)) % ord(s.group()), line)) ValueError: invalid literal for int(): % Does anyone see what I am doing wrong? From paddy3118 at netscape.net Thu May 4 14:13:14 2006 From: paddy3118 at netscape.net (Paddy) Date: 4 May 2006 11:13:14 -0700 Subject: Python for Perl programmers References: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> <e3dait$4us$1@panix2.panix.com> Message-ID: <1146766394.661333.103040@j73g2000cwa.googlegroups.com> I found this version of the phrasebook: http://wiki.python.org/moin/PerlPhrasebook its been edited recently but I didn't check for how current it is. -- Pad. From sjmachin at lexicon.net Wed May 17 08:50:06 2006 From: sjmachin at lexicon.net (John Machin) Date: 17 May 2006 05:50:06 -0700 Subject: Unable to extract Python source code using Windows In-Reply-To: <mecl62pdsp6rvg4ufapbnddnrqhooovbkf@4ax.com> References: <1147793161.867167.113480@g10g2000cwb.googlegroups.com> <1147826601.426636.4540@y43g2000cwc.googlegroups.com> <mecl62pdsp6rvg4ufapbnddnrqhooovbkf@4ax.com> Message-ID: <1147870205.935663.42810@38g2000cwa.googlegroups.com> > I'd blame WinZip for claiming rights to files it can't read You are probably right ... however in Windows Explorer on my box, .bz2 files have an "I don't know" type of icon, whereas .zip (of course(?)) and .tgz and.tar.gz files have the WinZip vice-squeezing icon. Are there two different lists of what exe handles what extension?? Cheers, John From eugene at boardkulture.com Fri May 26 05:02:26 2006 From: eugene at boardkulture.com (3KWA) Date: 26 May 2006 02:02:26 -0700 Subject: Python Programming Books? In-Reply-To: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> Message-ID: <1148634146.415738.182360@j33g2000cwa.googlegroups.com> http://www.greenteapress.com/thinkpython/ How to think like a computer scientist is a great first read I think. From socha at cs.washington.edu Thu May 25 00:42:29 2006 From: socha at cs.washington.edu (David Socha) Date: Wed, 24 May 2006 21:42:29 -0700 Subject: determining available space for Float32, for instance In-Reply-To: <e505uf$hkq$1@sea.gmane.org> Message-ID: <519D71619DEB5348BFCBC6AEBC3F9A03014E1180@exchsrv2.cseresearch.cs.washington.edu> Robert Kern wrote: > David Socha wrote: > > I am looking for a way to determine the maxium array size I can > > allocate for arrays of Float32 values (or Int32, or Int8, > ...) at an > > arbitrary point in the program's execution. This is needed because > > Python cannot allocate enough memory for all of the data we need to > > process, so we need to "chunk" the processing, as described below. > > > > Python's memory management process makes this more > complicated, since > > once memory is allocated for Float32, it cannot be used for > any other > > data type, such as Int32. > > Just for clarification, you're talking about Numeric arrays > here (judging from the names, you still haven't upgraded to > numpy), not general Python. Python itself has no notion of > Float32 or Int32 or allocating chunks of memory for those two > datatypes. Yes, I am talking about numarray arrays, not general Python. > > I'd like a solution that includes either memory that is not yet > > allocated, or memory that used to be allocated for that > type, but is > > no longer used. > > > > We do not want a solution that requires recompiling Python, > since we > > cannot expect our end users to do that. > > OTOH, *you* could recompile Python and distribute your Python > with your application. We do that at Enthought although for > different reasons. However, I don't think it will come to that. We could, but that seems like it simply creates a secondar problems, since then the user would have to choose between installing our version of Python or Enthought's version, for instance. > > Does anyone know how to do this? > > With numpy, it's easy enough to change the datatype of an > array on-the-fly as long as the sizes match up. > > In [8]: from numpy import * > > In [9]: a = ones(10, dtype=float32) > > In [10]: a > Out[10]: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., > 1.], dtype=float32) > > In [11]: a.dtype = int32 > > In [12]: a > Out[12]: > array([1065353216, 1065353216, 1065353216, 1065353216, 1065353216, > 1065353216, 1065353216, 1065353216, 1065353216, > 1065353216], dtype=int32) > > However, keeping track of the sizes of your arrays and the > size of your datatypes may be a bit much to ask. Exactly. Building a duplicate mechanism for tracking this informaiton would be a sad solution. Surely Python has access to the amount of memory being used by the different data types. How can I get to that information? > [snip] > numpy (definitely not Numeric) does have a feature called > record arrays which will allow you to deal with your agents > much more conveniently: > > http://www.scipy.org/RecordArrays > > Also, you will certainly want to look at using PyTables to > store and access your data. With PyTables you can leave all > of your data on disk and access arbitrary parts of it in a > relatively clean fashion without doing the fiddly work of > swapping chunks of memory from disk and back again: > > http://www.pytables.org/moin Do RecordArrays and PyTables work well together? Thanks for the info. The PyTables looks quite promising for our application (I had been looking for an HDF5 interface, but couldn't recall the 'HDF5' name). David Socha Center for Urban Simulation and Policy Analysis University of Washington 206 616-4495 From ptmcg at austin.rr._bogus_.com Fri May 19 12:03:39 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 16:03:39 GMT Subject: Complex evaluation bug References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> <mailman.5897.1147971519.27775.python-list@python.org> <446d79da$0$7144$626a54ce@news.free.fr> <mailman.5929.1148026521.27775.python-list@python.org> <446d8209$0$7139$626a54ce@news.free.fr> Message-ID: <v%lbg.46822$CH2.40151@tornado.texas.rr.com> "Christophe" <chris.cavalaria at free.fr> wrote in message news:446d8209$0$7139$626a54ce at news.free.fr... <snip> > Oups, I was too fast to read what was written. I though you only changed > one of the terms ( str -> repr ). > > You'll note that repr and str produce the exact same result for complex. > And also, I'm not sure using eval anywhere is a good idea so it probably > doesn't help for what the OP wants to do. An eval-less approach - the problem is the enclosing parens. >>> a = 1+3j >>> str(a) '(1+3j)' >>> complex(str(a)) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: complex() arg is a malformed string >>> complex(str(a)[1:-1]) (1+3j) >>> complex(str(a).strip("()")) (1+3j) -- Paul From nojhan at free.fr Sun May 14 03:25:51 2006 From: nojhan at free.fr (nojhan) Date: Sun, 14 May 2006 09:25:51 +0200 Subject: Python API, Initialization, Path and classes Message-ID: <pan.2006.05.14.07.25.48.544402@free.fr> I'm trying to embbed the python interpreter as a class attribute, initializing it in the constructor, and finalizing in destructor. The code is rather simple: // base_path is an attribute of the class, // initialized with argv[0] at the instanciation clog << "Python base program name asked: " << base_path << endl; Py_SetProgramName( base_path ); Py_Initialize(); clog << "Python isInitialized ? " << ( Py_IsInitialized()?"yes":"no" ) << endl; clog << "Python base program name set:" << Py_GetProgramName() << endl; clog << "Python path: " << Py_GetPath() << endl; But it produce a rather strange output : Python base program name asked: /home/nojhan/travail/openMetaheuristic/source/ometah/ometah Python isInitialized ? yes Python base program name set:/home/nojhan/travail/openMetaheuristic/source/ometah/ometah Python path: /usr/lib/python24.zip:/usr/lib/python2.4/:/usr/lib/python2.4/plat-linux2:/usr/lib/python2.4/lib-tk:/usr/lib/python2.4/lib-dynload The code ends in an ImportError if I try to import a module in the current path. Note that the python C API reference manual precise that Py_Initialize() "initializes the module search path (sys.path)" [1]. I'm searching for a way to force the python interpreter considering the current path when searching for available modules. [1] http://docs.python.org/api/initialization.html -- NoJhan (Cross-posted to comp.python.c++) From bdesth.quelquechose at free.quelquepart.fr Wed May 31 22:14:20 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 01 Jun 2006 04:14:20 +0200 Subject: is a wiki engine based on a cvs/svn a good idea? In-Reply-To: <mailman.6384.1149113085.27775.python-list@python.org> References: <mailman.6384.1149113085.27775.python-list@python.org> Message-ID: <447e1dfc$0$20866$626a54ce@news.free.fr> piotr maliski a ?crit : > I'm planning to wite a fully featured wiki in Python Then first have a look at both moinmoin and Trac. Good part of the job is already done. > in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. This has been discussed for Trac, cf: http://projects.edgewall.com/trac/wiki/TighterSubversionIntegration http://projects.edgewall.com/trac/wiki/WhySQLite > Pro: versioning / diffs, > Cons: you need your own svn/cvs repository, > can pyLucene or Xapwrap index this? From siona at chiark.greenend.org.uk Thu May 18 09:49:07 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 18 May 2006 14:49:07 +0100 (BST) Subject: How to tell if function was passed a list or a string? References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> Message-ID: <xlm*u7Xgr@news.chiark.greenend.org.uk> rh0dium <steven.klass at gmail.com> wrote: > [ ... ] Since you have lots of answers to your real question: > an.append(re.sub(",","", str(a))) an.append(str(a).replace(",", "")) -- \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 tim.golden at viacom-outdoor.co.uk Fri May 19 05:56:11 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Fri, 19 May 2006 10:56:11 +0100 Subject: Windows Registry Dump Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1DD@vogbs009.gb.vo.local> [Dirk Hagemann] | @Diez: I'm not trying to hack into somebody's computer - it is about | collecting data from my company's anti-virus-parent-server. | And all the | information is only available in the registry (thanks Symantec...). | | @Tim, olso and Fredrik: THANKS - I will have a closer look at these | modules. One thing occurred to me later, Dirk: are you trying to get the conventional .reg dump file, ie something which you could reload later into the same or another computer? Or are you simply looking for a textual representation of the registry for analysis etc.? From your comment above it sounds like the latter. Be aware, btw, if you go down the .reg route (the one I suggested): the data in the files are UTF-16 encoded. 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 ptmcg at austin.rr._bogus_.com Thu May 18 14:08:57 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Thu, 18 May 2006 18:08:57 GMT Subject: Complex evaluation bug References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> <Yk2bg.8862$aa4.296336@news20.bellglobal.com> Message-ID: <ZK2bg.44468$CH2.2878@tornado.texas.rr.com> "Mel Wilson" <mwilson-to at sympatico.ca> wrote in message news:Yk2bg.8862$aa4.296336 at news20.bellglobal.com... > of wrote: > > a = 1+3j > > complex(str(a)) > > > > Why does this not work ? It should > > It would be nice. > Looks like str(1+3j) is returning an expression in string > form. Maybe there is no actual complex literal. > The problem is that str(1+3j) emits a string enclosed in parens. Stripping them off makes the string acceptable to complex's constructor, without invoking eval. >>> a = 1+3j >>> str(a) '(1+3j)' >>> complex(str(a)) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: complex() arg is a malformed string >>> complex(str(a)[1:-1]) (1+3j) >>> complex(str(a).strip("()")) (1+3j) -- Paul From onurb at xiludom.gro Thu May 18 10:51:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 16:51:18 +0200 Subject: Python - Web Display Technology In-Reply-To: <1147961355.652526.230610@i39g2000cwa.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5872.1147945818.27775.python-list@python.org> <1147961355.652526.230610@i39g2000cwa.googlegroups.com> Message-ID: <446c8a4e$0$6838$636a55ce@news.free.fr> SamFeltus wrote: > I guess there isn't much to understand. If you are satisfied with a > text based, static image web, that is light on artistic possabilities, > all that HTML stuff is acceptable. 1. artistic != animated. 2. the web has mostly been designed for text-based content. > Perhaps the HTML/JS group will even > get off their rear ends and bring some decent cross platform graphics > capabilities to the web one decade? Perhaps even bring some 90's style > graphics to the browser one decade? Ever heard of SVG ? FWIW, your site is maybe very artistic, but it's content doesn't show up much in google : http://www.google.com/search?q=site:samfeltus.com Compare with: http://www.google.com/search?q=site:python.org -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From grante at visi.com Wed May 10 22:33:39 2006 From: grante at visi.com (Grant Edwards) Date: Thu, 11 May 2006 02:33:39 -0000 Subject: hyperthreading locks up sleeping threads References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> <1147292178.325015.172460@y43g2000cwc.googlegroups.com> <1264k82rk3pvu26@corp.supernews.com> <1147297144.537106.161310@j73g2000cwa.googlegroups.com> Message-ID: <12658k3mo9isi93@corp.supernews.com> On 2006-05-10, OlafMeding at gmail.com <OlafMeding at gmail.com> wrote: > Grant > >> You might want to run some memory tests. > > We have multiple identical boxes and they all have the same problem. Maybe whoever built them got a bad batch of RAM. Or maybe the just used RAM with the wrong specs. It doesn't really cost anything to run a memory test for a few hours, and if it passes, then you can cross that off the list. -- Grant Edwards grante Yow! KARL MALDEN'S NOSE at just won an ACADEMY AWARD!! visi.com From maxerickson at gmail.com Tue May 23 09:20:32 2006 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 23 May 2006 13:20:32 +0000 (UTC) Subject: Accessing object parent properties References: <af3c42f10605230527o75d06818x42a177f41e480d6e@mail.gmail.com> Message-ID: <Xns97CC5F55ECF8Bmaxericksongmailcom@80.91.229.5> One way: class Boo: def __init__(self, parent): self.parent=parent class Foo: X=1 def __init__(self): self.test=boo(self) From johnjsal at NOSPAMgmail.com Sat May 20 12:16:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 20 May 2006 12:16:09 -0400 Subject: combining a C# GUI with Python code? In-Reply-To: <mn.a2757d657d031da4.43626@yahoo.fr.invalid> References: <3Dnbg.2135$No6.46516@news.tufts.edu> <mn.a2757d657d031da4.43626@yahoo.fr.invalid> Message-ID: <446f4058$0$1987$c3e8da3@news.astraweb.com> Rony Steelandt wrote: > Isn't it a bit overkill to implement the whole .net framework 'Just' > for a GUI ?? > > If you want to build quickly nice GUI's for your python program, have a > look at wxpython & wxdesigner wxdesigner looked good until I had to pay. :( From netvaibhav at gmail.com Sat May 20 03:18:58 2006 From: netvaibhav at gmail.com (netvaibhav at gmail.com) Date: 20 May 2006 00:18:58 -0700 Subject: altering an object as you iterate over it? In-Reply-To: <446e1def$0$6919$626a54ce@news.free.fr> References: <1Mobg.2139$No6.46432@news.tufts.edu> <446e1def$0$6919$626a54ce@news.free.fr> Message-ID: <1148109538.785965.41350@j33g2000cwa.googlegroups.com> bruno at modulix wrote: > fin = open(path, 'r') > fout = open(temp, 'w') > for line in fin: > if line.strip(): > fout.write(line) > fin.close() > fout.close() > > then delete path and rename temp, and you're done. And yes, this is > actually the canonical way to do this !-) What if there's a hard link to path? -- Vaibhav From ask at me Wed May 24 22:18:26 2006 From: ask at me (AndyL) Date: Wed, 24 May 2006 22:18:26 -0400 Subject: deploying big python applications Message-ID: <Z42dnQKXWvZivOjZnZ2dnUVZ_v6dnZ2d@comcast.com> Hi, let me describe how I do that today. There is standard python taken from python.org installed in a c:\python23 with at least dozen different additional python packages (e.g. SOAPpy, Twisted, wx, many smaller ones etc) included. Also python23.dll moved from c:\windows to c:\python23. This is zipped and available as over 100MB file to anyone to manually unzip on his/her PC. This is a one time step. On top of that there is 30K lines of code with over 100 .py files application laid out within a directory tree. Very specific for the domain, typical application. This again is zipped and available to anyone as much smaller file to unzip and use. This step is per software releases. There is one obvious drawback - I can not separate python from standard libraries easily. So when upgrade to 2.4 comes, I need to reinstall all the packages. In order to address that as well as the Linux port I project following structure: -default python.org installation or one time step on Windows -set of platform dependent libraries in directory A -set of platform independent libraries in directory B -application in directory C This way I can easily port (or just use) entire software under Linux/Unix yet do not have to worry about collecting all the packages evry time I change the platform or the version of Python. I hope I described it well enough. How to achieve it, is there any better solution, or ready one. Please advice. Thx in advance, A. From phil at riverbankcomputing.co.uk Tue May 2 08:11:20 2006 From: phil at riverbankcomputing.co.uk (Phil Thompson) Date: Tue, 2 May 2006 13:11:20 +0100 Subject: pyqt v3.* and v4.* In-Reply-To: <e37hnm$51k$1@news2.ipartners.pl> References: <e37hnm$51k$1@news2.ipartners.pl> Message-ID: <200605021311.20320.phil@riverbankcomputing.co.uk> On Tuesday 02 May 2006 1:01 pm, Skink wrote: > Hi, > > Is it possible to have both versions of pyqt (in my case 3.14.1 and 4.0)? Yes - but not that version of PyQt3. > Version 3 is built using sip 4.2.1, version 4 is built using sip 4.4.3 > > When I run pyqt 4.0 (but with installed sip 4.2.1) I get: > > from PyQt4 import QtCore, QtGui > TypeError: invalid argument to sipBadCatcherResult() > > When I run pyqt 3.14 (but with installed sip 4.4.3) I get: > > import qt > Segmentation fault > > > Both 3.14 and 4.0 work, but not when installed together. Install the latest versions of PyQt3 and SIP. Phil From userprogoogle-139 at yahoo.co.uk Wed May 3 12:15:34 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 3 May 2006 09:15:34 -0700 Subject: Strange Threads Behaviour... Message-ID: <1146672934.622365.99020@u72g2000cwu.googlegroups.com> I have written an application which uses threads and the XMPP library - this is a library which supports the jabber instant messaging protocol. The application works fine when run from Idle, however I get thread errors when I try to run it as an EXE created with Py2Exe or when it is run within other editors such as SPE. I need to ship the application to end users so any pointers on thread handling when creating shipping apps would be useful. For reasons of confidentiality I cannot post all the source code, however the error log is below. Thanks in advance. Best, rod update (server adddress deleted) Jabber Login Successful Greg forced SASL not to be used. Auhentication fails if it is used. Warning: unable to perform SASL auth os (serger address deleted). Old authentication method used! idname: glocopex executing Exception in thread Thread-1 (most likely raised during interpreter shutdown): Traceback (most recent call last): File "C:\Python23\lib\threading.py", line 442, in __bootstrap File "I:\My Documents\pyscripts\Newclient\newclient.py", line 368, in run File "I:\My Documents\pyscripts\Newclient\newclient.py", line 404, in GoOn File "I:\My Documents\pyscripts\Newclient\newclient.py", line 399, in StepOn File "C:\Python23\lib\site-packages\xmpp\dispatcher.py", line 116, in Process File "C:\Python23\lib\site-packages\xmpp\transports.py", line 101, in receive Script terminated. From paddy3118 at netscape.net Tue May 16 15:38:53 2006 From: paddy3118 at netscape.net (Paddy) Date: 16 May 2006 12:38:53 -0700 Subject: Using python for a CAD program In-Reply-To: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Message-ID: <1147808333.652756.5180@u72g2000cwu.googlegroups.com> Unfortunately, Cadence got their first with their DFII environment for Schematic based design and their Lisp based language SKILL (http://www-mtl.mit.edu/users/xiaolin/skill/sklanguser/sklanguserTOC.html) I used their environment several years ago and can only say that it was all you have stated above, and probably more. The environment seems to be totally accessable by SKILL, from the Schematic database to dash patterns for drawing lines. Their stuff is optimised for working with todays Electronics designs. I too have played what-if games about this and thought wouldn't it be great to tie Python for the language together with SVG for the graphics and ??? for the database but it remains a dream for me as it is a BIG job. Before you set out on this path, you might waant to see if you can be shown around Cadence Virtuoso and SKILL? - Pad. From ronnyma at math.uio.no Mon May 8 15:30:10 2006 From: ronnyma at math.uio.no (Ronny Mandal) Date: Mon, 08 May 2006 21:30:10 +0200 Subject: PyX custom x-labels Message-ID: <mu6v525qrsm30a1qokbuoostfau2is6f89@4ax.com> Hello. I need to draw a graph, with letters on the x-axis and a numeric value on the y-axis, e.g.. a = 3, b = 6 etc. Suggestions? Thanks, Ronny Mandal From nobody at 127.0.0.1 Wed May 3 13:51:03 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 17:51:03 GMT Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <I9O5g.2039$No6.43918@news.tufts.edu> <pan.2006.05.02.19.35.15.219815@hastings.org> <4457b69b$1_1@news.bluewin.ch> <pan.2006.05.03.04.02.14.139249@hastings.org> Message-ID: <b466g.72406$H71.46987@newssvr13.news.prodigy.com> Steve R. Hastings wrote: > You could also use a function that counts all different values in a list, > reducing the list to a dictionary whose keys are the unique values from > the list. Wouldn't reducing to a set instead of a dict make more sense if all you want to do is count uniq elements? From cmackin+nn at clearspot.net Sat May 6 21:30:00 2006 From: cmackin+nn at clearspot.net (Cameron MacKinnon) Date: Sat, 06 May 2006 21:30:00 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> Message-ID: <445d4f39$0$15787$14726298@news.sunsite.dk> Alex Martelli wrote: > Ken Tilton <kentilton at gmail.com> wrote: > ... > >>True but circular, because my very point is that () was a great design >>choice in that it made macros possible and they made CL almost >>infinitely extensible, while indentation-sensitivity was a mistaken >>design choice because it makes for very clean code (I agree >>wholeheartedly) but placed a ceiling on its expressiveness. > > > Having to give functions a name places no "ceiling on expressiveness", > any more than, say, having to give _macros_ a name. As was pointed out, if a Lisper wants anonymous macros, it's a cinch to create a scheme to allow this. Whether or not it's a good idea in general, if someone feels they need it, they can do it. An attitude like that beats "No you can't do that, but you shouldn't do it anyway." >>(defun |(| (aside) (format nil "Parenthetically speaking...~a." aside)) >>=> |(| >>(|(| "your Lisp /is/ rusty.") >>=> "Parenthetically speaking...your Lisp /is/ rusty.." > Interestingly, the SECOND lisper to prove himself unable to read the > very text he's quoting. Reread carefully, *USE THE ***SINGLE*** > CHARACTER* ... *AS AN ORDINARY IDENTIFIER*. What makes you read a > ``PART OF'' that I had never written? You've shown how to use the > characters as *PART* of an identifier [[and I believe it couldn't be the > very start]], and you appear to believe that this somehow refutes my > assertion? Those vertical bars are just quoting characters, rather like the quoting characters you'd undoubtedly need in Python to create a variable name with a space in it. > The point is, OF COURSE any design choice places limitations on future > design choices; but some limitations are even DESIRABLE (a language > where *every* single isolated character could mean anything whatsoever > would not be "expressive", but rather totally unreadable) or at least > utterly trivial (syntax-sugar level issues most typically are). Yeah, a language like that would probably have some strange name like "TeX." But we'd never know, because nobody would ever use it. > Yes, we are, because the debate about why it's better for Python (as a > language used in real-world production systems, *SCALABLE* to extremely > large-scale ones) to *NOT* be insanely extensible and mutable is a > separate one -- Python's uniformity of style allows SCALABILITY of > teams, and teams-of-teams, which is as crucial in the real world as > obviously not understood by you (the law you misquoted was about adding > personnel to a LATE project making it later -- nothing to do with how > desirable it can be to add personnel to a large and growing collection > of projects, scaling and growing in an agile, iterative way to meet > equally growing needs and market opportunities). You seem to be using the most primitive definition of scalable that there is, viz, if one coder can write one one page program in a day, two coders can write two (or more likely 1.8) one page programs in a day. Lispers tend to the view that *OF COURSE* most other decent languages scale linearly, but what we want is force multipliers and exponential scaling, not "throw money at it" scaling. Thus program writing programs, program analyzing programs, compiled domain specific languages and great quotes like "I'd rather write programs to write programs than write programs." "Programs that write programs are the happiest programs in the world." From scott.daniels at acm.org Wed May 17 17:15:31 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 17 May 2006 14:15:31 -0700 Subject: IDLE confusion In-Reply-To: <446b27eb$0$5316$626a54ce@news.free.fr> References: <1147767977.928350.261650@i39g2000cwa.googlegroups.com><e4c34c$5l6$1@newsreader3.netcologne.de> <446991de$0$7690$626a54ce@news.free.fr> <mailman.5769.1147812265.27775.python-list@python.org> <446b27eb$0$5316$626a54ce@news.free.fr> Message-ID: <446b8e78$1@nntp0.pdx.net> Christophe wrote: > Terry Reedy a ?crit : >> "Christophe" <chris.cavalaria at free.fr> wrote in message >> news:446991de$0$7690$626a54ce at news.free.fr... >> >>> Try in the IDLE menu [Shell] "Restart Shell" (Ctrl+F6) each time you >>> have changed something in your files - this "resets" anything previously >>> imported, which stays the same way otherwise. >> >> >> And I though that "bug" was fixed already :) >> >> On my system, the current 2.4.3 version of Python+IDLE *does* auto >> restart with each run (F5). So either the OP is using a much older >> version (did not specify) or the respondant mis-diagnosed the problem. > > I was looking at some idlefork info not long ago and I found something > which might get those different behaviours with a recent version of idle > : if idle cannot open it's RPC socket, it'll execute all python code in > it's own interpreter. There's an option for that in fact. The option (for those playing along) is '-n' So: Windows: command is: \python24\Lib\idlelib\idle.pyw -n OS-X: command is: pythonw ?/python24/Lib/idlelib/idle.pyw -n Linux & such: python ?/python24/Lib/idlelib/idle.pyw -n (I think these don't distinguish python & pythonw) It is useful if you are having some socket-to-self issues typically caused by over-conservative firewall settings, because no socket is allocated for communication. It is also useful for experimenting with Tkinter, because a Tkinter display loop is already running, so you can see the effects of your Tkinter commands as they are entered. --Scott David Daniels scott.daniels at acm.org From bill_maxwell_notMyRealAddress at notreal.net Sun May 7 01:26:37 2006 From: bill_maxwell_notMyRealAddress at notreal.net (Bill Maxwell) Date: Sun, 07 May 2006 01:26:37 -0400 Subject: wxPython problem References: <1146239805.779041.187600@i40g2000cwc.googlegroups.com> <4betukF10g020U1@uni-berlin.de> <1146241910.998540.63580@g10g2000cwb.googlegroups.com> <1146244617.525004.184950@e56g2000cwe.googlegroups.com> Message-ID: <9rvq52he5glao1n37mu4j7bilnok2mtcef@4ax.com> On 28 Apr 2006 10:16:57 -0700, scottholdensmith at gmail.com wrote: >What I'm wondering is, perhaps it has something to do with the wx.pth >file? I can't seem to find anything in the documentation about what the >path should be, which file it should be pointing to. Mine has this in it: wx-2.6-msw-unicode this points to a subdirectory of the site-packages directory. Mine looks like this: D:\Programs\Python\Lib\site-packages\wx-2.6-msw-unicode\wx D:\Programs\Python\Lib\site-packages\wx-2.6-msw-unicode\wxPython My understanding is that the wx.pth adds to the Python path. So, this directory in your system: site-packages/wx-2.6-gtk2-unicode is searched automatically. From there, you need to import wx or wxPython, then access using "wx." or "wxPython." Regards, Bill From jerry.levan at gmail.com Tue May 30 08:51:04 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 30 May 2006 05:51:04 -0700 Subject: How to use tk.call ? In-Reply-To: <optacr791krqur0o@eb.pragmadev> References: <1148944211.145450.46030@j33g2000cwa.googlegroups.com> <e5gb0m$aht$1@daisy.noc.ucla.edu> <1148962387.776015.157320@j33g2000cwa.googlegroups.com> <optacr791krqur0o@eb.pragmadev> Message-ID: <1148993464.300742.158330@r44g2000cwb.googlegroups.com> Eric, Thanks, your tip did the trick... Is there someplace where tk.call is discussed? Jerry From sybrenUSE at YOURthirdtower.com.imagination Thu May 18 13:55:26 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 18 May 2006 19:55:26 +0200 Subject: SPE output References: <1147971328.648561.222850@u72g2000cwu.googlegroups.com> Message-ID: <slrne6pd8e.l4i.sybrenUSE@schuimige.stuvel.eu> Alex Pavluck enlightened us with: > SPE is amazing with the intellisense but maybe there is a better > choice out there. Check VIM. The newly released VIM 7.0 has smart completion too (intellisense is a trademark of Microsoft) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From sybrenUSE at YOURthirdtower.com.imagination Wed May 10 04:55:56 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 10 May 2006 10:55:56 +0200 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> Message-ID: <slrne63aks.96g.sybrenUSE@schuimige.stuvel.eu> yairchu at gmail.com enlightened us with: > multi-line lambdas, had it been added to python a long time ago, > would had reduced a lot of complexity in the language. for example > - with multi-line lambdas - decorators are unneccesary. I love decorators. > just give the multi-line lambda as an argument to a function - no > need for special syntax.. Ehm... multi-line lamda /is/ a special syntax. > the alternative decorators would also be simpler. currently when > you want to create a "decorator-that-accepts-additional- arguments" > you gotta make a funtion that gets those additional-arguments and > returns a function that will be the decorator. A bit tricky, but so far easier to understand than the multi-line lambda tricks proposed. Sure, it's a function that returns a function that returns a function, but still except for the @ it's syntactically "just Python". Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From gandalf at designaproduct.biz Mon May 29 08:01:43 2006 From: gandalf at designaproduct.biz (Laszlo Nagy) Date: Mon, 29 May 2006 14:01:43 +0200 Subject: Running Python scripts under a different user In-Reply-To: <61d0e2b40605261017l367b4642i5bd0e2208ea502eb@mail.gmail.com> References: <mailman.6246.1148657024.27775.python-list@python.org> <4dolv4F1b8m87U1@uni-berlin.de> <447725C3.2000901@designaproduct.biz> <61d0e2b40605261017l367b4642i5bd0e2208ea502eb@mail.gmail.com> Message-ID: <447AE2A7.60800@designaproduct.biz> >> >> From what you wrote, I think that you need to change architecture. You >> should write your own service rather than write tricky programs. This >> way you can develop your own security system, and restrict access to >> specific files/programs. You can write tools that can connect to your >> service. The service program can be ran on the background, with >> sufficient privileges. How does it sound? > > [Bermard] Any ressource you could point me to as to write services? > I'm totally unexperienced with that. I'm sorry, I was out of town in the weekend. You can try to write a multi-threaded application server that provides services through TCP/IP. Probably, the easiest to start with an existing framework: http://twistedmatrix.com/projects/core/ http://www.webwareforpython.org/ There are many other libraries, you can look for them in the cheeseshop. http://cheeseshop.python.org/pypi You can also develop your own protocol with SocketServer or xmlrpc: http://docs.python.org/lib/module-SocketServer.html http://docs.python.org/lib/module-xmlrpclib.html Best, Laszlo From cvanarsdall at mvista.com Tue May 2 17:55:21 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 02 May 2006 14:55:21 -0700 Subject: Wake on LAN and Shutdown for Windows and Linux In-Reply-To: <200605022351.46872.me+python@modelnine.org> References: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> <200605022351.46872.me+python@modelnine.org> Message-ID: <4457D549.7040508@mvista.com> Heiko Wundram wrote: > Am Dienstag 02 Mai 2006 21:02 schrieb diffuser78 at gmail.com: > >> Also, How can I shutdown other Linux terminals from my Main (Linux) ? >> > > Has this got anything to do with Python? > > I could actually see that as a useful python function if i was writing some type of manager for a computing farm or something like that. -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From olsongt at verizon.net Wed May 24 11:32:56 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 24 May 2006 08:32:56 -0700 Subject: John Bokma harassment In-Reply-To: <Xns97CD6A2A4F305castleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> Message-ID: <1148484776.213699.34610@i39g2000cwa.googlegroups.com> John Bokma wrote: > "Ant" <antroy at gmail.com> wrote: > > > I have no particular affinity for Xah's views, but what does get up my > > nose is usenet Nazism. > > That's because you're clueless. > > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html Time for a game! Both johnbokma.com and castleamber.com are hosted by seagull.net. Here is a link to their TOS: http://www.seagull.net/tos.html Who can come up with the most violations that John is committing on this thread? I count 4. From kent at kentsjohnson.com Thu May 11 07:48:49 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 11 May 2006 07:48:49 -0400 Subject: unittest: How to fail if environment does not allow execution? In-Reply-To: <44622274.5040907@verizonbusiness.com> References: <44622274.5040907@verizonbusiness.com> Message-ID: <44632415$1_2@newspeer2.tds.net> Kai Grossjohann wrote: > I wrote a test case that depends on a certain file existing in the > environment. So, I guess I should test that the file exists in the > setUp method. But what if it doesn't exist? How do I fail in that case? > > I would like to emit an error message explaining what is wrong. I would just use the file normally in the test. If it's not there you will get an IOError with a traceback and a helpful error message. Kent From bignose+hates-spam at benfinney.id.au Tue May 16 20:17:34 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 10:17:34 +1000 Subject: Using python for a CAD program References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> Message-ID: <87wtclpkrl.fsf@benfinney.id.au> baalbek <rcs at bgoark.no> writes: > If you really want to revolutionize the CAD business, PLEASE don't > base your CAD system on a file based system (ala Autocad). > > CAD systems available today (Autocad, Archicad, Architectural > Desktop, etc) have one huge flaw: they don't store data to a SQL > database, but to binary files. Using Python 2.5, one could store (and distribute to others) the data in a binary file that *is* an SQL database: <URL:http://docs.python.org/dev/lib/module-sqlite3.html> -- \ "I was sleeping the other night, alone, thanks to the | `\ exterminator." -- Emo Philips | _o__) | Ben Finney From scott.daniels at acm.org Wed May 3 18:38:44 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 03 May 2006 15:38:44 -0700 Subject: Mutable String In-Reply-To: <1146680841.991313.248410@i40g2000cwc.googlegroups.com> References: <1146680841.991313.248410@i40g2000cwc.googlegroups.com> Message-ID: <44592d5f$1@nntp0.pdx.net> Pierre Thibault wrote: > I would like to know if there are modules offering a mutable version of > strings in Python? Nope. But, for some uses: import array stringish = array.array{'c', 'Whatever, kiddo!') stringish[-6:-1] = array.array('c', 'dudes') print stringish.tostring() -- -Scott David Daniels scott.daniels at acm.org From bencvt at gmail.com Mon May 8 19:11:32 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 8 May 2006 16:11:32 -0700 Subject: i don't understand this RE example from the documentation References: <oZN7g.2061$No6.45493@news.tufts.edu> <d2O7g.2063$No6.45493@news.tufts.edu> Message-ID: <1147129892.758708.207620@y43g2000cwc.googlegroups.com> John Salerno wrote: > John Salerno wrote: > > Ok, I've been staring at this and figuring it out for a while. I'm close > > to getting it, but I'm confused by the examples: > > > > (?(id/name)yes-pattern|no-pattern) > > Will try to match with yes-pattern if the group with given id or name > > exists, and with no-pattern if it doesn't. |no-pattern is optional and > > can be omitted. > > > > For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>) is a poor email matching > > pattern, which will match with '<user at host.com>' as well as > > 'user at host.com', but not with '<user at host.com'. New in version 2.4. > > > > group(1) is the email address pattern, right? So why does the above RE > > match 'user at host.com'. If the email address exists, does the last part > > of the RE: (?(1)>) mean that it has to end with a '>'? > > I think I got it. The group(1) is referring to the opening '<', not the > email address. I had seen an earlier example that used group(0), so I > thought maybe the groups were 0-based. The groups *are* 0-based. The 0th group is the whole match, e.g.: >>> import re >>> m = re.match(r'a(b+)', 'abbbb') >>> m.group(0) 'abbbb' >>> m.group(1) 'bbbb' And for the pattern you were looking at: >>> m = re.match(r'(<)?(\w+@\w+(?:\.\w+)+)(?(1)>)', '<foo at test.com>') >>> m.group(0) '<foo at test.com>' >>> m.group(1) '<' >>> m.group(2) 'foo at test.com' --Ben From bnblazer at gmail.com Mon May 22 06:39:42 2006 From: bnblazer at gmail.com (Brian) Date: 22 May 2006 03:39:42 -0700 Subject: performance difference between OSx and Windows References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> <1148254182.824583.195370@i40g2000cwc.googlegroups.com> <1148255177.190455.217840@u72g2000cwu.googlegroups.com> <1148263521.205652.286240@j55g2000cwa.googlegroups.com> <1148267986.876892.123110@i40g2000cwc.googlegroups.com> Message-ID: <1148294382.741146.274830@j55g2000cwa.googlegroups.com> As one additional question, can someone point me in the direction of a resource that would explain how I could use Python to tell me what core is actually handling the process? I am not even sure if something like this exists, but it would be an interesting feature to explore. Thanks, Brian From grante at visi.com Mon May 29 12:52:59 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 29 May 2006 16:52:59 -0000 Subject: saving settings References: <e5e6g2$nbv$1@ss408.t-com.hr> <pan.2006.05.29.07.30.20.70376@spam.me.please> <e5els6$5sa$1@ss408.t-com.hr> <4e07c8F1c7r6jU1@uni-berlin.de> Message-ID: <127m9nbemdmsha2@corp.supernews.com> On 2006-05-29, Diez B. Roggisch <deets at nospam.web.de> wrote: > It _might_ come as a shock to you, but when you install e.g. > Word on another computer, there aren't any documents coming > with it. Documents and settings aren't quite the same thing, but it's a valid point. > Especially not the ones you wrote on that other machine. > > Seriously: Who is going to copy a executable around? I do. I copy putty.exe around all of the time. > Do you know of any other program that behaves like that? Back in the day, that used to be fairly common under DOS/Windows. Not that it's still not a really bad idea. -- Grant Edwards grante Yow! I'm wet! I'm wild! at visi.com From bdesth.quelquechose at free.quelquepart.fr Thu May 18 21:09:14 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 19 May 2006 03:09:14 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <mailman.5903.1147987032.27775.python-list@python.org> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147980462.464427.323030@u72g2000cwu.googlegroups.com> <446cdd6b$0$7043$636a55ce@news.free.fr> <mailman.5903.1147987032.27775.python-list@python.org> Message-ID: <446ceb96$0$7024$636a55ce@news.free.fr> Heiko Wundram a ?crit : > Am Freitag 19 Mai 2006 02:08 schrieb Bruno Desthuilliers: > >>We'd need the make: statement, but the BDFL has pronounced against. >> >>I'm still -2 against your proposition, but it could make a good use case >>for the make statement. I gave an eye at the new 'with' statement, but >>I'm not sure it could be used to solve this. > > > Couldn't. "with" is a blatant misnomer for that it's functionality is > (basically a "protected" generator), at least if you know what with does in > VB (god, am I really comparing VB with Python? Lol !-) > And I've never even programmed > in the former...) I did in a previous life. And believe me, this is kind of a WTF language... To quote the poet : "Dumb all over, a little ugly on the side". But I was not thinking about anything related to VB's 'with' !-) Just about what other (than class) statements defines a block that then becomes a namespace you can manipulate. Something like: with Node('root') as root: with Node('head') as head: with Node('title') as title: title.content = "Page Title" for s in section: with Node('section %s' % s['title']) as section: section.content = s['content'] Now the question is : how to we get the Node objects back ? If possible without adding them explicitely to the parent object ? (which would not solve the problem of the root Node anyway). From rjh at cyberscience.com Tue May 9 08:48:29 2006 From: rjh at cyberscience.com (Richie Hindle) Date: Tue, 09 May 2006 13:48:29 +0100 Subject: ascii to latin1 In-Reply-To: <4460831e$0$15794$14726298@news.sunsite.dk> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <mailman.5504.1147171291.27775.python-list@python.org> <4460831e$0$15794$14726298@news.sunsite.dk> Message-ID: <um31629tln3mnrmgaqlc7nocavi54ve5i2@4ax.com> [Luis] > When I used the "NFD" option, I came across many errors on these and > possibly other codes: \xba, \xc9, \xcd. What errors? This works fine for me, printing "Ecoute": import unicodedata def search_key(s): de_str = unicodedata.normalize("NFD", s) return ''.join([cp for cp in de_str if not unicodedata.category(cp).startswith('M')]) print search_key(u"\xc9coute") Are you using unicode code point \xc9, or is that a byte in some encoding? Which encoding? -- Richie From antroy at gmail.com Wed May 24 12:08:39 2006 From: antroy at gmail.com (Ant) Date: 24 May 2006 09:08:39 -0700 Subject: John Bokma harassment In-Reply-To: <1148484597.410529.219960@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148484597.410529.219960@j33g2000cwa.googlegroups.com> Message-ID: <1148486919.493611.145780@j55g2000cwa.googlegroups.com> Getting eloquent isn't he? ;-) From python.list at tim.thechases.com Tue May 9 08:07:16 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 09 May 2006 07:07:16 -0500 Subject: Enumerating Regular Expressions In-Reply-To: <1147163458.940646.303270@i40g2000cwc.googlegroups.com> References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> <IHX7g.55413$hD6.14115@fe25.usenetserver.com> <1147163458.940646.303270@i40g2000cwc.googlegroups.com> Message-ID: <446085F4.6080502@tim.thechases.com> > Why are people getting stuck on infinite regular > languages? I've made it quite clear that I'm only really > interested in doing this for finite languages, but that > shouldn't matter anyway. The power of regular expressions is that they define a consice means to encapsulate an infinite number of inputs. If you're not tapping this power, the general wisdom is to not use regular expressions. That said, unless you can ensure you don't have an infinite grammer (in particular, no asterisks or plus-signs or unbounded ranges like "{4,}"), you then have the problem of how to navigate that infinite set. Taking for example the most common/simple regexp: ".*" That matches any and every string. There's a whole library of Congress for which every written work will match that string. It sounds a lot like Jorge Luis Borges's 1956 "The Library of Babel". Do you begin searching depth-first with "a" and then "aa" and then "aaa"? Or do you begin breadth-first with "a", then "b"...then "z", then "aa", "ab", ...? Depth-first is far more efficient when searching a branching set of data, but when you have infinite depth, it will take a while ;) Alternatively, you can use some sort of iterative-deepening search which puts an increasing bound on how deep the depth-first search will go before giving up for that particular iteration. Googling on "iteritave deepening" should bring back some ideas for that one. If you truely have a finite grammer, it would be feasible to write some sort of parser, ugly as it might be. As a first pass, I'd have my parser emit python code to write N nested loops to try each combination of each element, so something like "[a-zA-Z_][a-zA-Z0-9_]" became something like def tries(): s1 = set(range(ord('a'),ord('z')+1)) s1.add(range(ord('A'),ord('Z')+1)) s1.add(ord('_')) s2 = set(range(ord('a'),ord('z')+1)) s2.add(range(ord('A'),ord('Z')+1)) s2.add(range(ord('0'),ord('9')+1)) s2.add(ord('_')) for a1 in s1: for a2 in s2: yield "%s%s" % (chr(a1), chr(a2)) Thus, the input regexp would generate python code that you could then include in your project. Ugly, but a possible solution. There are lots of peculiarities though that would need to be handled. Branching, escaped characters in character sets (well, escaping in general is a headache). An alternative might be brute-forcing your regexp: for a1 in range(0,256): for a2 in range(0,256): s = "%s%s" % (chr(a1),chr(a2)) m = re.match(s) if m: yield s nested to however deep you're interested in. All will be slow. All are pretty ugly. -tkc From beliavsky at aol.com Tue May 2 17:51:06 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 2 May 2006 14:51:06 -0700 Subject: search file for tabs Message-ID: <1146606666.249084.12810@j73g2000cwa.googlegroups.com> The following code to search a file for tabs does not work, at least on Windows XP. Could someone please tell me what's wrong? Thanks. xfile = "file_with_tabs.txt" for text in open(xfile,"r"): text = text.strip() if ("\t" in text): print text From telesphore4 at gmail.com Mon May 22 12:33:01 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 22 May 2006 09:33:01 -0700 Subject: Using metaclasses to inherit class variables References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> Message-ID: <1148315581.385405.204750@i40g2000cwc.googlegroups.com> OK no question. I'm only posting b/c it may be something another newbie will want to google in the future. Now that I've worked thru the process this turns out to be fairly easy. However, if there are better ways please let me know. Module = ClassVars.py import copy class ClassVars(type): classVars = {} def __init__(cls, name, bases, dict): for name, value in type(cls).classVars.iteritems(): if name not in dict: setattr(cls, name, copy.copy(value)) count = 0 # Not really needed but it semed nice to name the new types def are(dict): global count count += 1 return type('ClassVars%d' % count, (ClassVars,), {'classVars':dict}) To use in another module: import ClassVars class MyClass(str): __metaclass__ = ClassVars.are(dict(name=None, desc=None, myList=[])) # Rest of class definition ... Thanks for the help. t4 From duncan.booth at invalid.invalid Fri May 19 03:18:03 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 19 May 2006 07:18:03 GMT Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <mailman.5801.1147872851.27775.python-list@python.org> <pan.2006.05.18.07.37.44.126396@internode.on.net> <Xns97C760A237F69duncanbooth@127.0.0.1> <pan.2006.05.19.06.29.29.262257@internode.on.net> Message-ID: <Xns97C8546247008duncanbooth@127.0.0.1> PoD wrote: > I think it is universally accepted that mixed tabs and spaces is indeed > **EVIL** > > I should have said any code using tabs exclusively. > Can you point at any significant body of publically visible Python code which uses tabs exclusively? All of the Python projects I've ever been involved with use spaces only as a convention (although as I pointed out in my previous post, some with more success than others). The problem with conventions such as 'tabs only' or 'space only' is that they only work if everyone sticks to the conventions, and it helps if the same conventions are in place everywhere (otherwise people forget when they switch from one project to another). Also, in the open source universe you are quite likely to pull in bits of code from other projects, and you don't want to either have to reformat it or to switch your editor settings for some files. My experience of programming with either spaces or tabs has taught me that tabs are evil not for themselves, but simply because no matter how hard you try they always end up being mixed with spaces. Do you know of any open-source projects which actually try to enforce a 'tab only' convention for Python? I'd really like to see a similar scan over some 'tab only' code as I did over Plone to see whether they actually manage to remain 'pure'. From steve at hastings.org Wed May 3 02:34:02 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 02 May 2006 23:34:02 -0700 Subject: NewB question on text manipulation References: <1146634624.622224.323010@u72g2000cwu.googlegroups.com> Message-ID: <pan.2006.05.03.06.34.01.189173@hastings.org> On Tue, 02 May 2006 22:37:04 -0700, ProvoWallis wrote: > I have a file that looks like this: > > <SC>APPEAL<XC>40-24; 40-46; 42-46; 42-48; 42-62; 42-63 <SC>PROC > GUIDE<XC>92<LT>1(b)(1) > > (i.e., <<SC>[chapter name]<XC>[multiple or single book page > ranges]<SC>[chapter name]<XC>[multiple or single book page > ranges]<LT>[code] > > but I want to change it so that it looks like this > > <1><SC>APPEAL<XC>40-24<LT>1(b)(1) > <1><SC>APPEAL<XC>40-46<LT>1(b)(1) > <1><SC>APPEAL<XC>42-46<LT>1(b)(1) > <1><SC>APPEAL<XC>42-48<LT>1(b)(1) > <1><SC>APPEAL<XC>42-62<LT>1(b)(1) > <1><SC>APPEAL<XC>42-63<LT>1(b)(1) > <1><SC>PROC GUIDE<XC>92<LT>1(b)(1) I'll show my code first, then explain it. -- cut here -- cut here -- cut here -- cut here -- cut here -- import re s = "<SC>APPEAL<XC>40-24; 40-46; 42-46; 42-48; 42-62; 42-63 " + \ "<SC>PROC GUIDE<XC>92<LT>1(b)(1)" s_space = " " # a single space s_empty = "" # empty string pat = re.compile("\s*<SC>([^<]+)<XC>([^<]+)") lst = [] while True: m = pat.search(s) if not m: break title = m.group(1).strip() xc = m.group(2) xc = xc.replace(s_space, s_empty) tup = (title, xc) lst.append(tup) s = pat.sub(s_empty, s, 1) lt = s.strip() for title, xc in lst: lst_pp = xc.split(";") for pp in lst_pp: print "<1><SC>%s<XC>%s%s" % (title, pp, lt) -- cut here -- cut here -- cut here -- cut here -- cut here -- My strategy here is to divide the problem into two separate parts: first, I collect all the data we need; then, I reformat the collected data and print it in the desired format. "pat" is a compiled regular expression. It recognizes the SC and XC codes, and collects the strings enclosed by those codes: ([^<]+) The above regular expression means "any character that is not a '<'", "one or more of them", and since it's in parentheses it's remembered so we can collect it later. So we collect title and the XC page ranges. We tidy them up a bit: title.strip() will remove any leading or trailing white space from the title. The replace() on the XC string gets rid of any spaces; I'm assuming that the spaces are optional and the semicolons are the real separators here. Now, we could save the title and XC string in two lists, but that would be silly in Python. It's easier to pair them up in a tuple, and save the tuple in a single list. You can do it in one line, but I made the tuple explicit ("tup"). After we collect them, we use a sub() to chop the collected data out of the source string. A while loop runs until all the SC and XC values are collected; anything left over is assumed to be the LT. Now, we have all the data; it's easy enough to rearrange it. We can convert the XC string into a list of page ranges just by calling .split(";"), which will split on semicolons. Loop over this list, printing each time, and there you go. I'll leave packaging these up into tidy functions, reading the data from the file, etc. as exercises for the reader. :-) If you have any questions on how this works or why I did things the way I did, ask away. Good luck! -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From maric at aristote.info Mon May 15 13:45:15 2006 From: maric at aristote.info (Maric Michaud) Date: Mon, 15 May 2006 19:45:15 +0200 Subject: Large Dictionaries In-Reply-To: <e4adgk$196$1@reader1.panix.com> References: <1147699064.107490@teuthos> <e4abj6$p6a$1@panix1.panix.com> <e4adgk$196$1@reader1.panix.com> Message-ID: <200605151945.16459.maric@aristote.info> Le Lundi 15 Mai 2006 19:24, Roy Smith a ?crit?: > d = {} > d.reserve (10*1000*1000) d={}.fromkeys(xrange(5*10**6)) ? -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From aum at spam.me.please Mon May 29 16:30:02 2006 From: aum at spam.me.please (aum) Date: Tue, 30 May 2006 08:30:02 +1200 Subject: Another option - Re: saving settings References: <e5e6g2$nbv$1@ss408.t-com.hr> Message-ID: <pan.2006.05.29.20.30.02.197225@spam.me.please> On Mon, 29 May 2006 09:05:36 +0200, SuperHik wrote: > Hi, > > I was wondering how to make a single .exe file, say some kind od clock, > and be able to save some settings (alarm for example) into the same > file? Basically make code rewrite it self... > > thanks! Another option I thought of: - get the Nullsoft NSIS installer - write a Python wrapper to NSIS if desired - within your app, include: - embedded py2exe - embedded/wrapped NSIS - within your app offer a menu option to 'export this program', which changes data files as needed, then invokes py2exe and NSIS to create a whole new installer exe That way, you'd have what you're after - a way to distribute your app, including its current state, as a single EXE file. Also, it would have the advantage of this EXE being an installer which sets up start menu shortcuts. -- Cheers aum From tim.golden at viacom-outdoor.co.uk Wed May 17 06:54:15 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 17 May 2006 11:54:15 +0100 Subject: how to traverse network devices in our system? Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1CF@vogbs009.gb.vo.local> [chaks.yoper at gmail.com] | i would like to know whether python can help me querying the network | devices attached to my system (ethernet,wireless) and display their | module name and vendor name? Which OS? If it's windows, you can use WMI. I would guess Linux, tho', from your mention of module name. 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 adonisv at DELETETHISTEXTearthlink.net Wed May 3 20:49:49 2006 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Thu, 04 May 2006 00:49:49 GMT Subject: Gettings subdirectories In-Reply-To: <e3au5u$drm$1@news.in.tum.de> References: <e3au5u$drm$1@news.in.tum.de> Message-ID: <Ncc6g.5297$DT5.1781@newsread3.news.pas.earthlink.net> Florian Lindner wrote: > Hello, > how can I get all subdirectories of a given directories? os.listdir() gives > me all entries and I've found no way to tell if an object is a file or a > directory. > > Thanks, > > Florian Here is a quick hack: import os import os.path givenDir = "/" listing = os.listdir(givenDir) for item in listing: joinPath = os.path.join(givenDir, item) normPath = os.path.normpath(joinPath) if os.path.isdir(normPath): print normPath From mailpitches at email.com Thu May 25 01:17:19 2006 From: mailpitches at email.com (mp) Date: 24 May 2006 22:17:19 -0700 Subject: Modify one character in a string Message-ID: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> X-No-Archive How do I go about modifying one character in a string elegantly? In other words, I want a function that will change 'aaaa' to 'aaza', given the index 2 of the character in the string. Also, how do I do this when dealing with a file ; which file mode should I use and what function should I use to modify a single character once in that file mode? Thanks MP From sjmachin at lexicon.net Fri May 19 07:38:46 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 May 2006 04:38:46 -0700 Subject: newb: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <4d4chmF185ohoU1@uni-berlin.de> Message-ID: <1148038726.023455.145900@j73g2000cwa.googlegroups.com> > Use the levenshtein distance. Given the constraint that the two strings are the same length, I'm assuming (as other posters appear to have done) that "vary by only one character" precludes insertion and deletion operations. In that case, the problem can be solved in O(n) time by a simple loop which counts the number of differences and notes the position of the first (if any) difference. Any full-distance Levenshtein method that does no pre-processing must take O(n**2) time. It is possible to take advantage of the fact that the OP doesn't care about what the distance is exactly if it is not 1; 0 is just as bad as 2, 3, 4, etc. In this case it is possible to achieve O(n) time [ref. Ukkonen]. However (a) one still needs to track where the difference arose (b) we are talking about extreme overkill for the OP's problem. From dirk at dulb.net Tue May 23 12:39:28 2006 From: dirk at dulb.net (Dirk Beste) Date: Tue, 23 May 2006 18:39:28 +0200 Subject: New beginner to python for advice In-Reply-To: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> References: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> Message-ID: <4dgs5sF19ip84U1@uni-berlin.de> Minlar Ginger wrote: > HIi all: > I am a new beginner to python, would you like give me some advice on > studying it? > Welcome to list some book on python for me. > Thanks a lot. > If you like a practical approach you can try Langtangen's Python Scripting for Computational Science. From jstroud at ucla.edu Tue May 9 21:10:44 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 09 May 2006 18:10:44 -0700 Subject: List of lists of lists of lists... In-Reply-To: <e3n81d$9o0$1@emma.aioe.org> References: <e3n81d$9o0$1@emma.aioe.org> Message-ID: <e3reik$seq$1@daisy.noc.ucla.edu> ?ngel Guti?rrez Rodr?guez wrote: > I would like to have a list of lists N times deep, and my solution is (in > pseudocode): > > def deep(x): > a=[x] > return a > > mylist=[] > for N: mylist=deep(mylist) > > Is there a more elegant way to do it? > > The maine idea is: from a list having the numbre of steps along N > dimensions, generate a list with an item at each possible point. > > Example 1: N=2 list=[2,3] result=[[1,2],[1,2],[1,2]] > Example 2: N=3 list=[3,1,2] result=[[[1,2,3]],[[1,2,3]]] Numarray does this sort of thing, but you have to familiarize yourself with its indexing conventions: py> import numarray py> numarray.ones((3,2)) array([[1, 1], [1, 1], [1, 1]]) py> numarray.ones((1,2,3)) array([[[1, 1, 1], [1, 1, 1]]]) James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From python at hope.cz Wed May 24 10:05:57 2006 From: python at hope.cz (Lad) Date: 24 May 2006 07:05:57 -0700 Subject: How to find out a date/time difference Message-ID: <1148479557.226541.323100@i40g2000cwc.googlegroups.com> I use datetime class in my program and now I have two fields that have the datetime format like this datetime.datetime(2006, 5, 24, 16, 1, 26) How can I find out the date/time difference ( in days) of such two fields? Thank you for help? L From fredrik at pythonware.com Mon May 8 04:37:15 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 May 2006 10:37:15 +0200 Subject: Image SIG ML Moderator does not respond References: <76fd5acf0605072022l46d331b4v413b1a4da7a7b0c8@mail.gmail.com> Message-ID: <e3mvvu$5vf$1@sea.gmane.org> Calvin Spealman wrote: > I have tried repeatedly to make a post to the Image SIG ML, and get nothing > but automated responses that I must wait for word from the moderator to > approve my posting on the list. I have gotten no reply, positive or not, in > over a month. I am assuming the Image SIG moderator is currently MIA. is this the post you're talking about ? http://article.gmane.org/gmane.comp.python.image/2093 </F> From larry.bates at websafe.com Tue May 16 12:19:16 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 16 May 2006 11:19:16 -0500 Subject: simultaneous reading and writing a textfile In-Reply-To: <4469f3d6$0$11070$9b4e6d93@newsread4.arcor-online.net> References: <4469f3d6$0$11070$9b4e6d93@newsread4.arcor-online.net> Message-ID: <GtGdnR9EUpgfZvTZ4p2dnA@comcast.com> Marco Herrn wrote: > Hi, > > I have a text file with some lines in it. > Now I want to iterate over this file and exchange some lines with some > others. I tried this approach: > > try: > myfile= file('myfile', 'r+') > > while 1: > line= myfile.readline() > if not line: break > > l= line.strip().split() > if len(l) == 1: > hostname= l[0] > myfile.write(hostname+' '+mac+'\n') > break > > finally: > if not myfile is None: > myfile.close() > > > This should inspect the file and find the first line, that can't be > split into two parts (that means, which has only one word in it). > This line should be exchanged with a line that contains some more > info. > > Unfortunately (or how better python programmers than I am would say, > "of course") this doesn't work. The line is exchanged, but also some > more lines. > > Now how can I achieve, what I want? Really exchange one line with > another, regardless of their length. Is this possible? If this is not > possible, then what would be the best approach to do this? > > I do not want to read the whole file, exchange the line in memory and > then write the whole file. This would be quite slow with large files. > > Regard1s > Marco The only way that in-place writes will work is if you adopt a fixed line length for the file and use read(bytes) instead of readline() method. You could create file with fixed length lines and write them in-place without disturbing lines that follow. Take a look at seek(), write() methods. The alternative is to create a different file (read/write the entire file)each time you want to make a change. Unless the file is REALLY long, this will be extremely fast. If you have a LOT of data you want to work with this way and it is changing a lot, you need to use a database not a text file for data storage. -Larry From eval.apply at gmail.com Mon May 8 13:13:41 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 8 May 2006 10:13:41 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1heznxs.1m1eqceeowwsrN%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> Message-ID: <1147108421.090707.226700@i40g2000cwc.googlegroups.com> Alex Martelli wrote: > > Your "pragmatic benefits", if such they were, would also apply to the > issue of "magic numbers", which was discussed in another subthread of > this unending thread; are you therefore arguing, contrary to widespread > opinion [also concurred in by an apparently-Lisp-oriented discussant], > that it's BETTER to have magic unexplained numbers appear as numeric > constants "out of nowhere" smack in the middle of expressions, rather > than get NAMED separately and then have the names be used? If you > really believe in the importance of the "pragmatic benefits" you claim, > then to be consistent you should be arguing that...: > > return total_amount * 1.19 > > is vastly superior to the alternative which most everybody would deem > preferable, > > VAT_MULTIPLIER = 1.19 > return total_amount * VAT_MULTIPLIER > > because the alternative with the magic number splattered inexplicably > smack in the middle of code "communicated the fact" that it's used only > within that expression, and makes all context available without having > to look "elsewhere" (just one statement up of course, but then this > would be identically so if the "one statement up" was a def, and we were > discussing named vs unnamed functions vs "magic numbers"). Most languages allow `unnamed numbers'. The `VAT_MULTIPLIER' argument is a strawman. Would you want to have to use a special syntax to name the increment in loop? defnumber zero 0 defnumber one { successor (zero); } for (int i = zero; i < limit; i += one) { ...} If you language allows unnamed integers, unnamed strings, unnamed characters, unnamed arrays or aggregates, unnamed floats, unnamed expressions, unnamed statements, unnamed argument lists, etc. why *require* a name for trivial functions? Wouldn't all the other constructs benefit by having a required name as well? > > To my view of thinking, offering multiple semantically equivalent ways > (or, perhaps worse, "nearly equivalent but with subtle differences" > ones) to perform identical tasks is a *HUGE* conceptual cost: I like > languages that are and stay SMALL and SIMPLE. Then why not stick with S and K combinators? There are few languages SMALLER and SIMPLER. From robin.meier at gmail.com Wed May 31 05:10:48 2006 From: robin.meier at gmail.com (robin) Date: 31 May 2006 02:10:48 -0700 Subject: problem with google api / xml Message-ID: <1149066648.521045.152480@h76g2000cwa.googlegroups.com> hello, i installed SOAPpy 0.12.0 and pyXML 0.8.4 in order to try out the google-search example in diveintopython http://diveintopython.org/soap_web_services/index.html however, i'v been trying and trying and won't get it to work :-( whenever i run this code, i get the attached exception... from SOAPpy import WSDL WSDLFILE = '/pathtomy/googleapi/GoogleSearch.wsdl' APIKEY = '....' _server = WSDL.Proxy(WSDLFILE) any help would be very much appreciated! thanks in advance, robin Traceback (most recent call last): File "<stdin>", line 1, in ? File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/SOAPpy/WSDL.py", line 67, in __init__ self.wsdl = reader.loadFromString(str(wsdlsource)) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/SOAPpy/wstools/WSDLTools.py", line 47, in loadFromString return self.loadFromStream(StringIO(data)) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/SOAPpy/wstools/WSDLTools.py", line 28, in loadFromStream document = DOM.loadDocument(stream) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/SOAPpy/wstools/Utility.py", line 602, in loadDocument return xml.dom.minidom.parse(data) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/_xmlplus/dom/minidom.py", line 1915, in parse return expatbuilder.parse(file) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/_xmlplus/dom/expatbuilder.py", line 930, in parse result = builder.parseFile(file) File "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/_xmlplus/dom/expatbuilder.py", line 207, in parseFile parser.Parse(buffer, 0) xml.parsers.expat.ExpatError: not well-formed (invalid token): line 1, column 0 From bens_dev_lists at waypointdatasolutions.com Fri May 19 11:22:01 2006 From: bens_dev_lists at waypointdatasolutions.com (Ben Stroud) Date: Fri, 19 May 2006 11:22:01 -0400 Subject: number of different lines in a file In-Reply-To: <446DD5E4.5090701@anansispaceworks.com> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <mailman.5913.1147991572.27775.python-list@python.org> <iY7bg.3778$x4.261@newsread3.news.pas.earthlink.net> <e4jnbd$vmg$1@sea.gmane.org> <446DD5E4.5090701@anansispaceworks.com> Message-ID: <446DE299.8010008@waypointdatasolutions.com> > >It never occured to me to use the Python dict/set approach. Now I >wonder if it would've worked better somehow. Of course my file was >26,000 X larger than the one in this problem, and definitely would >not fit in memory. I suspect that there were as many as a million >duplicates for some messages in that file. Would the generator >version above have helped me out, I wonder? > > > > You could use a dbm file approach which would provide a external dict/set interface through Python bindings. This would use less memory. 1. Add records to dbm as keys 2. dbm (if configured correctly) will only keep unique keys 3. Count keys Cheers, Ben From johnjsal at NOSPAMgmail.com Fri May 19 10:38:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 14:38:21 GMT Subject: who can give me the detailed introduction of re modle? In-Reply-To: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: <xLkbg.2125$No6.46433@news.tufts.edu> softwindow wrote: > the re module is too large and difficult to study > > i need a detaild introduction. I don't know what your experience has been so far, but I have almost no programming experience beyond what I've taught myself, and I found the re module very easy to understand after reading the docs. Just go through each page slowly. Start with the syntax, then read about the functions and objects (and their methods) and write a few REs yourself. I hate to say it, but it's actually kind of fun! :) And not nearly as difficult as I thought it would be when I first encountered REs. You can also consult this place: http://www.regular-expressions.info/ From telesphore4 at gmail.com Wed May 17 09:07:32 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 17 May 2006 06:07:32 -0700 Subject: A better way of making subsclassing of built-in types stick for attributes? References: <1147839432.816504.318290@38g2000cwa.googlegroups.com> <mailman.5780.1147841942.27775.python-list@python.org> Message-ID: <1147871252.088349.39340@u72g2000cwu.googlegroups.com> Thanks. Ben Finney wrote: > "telesphore4 at gmail.com" <telesphore4 at gmail.com> writes: > > > Of course, whenever you then set mystr = 'a string' > > ... you're instantiating a 'str' object, since that's what the syntax > you use will do. > > > you loose the extra goodies that I have attached in the > > subclass. > > Because you haven't created an object of that subclass. > naturally. > > The syntax used to make the object assigned to 'foo' is just a > shortcut for the syntax used to assign to 'bar'. If you want to > instantiate anything else, you need to use that explicit syntax, such > as for the object assigned to 'baz'. > > If you're hoping that "subclass" means "modify the behaviour of the > original class", you're mistaken. It makes a *new* class that has > behaviour *inherited from* the original class. Nah. I was hoping that I hadn't muffed the implementation and there was a more Pythonic way of doing what I wanted. Sounds like I've gotten things mostly right from the get go. which is reassuring for a newbie. using __set__ is the correct way to hide the vectoring to the __new__ assignment... no further shortcuts. thanks again t4 From seannakasone at yahoo.com Wed May 10 20:46:33 2006 From: seannakasone at yahoo.com (seannakasone at yahoo.com) Date: 10 May 2006 17:46:33 -0700 Subject: glob() that traverses a folder tree Message-ID: <1147308393.712592.233200@j73g2000cwa.googlegroups.com> i'm looking for something like glob.glob() that traverses sub-directories. is there anything like that? i guess i'm looking for something to replace the unix find command. From aleaxit at yahoo.com Sun May 7 14:57:55 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 11:57:55 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> <87bquaskap.fsf@rpi.edu> <1146988487.941796.32550@j73g2000cwa.googlegroups.com> Message-ID: <1heyqab.a8408z1thjmadN%aleaxit@yahoo.com> <brian at sweetapp.com> wrote: ... > > Being able to keep pass around state with functions is useful. > > I agree and Python supports this. What is interesting is how > counter-intuitive many programmers find this. For example, one of my Funny: I have taught/mentored large number of people in Python, people coming from all different levels along the axis of "previous knowledge of programming in general", and closures are not among the issues where I ever noticed large number of people having problems. > So I try to use this sort of pattern sparingly because many programmers > don't think of closures as a way of saving state. That might be because > it is not possible to do so in most mainstream languages. I don't normally frame it in terms of "saving" state, but rather of "keeping some amount of state around" -- which means more or less the same thing but may perhaps be easier to digest (just trying to see what could explain the difference between my experience and yours). > There are already some people in the Python community who think that > Python has already gone too far in supporting "complex" language > features and now imposes two steep a learning curve i.e. you now have > to know a lot to be considered a Python expert. And there is a lot of > resistance to adding features that will raise the bar even higher. I might conditionally underwrite this, myself, but I guess my emphasis is different from that of the real "paladins" of this thesis (such as Mark Shuttleworth, who gave us all an earful about this when he delivered a Keynote at Europython 2004). I'm all for removing _redundant_ features, but I don't think of many things on the paladins' hitlist as such -- closures, itertools, genexps, etc, all look just fine to me (and I have a good track record of teaching them...). I _would_ love to push (for 3.0) further simplifications, e.g., I do hate it that [ x for x in container if predicate(x) ] is an exact synonym of the more legible list( x for x in container if predicate(x) ) and the proposed {1, 2, 3} is an exact synonym of set((1, 2, 3)) just to focus on a couple of redundant syntax-sugar ideas (one in today's Python but slated to remain in 3.0, one proposed for 3.0). It's not really about there being anything deep or complex about this, but each and every such redundancy _does_ "raise the bar" without any commensurate return. Ah well. Alex From OlafMeding at gmail.com Wed May 3 17:05:43 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 14:05:43 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <mailman.5279.1146689738.27775.python-list@python.org> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <mailman.5279.1146689738.27775.python-list@python.org> Message-ID: <1146690343.792470.123270@i39g2000cwa.googlegroups.com> Time >>> 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 2 1 1 2 1 2 1 2 1 2 1 >>> This is exactly what you should see. The problem I see is that after a while (minutes to hours) the printing of 1s and 2s stops! If you press ctrl-c at that point the threads will print how many seconds they were stuck in the sleep statements (proving that the threads were stuck in the sleep statement until you pressed ctrl-c). Could you please try again (perhaps let it run overnight)? Many, many thanks. Olaf From a.schmolck at gmail.com Fri May 12 13:00:28 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 12 May 2006 18:00:28 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> <m38xp7p7el.fsf@rigel.goldenthreadtech.com> Message-ID: <yfs3bffuqj7.fsf@oc.ex.ac.uk> jayessay <nospam at foo.com> writes: > "Michele Simionato" <michele.simionato at gmail.com> writes: > > > I was interested in a proof of concept, to show that Python can > > emulate Lisp special variables with no big effort. > > OK, but the sort of "proof of concept" given here is something you can > hack up in pretty much anything. Care to provide e.g. a java equivalent? 'as From laurent.pointal at limsi.fr Fri May 19 08:13:29 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Fri, 19 May 2006 14:13:29 +0200 Subject: WTF? Printing unicode strings In-Reply-To: <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> Message-ID: <e4kcpc$m45$1@upsn250.cri.u-psud.fr> Ron Garret a ?crit : > In article <mailman.5904.1147987926.27775.python-list at python.org>, > Fredrik Lundh <fredrik at pythonware.com> wrote: > >> Ron Garret wrote: >> >>>>>> u'\xbd' >>> u'\xbd' >>>>>> print _ >>> Traceback (most recent call last): >>> File "<stdin>", line 1, in ? >>> UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in >>> position 0: ordinal not in range(128) >> so stdout on your machine is ascii, and you don't understand why you >> cannot print a non-ascii unicode character to it? wtf? >> >> </F> > > I forgot to mention: > >>>> sys.getdefaultencoding() > 'utf-8' >>>> print u'\xbd' > Traceback (most recent call last): > File "<stdin>", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > position 0: ordinal not in range(128) This is default encoding for evaluation of expressions in u"..." strings, this has nothing to do with printing. For the output encoding, see sys.stdout.encoding. >>> import sys >>> sys.stdout.encoding 'cp850' >>> A+ Laurent. From sjmachin at lexicon.net Mon May 1 01:08:28 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 01 May 2006 15:08:28 +1000 Subject: How to prevent this from happening? In-Reply-To: <1146452135.108199.109180@e56g2000cwe.googlegroups.com> References: <1146452135.108199.109180@e56g2000cwe.googlegroups.com> Message-ID: <445597cd$1@news.eftel.com> On 1/05/2006 12:55 PM, phil_nospam_schmidt at yahoo.com wrote: > Regarding this expression: 1 << x > > I had a bug in my code that made x become Very Large - much larger than > I had intended. This caused Python, and my PC, to lock up tight as a > drum, and it appeared that the Python task (Windows XP) was happily and > rapidly consuming all available virtual memory. > > Presumably, Python was trying to create a really really long integer, > just as I had asked it. > > Is there a way to put a limit on Python, much like there is a stack > limit, so that this sort of thing can't get out of hand? > If you mean a command line argument to specify an upper limit for the RHS of a << operator, no there isn't one, and no there shouldn't be one. To cater for sillinesses that aren't caught by exceptions (or where it may be a very long time before the exception is triggered, as in your case), I'd suggest placing tests close to the action. For example, if you are doing some bit-bashing, "assert nshift <= wordsize" or something like that may be appropriate. From adonisv at DELETETHISTEXTearthlink.net Sat May 6 18:08:58 2006 From: adonisv at DELETETHISTEXTearthlink.net (Adonis) Date: Sat, 06 May 2006 22:08:58 GMT Subject: os.isfile() error In-Reply-To: <87ac9uygou.fsf@localhost.localdomain> References: <87ac9uygou.fsf@localhost.localdomain> Message-ID: <_797g.4477$Vn.3030@newsread4.news.pas.earthlink.net> Gary Wessle wrote: > Hi > > could someone help me to find out whats wrong with this code? > > **************** code **************** > import os, sys > > if len(sys.argv) < 2: > sys.exit("please enter a suitable directory.") > > dpath = sys.argv[1] > for name in os.listdir(dpath): > if os.isfile(dpath+name): > infile = open(os.path.join(dpath,name), 'rb') > print type(infile) > > > **************** error **************** > Traceback (most recent call last): > File "python/useful/cat2all.py", line 13, in ? > if os.isfile(dpath+name): > AttributeError: 'module' object has no attribute 'isfile' > > > thank you Where 'if os.isfile()' it should be 'os.path.isfile()', the isfile method is not available in the os module, but in os.path. For more information look at the module index: http://docs.python.org/modindex.html Hope this helps. Adonis From Serge.Orlov at gmail.com Thu May 4 18:45:31 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 4 May 2006 15:45:31 -0700 Subject: Why does built-in set not take keyword arguments? In-Reply-To: <mailman.5348.1146782346.27775.python-list@python.org> References: <E7CF22B2E2FEC4428A00E0D78269C6AB6DE036@msgusaemb01.autodesk.com> <mailman.5348.1146782346.27775.python-list@python.org> Message-ID: <1146782731.190244.161460@i39g2000cwa.googlegroups.com> Jack Diederich wrote: > On Thu, May 04, 2006 at 02:08:30PM -0400, Steven Watanabe wrote: > > I'm trying to do something like this in Python 2.4.3: > > > > class NamedSet(set): > > def __init__(self, items=(), name=''): > > set.__init__(self, items) > > self.name = name > > > > class NamedList(list): > > def __init__(self, items=(), name=''): > > list.__init__(self, items) > > self.name = name > > > > I can do: > > > > >>> mylist = NamedList(name='foo') > > > > but I can't do: > > > > >>> myset = NamedSet(name='bar') > > TypeError: set() does not take keyword arguments > > > > How come? How would I achieve what I'm trying to do? > > setobject.c checks for keyword arguments in it's __new__ instead > of its __init__. I can't think of a good reason other to enforce > inheriters to be maximally set-like. We're all adults here so > I'd call it a bug. bufferobect, rangeobject, and sliceobject all > do this too, but classmethod and staticmethod both check in tp_init. > Go figure. > > As a work around use a function to make the set-alike. > > class NamedSet(set): pass > > def make_namedset(vals, name): > ob = NamedSet(vals) > ob.name = name > return ob > > Then make_namedset as a constructor in place of NamedSet(vals, name) Or use this work around: class NamedSet(set): def __new__(cls, iterable=(), name=""): return super(NamedSet, cls).__new__(cls) def __init__(self, iterable=(), name=""): super(NamedSet, self).__init__(iterable) self.name = name From iddw at hotmail.com Wed May 10 14:23:14 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 10 May 2006 13:23:14 -0500 Subject: multiline strings and proper indentation/alignment References: <Ms48g.2070$No6.45827@news.tufts.edu> <mailman.5527.1147204632.27775.python-list@python.org> <44613e5d$0$9438$c3e8da3@news.astraweb.com> <4461c445$0$14031$626a54ce@news.free.fr> <Eim8g.2075$No6.45677@news.tufts.edu> <5iv3629eodhhq7g8hp42n5eclusli2r5qo@4ax.com> <iZn8g.2078$No6.45875@news.tufts.edu> Message-ID: <nfb462tma5ucq8rc1p9fcvvms3giguitcl@4ax.com> On Wed, 10 May 2006 15:50:38 GMT in comp.lang.python, John Salerno <johnjsal at NOSPAMgmail.com> wrote: >Dave Hansen wrote: > >>>>> print textwrap.dedent(s).strip().replace('\n',' ') >> this is a multiline triple-quted string with indentation for nicer >> code formatting > >But I have some newlines that are already embedded in the string, and I >wouldn't want those replaced. >>> s = """ I want the following line- concatenated, but leave this line break alone. """ >>> print textwrap.dedent(s).strip().replace('-\n',' ') I want the following line concatenated, but leave this line break alone. >>> But I'd still recommend using parens and string concatentation. >>> s2 = ( "I want the following line " "concatentated, but leave this\n" "line break alone." ) >>> print s2 I want the following line concatentated, but leave this line break alone. Regards, -=Dave -- Change is inevitable, progress is not. From Serge.Orlov at gmail.com Tue May 9 06:26:04 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 9 May 2006 03:26:04 -0700 Subject: Embedding Python References: <mailman.5499.1147164322.27775.python-list@python.org> Message-ID: <1147170364.206293.66230@y43g2000cwc.googlegroups.com> gavinpaterson wrote: > Dear Pythoners, > > I am writing as I am having trouble embedding a Python program into a > Win XP C++ console application. > > I have written a script file for importing and I am trying to use the > example for "Pure Embedding" found in the product documentation. > > The program fails to successfully execute past the line: > > if (pFunc && PyCallable_Check(pFunc)) > > I have checked the pFunc pointer at runtime and it is not null so I > assume that the PyCallable_Check fails. Looking at the source in "Pure Embedding" I see that it is supposed to print an error message if PyCallable_Check fails, have you got the message? From pjb at informatimago.com Tue May 16 11:40:54 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Tue, 16 May 2006 17:40:54 +0200 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> Message-ID: <87ves6yo3d.fsf@thalassa.informatimago.com> "opalpa at gmail.com opalinski from opalpaweb" <opalpa at gmail.com> writes: >> Simply put, tabs is proper, and spaces are improper. >> Why? This may seem >> ridiculously simple given the de facto ball of confusion: the semantics >> of tabs is what indenting is about, while, using spaces to align code >> is a hack. > > The reality of programming practice trumps original intent of tab > characters. The tab character and space character are pliable in that > if their use changes their semantics change. > >> ... and the solution is to advance >> the sciences such that your source code in some way >> embed such information. > > If/when time comes where such info is embeded perhaps then tabs will be > OK. > > --------------------------------------------------------------- > > I use spaces because of the many sources I've opened I have many times > sighed on opening tabed ones and never done so opening spaced ones. > > I don't get mad, but sighing is a clear indicator of negativity. > Anyway, the more code I write and read the less indentation matters to > me. My brain can now parse akward source correctly far bettter than it > did a few years ago. And anyways, C-x h C-M-\ comes automatically after C-x C-f source RET Just add this to your ~/.emacs : (add-hook 'find-file-hook (lambda () (indent-region (point-min) (point-max)) (pop-mark))) -- __Pascal Bourguignon__ http://www.informatimago.com/ IMPORTANT NOTICE TO PURCHASERS: The entire physical universe, including this product, may one day collapse back into an infinitesimally small space. Should another universe subsequently re-emerge, the existence of this product in that universe cannot be guaranteed. From bpeng at rice.edu Mon May 1 21:20:58 2006 From: bpeng at rice.edu (Bo Peng) Date: Mon, 01 May 2006 20:20:58 -0500 Subject: Python distutil: build libraries before modules Message-ID: <e36cal$25l$1@joe.rice.edu> Dear list, My python modules depend on a few boost libraries. For convenience, I include the source code of these libraries with my distribution and treat them as standard source files. This results in huge cc.exe command lines and I get an error saying error: command 'cc' failed: Invalid argument under win32/mingw. (I am not quite sure this is the reason though.) How can I let setup.py build these boost libraries separately so that I can link them to my modules? This will also save some link time because all my python modules link to the same boost libraries. Many thanks in advance. Bo From jparlar at cogeco.ca Sat May 13 16:40:53 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Sat, 13 May 2006 16:40:53 -0400 Subject: unzip zip files In-Reply-To: <1147470349.415553.324710@y43g2000cwc.googlegroups.com> References: <1147470349.415553.324710@y43g2000cwc.googlegroups.com> Message-ID: <150d2deddc413d1210c37cd91b8cc8f8@cogeco.ca> On May 12, 2006, at 5:45 PM, DataSmash wrote: > I need to unzip all zip file(s) in the current directory > into their own subdirectories. The zip file name(s) always > start with the string "usa" and end with ".zip". > The code below will make the subdirectory, move the zip > file into the subdirectory, but unzips the contents into the > root (current) directory. I want the contents of the zip file > unloaded into the newly created subdirectory where the zip file is. > > Any ideas? > Thanks. > R.D. > > import subprocess > > # Get all the zip files in the current directory. > for zip in os.listdir(''): > if zip.endswith(".zip"): > > # Remove the first 3 and the last 4 characters > # e.g. usa12345.zip becomes 12345 > zipBase = zip[3:-4] > > # Make directory for unzipping > os.mkdir(zipBase) > > # Move the zip file to the subdirectory > shutil.move(zip, zipBase) > > # Make system call "unzip" > subprocess.Popen(["unzip", zipBase + "\\" + zip]).wait() > Ouch... Is there any reason that you're using subprocess+'unzip', as opposed to using the 'zipfile' module from the standard library? Jay P. From michele.petrazzo at TOGLIunipex.it Fri May 26 10:27:15 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Fri, 26 May 2006 14:27:15 GMT Subject: Trying to get FreeImagePy to work. In-Reply-To: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> References: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> Message-ID: <7fEdg.13375$cX1.201311@twister2.libero.it> Iain King wrote: > I've installed ctypes and FreeImagePy. When I do this: > >>>> import FreeImagePy f = FreeImagePy.Image() > > I put a 'print self._name' in the ctypes __init__ file, just before > line 296 - it's printing out the 'find' just before the error. So, in > what specific way have I screwed up the install? What's your ctypes version? Is 0.9.9.6? If yes, can you download the last svn version, that solve that problem (I hope) and add some functions? If you can't I'll release a new version (1.2.5) > > Iain > Bye, Michele From __peter__ at web.de Tue May 9 12:06:42 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 May 2006 18:06:42 +0200 Subject: Deferred Evaluation in Recursive Expressions? References: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> <e3qc7h$ats$01$1@news.t-online.com> <1147189028.751527.157640@j73g2000cwa.googlegroups.com> Message-ID: <e3qej4$o8j$02$1@news.t-online.com> birchb at ozemail.com.au wrote: > How about mutual recursion? > > class LinkedListA(TypeDef): > typedef = (int, LinkedListB) > > class LinkedListB(TypeDef): > typedef = (int, LinkedListA) class Names(object): def __getattribute__(self, name): return name types = Names() class Type(type): all = {} def __new__(mcl, name, bases, dict): assert name not in mcl.all, "name clash" assert "_typedef" not in dict dict["_typedef"] = dict.pop("typedef", ()) cls = type.__new__(mcl, name, bases, dict) mcl.all[name] = cls return cls def get_typedef(cls): get = cls.all.get return tuple(get(item, item) for item in cls._typedef) def set_typedef(cls, value): cls._typedef = value typedef = property(get_typedef, set_typedef) class TypeDef: __metaclass__ = Type class LinkedListA(TypeDef): typedef = (int, types.LinkedListB) class LinkedListB(TypeDef): typedef = (int, types.LinkedListA) print LinkedListA.typedef print LinkedListB.typedef I'm sure it will break down somewhere :-) Peter From compboyxyz at gmail.com Sun May 7 12:15:10 2006 From: compboyxyz at gmail.com (compboy) Date: 7 May 2006 09:15:10 -0700 Subject: printing list Message-ID: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> How do you print elements of the list in one line? alist = [1, 2, 5, 10, 15] so it will be like this: 1, 2, 5, 10, 15 because if I use this code for i in alist: print i the result would be like this 1 2 5 10 15 Thanks. From scott.daniels at acm.org Fri May 26 19:43:56 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 26 May 2006 16:43:56 -0700 Subject: Looking for triangulator/interpolator In-Reply-To: <127f313dbhl7gf4@corp.supernews.com> References: <127f313dbhl7gf4@corp.supernews.com> Message-ID: <44778e7f$1@nntp0.pdx.net> Grant Edwards wrote: > I need to interpolate an irregularly spaced set of sampled > points: Given a set of x,y,z points, I need to interpolate z > values for a much finer x,y grid. > > I tried using the scipy sandbox delaunay module, but the > interpolators don't work: the natural neighbor interpolator > produces a surface with "holes" in it: the interpolator returns > NaNs for no reason for certain regions within the convex hull > (the convex hull looks right, and the input Z values in that > region don't look any different that regions that work). Sounds like a great opportunity for you to contribute. The easiest contribution would be to find as small a case as you can that demonstrates the problem, fixing it and add a test case would be, obviously, a greater contribution. --Scott David Daniels scott.daniels at acm.org From bucodi at yahoo.fr.invalid Sat May 20 04:29:07 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Sat, 20 May 2006 10:29:07 +0200 Subject: combining a C# GUI with Python code? References: <3Dnbg.2135$No6.46516@news.tufts.edu> Message-ID: <mn.a2757d657d031da4.43626@yahoo.fr.invalid> Isn't it a bit overkill to implement the whole .net framework 'Just' for a GUI ?? If you want to build quickly nice GUI's for your python program, have a look at wxpython & wxdesigner Rony > Is it possible to construct a C# form (using Visual Studio) but write only > Python code for the events? Is there some way to tell your program to run > Python whenever code is run, since it will be all Python code (e.g. for > button presses, etc.)? > > I know it's sort of silly, and it makes your program depend on .NET, but it > would be a nice and easy way to create a GUI while still writing in Python, > if it's possible. -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From grante at visi.com Fri May 26 20:38:19 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 00:38:19 -0000 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com> <44778e7f$1@nntp0.pdx.net> <127f61eluend535@corp.supernews.com> Message-ID: <127f7rrn8i2qea3@corp.supernews.com> On 2006-05-27, Grant Edwards <grante at visi.com> wrote: > On 2006-05-26, Scott David Daniels <scott.daniels at acm.org> wrote: > >>> I tried using the scipy sandbox delaunay module, but the >>> interpolators don't work: the natural neighbor interpolator >>> produces a surface with "holes" in it: the interpolator returns >>> NaNs for no reason for certain regions within the convex hull >>> (the convex hull looks right, and the input Z values in that >>> region don't look any different that regions that work). >> >> Sounds like a great opportunity for you to contribute. > > I'll try, but it looks like I'm going to be working all weekend > as it is. OTOH, it looks like I'm screwed either way. My python interpolator is so hopelessly slow it's useless in practice. It can only process 4 points per second and I need to process arrays of 10,000 to 50,000 elements. :( >> The easiest contribution would be to find as small a case as >> you can that demonstrates the problem, fixing it and add a >> test case would be, obviously, a greater contribution. -- Grant Edwards grante Yow! YOW!! Now I at understand advanced visi.com MICROBIOLOGY and th' new TAX REFORM laws!! From sjmachin at lexicon.net Mon May 29 21:12:32 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 May 2006 11:12:32 +1000 Subject: why not in python 2.4.3 In-Reply-To: <1148906849.894298.323790@g10g2000cwb.googlegroups.com> References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> <r94k725bfor7ssate10bd5veld2v6q6mm0@4ax.com> <1148851375.148311.320780@g10g2000cwb.googlegroups.com> <1148870627.058561.12800@y43g2000cwc.googlegroups.com> <1148897123.135779.91870@j33g2000cwa.googlegroups.com> <1148906849.894298.323790@g10g2000cwb.googlegroups.com> Message-ID: <447B9C00.9090504@lexicon.net> On 29/05/2006 10:47 PM, Serge Orlov wrote: > Rocco wrote: >> Also with ascii the function does not work. > > Well, at least you fixed misconfiguration ;) > > Googling for 1F8B (that's two first bytes from your strange python 2.4 > result) gives a hint: it's a beginning of gzip stream. Well done! > Maybe urllib2 in > python 2.4 reports to the server that it supports compressed data but > doesn't decompress it when receives the reply? > Something funny is happening here. Others reported it working with 2.4.3 and Rocco's original code as posted in this thread -- which works for me on 2.4.2, Windows XP. There was one suss thing about Rocco's problem description: First message ended with d=takefeed(url) But next message said print rss Is rss == d? Cheers, John From oweston at earthlink.net Mon May 22 15:17:19 2006 From: oweston at earthlink.net (wes weston) Date: Mon, 22 May 2006 19:17:19 GMT Subject: Class probkem - getting msg that self not defined In-Reply-To: <12742avhp3vmac8@corp.supernews.com> References: <12740frcoaju883@corp.supernews.com> <mFncg.420$Sf2.95@newsread1.news.pas.earthlink.net> <12742avhp3vmac8@corp.supernews.com> Message-ID: <37ocg.435$Sf2.424@newsread1.news.pas.earthlink.net> Andrew Robert wrote: > wes weston wrote: >> Andrew Robert wrote: >>> Hi Everyone, >>> >>> I am having a problem with a class and hope you can help. >>> >>> When I try to use the class listed below, I get the statement that self >>> is not defined. >>> >>> test=TriggerMessage(data) >> self is not known here; only inside the class. >> >>> var = test.decode(self.qname) >>> > <snip> > > I guess I was barking up the wrong tree on that one. > > How would I go about getting the required values out of the class? > > Return self? You can refer to the variables inside the class as test.version; for example - as they are not protected. Or, you could add access methods in the class like def GetVersion(self): return self.version If you want to protect version, call it self.__version which mangles the name from outside. wes From williams.jasonscott at gmail.com Mon May 15 23:04:00 2006 From: williams.jasonscott at gmail.com (williams.jasonscott at gmail.com) Date: 15 May 2006 20:04:00 -0700 Subject: C API: getting sys.argv Message-ID: <1147748640.699770.285430@g10g2000cwb.googlegroups.com> Hi, How would one go about getting sys.argv fom within the context of a C API extention module? I want to pass it along to C library that I'm calling from my module code. TIA~ I'm trying to load the sys module using: PyObject *_argv = PyImport_ImportModule("sys.argv"); but it is coming back NULL... From amk at amk.ca Fri May 5 07:10:57 2006 From: amk at amk.ca (A.M. Kuchling) Date: Fri, 05 May 2006 06:10:57 -0500 Subject: Swaying A Coder Away From Python References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <mailman.5309.1146740960.27775.python-list@python.org> Message-ID: <DtOdnVpAxsdcr8bZnZ2dnUVZ_t6dnZ2d@speakeasy.net> On Thu, 4 May 2006 13:08:52 +0200, Fredrik Lundh <fredrik at pythonware.com> wrote: > who's this, and why does he think that sampling some random comments by > some random bloggers should mean anything to anyone ? (and why do you > seem to think that this matters, btw ?) Michal Wallace, the original weblogger, was also working on Pirate, the Python-to-Parrot translator, so I'm not surprised that he might be bitter about not completing applications. :) I guess no one is working on Python-on-Parrot any more. --amk From chris.cavalaria at free.fr Sat May 20 10:29:52 2006 From: chris.cavalaria at free.fr (Christophe Cavalaria) Date: Sat, 20 May 2006 16:29:52 +0200 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <mailman.5801.1147872851.27775.python-list@python.org> <pan.2006.05.18.07.37.44.126396@internode.on.net> <Xns97C760A237F69duncanbooth@127.0.0.1> <pan.2006.05.19.06.29.29.262257@internode.on.net> <Xns97C8546247008duncanbooth@127.0.0.1> <mailman.5982.1148074774.27775.python-list@python.org> Message-ID: <446f27e0$0$7585$636a55ce@news.free.fr> Christopher Weimann wrote: > On 05/19/2006-07:18AM, Duncan Booth wrote: >> >> My experience of programming with either spaces or tabs has taught me >> that tabs are evil not for themselves, but simply because no matter how >> hard you try they always end up being mixed with spaces. >> > > Swap the word 'tabs' for the word 'spaces' and you get... > > My experience of programming with either tabs or spaces has taught me > that spaces are evil not for themselves, but simply because no matter > how hard you try they always end up being mixed with tabs. > > Which is just as vaild as the un-swapped paragraph. Both versions > express a bias. The first is biased in favor of spaces. The second is > biased in favor of tabs. Neither have any useful content. Mixing is bad > but that fact doesn't favor spaces OR tabs. The difference is that you cannot code without spaces but you can do it without tabs. From lolmcbride at googlemail.com Wed May 10 13:42:22 2006 From: lolmcbride at googlemail.com (lolmcbride at googlemail.com) Date: 10 May 2006 10:42:22 -0700 Subject: python sqlite3 api question Message-ID: <1147282942.425241.214990@g10g2000cwb.googlegroups.com> Hi, is it possible to pass args through the api which are the same as the args you can use on the sqlite3 command line? What I'm talking about is the .mode or .output commands which you can enter via the sqlite3 cli so I can dynamically change were the output goes. Ta From bucodi at yahoo.fr.invalid Wed May 31 06:32:11 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Wed, 31 May 2006 12:32:11 +0200 Subject: Best Python Editor References: <mailman.24508.1149069603.27774.python-list@python.org> <mailman.6359.1149069835.27775.python-list@python.org> <slrne7qr5e.8hi.sybrenUSE@schuimige.stuvel.eu> Message-ID: <mn.faf07d65c8bd2cd8.43626@yahoo.fr.invalid> > Manoj Kumar P enlightened us with: >> Can anyone tell me a good python editor/IDE? >> It would be great if you can provide the download link also. > > VIM 7 is great, http://www.vim.org/ > > Sybren Another VIM user here -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From zhushenli at gmail.com Tue May 9 03:23:24 2006 From: zhushenli at gmail.com (Davy) Date: 9 May 2006 00:23:24 -0700 Subject: Why 3.0/5.0 = 0.59999... Message-ID: <1147159404.498386.58860@g10g2000cwb.googlegroups.com> Hi all, I used to be a Matlab user. And want to use Python to replace some Matlab work. When I type 3.0/5.0, the result is 0.59999... Is there some precision loss? And how to overcome it? Any suggestions will be appreciated! Best regards, Davy From grante at visi.com Tue May 2 15:57:14 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 02 May 2006 19:57:14 -0000 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <4457b2fe$1_7@news.bluewin.ch> Message-ID: <125fecqqoro46e6@corp.supernews.com> On 2006-05-02, Boris Borcic <bborcic at gmail.com> wrote: > Grant Edwards wrote: >> Python knows how to count. :) >> >> def countFalse(seq): >> return len([v for v in seq if not v]) >> >> def countTrue(seq): >> return len([v for v in seq if v]) >> >> def truth_test(seq): >> return countTrue(seq) == 1 >> > > I'd suggest the more direct > > def countFalse(seq) : > return sum(1 for v in seq if not v) I guess I don't see how that is more direct. If you want to know how many items are in a seqneuce, you call len(). That's what it's for. The number of objects in a list is returned in O(1) time by len(sequence). Converting that list to a list of 1's and then summing the 1's is O(N). -- Grant Edwards grante Yow! Actually, what at I'd like is a little toy visi.com spaceship!! From nobody at 127.0.0.1 Wed May 10 02:44:27 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 10 May 2006 06:44:27 GMT Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <44605c5f$0$7085$626a54ce@news.free.fr> Message-ID: <fZf8g.70357$F_3.15098@newssvr29.news.prodigy.net> bruno at modulix wrote: > From a readability/maintenance POV, Perl is a perfect nightmare. It's certainly true that perl lacks the the eminently readable quality of python. But then so do C, C++, Java, and a lot of other languages. And I'll grant you that perl is more susceptible to the 'executable line-noise' style than most other languages. This results from its heritage as a quick-and-dirty awk/sed type text processing language. But perl doesn't *have* to look that way, and not every perl program is a 'perfect nightmare'. If you follow good practices like turning on strict checking, using readable variable names, avoiding $_, etc, you can produce pretty readable and maintainable code. It takes some discipline, but it's very doable. I've worked with some perl programs for over 5 years without any trouble. About the only thing you can't avoid are the sigils everywhere. Would I recommend perl for readable, maintainable code? No, not when better options like Python are available. But it can be done with some effort. From richie at entrian.com Tue May 9 16:55:50 2006 From: richie at entrian.com (richie at entrian.com) Date: 9 May 2006 13:55:50 -0700 Subject: ascii to latin1 In-Reply-To: <4460dec2$0$15791$14726298@news.sunsite.dk> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <mailman.5504.1147171291.27775.python-list@python.org> <4460831e$0$15794$14726298@news.sunsite.dk> <1147180014.685659.325830@i39g2000cwa.googlegroups.com> <4460dec2$0$15791$14726298@news.sunsite.dk> Message-ID: <1147208149.972583.115470@j73g2000cwa.googlegroups.com> [Luis] > The script converted the ?? from the first line, but not the ? from > the second one. That's because ?, 0xba, MASCULINE ORDINAL INDICATOR is classed as a letter and not a diacritic: http://www.fileformat.info/info/unicode/char/00ba/index.htm You can't encode it in ascii because it's not an ascii character, and the script doesn't remove it because it only removes diacritics. I don't know what the best thing to do with it would be - could you use latin-1 as your base encoding and leave it in there? I don't speak any language that uses it, but I'd guess that anyone searching for eg. 5? (forgive me if I have the gender wrong 8-) would actually type 5? - are there any Italian/Spanish/Portuguese speakers here who can confirm or deny that? In the general case, you have to decide what happens to characters that aren't diacritics and don't live in your base encoding - what happens when a Chinese user searches for a Chinese character? Probably you should just encode(base_encoding, 'ignore'). -- Richie Hindle richie at entrian.com From chris.uppal at metagnostic.REMOVE-THIS.org Fri May 26 08:11:42 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 26 May 2006 13:11:42 +0100 Subject: OT: Quote ? [was: John Bokma harassment] References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> <Xns97CE807F1ADC6castleamber@130.133.1.4> <Zpmdg.2874$%Z2.298786@news20.bellglobal.com> Message-ID: <4476efed$2$649$bed64819@news.gradwell.net> [apologies to the whole flaming crowd for sending this to the whole flaming crowd...] Geoffrey Summerhayes wrote: > After you kill Navarth, will it be nothing but gruff and deedle > with a little wobbly to fill in the chinks? Where does that come from ? It sounds like a quote, and Navarth is a Jack Vance name (and /what/ a character), but I don't remember the rest of it occurring in Vance. -- chris From max at alcyone.com Fri May 26 15:47:19 2006 From: max at alcyone.com (Erik Max Francis) Date: Fri, 26 May 2006 12:47:19 -0700 Subject: how to clear up a List in python? In-Reply-To: <1148639516.244264.37500@i40g2000cwc.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148612582.510390.48040@i39g2000cwa.googlegroups.com> <mailman.6227.1148638689.27775.python-list@python.org> <1148639516.244264.37500@i40g2000cwc.googlegroups.com> Message-ID: <LK2dnV-vYujaxurZnZ2dnUVZ_vWdnZ2d@speakeasy.net> vbgunz wrote: > Steve, I have no qualm with Fredrik over this '''if you don't know how > to do things, you don't need to post.''' but this ''' if you know why > this is about the dumbest way to do what you're doing, and you're > posted this on purpose, you really need to grow up.'''. > > The problem was I did post it on purpose, but not with the intent to > mess anyone up over it. His statement was a conditional. Since you're saying that the conditional does not apply, then neither does his conclusion. So his statement doesn't apply to you. So calm down. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis You make me feel like / I can be a better woman -- India Arie From onurb at xiludom.gro Tue May 2 07:36:06 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 02 May 2006 13:36:06 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> Message-ID: <44574481$0$18265$636a55ce@news.free.fr> Edward Elliott wrote: > Holger wrote: > >>oops, that was kinda embarrassing. > > > It's really not. You got a completely unhelpful error message saying you > passed 2 args when you only passed one explicitly. The fact the b is also > an argument to b.addfile(f) is totally nonobvious until you know that 1) b > is an object not a module*, and 2) objects pass references to themselves as > the first argument to their methods. Nope. It's the MethodType object (a descriptor) that wraps the function that do the job. The object itself is totally unaware of this. > The syntax "b." is completely > different from the syntax of any other type of parameter. > > The mismatch between the number of parameters declared in the method > signature and the number of arguments actually passed There's no mismatch at this level. The arguments passed to the *function *object wrapped by the method actually matches the *function* signature. > is nonobvious, > unintuitive, and would trip up anybody who didn't already know what was > going on. It's ugly and confusing. It's definitely a wart on the > langauge. I do agree that the error message is really unhelpful for newbies (now I don't know how difficult/costly it would be to correct this). > Making people pass 'self' s/self/the instance/ > explicitly is stupid No. It's actually a feature. > because it always has to be > the first argument, leading to these kinds of mistakes. The compiler > should handle it for you I don't think this would be possible if we want to keep the full dynamism of Python. How then could the compiler handle the following code ? class MyObj(object): def __init__(self, name): self.name = name def someFunc(obj): try: print obj.name except AttributeError: print "obj %s has no name" % obj import types m = MyObj('parrot') m.someMeth = types.MethodType(someFunc, obj, obj.__class__) m.someMeth() > - and no, explicit is not *always* better than > implicit, just often and perhaps usually. While it's easy to recognize > once you know what's going on, that doesn't make it any less of a wart. > > * technically modules may be objects also, s/may be/are/ > but in practice you don't declare > self as a parameter to module functions def someOtherFunc(): print "hello there" m.someFunc = someOtherFunc m.someFunc() -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From scott.daniels at acm.org Tue May 30 18:24:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 30 May 2006 15:24:50 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <1149024847.655949.227290@38g2000cwa.googlegroups.com> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <mailman.6282.1148767807.27775.python-list@python.org> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> <447c8c6e$1@nntp0.pdx.net> <1149016823.214610.258930@r44g2000cwb.googlegroups.com> <447cadf6$1@nntp0.pdx.net> <1149024847.655949.227290@38g2000cwa.googlegroups.com> Message-ID: <447cc1d8$1@nntp0.pdx.net> akameswaran at gmail.com wrote: > Scott David Daniels wrote: >> Sorry, "re-iterables". A file re-iterable is: >> >> class FileReIterable(object): ... >> def __iter__(self): >> self.file.seek(0) >> return iter(self.file) >> >> This works if-and-only-if it is only in use once at a time. >> If you have multiple simultaneous accesses, you need to do >> something like: >> >> class FileReIterable2(object): ... >> def __iter__(self): >> self.file.seek(0) >> for line in self.file: >> nextpos = self.file.tell() >> yield line >> self.file.seek(nextpos) > > Since I was doing this as a self education excercise. When you say is > in use once and only once, you mean I can only use a single instance of > the class? No. This works: f1 = FileReIterable("one.file") f2 = FileReIterable("another.file") ... free uses of ... This does not "work": gen = FileReIterable("one.file") for a in gen: for b in gen: print a, b This does "work": gen = FileReIterable2("one.file") for a in gen: for b in gen: print a, b That is, any instance of FileReIterable must not be used in a context where it may be in the midst of iterating a file, gets used to produce a result, and then must produce a result from the original iteration. If you think about what must happen to the file read pointer, the reason for all of this should become clear. --Scott David Daniels scott.daniels at acm.org From aleax at mac.com Tue May 30 00:43:46 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 29 May 2006 21:43:46 -0700 Subject: Ricerca Programmatore Python References: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> <447afc06@nntp0.pdx.net> <u9Ieg.103067$F_3.8485@newssvr29.news.prodigy.net> Message-ID: <1hg4bwp.6czyvq131rqvsN%aleax@mac.com> Edward Elliott <nobody at 127.0.0.1> wrote: > Scott David Daniels wrote: > > > I understand there is an Italian-language Python group, but _here_ > > the language is English, even if you begin by an apology in English. > > ... In consideration for such people, please limit yourself to English. > > I doubt he'll ever see your reprimand, looks like a hit-and-run job. Too Hmmm, doesn't look like that to me -- he also posted to the Italian group (correctly in that case, since it.comp.lang.python DOES welcome Python job offers in Italian), got responses offering existing free software to do multigraphs, followed up explaining he knows about those programs but (being a non-programmer with what he thinks is a good idea) still need a contract Python programmer to work on it, etc, etc. Sounds like a person with likely good intentions that's clueless about non-English posts (and apparently job offers) being unwelcome to this newgroup (and about netiquette more generally -- reading groups' charters before posting, etc). About job offers -- I got my current (dream!) job through a long chain of circumstances which DID begin with somebody posting a job offer to this group... so, I can't honestly sympathize with the distaste that some have expressed about seeing (relevant!-) job offers here (yeah, there ARE better venues, admittedly -- but some of us dinosaurs read newsgroups regularly but check out such sites only once in a while, and only when specifically LOOKING for a job, which at the time of that post that eventually got me a job, I definitely wasn't...;-). Alex From mwilson-to at sympatico.ca Tue May 2 23:04:51 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Tue, 02 May 2006 23:04:51 -0400 Subject: simultaneous assignment In-Reply-To: <1146599894.090292.69590@e56g2000cwe.googlegroups.com> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <1146599894.090292.69590@e56g2000cwe.googlegroups.com> Message-ID: <V7V5g.2713$ix6.217468@news20.bellglobal.com> Roger Miller wrote: > Steve R. Hastings wrote: > > >>a = 0 >>b = 0 >>a is b # always true > > > Is this guaranteed by the Python specification, or is it an artifact of > the current implementation? AFAIK it's an artifact. The performance hit it Python stopped sharing small integers could be enormous, nonetheless sharing isn't part of the specification > My understanding has been that an > implementation is free to share integer objects or not, so using 'is' > as an equality test takes you into undefined territory, regardless of > the size of the value. > I agree. "is" is for working with linked-lists or trees, or other applications where object identity is really and truly what you're interested in. Some amusing is/== facts, some suggested by recent threads Python 2.4.2 (#1, Jan 23 2006, 21:24:54) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 0 is 0.0 False >>> -0.0 is 0.0 False >>> 0 == 0.0 == -0.0 True >>> 1000000 is (2000000/2) False From bnblazer at gmail.com Sun May 21 18:24:31 2006 From: bnblazer at gmail.com (Brian) Date: 21 May 2006 15:24:31 -0700 Subject: performance difference between OSx and Windows Message-ID: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> I have been a Mac and linux guy since 1998 and except for a handful of times, have not touched a MS box since then. This changes a few days ago when I needed to get a MS box for another project. This leads me to my question... A while ago, I borrowed a python script from someone's blog that showed some interesting profiling schemes. I made some modifications to it, ran it and until I got this new machine forgot about it. Just for kicks I ran it again on both boxes to see what the differences were. To say I was surprised is an understatement. Here is the code: #!/usr/bin/env python import time elasped = 0 def slowS(): t1 = time.clock() slow_str='' for i in range(100000): slow_str = slow_str + str(i) print 'Slow concatenation finsished in', time.clock() - t1, 'sec.' def fastS(): t2 = time.clock() fast_str = [] for i in range(100000): fast_str.append(str(i)) fast_str = ''.join(fast_str) print 'fast concatenation finished in', time.clock() - t2, 'sec.' #slowS() #fastS() if __name__ == '__main__': import hotshot from hotshot import stats prof = hotshot.Profile("Concant_Stats") prof.runcall(slowS) prof.runcall(fastS) prof.close() s = stats.load("Concant_Stats") s.sort_stats("time").print_stats() On my Quad G5 Mac with 4g of memory I get this result... Slow concatenation finsished in 51.05 sec. fast concatenation finished in 0.63 sec. 15 function calls in 51.036 CPU seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 51.033 51.033 51.033 51.033 /Users/brian/Desktop/strTest.py:7(slowS) 1 0.003 0.003 0.003 0.003 /Users/brian/Desktop/strTest.py:14(fastS) 12 0.000 0.000 0.000 0.000 /Applications/Komodo.app/Contents/SharedSupport/dbgp/bin/pydbgp:83(write) 1 0.000 0.000 0.000 0.000 /Applications/Komodo.app/Contents/SharedSupport/dbgp/bin/pydbgp:95(__getattr__) 0 0.000 0.000 profile:0(profiler) The MS box is an HP with an Athlon 64 X2 Dual with 1g of memory. Here are it's results... Slow concatenation finsished in 23.798 sec fast concatenation finished in 0.622 sec 15 function calls in 87.417 CPU seconds Ordered by: internal time ncalls tottime percall cumtime percall filename:lineno(function) 1 85.188 85.188 85.188 85.188 c:\documents and settings\hp_administrator\desktop\strtest.py:5(slowS) 1 2.228 2.228 2.229 2.229 c:\documents and settings\hp_administrator\desktop\strtest.py:12(fastS) 12 0.001 0.000 0.001 0.000 c:\program files\activestate komodo 3.5\lib\support\dbgp\bin\pydbgp.py:83(write) 1 0.000 0.000 0.000 0.000 c:\program files\activestate komodo 3.5\lib\support\dbgp\bin\pydbgp.py:95(__getattr__) 0 0.000 0.000 profile:0(profiler) While the CPU speed on the G5 was faster the total execution time was much quicker on the MS box. Can anyone give some suggestions as to why this is? Thanks, Brian From crowell at mit.edu Mon May 15 17:39:28 2006 From: crowell at mit.edu (crowell at mit.edu) Date: 15 May 2006 14:39:28 -0700 Subject: HTTPServer and ThreadingMixIn Message-ID: <1147729168.873507.76410@i40g2000cwc.googlegroups.com> Hello, I am having trouble getting the ThreadingMixIn to do what I want. Looking over the docs (and some old code I wrote which successfully does what I want), I arrived at the following: import time import SocketServer import BaseHTTPServer class TheServer(SocketServer.ThreadingMixIn, BaseHTTPServer.HTTPServer): pass class TheHandler(BaseHTTPServer.BaseHTTPRequestHandler): def do_GET(self): print "sleeping..." time.sleep(10) print "awake!" if __name__ == "__main__": theServer = TheServer(('', 8083), TheHandler) theServer.serve_forever() I would like this server to print "sleeping..." when someone make a request, waits 10 seconds, then prints "awake!" This works, but it does not exhibit threading behavior; i.e. it handles the requests in sequential order: sleeping... awake! sleeping... awake! Is there some problem with using the time.sleep() method? Or have I done something else wrong? Sorry for asking such a simple question, but it seems I am unable to pinpoint my error. Thanks. --Rob From ilias at lazaridis.com Fri May 26 18:53:29 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 27 May 2006 01:53:29 +0300 Subject: PUDGE - Project Status, Alternative Solutions Message-ID: <447786E9.9010208@lazaridis.com> What is going on with the pudge project? Mr. Patrik O'Brien (Orbtech LLC) had told me that there is no similar tool available within the python domain, thus I have invested some effort to create a Website template, and to enable pudge to generate colored code: http://audit.lazaridis.com/schevo/wiki/SchevoWebsiteReview I like to reuse the results for personal projects, but I am wondering that the pudge email-list is death (since the server update) - and that no one of the project reacts to personal and public postings. Additionally, the schevo project removes the pudge stuff, mscott, the developer which has introduced pudge removes it again (although this was done with several other tools in the past, too): http://schevo.org/trac/changeset/2127 - Is there a similar tool available, with which I can generate python documentation / websites or both based on templates and reST? Or an overview of such tools? I mean such an organized tool is essential for developmente with python. . -- http://lazaridis.com From roger.miller at nova-sol.com Fri May 19 17:01:54 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 19 May 2006 14:01:54 -0700 Subject: memory error with zipfile module References: <mailman.5938.1148039030.27775.python-list@python.org> <A4x*kx3gr@news.chiark.greenend.org.uk> <446e07ab$0$12795$636a55ce@news.free.fr> Message-ID: <1148072514.207383.26370@j55g2000cwa.googlegroups.com> The basic problem is that the zipfile interface only reads and writes whole files, so it may perform poorly or fail on huge files. At one time I implemented a patch to allow reading files in chunks. However I believe that the current interface has too many problems to solve by incremental patching, and that a zipfile2 module is probably warranted. (Is anyone working on this?) In the meantime I think the best solution is often to just run an external zip/unzip utility to do the heavy lifting. From onurb at xiludom.gro Tue May 23 11:35:10 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 23 May 2006 17:35:10 +0200 Subject: Python - Web Display Technology In-Reply-To: <mailman.6050.1148253641.27775.python-list@python.org> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <mailman.6050.1148253641.27775.python-list@python.org> Message-ID: <44732c19$0$21103$626a54ce@news.free.fr> Ben Finney wrote: > "SamFeltus" <sam at nuevageorgia.com> writes: > > >>I keep trying to understand why people like HTML/JS, I don't think I >>am gonna understand. > > > It's fairly simple: HTML, CSS and JavaScript have all been > standardised independent of any single corporation, and are freely > implementable, resulting in competing free software > implementations. We can choose or improve upon the implementation we > like, or make our own, and share the result with others. Also: HTML is an easy to parse text format. I can programatically grab infos from HTML pages. Search engines can do it to. > >>I guess for better or worse, Flash is a very different mindset and >>approach to the web. > > One that shares none of the above qualities. > indeed. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From kevin.bell at slcgov.com Tue May 30 18:07:20 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Tue, 30 May 2006 16:07:20 -0600 Subject: interactive programme (voice) Message-ID: <2387F0EED10A4545A840B231BBAAC7226083C9@slcimail1.slcgov.com> http://www.cs.unc.edu/~parente/tech/tr02.shtml loads of fun. From nobody at 127.0.0.1 Thu May 4 14:43:15 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 04 May 2006 18:43:15 GMT Subject: Newbie question on code vetting References: <yvT5g.132$yh.117@trnddc04> <iokg521d387uvt3teoegi17t032ht6sjr5@4ax.com> <y356g.81306$dW3.7774@newssvr21.news.prodigy.com> <qBf6g.2650$g01.2436@trnddc01> Message-ID: <7Xr6g.81692$dW3.36318@newssvr21.news.prodigy.com> william.boquist at gte.net wrote: > I agree with your point, which is why I asked the question. Risk cannot be > eliminated, but it can be understood and managed so that useful work can > still be done. If there is any way I can find out what the commiters do > prior to reaching a decision to accept or reject a particular submission, > I would like to know about it. If committers make no checks on submitted code, that doesn't have to be an automatic showstopper, even for a risk-averse company. How many of the alternatives perform more stringent checks on their code? How much misappropriated code is floating around in closed commercial products, where the privacy of the source may encourage more liberal borrowing? Anyone can say they check their IP, but how many organizations put their money where their mouth is and provide indemnity? How visible will your company and your Python projects be? You can always try to make the case that even without ip checks python makes your company 1) no more vulnerable than the other software they already rely on, and 2) unlikely to be targetted for their use anyway. And if you can show the financial gains from using it are highger than the potential liability, you're golden. From johnjsal at NOSPAMgmail.com Thu May 11 11:35:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 11 May 2006 15:35:38 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: <e3vikl$ecv$1@mlucom4.urz.uni-halle.de> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> <E6r8g.2083$No6.45931@news.tufts.edu> <eir8g.2084$No6.45965@news.tufts.edu> <1147291197.423570.242440@g10g2000cwb.googlegroups.com> <e3v387$9tt$1@mlucom4.urz.uni-halle.de> <GGH8g.2085$No6.45839@news.tufts.edu> <e3vikl$ecv$1@mlucom4.urz.uni-halle.de> Message-ID: <eRI8g.2087$No6.45924@news.tufts.edu> Mirco Wahab wrote: > I have no idea how to do this > in Python in a terse way - but > I'll try ;-) > > In Perl, its easy. Here, the > "match construct" (\w)(?=(.)\1) > returns all captures in a > list (a 1 a 2 a 4 b 7 c 9) Ah, I see the difference. In Python you get a list of tuples, so there seems to be a little extra work to do to get the number out. From tomerfiliba at gmail.com Fri May 19 09:47:29 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 19 May 2006 06:47:29 -0700 Subject: released: RPyC 2.60 Message-ID: <1148046449.456746.184000@j73g2000cwa.googlegroups.com> Remote Python Call (RPyC) has been released. this release introduces delivering objects, reducing memory consumption with __slots__, and several other new/improved helper functions. see the release notes and changelog (on the site) for more info. home: http://rpyc.wikispaces.com -tomer From seeker1001 at lycos.com Tue May 2 05:06:05 2006 From: seeker1001 at lycos.com (seeker) Date: Tue, 02 May 2006 12:06:05 +0300 Subject: stripping blanks In-Reply-To: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> References: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> Message-ID: <445720fd$1_2@news.estpak.ee> micklee74 at hotmail.com wrote: > hi > i have a file test.dat eg > > abcdefgh > ijklmn > <-----newline > opqrs > tuvwxyz > <---newline > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break > #if not re.findall(r'^$',line): > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all..? > thanks > Last suggestion I made was bad. Here is the new one. Hopefully thats correct. f = open("test.dat") for line in f: printLine = line.rstrip("\n") if not printLine: continue print printLine From jason at tishler.net Thu May 4 08:16:10 2006 From: jason at tishler.net (Jason Tishler) Date: Thu, 4 May 2006 08:16:10 -0400 Subject: Problem building extension under Cygwin (ImportError: Bad address) In-Reply-To: <1146739813.157265.238320@i39g2000cwa.googlegroups.com> References: <1146739813.157265.238320@i39g2000cwa.googlegroups.com> Message-ID: <20060504121610.GA2340@tishler.net> Lars, On Thu, May 04, 2006 at 03:50:13AM -0700, Lars wrote: > I have problems building a simple handcoded C-extension (hello.c) with > Cygwin and gcc3.4.4. I hope somebody has encountered the same problem > before, and has some advice. > > [snip] The following works for me: $ gcc -shared -I/usr/include/python2.4 -o hello.dll hello.c -L/usr/lib/python2.4/config -lpython2.4 $ python -c'import hello;q = hello.message("Lars");print q' Hello, Lars $ python hellouse.py Hello, C Hello, module /tmp/Examples/PP2E/Integrate/Extend/Hello/hello.dll Hello, 0 Hello, 1 Hello, 2 Note I had to apply the attached patch to get hello.c to compile. Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 -------------- next part -------------- --- hello.c.orig 2006-05-04 08:06:06.769910400 -0400 +++ hello.c 2006-05-04 08:06:10.988633400 -0400 @@ -25,7 +25,7 @@ {"message", message, 1}, /* method name, C func ptr, always-tuple */ {NULL, NULL} /* end of table marker */ }; -, + /* module initializer */ void inithello() /* called on first import */ { /* name matters if loaded dynamically */ From johnjsal at NOSPAMgmail.com Thu May 11 10:16:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 11 May 2006 14:16:06 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: <e3v387$9tt$1@mlucom4.urz.uni-halle.de> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> <E6r8g.2083$No6.45931@news.tufts.edu> <eir8g.2084$No6.45965@news.tufts.edu> <1147291197.423570.242440@g10g2000cwb.googlegroups.com> <e3v387$9tt$1@mlucom4.urz.uni-halle.de> Message-ID: <GGH8g.2085$No6.45839@news.tufts.edu> Mirco Wahab wrote: > Py: > import re > tx = 'a1a2a3A4a35a6b7b8c9c' > rg = r'(\w)(?=(.\1))' > print re.findall(rg, tx) The only problem seems to be (and I ran into this with my original example too) that what gets returned by this code isn't exactly what you are looking for, i.e. the numbers '1', '2', etc. You get a list of tuples, and the second item in this tuple contains the number, but also the following \w character. So there still seems to be some work that must be done when dealing with overlapping patterns/look-ahead/behind. Oh wait, a thought just hit me. Instead of doing it as you did: rg = r'(\w)(?=(.\1))' Could you do: rg = r'(\w)(?=(.)\1)' That would at least isolate the number, although you'd still have to get it out of the list/tuple. From pydecker at gmail.com Mon May 15 13:33:46 2006 From: pydecker at gmail.com (Peter Decker) Date: Mon, 15 May 2006 13:33:46 -0400 Subject: Tabs versus Spaces in Source Code In-Reply-To: <4468B996.5000407@sweetapp.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <qz2ag.6572$fb2.2976@newssvr27.news.prodigy.net> <4468B996.5000407@sweetapp.com> Message-ID: <ca55a9900605151033h64bb4b0bre326c1c83acd0465@mail.gmail.com> On 5/15/06, Brian Quinlan <brian at sweetapp.com> wrote: > The problem with tabs is that people use tabs for alignment e.g. > > def foo(): > ->query = """SELECT * > -> -> -> FROM sometable > -> -> -> WHERE condition""" > > Now I change my editor to use 8-space tabs and the code is all messed > up. Of course, a very disciplined group of people could be trained to > never use tabs except to align with the current block level but, in > practice, that doesn't work. Therefore tabs are bad. And those of us who hate cutesy alignment like that think that people who do it are therefore bad. Spaces look like crap, too, when using proportional fonts. -- # p.d. From manstey at csu.edu.au Wed May 17 06:19:33 2006 From: manstey at csu.edu.au (manstey) Date: 17 May 2006 03:19:33 -0700 Subject: A Unicode problem -HELP In-Reply-To: <446abddb$0$31040$9b622d9e@news.freenet.de> References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <446AAFE6.4080008@v.loewis.de> <1147843788.969853.159420@g10g2000cwb.googlegroups.com> <446abddb$0$31040$9b622d9e@news.freenet.de> Message-ID: <1147861173.156979.303100@y43g2000cwc.googlegroups.com> Hi Martin, Thanks very much. Your def comma_separated_utf8(items): approach raises an exception in codecs.py, so I tried = u", ".join(word_info + parse + gloss), which works perfectly. So I want to understand exactly why this works. word_info and parse and gloss are all tuples. does str convert the three into an ascii string? but the join method retains their unicode status. In the text file, the unicode characters appear perfectly, so I'm very happy. cheers matthew From Serge.Orlov at gmail.com Tue May 30 07:09:38 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 30 May 2006 04:09:38 -0700 Subject: Is anybody knows about a linkable, quick MD5/SHA1 calculator library ? References: <mailman.6314.1148921878.27775.python-list@python.org> Message-ID: <1148987378.080172.327520@y43g2000cwc.googlegroups.com> DurumDara wrote: > Hi ! > > I need to speedup my MD5/SHA1 calculator app that working on > filesystem's files. > I use the Python standard modules, but I think that it can be faster if > I use C, or other module for it. > > I use FSUM before, but I got problems, because I "move" into "DOS area", > and the parameterizing of outer process maked me very angry (not working). > You will see this in this place: > http://mail.python.org/pipermail/python-win32/2006-May/004697.html FWIW I looked at what is the problem, apparently fsum converts the name back to unicode, tries to print it and silently corrupts the output. You give it short name XA02BB~1 of the file xA? and fsum prints xA Use python module or try another utility. From tgrav at mac.com Wed May 10 14:05:40 2006 From: tgrav at mac.com (Tommy Grav) Date: Wed, 10 May 2006 14:05:40 -0400 Subject: Masked arrays Message-ID: <F0B70A3B-CC34-4EED-BDE1-CB4B79D06B3F@mac.com> I am trying to get the flux of a star in an image. I have been using numpy and pyfits and have the code. def distance(im,xc,yc): (rows,cols) = im.shape dist = zeros([rows,cols]).astype(Float64) for row in range(rows): for col in range(cols): dist[row,col] = sqrt(((row + 0.5) - yc)**2 + ((col + 0.5) - xc)**2) return dist def apphot(im,x,y,r): dist = distance(im,x,y) appmask = where(dist <= r,1,0) fluxim = where(appmask,im,0) appflux = sum(sum(fluxim)) skymask = where(dist > r, 1,0) skyim = where(skymask,im,0) sky = mean(skyim) print skyim print sky return 1 Output: > array (20,20) , type = f, has 400 elements > [ 45.89742126, 45.92555847, 45.8874054 , 45.88538208, 45.88244934, 45.9353241 , 36.75245361, 29.85816345, 27.53547668, 22.93712311, 22.93178101, 22.93699799, 22.91038208, 27.4988739 , 29.84021606, 36.71789551, 45.86646729, 45.86741638, 45.85328979, 45.823349 ,] where im is a ndarray, x and y are the position of the star and r is the radius of the aperture. I calculate the flux inside the aperture, but when I want to calculate the mean of the pixels outside the aperture I run into problems as the pixels values inside the aperture is 0 and is still considered in the mean calculation. Is there a way to do this without using masked arrays? How would I use a masked array to do it? Cheers 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 genius -- and a lot of courage -- to move in the opposite direction" -- Albert Einstein -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060510/81568f0d/attachment.html> From deets at nospam.web.de Sat May 27 07:05:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sat, 27 May 2006 13:05:11 +0200 Subject: Pyrex speed In-Reply-To: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> Message-ID: <4dqq38F1bi6btU1@uni-berlin.de> Jim Lewis schrieb: > Has anyone found a good link on exactly how to speed up code using > pyrex? I found various info but the focus is usually not on code > speedup. The code speedup comes through the usage of C by pyrex itself, and using it to put a thin layer over C-functions available/coded for that purpose. Diez From brian.d.foy at gmail.com Wed May 17 17:03:43 2006 From: brian.d.foy at gmail.com (brian d foy) Date: Wed, 17 May 2006 16:03:43 -0500 Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> Message-ID: <170520061603434552%brian.d.foy@gmail.com> In article <IRuag.28298$4L1.9158 at newssvr11.news.prodigy.com>, Edward Elliott <nobody at 127.0.0.1> wrote: > This is just anecdotal, but I still find it interesting. Take it for what > it's worth. I'm interested in hearing others' perspectives, just please > don't turn this into a pissing contest. > > I'm in the process of converting some old perl programs to python. These > programs use some network code and do a lot of list/dict data processing. > The old ones work fine but are a pain to extend. After two conversions, > the python versions are noticeably shorter. You've got some hidden assumptions in there somehere, even if you aren't admitting them to yourself. :) You have to note that rewriting a program, even in the same language, tends to make it shorter, too. These things are measures of programmer skill, not the usefulness or merit of a particular language. Shorter doesn't really mean anything though, and line count means even less. The number of statements or the statement density might be slightly more meaningful. Furthermore, you can't judge a script by just the lines you see. Count the lines of all the libraries and support files that come into play. Even then, that's next to meaningless unless the two things do exactly the same thing and have exactly the same features and capabilities. I can write a one line (or very short) program (in any language) that does the same thing your scripts do just by hiding the good stuff in a library. One of my friends likes to talk about his program that implements Tetris in one statement (because he hardwired everything into a chip). That doesn't lead us to any greater understanding of anything though. *** Posted via a free Usenet account from http://www.teranews.com *** From kentilton at gmail.com Wed May 10 12:25:59 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 10 May 2006 12:25:59 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <egmzdqcm4s.fsf@polarvier.ii.uib.no> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1147194791.809735.251500@g10g2000cwb.googlegroups.com> <1hf33s3.1bdn2e4juoow0N%aleax@mac.com> <egmzdqcm4s.fsf@polarvier.ii.uib.no> Message-ID: <ruo8g.8$CQ6.1@fe11.lga> Ketil Malde wrote: > > Sometimes the best documentation is the code itself. Sometimes the > best name for a function is the code itself. Absolutely. When I take over someone else's code I begin by deleting all the comments. Then I read the code. If a variable or function name makes no sense (once I have figured out what they /really/ do) I do a global change. Pretty soon the system is "documented". And I usually find a couple of bugs as the renaming produces things like: count = count + weight I think one good argument for anonymous functions is a hefty Cells application, with literally hundreds of rules. The context is set by the instance and slot name, and as you say, the rule speaks for itself: (make-instance 'frame-widget :bounds (c? (apply 'rect-union (all-bounds (subwidgets self))))) Why do I have to give that a name? And if the algorithm gets hairier, well, why is the reader looking at my code? If the reader is debugging or intending to modify the rule, they damn well better be looking at the code, not the name and not the comments. (Never a problem with my code. <g>) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From bjourne at gmail.com Tue May 9 19:04:47 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Wed, 10 May 2006 01:04:47 +0200 Subject: Dictionaries -- ahh the fun.. (newbie help) In-Reply-To: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> References: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> Message-ID: <740c3aec0605091604n505797ewd593a7bc40a199d7@mail.gmail.com> > Can someone help me out. I am trying to determing for each run whether > or not the test should pass or fail but I can't seem to access the > results .. > > Alternatively can someone suggest a better structure ( and a lesson as > to the reasoning ) that would be great too!! Flat is better than nested. Pretend you write one billion cells in your cells dict. To save disk space and memory (and make code readable!) you wan't to make your structure as optimal as possible. [snip] > cells["NOR3X1"]= { > 'run' : [ 'lvs', 'drc' ], > 'results' : [{ 'lvs' : 'pass' }, > { 'drc' : 'fail' }] > } [snip] > def main(): > > for cell in cells: > print cell > for run in cells[cell]['run']: > print cell, run, "should", > cells[cell]['results'].index(run) That is good code and AFAICT it should work as you have described. Just replace cells[cell]['results'].index(run) with cells[cell]['results'][run] However, notice how you have defined each cell: > cells["NOR3X1"]= { > 'run' : [ 'lvs', 'drc' ], > 'results' : [{ 'lvs' : 'pass' }, > { 'drc' : 'fail' }] > } Here you have repetition, you are writing the string lvs and drc twice. Imagine you have hundreds of these in each cell, wouldn't it be annoying to have to type so much redundant data. So you optimize the structure: cells["NOR3X1"] = {'run' : [('lvs', 'pass'), ('drc', 'fail')]} Your code for printing the results become: for cell, d in cells.items(): print cell for testname, testresult in d['run']: print cell, testname, 'should', testresult for cell, d in cells.items() runs through all the key-value pairs in the dict. cell becomes "NOR3X1" (the key) and d becomes {'run' : [('lvs', 'pass'), ('drc', 'fail')]} (the value) for one loop for example. for testname, testresult in d['run'] runs through all items in the list d['run'] and "unpacks" them. testname becomes 'lvs' and testresult 'pass' for one loop for example. The next step in this refactoring is realizing that all items in the cell dict are a dict with just one element. I.e: {'run' : ('drc', 'fail')} for the 'AND3X1' item. So you can optimize your structure another step: cells["NOR3X1"] = [('lvs', 'pass'), ('drc', 'fail')] Here, we have just removed the subdict. Dicts with just one item are rarely useful so we replace the dict with its sole item. This I think is the optimal structure for your example, because it contains no needless repetition. The following is your original example using the reworked cells structure. P = 'pass' F = 'fail' cells['NOR3X1'] = [('lvs', P), ('drc', F)] cells['OR3X1'] = [('lvs', P')] cells['AND3X1] = [('drc', F)] for cellname, celltests in cells.items(): print cellname for testname, restresult in celltests: print cellname, testname, 'should', testresult As you can see I have replaced the 'pass' and 'fail' strings with the variables P and F. Sometimes that is a useful technique because it reduces repetitive typing. You are also less likely misspell things like 'flai' instead of 'fail'. One golden rule of programming is that you should never write the same thing twice. Ofcourse that is very hard to achieve in practice, but the stronger you get the less often you do it. If you can spot that you have written something twice or more times in your code, then you have also spotted what is wrong with your code. -- mvh Bj?rn From john at castleamber.com Tue May 16 08:46:37 2006 From: john at castleamber.com (John Bokma) Date: 16 May 2006 12:46:37 GMT Subject: Google-API Bad-Gateway-Error References: <1147783046.944898.43470@i39g2000cwa.googlegroups.com> Message-ID: <Xns97C54F1B3C90Acastleamber@130.133.1.4> DierkErdmann at mail.com wrote: > Hi, > > I am trying to query google from within a python script using the > Google-Api (pygoogle). > The following piece of codes gives me a "SOAPpy.Errors.HTTPError: > <HTTPError 502 Bad Gateway>", Not with Python, but with Perl, I am seeing now and then the same error. If you rerun the script, does the message go away? A week or 2-3 ago I had even the feeling that the Google API was gone for about a day. -- 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 Thu May 18 20:10:49 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 00:10:49 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <Xns97C7BC8549BA0castleamber@130.133.1.4> <1147996169.818933.252420@u72g2000cwu.googlegroups.com> Message-ID: <Xns97C7C31D1A937castleamber@130.133.1.4> "akameswaran at gmail.com" <akameswaran at gmail.com> wrote: > John, > Your hilarious... If you learn to quote, you don't need to address me. But it's beyond you I understand, so bye. -- 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 chris at kateandchris.net Sat May 6 23:57:59 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Sat, 6 May 2006 23:57:59 -0400 Subject: unittest.main-workalike that runs doctests too? In-Reply-To: <ur738l5xt.fsf@pobox.com> References: <uvesklpyi.fsf@pobox.com> <c325fb4b718fc0eb650e947eae1619bf@cogeco.ca> <ur738l5xt.fsf@pobox.com> Message-ID: <20060507035759.GA10421@kateandchris.net> On Fri, May 05, 2006 at 06:47:26PM +0100, John J. Lee wrote: > Jay Parlar <jparlar at cogeco.ca> writes: > > On May 5, 2006, at 6:35 AM, John J. Lee wrote: > [...] > > > I know about nose, but it seems just a little too magical for my > > > tastes, and includes stuff I don't really need. > [...] > > nose actually has very little magic, its operation is quite > > straightforward. I've played with its codebase before, and it's quite > > clean. > > Maybe (but note I *was* talking about what it does, not the > implementation of same). > I don't know what you think is magic about what it does. The documenation is very clear about how tests are found and how you integrate with doctest. Its 'native' test structure is way easier to use than doctest or unittest and it integrates with both. > > > And the new 0.9 branch uses a plugin system for some of the extra > > functionality, so you don't even have to install all the things it's > > capable of doing. > > Still seems a little OTT to require another library just to find the > tests. I did not need to install anything extra to make it work. I did eventually install Ned Batchelder's coverage.py, but I decided to do that even before realising that nose had support for it. I like nose a lot because its tests are so easy to set up. At a basic level all you need are functions prefixed with test. Assert a a condition, if the assertion fails, the test fails. Also installation is really easy. It's in the Cheese Shop so easy_install will find it, or you can go with the tradition python setup.py install. -Chris From onurb at xiludom.gro Fri May 19 10:10:32 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 16:10:32 +0200 Subject: noob import question In-Reply-To: <mailman.5945.1148045097.27775.python-list@python.org> References: <mailman.5945.1148045097.27775.python-list@python.org> Message-ID: <446dd240$0$7671$626a54ce@news.free.fr> Brian Blazer wrote: > OK, I have a very simple class here: > > class Student: class Student(object): > """Defines the student class""" > > def __init__(self, lName, fName, mi): > self.lName = lName > self.fName = fName > self.mi = mi Do yourself a favour: use meaningful names. > Then I have a small script that I am using as a test: > > from Student import * So your module is named Student.py ? The common convention is to use all_lower for modules, and CapNames for classes. BTW, unlike Java, the common use is to group closely related classes and functions in a same module. > s1 = Student("Brian", "Smith", "N") > > print s1.lName > > This works as expected. However, if I change the import statement to: > import Student > > I get an error: > TypeError: 'module' object is not callable Of course. And that's one for the reason for naming modules all_lower and classes CapNames. With from Student import * you import all the names (well... not all, read the doc about this) defined in the module Student directly in the current namespace. So, since the module Student contains the class Student, in this current namespace, the name Student refers to the class Student. With import Student you import the module name Student in the current namespace. You can then refer to names defined in module Student with the qualified name module.name. So here, to refer to the class Student, you need to use the qualified name Student.Student. You wouldn't have such a confusion if your module was named students !-) > I have tried to look up what is going on, but I have not found > anything. you could have done something like this: import Student print dir() print dir(Student) print type(Student) del Student from Student import * print dir() print dir(Student) print type(Student) Also, reading the doc migh help: http://www.python.org/doc/2.4.2/tut/node8.html HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From me+python at modelnine.org Thu May 18 07:36:21 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 18 May 2006 13:36:21 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <446c5a80$0$7024$636a55ce@news.free.fr> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147947048.303912.109150@38g2000cwa.googlegroups.com> <446c5a80$0$7024$636a55ce@news.free.fr> Message-ID: <200605181336.21093.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 13:27 schrieb bruno at modulix: > Adding ugly and unintuitive "operators" to try to turn a general purpose > programming language into a half-backed unusable HTML templating > language is of course *much* more pythonic... What about writing a mini-language that gets translated to Python? Think of Cheetah, which does exactly this (albeit not being limited to templating HTML data). Adding these kind of operators to Python is an absolute NoNo, because it's nothing general the OP is trying to achieve here. Creating a small wrapper language: why not? (it's not that we have enough templating languages already ;-)) By the way: the language you (the OP) are trying to implement here goes strictly against the MVC model of application programming. You know that, right? --- Heiko. From sjmachin at lexicon.net Wed May 17 19:22:57 2006 From: sjmachin at lexicon.net (John Machin) Date: 17 May 2006 16:22:57 -0700 Subject: excel centering columns References: <446ba8bd$0$61161$ae4e5890@news.nationwide.net> Message-ID: <1147908177.262141.61460@g10g2000cwb.googlegroups.com> > from win32com.client import constants > sh2.Columns(lastcol).HorizontalAlignment = constant.xlCenter > NameError: name 'constant' is not defined 1. So why not try reading the error message and fixing the problem instead of thrashing about madly? 2. You have run makepy on your Excel library, haven't you? From tomerfiliba at gmail.com Fri May 19 15:01:51 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 19 May 2006 12:01:51 -0700 Subject: bitstream Message-ID: <1148065311.920568.6870@i40g2000cwc.googlegroups.com> anyone has a good bit-stream reader and writer? (before i go to write my own) i.e. f = open(..) b = BitStream(f) b.write("10010010") b.read(5) # 10010 or something like that? -tomer From groups at theyoungfamily.co.uk Tue May 16 04:21:11 2006 From: groups at theyoungfamily.co.uk (Ben) Date: 16 May 2006 01:21:11 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <MD2ag.777$8K5.396@fe09.lga> References: <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> <d6lu07r7u0u.fsf@vipunen.hut.fi> <44681F95.9040400@gmail.com> <1147689991.541829.129550@u72g2000cwu.googlegroups.com> <MD2ag.777$8K5.396@fe09.lga> Message-ID: <1147767671.450912.152140@u72g2000cwu.googlegroups.com> Ok, I'm sorry. This kind of discussions between two groups of people, neither of who know the other person's language very well just wind me up something chronic! It wasn't your post as such, just reading through most of the thread in one go. That will teach me to post while cross :). Sorry for any offence. Anything that makes programming more fun is good, and I hope the Lisp true way explodes into my head at some point. Cheers, Ben From NA at NA.com Wed May 10 22:34:11 2006 From: NA at NA.com (N/A) Date: Thu, 11 May 2006 10:34:11 +0800 Subject: Econometrics in Panel data? In-Reply-To: <1147307104.586106.63890@g10g2000cwb.googlegroups.com> References: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <07l062li47gjhuskkkqsai7kji82fpfjnq@4ax.com> <44606dd5$0$3285$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <mub6j3-sne.ln1@lairds.us> <ff67j3-fih.ln1@lairds.us> <1147307104.586106.63890@g10g2000cwb.googlegroups.com> Message-ID: <e3u7r3$vp7$1@enyo.uwa.edu.au> Oh! I think I should stop wasting time to learn Python to do my econometric algorithms. >_< beliavsky at aol.com wrote: > Cameron Laird wrote: >> In article <mub6j3-sne.ln1 at lairds.us>, I counseled: >>> In article <44606dd5$0$3285$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>, >>> DeepBlue <123 at 321.com> wrote: >>>> so are you saying that Python is not an appropriate language for doing >>>> econometrics stuff? >>>> >>>> >>>> Dennis Lee Bieber wrote: >>>>> On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <123 at 321.com> declaimed the >>>>> following in comp.lang.python: >>>>> >>>>>> Hi all, >>>>>> >>>>>> I am new to Python. Just wondering can Python able to do econometric >>>>>> regression in either Time-series or pooled (panel) data? As well as test >>>>>> for hetero, autocorrelation, or endogeneity? >> . >> . >> . >>> There is not, however, a readily-accessible library targeted >>> for this sort of work. If I had the opportunity to work in >>> econometrics now, I'd think seriously about R, Lisp, and >>> Mathematica, and see what's available among the functional >>> languages, along with Python. >> Smalltalk, too; I'd throw it in the mix. Much serious econometrics >> has been done with Fortran, but I have no enthusiasm for pursuing >> that direction, mostly because I think too much of the computing >> world is going in a different one. > > There are many statistics packages and programming languages used in > econometrics and in general, so most of the computing world is going in > a different > "direction", no matter which package or language you choose. > > Enough programmers still use Fortran that major hardware vendors such > as Intel, IBM, and Sun are actively maintaining their Fortran 95 > compilers and adding features from Fortran 2003. G95 is free, available > almost everywhere that gcc is, and good enough for production use IMO. > > The recent book > http://methcenter.psu.edu/newbooks/fortranbook/thebook.html > Developing Statistical Software in Fortran 95 > by David R. Lemmon and Joseph L. Schafer > Spriger (2005) > > discusses how to build statistical software components in Fortran that > can be used in statistical packages. > > The IMSL and NAG software libraries have extensive statistical > functionality and are available in Fortran, among other languages. > > It is important for a programming language used for econometrics to > conveniently handle multidimensional arrays, and here Fortran outshines > C, C++, and Java (NumPy is good, though). > > I am a quantitative financial analyst who implements econometrics > algorithms. Data sets are getting bigger -- use of intraday data is now > common -- and the CPU time for many algorithms scales as the N^2 or > N^3, where N is the number of observations. Speed still matters. > From spohle at gmail.com Mon May 22 13:29:56 2006 From: spohle at gmail.com (spohle) Date: 22 May 2006 10:29:56 -0700 Subject: MAC Laptop right click/drag mouse button TKinter Message-ID: <1148318996.423158.327240@i39g2000cwa.googlegroups.com> hi, i programmed a small app with TK and use TK. some of the functions are called with events like rightDrag and rightClick on an item on the canvas. that works fine on a pc. on my mac laptop i only have the one button, so im used to use CTRL+ Mouse Button. that doesn't work with TK. any ideas how to get around that problems ? From AbrahamLincolnIllinois at yahoo.com Fri May 26 08:32:44 2006 From: AbrahamLincolnIllinois at yahoo.com (AbrahamLincolnIllinois at yahoo.com) Date: 26 May 2006 05:32:44 -0700 Subject: "Learning Python" 2nd ed. p479 error? Message-ID: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> Hello all. On page 479, the 2nd edition of the "Learning Python" book, this code appears class Derived(Base): def __init__(self, arg, *args, **kw): self.__init__(self, *args, **kw) Surely self.__init__ should be Base.__init__ Everything else in the book has been crystal clear. Up to page 479! It doesn't appear in the errata. What am I misunderstanding? Regards, Abraham From raathm at gmail.com Thu May 4 07:42:19 2006 From: raathm at gmail.com (Mike) Date: 4 May 2006 04:42:19 -0700 Subject: RegEx with multiple occurrences Message-ID: <1146742939.692014.201270@e56g2000cwe.googlegroups.com> Hi again. I'm trying to strip all script blocks from HTML, and am using the following re to do it: p = re.compile("(\<script.*>*\</script>)",re.IGNORECASE | re.DOTALL) m = p.search(data) The problem is that I'm getting everything from the 1st script's start tag to the last script's end tag in one group - so it seems like it parses the string from both ends therefore removing far more from that data than I want. What am I doing wrong? From m.yanowitz at kearfott.com Mon May 8 09:44:50 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Mon, 8 May 2006 09:44:50 -0400 Subject: PYTHONPATH vs PATH? In-Reply-To: <445BA18C.3080600@kearfott.com> Message-ID: <HGEOKIAPAMCIFPPBDALKMEIGCAAA.m.yanowitz@kearfott.com> Hello: Someone on my team tried out installing my Python code and found that setting PYTHONPATH does not work, but setting PATH environment variable works the way PYTHONPATH should. Is that how it supposed to be, or is that a bug or feature? -----Original Message----- (parts deleted) Subject: question on Python for windows I ran into trouble getting our software to work with the debuggers based on the user guide (updated after the CDROM). PYTHONPATH=.;..;DIRECTORY-CONTAINING-scenarios.py Where DIRECTORY-CONTAINING-PYTHON-SCRIPTS.py is the directory containing the Python scripts . this actually is the PATH, not PYTHONPATH, and is correct if you installed the Python scripts to the Python scripts folder, and then start up from the Python scripts folder, which I would say is normally not going to be the case. I installed our software to C:\sp I installed Python to E:\Python24 (the default is the same folder on C drive, I just changed the drive letter) when I installed the additional 3 packages they knew where Python was already and all I did was pick the default choices. but, the trouble was that the PYTHONPATH using . and .. does not find the Python scripts folder if you are in C:\sp I used this to make it work (based on Python in E:\Python24 and in C:\sp) set PATH=%PATH%;E:\Python24;E:\Python24\Scripts now I start in my C:\sp folder (where the config.txt file is) and everything works fine I did try just setting PYTHONPATH but it is actually PATH that matters. If you don't include the Python base and Scripts folders in the PATH it does not work. I verified that not setting PYTHONPATH but just set PATH to include the Python base and scripts folders does work. Thanks in advance: From eurleif at ecritters.biz Mon May 8 02:55:33 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 08 May 2006 02:55:33 -0400 Subject: which is better, string concatentation or substitution? In-Reply-To: <1147065351.819566.140900@j73g2000cwa.googlegroups.com> References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <1147065351.819566.140900@j73g2000cwa.googlegroups.com> Message-ID: <445eeab3$0$3681$4d3efbfe@news.sover.net> fuzzylollipop wrote: > niether .join() is the fastest Please quote what you're replying to. No, it's the slowest: leif at ubuntu:~$ python -m timeit "'<p>%s</p>\n\n' % 'foobar'" 1000000 loops, best of 3: 0.607 usec per loop leif at ubuntu:~$ python -m timeit "'<p>' + 'foobar' + '</p>\n\n'" 1000000 loops, best of 3: 0.38 usec per loop leif at ubuntu:~$ python -m timeit "''.join(['<p>', 'foobar', '</p>\n\n'])" 1000000 loops, best of 3: 0.817 usec per loop From onurb at xiludom.gro Fri May 19 15:33:26 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 21:33:26 +0200 Subject: altering an object as you iterate over it? In-Reply-To: <1Mobg.2139$No6.46432@news.tufts.edu> References: <1Mobg.2139$No6.46432@news.tufts.edu> Message-ID: <446e1def$0$6919$626a54ce@news.free.fr> John Salerno wrote: > What is the best way of altering something (in my case, a file) while > you are iterating over it? I've tried this before by accident and got an > error, naturally. > > I'm trying to read the lines of a file and remove all the blank ones. > One solution I tried is to open the file and use readlines(), then copy > that list into another variable, but this doesn't seem very efficient to > have two variables representing the file. If the file is huge, this can be a problem. But you cannot modify a text file in place anyway. For the general case, the best way to go would probably be an iterator: def iterfilter(fileObj): for line in fileObj: if line.strip(): yield line f = open(path, 'r') for line in iterfilter(f): doSomethingWith(line) Now if what you want to do is just to rewrite the file without the blank files, you need to use a second file: fin = open(path, 'r') fout = open(temp, 'w') for line in fin: if line.strip(): fout.write(line) fin.close() fout.close() then delete path and rename temp, and you're done. And yes, this is actually the canonical way to do this !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From deets at nospam.web.de Wed May 17 10:22:17 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 May 2006 16:22:17 +0200 Subject: using wxPython events inside a loop References: <1147873572.398048.188890@g10g2000cwb.googlegroups.com> Message-ID: <4d0psrF17qjh9U1@uni-berlin.de> Mr BigSmoke wrote: > I'm writting an applicatio that that does something like this: > > class batchSpy(wx.Frame): > > def __init__(self, parent): > > wx.Frame.__init__( self, None, -1, "Batch Spy", pos = (0,0), > size = mySize) > .... do layout ... > > self.searchAlarms() > > def searchAlarms(self): > for alm in self.alarms: # self.alarms is a list of > strings > self.almBox.WriteText(alm) #Alm box is a > wx.TextCtrl widget... > self.Refresh() > > > > I Know that writing like this my wxFrame just freeze. I've tried usind > wxTimer event but it doesn't help... Any hint? Use a thread if possible, or invoke the wx-event-loop periodically. No idea how to do that in wx though - but google should help. Diez From robert.kern at gmail.com Sat May 6 15:20:12 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 06 May 2006 14:20:12 -0500 Subject: NaN handling In-Reply-To: <yfsy7xfxr1x.fsf@oc.ex.ac.uk> References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> <mailman.5402.1146867973.27775.python-list@python.org> <125nlbgm8l1fi17@corp.supernews.com> <DE87348C-5BE0-4D55-B041-516FB72E7B04@mcmaster.ca> <mailman.5409.1146880569.27775.python-list@python.org> <yfsy7xfxr1x.fsf@oc.ex.ac.uk> Message-ID: <e3iste$msm$1@sea.gmane.org> Alexander Schmolck wrote: > Robert Kern <robert.kern at gmail.com> writes: >>Ivan Vinogradov wrote: >>>Since numpy seems to be working on a variety of platforms/hardware, >>>how hard would it be to extract this functionality from it to add to >>>Python proper? >> >>Harder than just enabling fpectl. > > Last thing I heard fpectl was considered to be completely broken -- it's > likely not disabled by default for no reason. Fair enough. If you want to go through numpy's code to rip out its floating point error handling, knock yourself out. It's not going to be trivial, though. It's heavily embedded in the ufunc machinery. -- 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 rwrii at charter.net Wed May 24 18:24:47 2006 From: rwrii at charter.net (rwr) Date: 24 May 2006 15:24:47 -0700 Subject: Compiling Python from Sources In-Reply-To: <1148509057.542733.217230@i39g2000cwa.googlegroups.com> References: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> <1148509057.542733.217230@i39g2000cwa.googlegroups.com> Message-ID: <1148509487.448417.294690@j33g2000cwa.googlegroups.com> This file contains any messages produced by compilers while running configure, to aid debugging if configure makes a mistake. It was created by python configure 2.3, which was generated by GNU Autoconf 2.59. Invocation command line was $ ./configure ## --------- ## ## Platform. ## ## --------- ## hostname = blackbeauty uname -m = i686 uname -r = 2.6.12-10-386 uname -s = Linux uname -v = #1 Fri Apr 28 13:13:44 UTC 2006 /usr/bin/uname -p = unknown /bin/uname -X = unknown /bin/arch = i686 /usr/bin/arch -k = unknown /usr/convex/getsysinfo = unknown hostinfo = unknown /bin/machine = unknown /usr/bin/oslevel = unknown /bin/universe = unknown PATH: /usr/local/sbin PATH: /usr/local/bin PATH: /usr/sbin PATH: /usr/bin PATH: /sbin PATH: /bin PATH: /usr/bin/X11 ## ----------- ## ## Core tests. ## ## ----------- ## configure:1443: checking MACHDEP configure:1552: result: linux2 configure:1558: checking EXTRAPLATDIR configure:1573: result: configure:1592: checking for --without-gcc configure:1641: result: no configure:1647: checking for --with-cxx=<compiler> configure:1668: result: no configure:1687: checking for c++ configure:1716: result: no configure:1687: checking for g++ configure:1716: result: no configure:1687: checking for gcc configure:1703: found /usr/bin/gcc configure:1713: result: gcc configure:1753: checking for C++ compiler default output file name configure:1756: gcc conftest.cc >&5 gcc: installation problem, cannot exec 'cc1plus': No such file or directory configure:1759: $? = 1 configure: failed program was: | /* confdefs.h. */ | | #define _GNU_SOURCE 1 | #define _NETBSD_SOURCE 1 | #define __BSD_VISIBLE 1 | #define _BSD_TYPES 1 | #define _XOPEN_SOURCE 600 | #define _XOPEN_SOURCE_EXTENDED 1 | #define _POSIX_C_SOURCE 200112L | /* end confdefs.h. */ | | int | main () | { | | ; | return 0; | } configure:1798: error: C++ compiler cannot create executables See `config.log' for more details. ## ---------------- ## ## Cache variables. ## ## ---------------- ## ac_cv_env_CC_set= ac_cv_env_CC_value= ac_cv_env_CFLAGS_set= ac_cv_env_CFLAGS_value= ac_cv_env_CPPFLAGS_set= ac_cv_env_CPPFLAGS_value= ac_cv_env_CPP_set= ac_cv_env_CPP_value= ac_cv_env_LDFLAGS_set= ac_cv_env_LDFLAGS_value= ac_cv_env_build_alias_set= ac_cv_env_build_alias_value= ac_cv_env_host_alias_set= ac_cv_env_host_alias_value= ac_cv_env_target_alias_set= ac_cv_env_target_alias_value= ac_cv_prog_CXX=gcc ## ----------------- ## ## Output variables. ## ## ----------------- ## AR='' BASECFLAGS='' BLDLIBRARY='' BLDSHARED='' BUILDEXEEXT='' CC='' CCSHARED='' CFLAGS='' CFLAGSFORSHARED='' CONFIGURE_MACOSX_DEPLOYMENT_TARGET='' CONFIG_ARGS='' CPP='' CPPFLAGS='' CXX='gcc' DEFS='' DLINCLDIR='' DLLLIBRARY='' DYNLOADFILE='' ECHO_C='' ECHO_N='-n' ECHO_T='' EGREP='' EXEEXT='' EXTRAMACHDEPPATH='' EXTRAPLATDIR='' HAVE_GETHOSTBYNAME='' HAVE_GETHOSTBYNAME_R='' HAVE_GETHOSTBYNAME_R_3_ARG='' HAVE_GETHOSTBYNAME_R_5_ARG='' HAVE_GETHOSTBYNAME_R_6_ARG='' INSTALL_DATA='' INSTALL_PROGRAM='' INSTALL_SCRIPT='' INSTSONAME='' LDFLAGS='' LDLAST='' LDLIBRARY='' LDLIBRARYDIR='' LDSHARED='' LIBC='' LIBM='' LIBOBJS='' LIBRARY='' LIBS='' LIBTOOL_CRUFT='' LINKCC='' LINKFORSHARED='' LN='' LTLIBOBJS='' MACHDEP='linux2' MACHDEP_OBJS='' MAINOBJ='python.o' OBJEXT='' OPT='' PACKAGE_BUGREPORT='' PACKAGE_NAME='python' PACKAGE_STRING='python 2.3' PACKAGE_TARNAME='python' PACKAGE_VERSION='2.3' PATH_SEPARATOR=':' PYTHONFRAMEWORK='' PYTHONFRAMEWORKDIR='no-framework' PYTHONFRAMEWORKINSTALLDIR='' PYTHONFRAMEWORKPREFIX='' RANLIB='' RUNSHARED='' SGI_ABI='' SHELL='/bin/sh' SHLIBS='' SIGNAL_OBJS='' SO='' SOVERSION='1.0' SRCDIRS='' THREADHEADERS='' THREADOBJ='' TRUE='' UNICODE_OBJS='' USE_SIGNAL_MODULE='' USE_THREAD_MODULE='' VERSION='2.3' ac_ct_CC='' ac_ct_RANLIB='' bindir='${exec_prefix}/bin' build_alias='' datadir='${prefix}/share' exec_prefix='NONE' host_alias='' includedir='${prefix}/include' infodir='${prefix}/info' libdir='${exec_prefix}/lib' libexecdir='${exec_prefix}/libexec' localstatedir='${prefix}/var' mandir='${prefix}/man' oldincludedir='/usr/include' prefix='NONE' program_transform_name='s,x,x,' sbindir='${exec_prefix}/sbin' sharedstatedir='${prefix}/com' sysconfdir='${prefix}/etc' target_alias='' ## ----------- ## ## confdefs.h. ## ## ----------- ## #define _BSD_TYPES 1 #define _GNU_SOURCE 1 #define _NETBSD_SOURCE 1 #define _POSIX_C_SOURCE 200112L #define _XOPEN_SOURCE 600 #define _XOPEN_SOURCE_EXTENDED 1 #define __BSD_VISIBLE 1 configure: exit 77 From chris at kateandchris.net Sun May 7 21:26:14 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Sun, 7 May 2006 21:26:14 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1heyqxs.4dbeogv9o591N%aleaxit@yahoo.com> References: <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1146990071.634244.83380@i39g2000cwa.googlegroups.com> <871wv6b3y0.fsf@rpi.edu> <1146996240.867564.139490@u72g2000cwu.googlegroups.com> <1heyqxs.4dbeogv9o591N%aleaxit@yahoo.com> Message-ID: <20060508012614.GC20209@kateandchris.net> On Sun, May 07, 2006 at 11:57:55AM -0700, Alex Martelli wrote: > > [1] I'm considering introducing bugs or misdesigns that have to be > > fixed > > as part of training for the purposes of this discussion. Also the > > Actually, doing it _deliberately_ (on "training projects" for new people > just coming onboard) might be a good training technique; what you learn > by finding and fixing bugs nicely complements what you learn by studying > "good" example code. I do not know of this technique being widely used > in real-life training, either by firms or universities, but I'd love to > learn about counterexamples. > When I was learning C in university my professor made us fix broken programs. He did this specifically to teach us to understand how to read compiler warnings/errors and also how to debug software. The advantage of this in the tutorial setting was that the TAs knew what the error was and could assist the people in finding bugs in a controlled environment. When I later worked with people who did not go through this training I found many of them had no clue how to decipher the often cryptic C/C++ compiler warnings/errors (think Borland Turbo C or MS Visual C++, GCC is pretty good in comparison) or where to start looking for a bug (an affliction I do not possess). -Chris From jg307 at cam.ac.uk Mon May 1 06:25:21 2006 From: jg307 at cam.ac.uk (James Graham) Date: Mon, 01 May 2006 11:25:21 +0100 Subject: python and xulrunner In-Reply-To: <1146439953.280364.309130@e56g2000cwe.googlegroups.com> References: <1146439953.280364.309130@e56g2000cwe.googlegroups.com> Message-ID: <e34nmh$6ci$1@gemini.csx.cam.ac.uk> joe.hrbek at gmail.com wrote: > I've been trying to get xulrunner compiled with python (in windows) but > have been unsuccessful. I've been following this: > <http://michaelthornhill.blogspot.com/2005/07/giving-python-legs-with-...>. I haven't tried it, but do the instructions at developer.mozilla.org[1] help? XULrunner in particular has changed quite a bit recently. [1] http://developer.mozilla.org/en/docs/Building_PyXPCOM From robert.kern at gmail.com Sun May 21 21:40:03 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 May 2006 20:40:03 -0500 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1146164100.552822.280630@j33g2000cwa.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> Message-ID: <e4r4pl$711$1@sea.gmane.org> sturlamolden wrote: > sturlamolden wrote: > >>I don't think this is safe. MinGW links with msvcrt.dll whereas the >>main Python distribution links with msvcr71.dll (due to Visual C++ >>2003). > > In order to make minGW link with msvcr71.dll, edit the text file > > c:\mingw\lib\gcc\mingw32\3.2.4\specs > > and change "-lmsvcrt" to "-lmsvcr71". > > Now MinGW will link with the same CRT as Python 2.4. However, MinGW's header files are still written for MSVCRT.dll. IIRC, isupper() and friends use a jump table called _ctype in MSVCRT.dll which is missing in MSVCR71.dll. Some extensions will compile okay, some won't. The order in which distutils adds 'msvcr71' to the list of libraries seems to make sure that the PYD picks up free, malloc, printf, and other important functions from MSVCR71.dll first before trying MSVCRT.dll. However, C++ modules that use std::cout, for example, will crash. AFAICT, there is currently no general solution for compiling Python 2.4 extension modules with MinGW. There probably won't be one unless MinGW is patched to fully use MSVCR71.dll. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From __peter__ at web.de Tue May 16 12:39:37 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 May 2006 18:39:37 +0200 Subject: simultaneous reading and writing a textfile References: <4469f3d6$0$11070$9b4e6d93@newsread4.arcor-online.net> Message-ID: <e4cv4f$jcg$00$1@news.t-online.com> Marco Herrn wrote: > I have a text file with some lines in it. > Now I want to iterate over this file and exchange some lines with some > others. I tried this approach: > This should inspect the file and find the first line, that can't be > split into two parts (that means, which has only one word in it). > This line should be exchanged with a line that contains some more > info. > > Unfortunately (or how better python programmers than I am would say, > "of course") this doesn't work. The line is exchanged, but also some > more lines. > > Now how can I achieve, what I want? Really exchange one line with > another, regardless of their length. Is this possible? If this is not > possible, then what would be the best approach to do this? A file is exposed as a sequence of bytes. You can only exchange a string of bytes with the same number of (different) bytes. Inserting or removing bytes means you have to rewrite the file from the insertion/deletion point onwards. Usually you don't bother and just rewrite the whole file. > I do not want to read the whole file, exchange the line in memory and > then write the whole file. This would be quite slow with large files. Here's a simple approach that can deal with large files: # does not work on windows BLOCKSIZE = 2**20 infile = open(filename) os.unlink(filename) # rename if you want to play it safe outfile = open(filename, "w") lines = iter(infile.readline, "") # copy one line at a time for line in lines: parts = line.split(None, 1) if len(parts) == 1: outfile.write("%s %s\n" % (parts[0], mac)) break outfile.write(line) # after the insertion point proceed with larger steps for block in iter(lambda: infile.read(BLOCKSIZE), ""): outfile.write(block) infile.close() outfile.close() When this becomes too slow you should consider a database. Peter From mateus.justino at gmail.com Wed May 31 09:35:50 2006 From: mateus.justino at gmail.com (mateus) Date: 31 May 2006 06:35:50 -0700 Subject: Variable name has a typo, but code still works. Why? References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> Message-ID: <1149082550.699525.6660@h76g2000cwa.googlegroups.com> mateus wrote: > print "hello world" > > I have a nested loop where the outer loop iterates over key value pairs > of a dictionary and the inner loop iterates over a list each list of > which is a mapped value from the dictionary > > def showReport(self): > for dev, sessions in self.logger.items(): > for tree in session: > self.addTestItem(self, tree) > > What I don't understand is why this executes w/o any problems when > "sessions" was spelled as plural (sessionS) while later being spelled > in the singular (session). > > Is there some type of name resolution of local variables where Python > makes assumptions? A few specs that I forgot to mention. Version: python-2.4.2 OS: Librix (Gentoo (Linux)) From george.sakkis at gmail.com Fri May 19 17:24:54 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 19 May 2006 14:24:54 -0700 Subject: Feature request: sorting a list slice References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <mailman.5974.1148066477.27775.python-list@python.org> Message-ID: <1148073894.399040.242890@j73g2000cwa.googlegroups.com> Heiko Wundram wrote: > Am Donnerstag 18 Mai 2006 19:27 schrieb George Sakkis: > > It would be useful if list.sort() accepted two more optional > > parameters, start and stop, so that you can sort a slice in place. > > I've just submitted: > > http://sourceforge.net/tracker/index.php?func=detail&aid=1491804&group_id=5470&atid=305470 > > to the bugtracker, which extends the (start, stop) keyword arguments to > list.reverse() (which I've needed more than once). The patch updates the test > suite, documentation, list object, and sorted() builtin to accept (or > specify) the new arguments. > > Any comment/feedback would be appreciated. > > --- Heiko. This is great, thanks Heiko ! Any idea on the chances of being considered for inclusion in 2.5 ? George From __peter__ at web.de Sun May 28 07:47:55 2006 From: __peter__ at web.de (Peter Otten) Date: Sun, 28 May 2006 13:47:55 +0200 Subject: unexpected behaviour for python regexp: caret symbol almost useless? References: <1148815719.082410.313870@38g2000cwa.googlegroups.com> Message-ID: <e5c2gt$duk$03$1@news.t-online.com> conan wrote: > The thing is i should expected to have to put caret explicitly to tell > the regexp to match at the start of the line, something like: > r'^<widget class=".*" id="(.*)">' > however python regexp is taking care of that for me. This is not a > desired behaviour for what i know about regexp, but maybe i'm missing > something. You want search(), not match(). http://docs.python.org/lib/matching-searching.html Peter From python at hope.cz Fri May 12 02:50:58 2006 From: python at hope.cz (Lad) Date: 11 May 2006 23:50:58 -0700 Subject: Decorator Message-ID: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> I use Python 2.3. I have heard about decorators in Python 2.4. What is the decorator useful for? Thanks for reply L. From andrea at rediff.com Wed May 24 22:03:45 2006 From: andrea at rediff.com (andrea at rediff.com) Date: 25 May 2006 02:03:45 -0000 Subject: Final_Call_SummerSchool2006 Message-ID: <20060525020345.15191.qmail@rediff.com> REGISTER NOW FOR PATTERN RECOGNITION EVENTS THIS SUMMER, 2006 Early Registration Deadline for ISSPR is 25 MAY, 2006 _______________________ 4TH INTERNATIONAL SUMMER SCHOOL ON PATTERN RECOGNITION (ISSPR, 2006) 23-28 JULY, UK http://www.PatternRecognitionSchool.com NEW...EXTENDED Early Bird Deadline for Registration. New Deadline 25th May 2006! and payments can be made Online CALL FOR PARTICIPATION The 4th International Summer School on Pattern Recognition will be organised at the University of Plymouth, UK (23-28 July, 2006). The school programme is listed below. Please pass on this email to your interested colleagues and students. This is a great summer school which I would recommend for everyone to attend. DEADLINE: Register BEFORE 25 MAY, 2006 through the website to get a discount on the fee. Limited seats left! Speakers at the Summer School (ISSPR'2006) Dr. Sam Roberts Mathworks, UK (Introduction to Matlab) Prof. Wojtek Krzanowski University of Exeter, UK (Multivariate Statistics: Data Description) Dr. Mike Tipping, Microsoft Research, UK (Bayesian Pattern Recognition: Principles and Practice) Prof. Chris Bishop, Microsoft Research, UK (Latent Variables, Mixture Models and EM) Dr. Richard Everson, University of Exeter, UK (Dimensionality Reduction) Dr. Peter Tino University of Birmingham, UK (Probabilistic framework for model-based topographic map formation) Prof. Chris Williams, University of Edinburgh, UK (Neural Networks and Kernel Machines) Dr. Colin Campbell, University of Bristol, UK (Support Vector Machines and Kernel Methods: An Introduction and Review) Prof. John Shawe- Taylor, University of Southampton, UK (Kernel Based Methods) Dr. Steve Gunn, University of Southampton, UK (Matlab for Support Vector Machines) Prof. Mahesan Niranjan, University of Sheffield, UK (Classifier Performance Particle Filters for Tracking and Sequential Problems) Dr. Andrew Webb Qinetiq, UK (Decision TreesData Clustering) Prof. Xin Yao, University of Birmingham, UK (A Gentle Introduction to Evolutionary Computation; ATutorial on Evolutionary Multi-objective Optimisation) Dr. Richard Deardon, University of Birmingham, UK (Sequential Decision Making; Markov Chains Monte Carlo Methods) Dr. Jeremy Wyatt, University of Birmingham, UK (An Introduction to Reinforcement Learning) Dr. Ludmila Kuncheva, University of Wales, UK (Classifier Combination) Prof. Joseph Kittler, University of Surrey, UK (Feature Selection and Extraction) Prof. Sameer Singh, Loughborough University, UK (Multiresolution Pattern Recognition) Prof. Susan Craw, Robert Gordon University, UK (Case Based Reasoning) SUPPORTED BY: Microsoft, Springer, British Computer Society, and Mathworks. _______________________ IEEE CVPR CONFERENCE www.CVPR.org/2006 17-22 June, 2006 Registration Deadline is now 2nd of June, 2006 _______________________ 18th INTERNATIONAL CONFERENCE ON PATTERN RECOGNITION www.comp.hkbu.edu.hk/~icpr06 August 20-24, 2006 Early Bird Registration: 31 May, 2006 ______________________ Please see the event websites to get FULL information. Compiled by: Dr. Heather Mclleland From nospam at foo.com Wed May 10 13:57:38 2006 From: nospam at foo.com (jayessay) Date: 10 May 2006 13:57:38 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> Message-ID: <m3irodpxt9.fsf@rigel.goldenthreadtech.com> "Michele Simionato" <michele.simionato at gmail.com> writes: > jayessay wrote: > > "Michele Simionato" <michele.simionato at gmail.com> writes: > > > > > Ken Tilton wrote: > > > > I was not thinking about the thread issue (of which I know little). The > > > > big deal for Cells is the dynamic bit: > > > > > > > > (let ((*dependent* me)) > > > > (funcall (rule me) me)) > > > > > > > > Then if a rule forces another cell to recalculate itself, *dependent* > > > > gets rebound and (the fun part) reverts back to the original dependent > > > > as soon as the scope of the let is exited. > > > > > > Python 2.5 has a "with" statement (yes, the name is Lispish on purpose) > > > that could be used to implement this. See > > > http://www.python.org/dev/peps/pep-0343 > > > > You are mistaken. In particular, VAR doesn't have dynamic scope. > > > > I said "it could be used to implement this", and since in a previous > post on mine in this > same thread I have shown how to implement thread local variables in > Python I figured > out people would be able to do the exercise for themselves. I was saying that you are mistaken in that pep-0343 could be used to implement dynamically scoped variables. That stands. /Jon -- 'j' - a n t h o n y at romeo/charley/november com From miki.tebeka at gmail.com Thu May 18 04:01:08 2006 From: miki.tebeka at gmail.com (Miki) Date: 18 May 2006 01:01:08 -0700 Subject: how to make the program notify me explicitly In-Reply-To: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> References: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> Message-ID: <1147939268.619806.147550@j73g2000cwa.googlegroups.com> Hello hankssong, You can alert yourself in many methods: * Open a message dialog - Use Tkinter or other GUI toolkit (such as wxPython) * Write yourself an email - Use email + smtplib library modules * Provide an RSS feed and read it - Use HTTPServer library * Write yourself an instant message - see msnpy and other libraries HTH, Miki http://pythonwise.blogspot.com/ From phillipsd at cromwell.co.uk Thu May 4 10:26:52 2006 From: phillipsd at cromwell.co.uk (Fuzzydave) Date: 4 May 2006 07:26:52 -0700 Subject: Calling a Postgres Function using CGI written in Python In-Reply-To: <lpkh52932bitlqgq4ario34kpkc3lmlraq@4ax.com> References: <1146648602.110172.191810@g10g2000cwb.googlegroups.com> <e39tpn$ktk$1@ucsnew1.ncl.ac.uk> <1146650684.089258.316120@i39g2000cwa.googlegroups.com> <lpkh52932bitlqgq4ario34kpkc3lmlraq@4ax.com> Message-ID: <1146752811.903413.113160@v46g2000cwv.googlegroups.com> cheers :) thats what i wanted to know :) David From johnjsal at NOSPAMgmail.com Wed May 17 22:48:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 22:48:31 -0400 Subject: creating a new database with mysqldb In-Reply-To: <126nj7utnok7u6e@corp.supernews.com> References: <gcKag.2113$No6.46302@news.tufts.edu> <126nj7utnok7u6e@corp.supernews.com> Message-ID: <446be190$0$5024$c3e8da3@news.astraweb.com> Jesse Hager wrote: > In every MySQL library I have ever seen, the database parameter is > optional. You may either omit it or pass an empty string. It is just a > shortcut so the application does not need to send a "USE" command to > select the active database. I tried it without the db parameter, then sent a CREATE TABLE query, but I got this: OperationalError: (1046, 'No Database Selected') From koko9991 at compuserve.de Sat May 20 18:41:39 2006 From: koko9991 at compuserve.de (Konrad Koller) Date: Sat, 20 May 2006 22:41:39 GMT Subject: Does anybody know how to install PythonMagick? Message-ID: <446f97fe.776259062@News.Individual.DE> I downloaded PythonMagick-0.6.tar, but then...? The installation process is obviously not as usual and python.netcrewzackpymagick.html is totally outdated. Thanks From mensanator at aol.com Mon May 22 21:10:26 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 22 May 2006 18:10:26 -0700 Subject: module confict? gmpy and operator Message-ID: <1148346626.184199.125740@38g2000cwa.googlegroups.com> ## Holy Mother of Pearl! ## ## >>> for i in range(10): ## for j in range(10): ## print '%4d' % (gmpy.mpz(i)*gmpy.mpz(j)), ## print ## ## ## 0 0 0 0 0 0 0 0 0 0 ## 0 1 2 3 1 5 6 7 2 9 ## 0 2 4 6 2 10 12 14 4 18 ## 0 3 6 9 3 15 18 21 6 27 ## 0 1 2 3 1 5 6 7 2 9 ## 0 5 10 15 5 25 30 35 10 45 ## 0 6 12 18 6 30 36 42 12 54 ## 0 7 14 21 7 35 42 49 14 63 ## 0 2 4 6 2 10 12 14 4 18 ## 0 9 18 27 9 45 54 63 18 81 No wonder I couldn't figure out why my program wasn't working, gmpy mutiplication seems to have stopped working. My guess is that when I did import gmpy import random import operator I somehow messed up gmpy's mutilpication. I brought in operator because I needed to do NN = sum(map(operator.__mul__,X,C)) which seemed to work ok. It was later when I got 8 * 3 = 6 (the 3 was an mpz) that I got in trouble. So I got rid of operator and did def product(a,b): return a*b NN = sum(map(product,X,C)) which seems to work ok. Am I correct that there is a conflict with import gmpy import operator Would reversing the import order help or should I just avoid mixing them? From claird at lairds.us Mon May 29 11:47:53 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 29 May 2006 15:47:53 +0000 Subject: access serial port in python References: <1148678743.109181.259710@i40g2000cwc.googlegroups.com> Message-ID: <9mhrk3-jdd.ln1@lairds.us> In article <1148678743.109181.259710 at i40g2000cwc.googlegroups.com>, <vipulagarwal.in at gmail.com> wrote: >hi >i hav written a code in python to send an SMS from a nokia 3310 >connected to my PC... >i wanted to receive a msg on my PC. In order to do so, the PC must know >when it has to read data frm the serial port ...thus an interrupt must >be generated when the serial port receives data frm the phone .....HOW >CAN I DO THIS IN PYTHON ?? >can anyone help me with this INTERRUPT HANDLING thing in PYTHON ??? >thanks > Others have answered your direct question about serial handling. Let me urge you to consider investigation of the gnokii and gammu projects, which handle MANY other aspects of SMS handling that I doubt you want to burden you. There turns out to be depressingly more to SMS than you might imagine (although it's just possible that you already have almost everything you need for the 3310). When researching these two projects, note that gammu is already aware of Python, but rather unstably so, and that gnokii's Windows story has brightened immensely in the last month. From blue99 at interia.pl Thu May 11 10:30:34 2006 From: blue99 at interia.pl (blue99 at interia.pl) Date: 11 May 2006 07:30:34 -0700 Subject: python equivalent of the following program In-Reply-To: <FbWdnZazBY8Aqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> References: <FbWdnZazBY8Aqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> Message-ID: <1147357834.547167.298510@j73g2000cwa.googlegroups.com> AndyL wrote: > Hi, > > What would by a python equivalent of following shell program: > > #!/bin/sh > > prog1 > file1 & > prog2 > file2 & > > > As you see, I need to spawn a few processes and redirect stdout to some > files. For example : ------------------cut here------------------------------- #!/usr/bin/env python import os # 1-st variant os.system("prog1 > tmp1.txt &") # or 2-nd variant os.popen("prog1 > tmp2.txt &") ---------------cut here------------------------------------- Regards, Rob From fredrik at pythonware.com Wed May 31 06:14:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 31 May 2006 12:14:16 +0200 Subject: Best Python Editor References: <mailman.24508.1149069603.27774.python-list@python.org> <BHEEKBFODALGBHHKCOFFOECKCGAA.manojk@sasken.com> Message-ID: <e5jq9o$sp8$1@sea.gmane.org> "Manoj Kumar P" wrote: > Can anyone tell me a good python editor/IDE? vim! > It would be great if you can provide the download link also. google it! </F> From mizipzor at gmail.com Mon May 15 07:18:46 2006 From: mizipzor at gmail.com (Alex) Date: Mon, 15 May 2006 13:18:46 +0200 Subject: How to organise classes and modules Message-ID: <fad9f1a90605150418p56e02d59oda564a901de4fb4e@mail.gmail.com> Hi, this is my first mail to the list so please correct me if Ive done anything wrong. What Im trying to figure out is a good way to organise my code. One class per .py file is a system I like, keeps stuff apart. If I do that, I usually name the .py file to the same as the class in it. File: Foo.py *********************** class Foo: def __init__(self): pass def bar(self): print 'hello world' ************************ Now, in my other module, I want to include this class. I tried these two ways: >>> import Foo >>> Foo.Foo.bar() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead) Some unbound method error. Have I missunderstood something or am I on the right track here? I did this to, almost the same thing: >>> from Foo import Foo >>> Foo.bar() Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: unbound method bar() must be called with Foo instance as first argument (got nothing instead) One thing that I tried that worked ok was this: >>> import Foo >>> instance=Foo.Foo() >>> instance.bar() hello world But in my opinion, this is very ugly. Especially if the class names are long, like my module/class TileDataBaseManager. But is this the "right" way in python? Another (ugly) way that Ive considered is the following. Break it out of the class, save the functions in a file alone, import the file and treat it like a class: File: Foo2.py *********************** def bar(self): print 'hello world' ************************ >>> import Foo2 >>> Foo2.bar() hello world Very clean from the outside. I would like something like this. But, here, I loose the __init__ function. I have to call it manually that is, which s not good. Also, maybe the biggest drawback, its no longer in a class. Maybe its not that important in python but from what Ive learned (in c++) object orientation is something to strive for. So, to sum it up, I have one class in one file, both with the same name. How do I store/import/handle it in a nice, clean and python-like manner? Thank you very much in advance. / Alex From wrongbad at gmail.com Sat May 6 21:31:13 2006 From: wrongbad at gmail.com (I V) Date: Sat, 06 May 2006 18:31:13 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> <87bquaskap.fsf@rpi.edu> Message-ID: <pan.2006.05.07.01.31.10.972127@gmail.com> On Sat, 06 May 2006 21:19:58 -0400, Bill Atkins wrote: > There are also cases where a function is so trivial that the simplest > way to describe it is with its source code, where giving it a name and > putting it at the beginning of a function is just distracting and > time-consuming. E.g.: > > (remove-if (lambda (name) > (find #\- name :test #'char=)) > list-of-names) > > What's the sense of giving that function its own name? It's much > clearer to simply write it in place. Yes, it's _possible_ to use > named functions, but in this case its functionality is so simple that > it's clearer to simply type it in place. Why is this expressiveness a > bad thing, aside from its power to wreck an indentation-significant > language? Well, you can do that with python's current, non-indentation-significance-wrecking, lambda syntax, so I don't think that's a particularly persuasive example. Note also that the only limitation python has on where you can define functions is that you can't define them inside expressions (they have to be statements), so you could define a named function right before the call to remove-if, which removes some of the advantage you get from the lambda (that is, the function definition is not very far from when it's used). Actually, I think the limitation on python that is operative here is not significant whitespace, but the distinction between statements and expressions. (crossposts trimmed) From alf at merlin.fayauffre.org Thu May 4 10:57:18 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Thu, 4 May 2006 14:57:18 +0000 (UTC) Subject: Unicode code has no method float() ? References: <mn.23f87d659ec61f57.43626@yahoo.fr.invalid> Message-ID: <slrne5k5i4.acl.alf@merlin.fayauffre.org> Le 04-05-2006, Rony <bucodi at yahoo.fr.invalid> nous disait: > How can I get the value of a Unicode object ? > > When I do myobject.float() I get the error message that it doesn't have > a float() attribute Try to use the float builtin function, as in: float(myobject) instead of a method. -- Alexandre Fayolle 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 fredrik at pythonware.com Thu May 25 17:32:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 May 2006 23:32:13 +0200 Subject: Multi-dimensional list initialization trouble In-Reply-To: <1148592170.709560.307030@j55g2000cwa.googlegroups.com> References: <1148592170.709560.307030@j55g2000cwa.googlegroups.com> Message-ID: <e557oo$u1$2@sea.gmane.org> jonkje at gmail.com wrote: > Hello I found this very strange; is it a bug, is it a "feature", am I > being naughty or what? the repeat operator (*) creates a new list with references to the same inner objects, so you end up with a list containing multiple references to the same list. also see: http://pyfaq.infogami.com/how-do-i-create-a-multidimensional-list </F> From keesvanschaik at gmail.com Wed May 24 22:25:46 2006 From: keesvanschaik at gmail.com (KvS) Date: 24 May 2006 19:25:46 -0700 Subject: wxPython: changing entries of a HtmlListBox Message-ID: <1148523945.995343.228070@j55g2000cwa.googlegroups.com> Hi all, a question wrt renewing the entries in a wx.HtmlListBox, I don't understand how to do it. I have some global variable containing a list: gl_NAWList=["Bet","Dik"] then I create a subclass of wx.HtmlListBox as described in the wxPython demo: class MyHtmlListBox(wx.HtmlListBox): def OnGetItem(self, n): return gl_NAWList[n] and this works well after putting an instance called "hlb" of it in a frame etc. Now I want to change the entries in hlb and I thought I should simply be able to call the following function (bound to a button click, "self" refers to the frame on which both teh button and hlb are placed): def klik(self, event): gl_NAWList=["Boy","Boy"] #print "gl_NAWList = ",gl_NAWList self.hlb.SetItemCount(len(gl_NAWList)) self.Refresh() but that doesn't seem to be working in the sense that the entries are still "Bet" and "Dik". Also if I change this code to completely destroy teh existing hlb and create a new instance it's not working. As will probably be painfully clear ;) I just started playing a bit around with wxPython. Any hints would be very much appreciated! Thanks, Kees From softwindow at gmail.com Fri May 19 04:12:32 2006 From: softwindow at gmail.com (softwindow) Date: 19 May 2006 01:12:32 -0700 Subject: Getting URL's In-Reply-To: <7Hdbg.41202$Qq.40549@tornado.texas.rr.com> References: <1148019975.277742.253400@y43g2000cwc.googlegroups.com> <7Hdbg.41202$Qq.40549@tornado.texas.rr.com> Message-ID: <1148026352.141338.89290@j73g2000cwa.googlegroups.com> it is difficult to get all URL's in a page you can use sgmllib module to parse html files can get the standard href . From roy at panix.com Sun May 7 22:59:33 2006 From: roy at panix.com (Roy Smith) Date: Sun, 07 May 2006 22:59:33 -0400 Subject: evaluation of > References: <87bqu99qv7.fsf@localhost.localdomain> Message-ID: <roy-E17BCB.22593307052006@reader1.panix.com> In article <87bqu99qv7.fsf at localhost.localdomain>, Gary Wessle <phddas at yahoo.com> wrote: > Hi > > what does the i > a in this code mean. because the code below is > giving False for all the iteration. isn't suppose to evaluate each > value of i to the whole list? thanks > > a = range(8) > i = 0 > while i < 11: > print i > a > i = i + 1 > > False > False > False > False > False > False > False > False > False > False > False > > > thanks I'm not sure what you're expecting to happen, or what you're trying to do, but comparing an integer to a list is (almost) meaningless. See http://docs.python.org/ref/comparisons.html, where it says, "objects of different types always compare unequal, and are ordered consistently but arbitrarily". From onurb at xiludom.gro Fri May 12 07:49:02 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 13:49:02 +0200 Subject: deleting texts between patterns In-Reply-To: <mailman.5617.1147422623.27775.python-list@python.org> References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <mailman.5617.1147422623.27775.python-list@python.org> Message-ID: <44647691$0$306$626a54ce@news.free.fr> Fredrik Lundh wrote: (snip) > to print to a file instead of stdout, just replace the print line with a f.write call. > Or redirect stdout to a file when calling the program !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sybrenUSE at YOURthirdtower.com.imagination Thu May 11 05:53:08 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 11 May 2006 11:53:08 +0200 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <slrne63ahp.dac.apardon@rcpc42.vub.ac.be> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> <1147333696.789718.189050@v46g2000cwv.googlegroups.com> Message-ID: <slrne662c4.9qk.sybrenUSE@schuimige.stuvel.eu> yairchu at gmail.com enlightened us with: > this is how I think it should be done with multi-line lambdas: > > def arg_range(inf, sup, f): > return lambda(arg): > if inf <= arg <= sup: > return f(arg) > else: > raise ValueError This is going to be fun to debug if anything goes wrong. Ever seen such a traceback? > and instead of > @arg_range(5, 17) > def f(arg): > return arg*2 > > you do: > f = arg_range(5, 17, lambda(arg)): > return arg*2 A function decorator is supposed to add something to a function. The syntax that sticks the closest to that of defining a function seems most Pythonic to me. I can already foresee that I'll have a tougher time explaining your lambda-based "decorators", than the current decorators, to people learning Python. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From dongdonglove8 at hotmail.com Thu May 25 09:49:00 2006 From: dongdonglove8 at hotmail.com (python) Date: 25 May 2006 06:49:00 -0700 Subject: how to clear up a List in python? Message-ID: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> I have new a list , when it hava large number of values, I wonna to delete all the values in it,how to do? And, if a list have 801 values, I want to get its values index from 300 to 400, could use list1[300:400],are right me? From luismgz at gmail.com Thu May 25 19:30:52 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 25 May 2006 16:30:52 -0700 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> Message-ID: <1148599852.040381.290030@y43g2000cwc.googlegroups.com> Free online resources for learning Python: To get started, I strongly suggest Josh Cogliati's "Non-Programmers Tutorial for Python" ( http://honors.montana.edu/~jjc/easytut/easytut/ ). I learned programming with this little tutorial, which is a very good introduction. After that, you could check these ones: "A Byte of Python" by Swaroop CH "Learning to Program" by Alan Gauld (http://www.freenetpages.co.uk/hp/alan.gauld/) The last one is specially good to grasp the basics of object oriented programming. It has a very good example of a banking application that was a real eye opener to me. Good luck, LUIS From tdw at tdw.net Sat May 6 08:31:40 2006 From: tdw at tdw.net (Tim Williams) Date: Sat, 6 May 2006 13:31:40 +0100 Subject: combined files together In-Reply-To: <B40996220.463.62104.1@mx-extra.net> References: <B40996220.463.62104.1@mx-extra.net> Message-ID: <9afea2ac0605060531s36852493od02b4b8da20872c3@mail.gmail.com> On 06 May 2006 16:41:45 +1000, Gary Wessle <phddas at yahoo.com> wrote: > is there a module to do things like concatenate all files in a given > directory into a big file, where all the files have the same data > formate? If you want to combine text files file1 and file2 into a combined file1 >>> txt = open('file2.txt', 'r').read() >>> open('file1.txt', 'a').write(txt) or less easy to read >>> open('file1.txt', 'a').write( open('file2.txt', 'r').read() ) If you want to combine file1 and file2 into a brand new new file3 >>> txt1 = open('file1.txt', 'r').read() >>> txt2 = open('file2.txt', 'r').read() if you have a trailing newline on file1 use >>> txt1 = open('file1.txt', 'r').read()[:-1] then something like >>> open('file3.txt', 'w').write(txt1) >>> open('file3.txt', 'a').write(txt2) or maybe >>> open('file3.txt', 'w').write(txt1+txt2) If you already have file3 and want to keep its contents, change the writes above ( 'w' ) to appends ( 'a' ) HTH :) From greg at cosc.canterbury.ac.nz Sat May 27 05:31:26 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 27 May 2006 21:31:26 +1200 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1148598181.033043.28820@38g2000cwa.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> <1148251275.211468.221460@g10g2000cwb.googlegroups.com> <mailman.6055.1148262320.27775.python-list@python.org> <1148344720.139905.282630@y43g2000cwc.googlegroups.com> <mailman.6093.1148349627.27775.python-list@python.org> <1148598181.033043.28820@38g2000cwa.googlegroups.com> Message-ID: <4dqkiaF1blqapU1@individual.net> Jim Lewis wrote: > Thanks but now another problem :-( > Examples in books show importing a global so why does below give: > AttributeError: 'module' object has no attribute 'globalvar' > > primes.pyx: > from run import globalvar > def prime(int kmax): > result = [run.globalvar] > ... > > run.py: > from primes import prime > globalvar = 999 > while True: > print prime (10) The first thing run does is import primes, which immediately imports run and tries to access the name globalvar in it, before it has been defined. There are ways of fixing that, but for various reasons it's usually a bad idea for subsidiary modules to try to import things from the main module of a program. It would be better to move globalvar into a third module. Even better again would probably be not to use a global at all, but pass it in as a parameter to the prime() function. -- Greg From sybrenUSE at YOURthirdtower.com.imagination Mon May 8 09:18:55 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 8 May 2006 15:18:55 +0200 Subject: Web framework comparison video References: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> Message-ID: <slrne5uh9v.3lr.sybrenUSE@schuimige.stuvel.eu> Iain King enlightened us with: > http://compoundthinking.com/blog/index.php/2006/03/10/framework-comparison-video/ > > Thought this might be interesting to y'all. (I can't watch it 'cos > I'm at work, so any comments about it would be appreciated :) It's a nice video, I really enjoyed it. Even though the website you linked says it's a 60 minute vid, it's only just over 30 minutes. So far, I've created my own web framework - mostly because I didn't see a simple to use framework that could do what I wanted it to do: properly handle client-side caching. Looking at the Plone website, it looks like they do support that. Perhaps I'll look into Plone for my site in the future ;-) For now, I'm very happy with my own framework (http://www.unrealtower.org/engine) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From larry.bates at websafe.com Fri May 5 13:51:13 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 05 May 2006 12:51:13 -0500 Subject: to thine own SELF be true... In-Reply-To: <cEL6g.73268$H71.7968@newssvr13.news.prodigy.com> References: <cEL6g.73268$H71.7968@newssvr13.news.prodigy.com> Message-ID: <445B9091.40605@websafe.com> Mark Harrison wrote: > Is there a way to do something equivalent to "import * from self"? > Perhaps I'm doing something wrong, but I'm having a headache > when dealing with class instance data, forgetting to always > put the "self." prefix > > For example, in my brain I'm thinking: > > optc,args=getopt.getopt(args,cmdopts[cmd][0], cmdopts[cmd][1]) > > but I'm having to type: > > self.optc,self.args=getopt.getopt(self.args,self.cmdopts[self.cmd][0], > self.cmdopts[self.cmd][1]) > > > Is there a way to get rid of those the "self." references, or is this > just something I need to get my brain to accept? > > Many TIA, > Mark > The ones without "self." in front of them will die when you leave the method (e.g. sort of like local variables in a function). If you want them to be instance attributes the "self." is required. Now if you use them a lot you can create shortcuts inside the method. The lack of "self." is how python knows if this is a temporary local variable (lasts until the method is exited) or an instance attribute that lasts across methods. Hopefully this will help. -Larry From unmiserable at gmail.com Sun May 21 19:41:32 2006 From: unmiserable at gmail.com (Petter Haggholm) Date: 21 May 2006 16:41:32 -0700 Subject: Python source sensitive to PyObject_HEAD layout? Message-ID: <1148254892.114251.45770@j55g2000cwa.googlegroups.com> For academic reasons, I'm hacking on the Python source trying to add some new capabilities. At present, I'm making minor changes mostly to familiarise myself with the code and gain awareness of what issues I may encounter, with the result that I encountered a fairly strange one (to me, anyway). As I wanted to add new fields to all Python objects, it seemed to make the most sense to add them to PyObject_HEAD. When I added an int field to the end of PyObject_HEAD, however, the make process failed (see below). This was on a Pentium-M running GCC 3.4.6 under Gentoo Linux. I switched to my other computer, and Athlon 64 running GCC 4.1.0 under Gentoo Linux, and it compiled; I dismissed the earlier failure as an irritating but fixed GCC bug, and went on---until I added another int field and ran into a failure at exactly the same place. The error looks fairly uninformative, as such: /bin/sh: line 1: 6926 Segmentation fault CC='gcc -pthread' LDSHARED='gcc -pthread -shared' OPT='-DNDEBUG -g -O3 -Wall -Wstrict-prototypes' ./python -E ./setup.py build make: *** [sharedmods] Error 139 I can supply more information if desired (I ran a GDB backtrace), but it really didn't tell me very much. None of the functions on the stack were ones I had modified, so the only factor is the presence of that second additional field in PyObject_HEAD (I can make it build by simply commenting out that field and its initialiser in PyObject_HEAD_INIT). My question is therefore a vague, nebulous, open, and at least mildly desperate one: What is the problem? The only notion that occurs to me is that some part of the Python source is somehow upset by alignment issues (or padding of some sort); if so then I have no clue where that might be. If not, then I have no idea what's causing the errors at all. Any help, thoughts, or advice would be vastly appreciated. -- Petter Haggholm From jmdeschamps at gmail.com Tue May 16 17:13:54 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 16 May 2006 14:13:54 -0700 Subject: still don't get unicode and xml - help! Message-ID: <1147814034.864384.243350@38g2000cwa.googlegroups.com> I have to work with XML data containing accented characters (ISO-8859-1 encoding) Using ElementTree, the only way i found to get the text attribute of a node was to encode it individually, if you want. It doubles the amount of time to process :-( i surely doing this wrong... What is the good way to do it? I didn't see an obvious way to do it this time... Thanks ############## My XML Encoding Program #! c:/python24/python -u # -*- coding: iso-8859-1 -*- import elementtree.ElementTree as ET import time def getMyXML(accentedTest): filename="pagemembre.xml" tree = ET.parse(filename) elem = tree.getroot() if accentedTest: for i in elem: f= i.text.encode("iso-8859-1") #encode pour lire les accents else: for i in elem: f= i.text print f def writeMyXML(myrange,accentedTest): root = ET.Element("mondoc") if accentedTest: for i in range(myrange): ch=ET.SubElement(root, "monchapitre") ch.text="bel ?t? et je serai la pr?mi?re de la classe" else: for i in range(myrange): ch=ET.SubElement(root, "monchapitre") ch.text="bel ete et je serai la premiere de la classe" tree = ET.ElementTree(root) tree.write("pageMembre.xml","iso-8859-1") if __name__ =="__main__": accentedTest=int(raw_input("set 1 for accented test, 0 for ascii")) print "First, writing" t1=time.clock() writeMyXML(20000,accentedTest) t2=time.clock() print "Now, reading" t3=time.clock() getMyXML(accentedTest) t4=time.clock() print "accents are",accentedTest,"writing=",str(t2-t1),"reading=",str(t4-t3) s=raw_input("END XML TEST") ######### End XML Encoding Program From nobody at 127.0.0.1 Thu May 18 12:58:34 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 16:58:34 GMT Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <mailman.5846.1147904183.27775.python-list@python.org> <446c3055$0$5298$626a54ce@news.free.fr> Message-ID: <_I1bg.73209$_S7.35669@newssvr14.news.prodigy.com> Christophe wrote: > No, it's really easy : a simple precoomit hook which will refuse any .py > file with the \t char in it and it's done ;) $ echo \t t Why would you wan_ _o remove all _ee charac_ers? Isn'_ _ha_ a li__le awkward? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From qrczak at knm.org.pl Sat May 13 06:39:05 2006 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Sat, 13 May 2006 12:39:05 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> <m38xp7p7el.fsf@rigel.goldenthreadtech.com> <yfs3bffuqj7.fsf@oc.ex.ac.uk> <r559g.16$Id.14@fe10.lga> Message-ID: <87k68qjjjq.fsf@qrnik.zagroda> Ken Tilton <kentilton at gmail.com> writes: > I think the point is that, with the variable actually being just > a string and with dedicated new explicit functions required as > "accessors", well, you could hack that up in any language with > dictionaries. It is the beginnings of an interpreter, not Python > itself even feigning special behavior. If the semantics and the global structure of the code is right, only you don't like the local concrete syntax, then the complaint is at most as justified as complaints against Lisp parentheses. -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From deets at nospam.web.de Mon May 1 13:17:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 May 2006 19:17:56 +0200 Subject: list*list References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com><4bmotsF126gicU1@uni-berlin.de> <m%q5g.11251$Un3.9202@trnddc05> <mailman.5185.1146503294.27775.python-list@python.org> Message-ID: <4bmu66F12877gU1@uni-berlin.de> > and for short sequences, it doesn't really matter much in the 2.X series. > it's definitely not "bad style" to use range instead of xrange for a ten > to, say, 1000 item loop. You and me are aware of that - but I figured the OP wasn't. And just the other day somebody on de.c.l.py wondered about the memory consumption of his little script that contained a range(9000000) which he used for a loop. And as in the case of a "for in" one can't even access the list produced by range() and thus there is virtually no difference to xrange, I'd consider it a code smell if it's used there - why creating an object you don't use when you can't even get a reference to it? Diez From edcjones at comcast.net Fri May 19 15:14:25 2006 From: edcjones at comcast.net (Edward C. Jones) Date: Fri, 19 May 2006 15:14:25 -0400 Subject: Modifying a variable in a non-global outer scope? Message-ID: <-tKdnSU7GKuPhPPZRVn-rg@comcast.com> #! /usr/bin/env python """ When I run the following program I get the error message: UnboundLocalError: local variable 'x' referenced before assignment Can "inner" change the value of a variable defined in "outer"? Where is this explained in the docs? """ def outer(): def inner(): x = x + 1 x = 3 inner() print x outer() From keesvanschaik at gmail.com Wed May 17 13:06:58 2006 From: keesvanschaik at gmail.com (KvS) Date: 17 May 2006 10:06:58 -0700 Subject: Beautiful parse joy - Oh what fun In-Reply-To: <1147813885.337318.141070@g10g2000cwb.googlegroups.com> References: <1147813885.337318.141070@g10g2000cwb.googlegroups.com> Message-ID: <1147885618.136733.98650@j33g2000cwa.googlegroups.com> Maybe a more robust approach is just to walk through the string counting the (increments) of the number of brackets "<" and ">" as you know that all the relevant text occurs right after a ">" has occured that sets your counter to 0 (meaning you're at the "highest level"). There's no relevant text if the next character is again a "<". From jcb at iteris.com Wed May 10 18:23:08 2006 From: jcb at iteris.com (Metalone) Date: 10 May 2006 15:23:08 -0700 Subject: interactive shell -- reload definitions? In-Reply-To: <mailman.5559.1147283149.27775.python-list@python.org> References: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> <4461d67a$0$3551$626a54ce@news.free.fr> <1147280438.193621.66340@u72g2000cwu.googlegroups.com> <mailman.5559.1147283149.27775.python-list@python.org> Message-ID: <1147299788.708658.267910@g10g2000cwb.googlegroups.com> Thanks everybody. From my_email_is_posted_on_my_website at munged.invalid Fri May 19 21:44:10 2006 From: my_email_is_posted_on_my_website at munged.invalid (Roedy Green) Date: Sat, 20 May 2006 01:44:10 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> Message-ID: <s0ts62dff4c8mamdo8c4rqflqlqkoimsm8@4ax.com> On Mon, 15 May 2006 02:44:54 GMT, Eli Gottlieb <eligottlieb at gmail.com> wrote, quoted or indirectly quoted someone who said : >Actually, spaces are better for indenting code. Agreed. All it takes is one programmer to use a different tab expansion convention to screw up a project. Spaces are unambiguous. Ideally though you should run code through a beautifier before checkin to avoid false deltas with people manually formatting code slightly differently. -- Canadian Mind Products, Roedy Green. http://mindprod.com Java custom programming, consulting and coaching. From aleax at mac.com Wed May 10 11:02:39 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 10 May 2006 08:02:39 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <joadnUiUIdmNsP3ZnZ2dnUVZ_tKdnZ2d@speakeasy.net> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> <87ac9r1tem.fsf@snobis.de> <1hf26zk.1uqniari93h7fN%aleax@mac.com> <1ZadnfwKY5_XG_zZRVn-sg@speakeasy.net> Message-ID: <1hf42xy.1ue69gu1is75oxN%aleax@mac.com> M Jared Finder <jared at hpalace.com> wrote: ... > Your reasoning, taken to the extreme, implies that an assembly language, > by virtue of having the fewest constructs, is the best designed language Except that the major premise is faulty! Try e.g. <http://docs.sun.com/app/docs/doc/817-5477/6mkuavhrf#hic> and count the number of distinct instructions -- general purpose, floating point, SIMD, MMX, SSE, SSE2, OS support... there's *hundreds*, each with its own rules as to what operand(s) are allowed plus variants such as (e.g.) cmovbe{w,l,q} for "conditional move if below or equal" for word, long, quadword (no byte variant) -- but e.g cmpxchg{b,w,l,q} DOES have a byte variant too, while setbe for "set if below or equal" ONLY has a byte variant, etc, etc -- endless memorization;-). When you set up your strawman arguments, try to have at least ONE of the premises appear sensible, will you?-) I never argued against keeping languages at a high level, of course (that's why your so utterly unfounded argument would be a "strawman" even if it WAS better founded;-). > prone, code. I think the advantages of anonymous functions: ... > e) making the language simpler to implement Adding one construct (e.g., in Python, having both def and lambda with vast semantic overlap, rather than just one) cannot "make the language simpler to implement" -- no doubt this kind of "reasoning" (?) is what ended up making the instruction-set architecture of the dominant families of CPUs so bizarre, intricate, and abstruse!-) Alex From jg.campbell.ng at gmail.com Tue May 30 04:56:37 2006 From: jg.campbell.ng at gmail.com (jg.campbell.ng at gmail.com) Date: 30 May 2006 01:56:37 -0700 Subject: Beginner Python OpenGL difficulties In-Reply-To: <mailman.6322.1148939452.27775.python-list@python.org> References: <1148833256.751748.291270@j55g2000cwa.googlegroups.com> <mailman.6322.1148939452.27775.python-list@python.org> Message-ID: <1148979397.531861.316140@y43g2000cwc.googlegroups.com> Mike C. Fletcher wrote: > jg.campbell.ng at gmail.com wrote: > > I'm beginning learning Python and OpenGL in Python. > > [...] > > ImportError: No module named OpenGL.GLUT > > > > jc at localhost~/etc/python>$ echo $PYTHONPATH > > /usr/lib/python2.2/site-packages/OpenGL > > > You should already have site-packages in your PythonPath. You want the > directory *above* OpenGL in the path, not OpenGL itself. Yes, tried that: $ echo $PYTHONPATH /usr/lib/python2.2/site-packages/ and no improvement. Should there be a file or directory named GLUT* in /usr/lib/python2.2/site-packages/OpenGL/ ? All I can see are GL, GLU and GLX directories. I'm unsure why > you're running a Python 2.2 instance on a modern Linux. jc at localhost~/etc/python>$ python2 Python 2.4.2 (#1, Feb 12 2006, 03:59:46) [GCC 4.1.0 20060210 (Red Hat 4.1.0-0.24)] on linux2 The OpenGL stuff was from an RPM that I sound on the web. Many thanks, Jon C. From rrrn at yahoo.com Sat May 6 11:55:52 2006 From: rrrn at yahoo.com (Butternut squash) Date: Sat, 06 May 2006 15:55:52 GMT Subject: Job opportunity in France References: <mn.2a417d6545f2820b.43626@yahoo.fr.invalid> Message-ID: <cG37g.53396$eR6.17008@bgtnsc04-news.ops.worldnet.att.net> Rony Steelandt wrote: > We have a vacancy for a python programmer for a 6 months assignement. > > If interested, please visit www.bucodi.com > > And don't worry we speak english :) > > R_ > seriously, a job opportunity in France?? I heard that the unemployment rate is not doing too well. From johnjsal at NOSPAMgmail.com Mon May 15 16:14:29 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 20:14:29 GMT Subject: Aggregate funuctions broken in MySQLdb? In-Reply-To: <lorenzo-CCA9BC.14511415052006@hedley.thethurmans.com> References: <lorenzo-33D2D1.20511013052006@hedley.internal.thethurmans.com> <1147623011.319336.11820@v46g2000cwv.googlegroups.com> <lorenzo-CCA9BC.14511415052006@hedley.thethurmans.com> Message-ID: <Fi5ag.2101$No6.46182@news.tufts.edu> Lorenzo Thurman wrote: > Thanks, that was my problem. Can you point me to some documentation on > MySQLdb? I've been googling to get answers and that obviously has not > been working. I've been looking into this too lately, and finding thorough docs for it is hard. Have you seen these yet: http://sourceforge.net/docman/?group_id=22307 From timr at probo.com Fri May 26 01:39:33 2006 From: timr at probo.com (Tim Roberts) Date: Fri, 26 May 2006 05:39:33 GMT Subject: can't figure out error: module has no attribute... References: <1148392551.118437.255680@i39g2000cwa.googlegroups.com> <44732ee1$1_3@newspeer2.tds.net> <1148453323.005374.160470@i40g2000cwc.googlegroups.com> Message-ID: <325d7298nkt83tjiscmlit1bogji3hubf6@4ax.com> "Chris_147" <chris.van.bael at gmail.com> wrote: >Thanks for the reply. > >you are indeed right, they were included from different places. >from C:\Python24\Lib and D:\mydir > >But the strange thing is: >anywhere on C: the file from C:\Python24\Lib was included. >in D:\mydir the one from that directory >BUT: anywhere else on D: apparantly the one from D:\mydir was included >?! >I would expect it would come from c:\Python24\Lib. ** PLEASE ** do not copy your OWN files into c:\Python24\Lib. That directory is intended to contain ONLY the Python standard library. Modules that are part of a single project should be in a common directory for that project. Modules that are of general interest to you for multiple projects should be in \Python24\Lib\site-packages. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From ilias at lazaridis.com Thu May 4 15:14:18 2006 From: ilias at lazaridis.com (lazaridis_com) Date: 4 May 2006 12:14:18 -0700 Subject: [HOST] - Flexible Project Hosting with Python (similar to Assembla Breakout) Message-ID: <1146770058.757060.305770@g10g2000cwb.googlegroups.com> For a larger scale project, a collaboration infrastructure and toolset should be selected. More information about the overall project: http://lazaridis.com/pj The actually active system is a Dedicated Server (with Trac & SVN). A Project Host Candidate which comes close to the needed system is Assembla ( http://assembla.com ), but currently it does not comply fully to the Basic Requirements. You can find the actual selection case here: http://case.lazaridis.com/host Are there any other Python-Centric Project Hosts available (which could comply to the stated requirements)? Any suggestions are very welcome. From python.list at tim.thechases.com Thu May 11 11:58:12 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 11 May 2006 10:58:12 -0500 Subject: find all index positions In-Reply-To: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> Message-ID: <44635F14.2040409@tim.thechases.com> > say i have string like this > astring = 'abcd efgd 1234 fsdf gfds abcde 1234' > if i want to find which postion is 1234, how can i > achieve this...? i want to use index() but it only give > me the first occurence. I want to know the positions of > both "1234" Well, I'm not sure how efficient it is, but the following seemed to do it for me: >>> a = 'abcd efgd 1234 fsdf gfds abcde 1234' >>> thing = '1234' >>> offsets = [i for i in range(len(a)) if a.startswith(thing, i)] >>> print offsets [10, 31] HTH, -tkc From paddy3118 at netscape.net Wed May 3 02:15:22 2006 From: paddy3118 at netscape.net (Paddy) Date: 2 May 2006 23:15:22 -0700 Subject: Recommended data structure for newbie References: <1146626916.066395.206540@y43g2000cwc.googlegroups.com> Message-ID: <1146636922.070700.295820@j73g2000cwa.googlegroups.com> Hi Matthew, >From your example, it is hard to work out what character or character string is a separator, and what string needs to become a separate word when seen in the original file. In the example below you need to learn about regular expressions. the split is based on the two RE's held in variables 'separators' and 'otherwords'. the first is used to split a line the second is used to extract sub-words. The output is printed in two formats that could be piped to a file for later re-use; as a python list, then as space separated lines of words. The csv module could be used to create a csv file for reading into spreadsheets and databases. No doubt an XML formatted output is just as straight-forward, (but XML is not, yet, my cup of tea). The prog: word_up.py: import re import pprint instring = '''gee fre asd[234 ger dsf asd[243 gwer af as.:^25a ''' separators = r'''[ \t\r\f\v]+''' otherwords = r'''(?x) (.*) ( \[ | \^ ) (.*) ''' def word_up(instring, separators, otherwords): """ for less confusing names substitute line for cameo, and w for jockstrap in the function body :-) # doctest >>> from pprint import pprint as pp >>> i = 'gee fre asd[234\nger dsf asd[243\ngwer af as.:^25a\n' >>> print i gee fre asd[234 ger dsf asd[243 gwer af as.:^25a >>> s = r'''[ \t\r\f\v]+''' >>> o = '(?x)\n (.*)\n (\n \\[\n | \\^\n )\n (.*)\n' >>> print o (?x) (.*) ( \[ | \^ ) (.*) >>> pp(word_up(i, s, o)) [['gee', 'fre', 'asd', '[', '234'], ['ger', 'dsf', 'asd', '[', '243'], ['gwer', 'af', 'as.:', '^', '25a']] >>> """ line_words = [] for cameo in instring.splitlines(): # some words are separated by separator chars word_split = re.split(separators, cameo) # extract separate sub_words word_extracts = [] for word in word_split: matched = re.match(otherwords, word) if matched: word_extracts += [jockstrap for jockstrap in matched.groups() if jockstrap] else: word_extracts.append(word) line_words.append(word_extracts) return line_words line_words = word_up(instring, separators, otherwords) print '\n# Python format extracted words as list of lists' pprint.pprint(line_words) print '\n# Unix friendly space separated words' for l in line_words: for w in l: print w, print -- Paddy From john at castleamber.com Thu May 18 19:19:54 2006 From: john at castleamber.com (John Bokma) Date: 18 May 2006 23:19:54 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147989047.427015.193270@j55g2000cwa.googlegroups.com> Message-ID: <Xns97C7BA7A8889castleamber@130.133.1.4> "akameswaran at gmail.com" <akameswaran at gmail.com> wrote: > THe interest, on my part, is more academic than practical. I find > data, particularly "dirty" data very fascinating Me less, maybe that's why I originally had gg kill filed... I prefer quotes. -- 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 Avizoa at gmail.com Tue May 9 10:59:13 2006 From: Avizoa at gmail.com (Avizoa at gmail.com) Date: 9 May 2006 07:59:13 -0700 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <1147186752.097502.59240@y43g2000cwc.googlegroups.com> No lockup for me after 28 hours. Of course, I don't have HT. It's a dual Opteron system with WinXP. From webraviteja at gmail.com Wed May 24 02:38:40 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 23 May 2006 23:38:40 -0700 Subject: Access C++, Java APIs from Python.. In-Reply-To: <mailman.6138.1148451960.27775.python-list@python.org> References: <mailman.23185.1148370303.27774.python-list@python.org> <mailman.6138.1148451960.27775.python-list@python.org> Message-ID: <1148452720.723648.219130@j33g2000cwa.googlegroups.com> > I'm new to python. > I would like to know whether is it possible to access Java/C++ APIs from > python. > I have two applications written in Java and API, I wanted to call the APIs > of these applications from Python. > I'm developing web-based application using Zope. CPython can access Java through JPype (http://jpype.sourceforge.net/). C++ API can be wrapped/accessed with SWIG, SIP, Boost, Weave or PyCXX (Google for each). From deets at nospam.web.de Fri May 26 07:03:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 26 May 2006 13:03:56 +0200 Subject: list comprehensions put non-names into namespaces! In-Reply-To: <1148602348.917853.107210@g10g2000cwb.googlegroups.com> References: <1148577813.000229.225330@y43g2000cwc.googlegroups.com> <mailman.6206.1148586159.27775.python-list@python.org> <1148602348.917853.107210@g10g2000cwb.googlegroups.com> Message-ID: <4do5ksF1b7826U1@uni-berlin.de> Ben Cartwright schrieb: > skip at pobox.com wrote: >> Lonnie> List comprehensions appear to store their temporary result in a >> Lonnie> variable named "_[1]" (or presumably "_[2]", "_[3]" etc for >> Lonnie> nested comprehensions) >> >> Known issue. Fixed in generator comprehensions. Dunno about plans to fix >> it in list comprehensions. I believe at some point in the future they may >> just go away or become syntactic sugar for a gen comp wrapped in a list() >> call. > > The latter, starting in Python 3.0. It won't be fixed before Python > 3.0 because it has the potential to break existing 2.x code. From PEP > 289: That is a different beast. Lonnie is after the temporary list variables created, with otherwise illegal names in python. Diez From Serge.Orlov at gmail.com Thu May 18 21:44:31 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 18 May 2006 18:44:31 -0700 Subject: newb: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> Message-ID: <1148003071.529525.236760@j33g2000cwa.googlegroups.com> manstey wrote: > Hi, > > Is there a clever way to see if two strings of the same length vary by > only one character, and what the character is in both strings. > > E.g. str1=yaqtil str2=yaqtel > > they differ at str1[4] and the difference is ('i','e') > > But if there was str1=yiqtol and str2=yaqtel, I am not interested. > > can anyone suggest a simple way to do this? > > My next problem is, I have a list of 300,000+ words and I want to find > every pair of such strings. I thought I would first sort on length of > string, but how do I iterate through the following: > > str1 > str2 > str3 > str4 > str5 > > so that I compare str1 & str2, str1 & str3, str 1 & str4, str1 & str5, > str2 & str3, str3 & str4, str3 & str5, str4 & str5. If your strings are pretty short you can do it like this even without sorting by length first: def fuzzy_keys(s): for pos in range(len(s)): yield s[0:pos]+chr(0)+s[pos+1:] def fuzzy_insert(d, s): for fuzzy_key in fuzzy_keys(s): if fuzzy_key in d: strings = d[fuzzy_key] if type(strings) is list: strings += s else: d[fuzzy_key] = [strings, s] else: d[fuzzy_key] = s def gather_fuzzy_matches(d): for strings in d.itervalues(): if type(strings) is list: yield strings acc = {} fuzzy_insert(acc, "yaqtel") fuzzy_insert(acc, "yaqtil") fuzzy_insert(acc, "oaqtil") print list(gather_fuzzy_matches(acc)) prints [['yaqtil', 'oaqtil'], ['yaqtel', 'yaqtil']] From rupole at hotmail.com Sat May 13 05:35:43 2006 From: rupole at hotmail.com (Roger Upole) Date: Sat, 13 May 2006 05:35:43 -0400 Subject: Is it possible to set the date/time of a directory in windows with Python? If so how? References: <1147509953.594320.172890@d71g2000cwd.googlegroups.com> Message-ID: <1147512711_6767@sp6iad.superfeed.net> "ToddLMorgan" <ToddLMorgan at gmail.com> wrote in message news:1147509953.594320.172890 at d71g2000cwd.googlegroups.com... > I'm trying to set any of the dates (create, modification, access) of a > directory under windows with python. > > I'm trying to do this as I'm trying to write a unittest for a directory > cleaning script I'm writing (ie I need the test to set the create/mod > time for some of the directories so that I can be sure that the script > works properly - as it picks dirs based upon their age). > > I've tried using the utime( path, times). That doesn't work as the doco > states > "Whether a directory can be given for path depends on whether the > operating system implements directories as files (for example, Windows > does not)." > > So that doesn't work. > > So I tried mark hammonds win32 extensions with something like this > > import win32file, win32con, pywintypes > filehandle = win32file.CreateFile(file, > win32file.GENERIC_WRITE,win32file.FILE_SHARE_WRITE, > None,win32con.OPEN_ALWAYS, 0, None) > nowWin32=pywintypes.Time(theTime) > win32file.SetFileTime(filehandle, nowWin32, nowWin32, nowWin32) > > which works fine for files but fails with "Access Denied" when I invoke > the CreateFile with a directory. This seems to occur no matter the > combination of READ or WRITE I choose for the parameters. > > So does anyone have any useful suggestions (other than not using > windows)? > > I've thought of a couple of reallly nasty solutions: > 1. Temporarily alter the underlying system clock back to the required > time and create the directory then resetting it back again afterwards. > 2. Create the required directory in some form of virtual filesystem - > eg Zip file, rar archive, tar etc. Then extract it to the real > filesystem and hope windows honors the timestamps (untested at this > point). > > None of those is particularly appealing. > > Thanks for listening. To create a handle to a directory, you have to use FILE_FLAG_BACK_SEMANTICS. Roger From roy at panix.com Mon May 8 12:14:01 2006 From: roy at panix.com (Roy Smith) Date: Mon, 8 May 2006 16:14:01 +0000 (UTC) Subject: which is better, string concatentation or substitution? References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <IWH7g.2053$No6.45672@news.tufts.edu> <e3nnv0$jbm$1@reader1.panix.com> <aMJ7g.2058$No6.45704@news.tufts.edu> Message-ID: <e3nqo9$45o$1@reader1.panix.com> In article <aMJ7g.2058$No6.45704 at news.tufts.edu>, John Salerno <johnjsal at NOSPAMgmail.com> wrote: >Roy Smith wrote: > >> OK, here's a quick tutorial to "big-oh" notation. > >Wow, that was fantastic (and interesting)! Did you just write that? That >should be saved somewhere! Mind if I post it on my website? (don't >worry, no one goes there anyway) :) Sure, feel free. Once you post something on usenet, anybody can pretty much do anything they want with it. I do prefer if people don't use what I write to line birdcages with, but have no control over that either :-) From deets at nospam.web.de Mon May 29 10:57:35 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 29 May 2006 16:57:35 +0200 Subject: omniorbpy: problems sending float values References: <1148914432.514658.216050@38g2000cwa.googlegroups.com> Message-ID: <4e0ghvF1calmlU1@uni-berlin.de> Juergen wrote: > hi, > > I've got a problem sending floating point values to an corba server. > With other datatyes like short or string it works fine. <snip/> It works fine for me with floats, too. You'd better ask this on the omniorb ML, and don't forget to give some more details on the python & omniorb & OS versions you're using. Diez From me at privacy.net Fri May 19 19:47:21 2006 From: me at privacy.net (Dan Sommers) Date: Fri, 19 May 2006 19:47:21 -0400 Subject: Python sqlite and regex. References: <mailman.5942.1148042842.27775.python-list@python.org> <1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> <hunbg.46845$CH2.29994@tornado.texas.rr.com> <m2u07lq2s5.fsf@unique.fqdn> <Wtobg.46855$CH2.42030@tornado.texas.rr.com> Message-ID: <m2psi9pofq.fsf@unique.fqdn> On Fri, 19 May 2006 18:52:38 GMT, "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote: > "Dan Sommers" <me at privacy.net> wrote in message > news:m2u07lq2s5.fsf at unique.fqdn... >> Doesn't SQL already have lightweight wildcards? >> >> SELECT somefield FROM sometable WHERE someotherfield LIKE '%foo%' > Yes it does - '%' is like '*', and '_' is like '?'. But it is rare > for application users to be familiar with these. In my experience, > users are more likely to have seen '*' and '?'. > The reason I keep citing end/application users, as opposed to > developers ... Users, application users, end users, etc., vary over time. Since this is c.l.p., though, we'd better just agree to disagree over which user(s) may or may not be familiar with which (or any) wildcard conventions. > ... the case where the user has filled in some kind of wildcard search > field, to be passed to SQL in a query. Woe to the app designer who > figures that users want to enter a regular expression in such a field > ... Woe to the app designer who fails to target the app to the users, make it clear to the users what is expected in any given field, and accept "constructive criticism" from unhappy users. ;-) Knowing your users is one of the most important factors in software design. > ... '%' and '_' wildcards a little better, but frankly, I think '*' > and '?' looks more like a wildcards than '%' and '_'. Ah, but then you're not an end user, are you? ;-) Regards, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From justin.frost at gmail.com Mon May 1 01:35:26 2006 From: justin.frost at gmail.com (MakaMaka) Date: 30 Apr 2006 22:35:26 -0700 Subject: SPE / winpdb problem Message-ID: <1146461726.790649.318060@u72g2000cwu.googlegroups.com> Hi All, I'm having a problem with Stani's Python Editor (SPE) that I'm hoping somebody has run into before. If I create a simple hello world program: print "hello" and try and run it in winpdb via the SPE command ALT-F9, the program does not launch and the following results (It's at the bottom): Spe Warning: Spe was developped on wxPython v2.6.1.0., but v2.6.3.2. was found. If you experience any problems please install wxPython v2.6.1.0. SPE v0.8.2.a (c)2003-2005 www.stani.be If spe fails to start: - type "python SPE.py --debug > debug.txt 2>&1" at the command prompt (or if you use tcsh: "python SPE.py --debug >& debug.txt") - send debug.txt with some info to spe.stani.be[at]gmail.com Spe Warning: Spe was developped on wxPython v2.6.1.0., but v2.6.3.2. was found. If you experience any problems please install wxPython v2.6.1.0. Blender support disabled (run SPE inside Blender to enable). Encrypted debugging disabled. If you prefer encrypted debugging, install the "Python Cryptography Toolkit" from http://www.amk.ca/python/code/crypto Launching application... Traceback (most recent call last): File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", line 3313, in ? ret = main() File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", line 3303, in main return rpdb2.main(StartClient) File "C:\Python24\Lib\site-packages\_spe\plugins\winpdb\rpdb2.py", line 7221, in main StartClient_func(_args, fAttach, fchdir, pwd, fAllowUnencrypted, fRemote, ho st) File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", line 3293, in StartClient app = CWinpdbApp(sm, fchdir, command_line, fAttach, fAllowUnencrypted) File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", line 1528, in __init__ wx.App.__init__(self, redirect = False) File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", line 7700, i n __init__ self._BootstrapApp() File "C:\Python24\Lib\site-packages\wx-2.6-msw-ansi\wx\_core.py", line 7352, i n _BootstrapApp return _core_.PyApp__BootstrapApp(*args, **kwargs) File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", line 1533, in OnInit self.m_settings.load_settings() File "C:\Python24\lib\site-packages\_spe\plugins\winpdb\winpdb.py", line 638, in load_settings d = cPickle.load(f) EOFError Any ideas what is going on? Thanks! From jstroud at ucla.edu Sat May 27 16:00:53 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 27 May 2006 13:00:53 -0700 Subject: Using a package like PyInstaller In-Reply-To: <FyYdg.2216$As2.860@trnddc02> References: <FyYdg.2216$As2.860@trnddc02> Message-ID: <e5ab5l$tkm$1@daisy.noc.ucla.edu> LittlePython wrote: > Is it possible when using packages like PyInstaller to create an .exe for > distribution that parts of the package can bleed out and be left on a system > when the .exe is executed? > > Thx > > Look at innosetup. -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From chad at imvu.com Wed May 10 09:56:19 2006 From: chad at imvu.com (Chad Austin) Date: Wed, 10 May 2006 06:56:19 -0700 Subject: clearerr called on NULL FILE* ? In-Reply-To: <4457CE4C.9000800@imvu.com> References: <4457CE4C.9000800@imvu.com> Message-ID: <4461F103.8050203@imvu.com> Sorry to respond to myself; I wanted to give an update on this crash. It turns out it's a race condition with multiple threads accessing the same Python file object! http://sourceforge.net/tracker/index.php?func=detail&aid=595601&group_id=5470&atid=105470 Python-dev thread at http://mail.python.org/pipermail/python-dev/2003-June/036537.html I wrote about the experience at http://aegisknight.livejournal.com/128191.html. I agree that our program was incorrect to be writing to a log on one thread while it rotated them on another, but it'd be nice to get an exception that unambiguously shows what's going on rather than having random crashes reported in the field. Chad Chad Austin wrote: > Hi all, > > My first post to the list. :) I'm debugging one of our application > crashes, and I thought maybe one of you has seen something similar > before. Our application is mostly Python, with some work being done in > a native C++ module. Anyway, I'm getting a memory access violation at > the following stack: > > > CRASHING THREAD > EXCEPTION POINTERS: 0x0012e424 > ExceptionRecord: 0x0012e518 > ExceptionCode: 0xc0000005 EXCEPTION_ACCESS_VIOLATION > ExceptionFlags: 0x00000000 > ExceptionAddress: 0x7c901010 > NumberParameters: 2 > ExceptionInformation[0]: 0x00000000 > ExceptionInformation[1]: 0x00000034 > ExceptionRecord: 0x00000000 > > THREAD ID: 10b0 frame count: 4 > PYTHON23!0x000baa00 - PyFile_Type > PYTHON23!0x0003ac27 - PyFile_SetEncoding > MSVCRT!0x00030a06 - clearerr > ntdll!0x00001010 - RtlEnterCriticalSection > > > Here's my understanding: something is getting called on a PyFileObject > where f_fp is NULL, and clearerr in the multithreaded runtime tries to > enter an invalid critical section. It looks like PyFile_SetEncoding in > the stack, but I can't figure out how in the Python source how > SetEncoding calls clearerr. > > Based on the timing of the crashes, I also think it might have something > to do with log rollovers in RotatingFileHandler. > > Has anyone run into something similar? I don't expect anyone to spend a > lot of time on this, but if there are any quick tips, they would be > greatly appreciated... > > We're using Python 2.3.5 and Visual C++ 6. > > -- > Chad Austin > http://imvu.com/technology > From reply.in.the.newsgroup at my.address.is.invalid Mon May 8 21:00:50 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 09 May 2006 03:00:50 +0200 Subject: ascii to latin1 References: <445fdc6c$0$15793$14726298@news.sunsite.dk> Message-ID: <g9qv521tu8ptlnp25palofun0u0kd21os8@4ax.com> Luis P. Mendes: >I'm developing a django based intranet web server that has a search page. > >Data contained in the database is mixed. Some of the words are >accented, some are not but they should be. This is because the >collection of data began a long time ago when ascii was the only way to go. > >The problem is users have to search more than once for some word, >because the searched word can be or not be accented. If we consider >that some expressions can have several letters that can be accented, the >search effort is too much. I guess the best solution is to index all data in ASCII. That is, convert a field to ASCII (from accented character to its unaccented constituent) and index that. Then, on a search, you also need to unaccent the search phrase, and match it against the asciified index. -- Ren? Pijlman From david at david-steuber.com Mon May 15 00:35:42 2006 From: david at david-steuber.com (David Steuber) Date: 15 May 2006 00:35:42 -0400 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> Message-ID: <87hd3rq50h.fsf@david-steuber.com> Spaces work better. Hitting the TAB key in my Emacs will auto-indent the current line. Only spaces will be used for fill. The worst thing you can do is mix the two regardless of how you feel about tab vs space. The next step in evil is to give tab actual significance like in make. Xah Lee is getting better at trolling. He might fill up Google's storage. -- http://www.david-steuber.com/ 1998 Subaru Impreza Outback Sport 2006 Honda 599 Hornet (CB600F) x 2 Crash & Slider The lithobraker. Zero distance stops at any speed. From dale at riverhall.nospam.co.uk Tue May 23 08:10:52 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Tue, 23 May 2006 13:10:52 +0100 Subject: XML/HTML Encoding problem References: <Emkcg.80446$fj3.40225@fe48.usenetserver.com> <Xns97CBA6FCDF128duncanbooth@127.0.0.1> Message-ID: <hZCcg.117866$2b1.61016@fe32.usenetserver.com> Thanks, Duncan. That did the trick. If you're EuroPythoning, I'll buy you a drink. Cheers. Duncan Booth wrote: > First up, when I repeat what you did I don't get the same output. toxml() > without an encoding argument produces a unicode string, and no encoding > attribute in the <?xml ...?> > > toxml() only takes a single encoding argument, so unfortunately there > isn't any way to tell it what to do for unicode characters which are not > supported in the encoding you are using. However, if you then encode the > unicode output to ascii with entity escapes, I think you should be alright > (unless I've missed something): > You lose the encoding at the top of the output, but since the output is > entirely ascii I don't think that matters. -- Dale Strickland-Clark Riverhall Systems www.riverhall.co.uk From scott.daniels at acm.org Mon May 15 12:09:13 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 15 May 2006 09:09:13 -0700 Subject: [ANN] PyYAML-3.02: YAML parser and emitter for Python In-Reply-To: <mailman.5704.1147693647.27775.python-list@python.org> References: <mailman.5704.1147693647.27775.python-list@python.org> Message-ID: <4468a3be$1@nntp0.pdx.net> Kirill Simonov wrote: > ======================== > Announcing PyYAML-3.02 > ======================== > > A new bug-fix release of PyYAML is now available: > > http://pyyaml.org/wiki/PyYAML Another fix provided for Python 2.5 and friends. -- -Scott David Daniels scott.daniels at acm.org From me+python at modelnine.org Wed May 17 11:53:17 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 17 May 2006 17:53:17 +0200 Subject: Pyparsing: Grammar Suggestion In-Reply-To: <3d00e6dc0605170824q6abe919dq49e72970baf46244@mail.gmail.com> References: <3d00e6dc0605170824q6abe919dq49e72970baf46244@mail.gmail.com> Message-ID: <200605171753.17467.me+python@modelnine.org> Am Mittwoch 17 Mai 2006 17:24 schrieb Khoa Nguyen: > Any suggestions? If you're not limited to PyParsing, pyrr.ltk/ptk might be appropriate for you here (if you're used to bison/flex). The following file implements a small sample lexer/parser which does exactly what you need. pyrr.ltk (the lexing toolkit) is stable, but pyrr.ptk isn't yet, but it's nevertheless available under: http://hg.modelnine.org/hg/pyrr as a mercurial repository. I'd advise you to take the version from the repository, if you're interested in it, as my packaged versions always had quirks, which the current head of the repository doesn't, AFAICT. Anyway, the following implements the parser/lexer for you: >>> from pyrr.ltk import LexerBase, IgnoreMatch from pyrr.ptk import ParserBase class SampleLexer(LexerBase): def f(self,match,data): r""" f1 [10]-> /f1/ f2 [10]-> /f2/ f3 [10]-> /f3/ f4 [10]-> /f4/ f5 [10]-> /f5/ f6 [10]-> /f6/ Create your specific matches for each of the fs here... """ return data def fid(self,match,data): r""" fid -> ri/[a-z_][a-z0-9_]*/ Match a record identifier. """ return data def end_of_record(self,match,data): r""" EOR -> /END_OF_RECORD/ Your end of record marker... """ def operators(self,match,data): r""" nl -> e/\n/ c -> /,/ eq -> /=/ Newline is something that I have inserted here... """ def ws(self,match,data): r""" ws -> r/\s+/ Ignore all whitespace that occurs somewhere in the input. """ raise IgnoreMatch class SampleParser(ParserBase): __start__ = "ifile" def ifile(self,data): """ ifile -> record+ """ return dict(data) def record(self,fid,eq,f1,c1,f2,c2,f3,c3,f4,c4,f5,c5,f6,eor,nl): """ record -> /fid/ /eq/ /f1/? /c/ /f2/? /c/ /f3/? /c/ /f4/? /c/ /f5/? /c/ /f6/? /EOR/ /nl/ """ return (fid,(f1,f2,f3,f4,f5,f6)) data = r"""recmark = f1,f2,,f4,f5,f6 END_OF_RECORD recmark2 = f1,f2,f3,f4,,f6 END_OF_RECORD """ print SampleParser.parse(SampleLexer(data)) >>> HTH! --- Heiko. From mslists at 256bit.org Thu May 11 14:51:18 2006 From: mslists at 256bit.org (Marc Schoechlin) Date: 11 May 2006 18:51:18 GMT Subject: websphere6 ND soap access Message-ID: <slrne671t6.j5r.mslists@256bit.org> Hi ! Websphere ND Application server offers access to it`s internal management api via jython using the wsadmin frontend. Does anybody know if there is a possibility to use real python (including it`s standard api) to automate websphere administration tasks ? The "wsasmin" console connects to the deploymentmanager over SOAP - so the following questions are very interesting: - Is the complete websphere administration-api accessible over SOAP - Which visible components of the functionality of wsadmin are implemented in the wsadmin-program ? Best regards Marc Schoechlin -- I prefer non-proprietary document-exchange. http://sector7g.wurzel6.de/pdfcreator/ http://www.prooo-box.org/ Contact me via jabber: ms at 256bit.org From george.sakkis at gmail.com Wed May 17 17:01:40 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 17 May 2006 14:01:40 -0700 Subject: Question about exausted iterators References: <446b48e2$0$5293$626a54ce@news.free.fr> Message-ID: <1147899700.845737.294570@g10g2000cwb.googlegroups.com> Christophe wrote: > Is there a good reason why when you try to take an element from an > already exausted iterator, it throws StopIteration instead of some other > exception ? I've lost quite some times already because I was using a lot > of iterators and I forgot that that specific function parameter was one. > > Exemple : > > >>> def f(i): > ... print list(i) > ... print list(i) > ... > >>> f(iter(range(2))) > [0, 1] > [] Whether trying to iterate over an exhausted iterator should be treated differently is appication dependent. In most cases, you don't really care to distinguish between an iterator that yields no elements and an iterator that did yield some elements before but it has been exhausted. If you do care, you can roll your own iterator wrapper: class ExhaustibleIterator(object): def __init__(self, iterable): self._next = getattr(iterable, 'next', iter(iterable).next) self._exhausted = False def next(self): if self._exhausted: raise ExhaustedIteratorException() try: return self._next() except StopIteration: self._exhausted = True raise def __iter__(self): return self class ExhaustedIteratorException(Exception): pass And then in your function: def f(i): i = ExhaustibleIterator(i) print list(i) print list(i) HTH, George From grante at visi.com Sat May 27 01:30:49 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 05:30:49 -0000 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com> <mailman.6267.1148697006.27775.python-list@python.org> Message-ID: <127fp09e6v176a5@corp.supernews.com> On 2006-05-27, Travis E. Oliphant <oliphant.travis at ieee.org> wrote: >> I need to interpolate an irregularly spaced set of sampled >> points: Given a set of x,y,z points, I need to interpolate z >> values for a much finer x,y grid. > > How many x,y,z points do you have? I've got about 700 data points. They're arranged irregularly along arcs arranged in sort of truncated fan-shape. > Did you try the fitpack function bisplrep in scipy? Not recently. I spent a month or so wrestling with bisplrep a while back, but was unable to get stable results (either with real world data or with the example from the tutorial): http://www.visi.com/~grante/scipy/interpolate.html http://www.scipy.net/pipermail/scipy-user/2004-December/003921.html I switched to a trianguation scheme shortly after that posting, and haven't tired bisplrep since then. -- Grant Edwards grante Yow! I call it a "SARDINE at ON WHEAT"! visi.com From __peter__ at web.de Tue May 9 16:27:06 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 09 May 2006 22:27:06 +0200 Subject: ascii to latin1 References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <mailman.5504.1147171291.27775.python-list@python.org> <4460831e$0$15794$14726298@news.sunsite.dk> <1147180014.685659.325830@i39g2000cwa.googlegroups.com> <4460dec2$0$15791$14726298@news.sunsite.dk> Message-ID: <e3qtrb$ldp$01$1@news.t-online.com> Luis P. Mendes wrote: > The script converted the ?? from the first line, but not the ? from the > second one. Still in *, I also don't get a list as [115448,DA??O] but a > [u'115448,DA??O'] element, which doesn't suit my needs. > > Would you mind telling me what should I change? Sometimes you are faster if you put the gloves off. Just write the translation table with the desired substitute for every non-ascii character in the latin1 charset by hand and be done. Cyril Kyree From grflanagan at yahoo.co.uk Sat May 13 01:10:59 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 12 May 2006 22:10:59 -0700 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <jz09g.2091$No6.46071@news.tufts.edu> References: <jz09g.2091$No6.46071@news.tufts.edu> Message-ID: <1147497059.393293.182010@j73g2000cwa.googlegroups.com> John Salerno wrote: > Ok, I've been browsing through the MySQLdb docs, and I *think* I know > the kind of code I need to write (connect, cursor, manipulate data, > commmit, etc. -- although I probably need to get more familiar with > actual SQL commands too), but here's my problem: I don't know where [...] > > So without actually giving you some code and tracebacks, is there any > general advice about how to set up these scripts? Also, is there any > better documentation than this: > http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307 > > It doesn't seem too thorough, and it also doesn't cover actual SQL > queries that you'd have to pass to the query method. Maybe I will just > have to find that information in a MySQL tutorial. > > Thanks. Interactive SQL tutorial: http://www.sqlcourse.com/ ; http://sqlcourse2.com/ Indirectly helpful maybe: http://initd.org/tracker/pysqlite/wiki/basicintro HTH Gerard From duncan.booth at invalid.invalid Thu May 25 03:46:44 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 25 May 2006 07:46:44 GMT Subject: NEWB: how to convert a string to dict (dictionary) References: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> <mailman.6141.1148453462.27775.python-list@python.org> <1148514268.491292.276670@38g2000cwa.googlegroups.com> Message-ID: <Xns97CE594BEEEAduncanbooth@127.0.0.1> manstey wrote: > Thanks. I didn't know eval could do that. But why do many posts say > they want a solution that doesn't use eval? > Because it is a sledgehammer: capable of driving in nails or breaking rocks. Most times people say 'I want to use eval' they are using it to drive nails and something like 'getattr' would be more appropriate. If you have a string which could have come from an untrusted source it can be dangerous. Quite easily you can construct strings which will execute arbitrary Python code. e.g. If you are running an application on a web server and part or all of the string has come from another system (which you don't necessarily trust), then using eval could potentially do anything. Don't give people you don't know a sledgehammer to use on your code. From diffuser78 at gmail.com Thu May 4 11:08:30 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 4 May 2006 08:08:30 -0700 Subject: Wake on LAN and Shutdown for Windows and Linux In-Reply-To: <dgkg525esp0f8np5aif7o99kcgba5e0d6d@4ax.com> References: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> <dgkg525esp0f8np5aif7o99kcgba5e0d6d@4ax.com> Message-ID: <1146755310.550240.303960@u72g2000cwu.googlegroups.com> Any help is appreciated From bignose+hates-spam at benfinney.id.au Wed May 17 02:20:14 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 16:20:14 +1000 Subject: A Unicode problem -HELP References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <446AAFE6.4080008@v.loewis.de> <1147843788.969853.159420@g10g2000cwb.googlegroups.com> Message-ID: <87psidnpep.fsf@benfinney.id.au> "manstey" <manstey at csu.edu.au> writes: > 1. Here is my input data file, line 2: > gn1:1,1.2 R")$I73YT R")$IYT at ncfsa Your program is reading this using the 'utf-8' encoding. When it does so, all the characters you show above will be read in happily as you see them (so long as you view them with the 'utf-8' encoding), and converted to Unicode characters representing the same thing. Do you have any other information that might indicate this is *not* utf-8 encoded data? > 2. Here is my output data file, line 2: > u'gn', u'1', u'1', u'1', u'2', u'-', u'R")$I73YT', u'R")$IYT', > u'R")$IYT', u'@', u'ncfsa', u'nc', '', '', '', u'f', u's', u'a', '', > '', '', '', '', '', '', '', u'B.:R")$I^YT', u'b.:cv)cv^yc', '\xc9\x94' As you can see, reading the file with 'utf-8' encoding and writing it out again as 'utf-8' encoding, the characters (as you posted them in the message) have been faithfully preserved by Unicode processing and encoding. Bear in mind that when you present the "input data file, line 2" to us, your message is itself encoded using a particular character encoding. (In the case of the message where you wrote the above, it's 'utf-8'.) This means we may or may not be seeing the exact same bytes you see in the input file; we're seeing characters in the encoding you used to post the message. You need to know what encoding was used when the data in that file was written. You can then read the file using that encoding, and convert the characters to unicode for processing inside your program. When you write them out again, you can choose the 'utf-8' encoding as you have done. Have you read this excellent article on understanding the programming implications of character sets and Unicode? "The Absolute Minimum Every Software Developer Absolutely, Positively Must Know About Unicode and Character Sets (No Excuses!)" <URL:http://www.joelonsoftware.com/articles/Unicode.html> -- \ "I'd like to see a nude opera, because when they hit those high | `\ notes, I bet you can really see it in those genitals." -- Jack | _o__) Handey | Ben Finney From nospamjynyl at yahoo.co.nz Wed May 10 14:54:14 2006 From: nospamjynyl at yahoo.co.nz (Peter) Date: Thu, 11 May 2006 06:54:14 +1200 Subject: data entry tool References: <445f038f@news.maxnet.co.nz><4c8gkoF14mu9cU1@uni-berlin.de> <4461a499@news.maxnet.co.nz> <1147267750.833367.234180@v46g2000cwv.googlegroups.com> Message-ID: <446236d5@news.maxnet.co.nz> Serge Orlov wrote: > Peter wrote: >> A webapp isn't feasible as most of the users are on dial up (this is in >> New Zealand and broadband isn't available for lots of people). > > I don't see connection here, why it's not feasible? Our volunteers won't sit on their dial up connection for hours at a time. Many dial up plans charge an hourly rate after the first so many hours per month, plus it means you can't use your phone line to receive or make phone calls. > You can do it using for example Tkinter > <http://wiki.python.org/moin/TkInter> that comes with python > distribution for windows. thanks - I'll take a look. > Keep in mind that standalone application for windows will be about 2Mb. Wow - why so big for such a simple tool? 2MB sounds like a LOT of coding. Peter From carsten at uniqsys.com Sat May 13 17:10:01 2006 From: carsten at uniqsys.com (Carsten Haese) Date: Sat, 13 May 2006 17:10:01 -0400 Subject: Setting up InformixDb In-Reply-To: <C08B990E.5807%noemail@junk.com> References: <C08B990E.5807%noemail@junk.com> Message-ID: <20060513205025.M10476@uniqsys.com> On Sat, 13 May 2006 14:09:19 -0400, The Shaffer s wrote > I have an informix database on a unix machine which I want to > access. I downloaded InformixDb-2.2 and managed to get it built and > installed and it works fine with python. > > My problem is I want to access the same database from a PC remotely. > Yes, I already have informix setup and configured on the unix > machine to accept connections remotely. And, I can connect to it > fine from an ODBC interface to Excel and Access. > > But, to build the informix module requires the INFORMIXDIR > environment variable set to it which I don't believe I can set to a > remote machine. > > So, how can I get this module built without having an informix > installed on my PC? On the PC, you'll have to install either the Informix Client SDK (http://www.ibm.com/software/data/informix/tools/csdk/) or Informix Connect (http://www.ibm.com/software/data/informix/tools/connect/). Both are free downloads. If you plan on building InformixDB from source, you'll need CSDK. If you want to simply use a pre-built binary, such as the one I provide at Sourceforge, either CSDK or Informix Connect will do. In either case, INFORMIXDIR on the PC should point to where you installed the Informix client software, and INFORMIXSERVER points to the server instance you're connecting to. Hope this helps, Carsten. From envyisevil at yahoo.com Tue May 9 14:41:05 2006 From: envyisevil at yahoo.com (envyisevil at yahoo.com) Date: 9 May 2006 11:41:05 -0700 Subject: Is Welfare Part of Capitalism? Message-ID: <1147200065.889769.76050@v46g2000cwv.googlegroups.com> This article is dedicated to: A man I met, with most of his body heavily burned, simply because he was a Chinese during the 1998 May Riot in Indonesia. Lots of capitalists that are slaughtered during the cultural evolution. Ten thousands of peaceful smugglers that are massacred in Banda island by the Dutch for conducting peaceful spice trade and all that are similar to them. All minority groups and individuals that face discrimination, even genocide, for economically contributing too much for their society. All customers that have to pay higher products due to protection of tariff and trades. Productive people that are fined with income tax for the victimless crime of making honest money. Smart students that are slowed down so not to move too fast. Industries that do not get subsidy, or even banned to protect unproductive industry and laborers that earn much less due to such restrictions. Poor starving people that could have been rich had their countries choose to embrace free market. Women and males that are trapped in unhappy marriage which they have a hard time getting out. Women and children that have lots of their best choices taken under the pretext of protection. Immigrants and refuges. Is welfare part of capitalism? In short, no. In consensually, punishing the productive through income tax to reward parasitic behavior is the biggest affront against the principle of free market. In fact, from many governments intervention in economy, the one that proponents of free market often oppose the most is welfare. However, when we look further, capitalism and welfare is not really total opposites. Most importantly, properly done, a straight forward welfare program can cause less market distortion, and hence an efficient replacement to buy votes from losers, than farm subsidies, public schools, minimum wage, trades restrictions, tariffs, and sex laws. If it's done by taxing wealth, rather than income, the amount of market distortion can be minimized further. Welfare is also cheap. It'll cost $5000/year to a welfare recipient in USA, for example. However, we need to remember that the recipients' lifestyle worth only $500. The other $4500 goes to implicit welfare due to higher living costs. That implicit welfare includes minimum wage, immigrations laws, and food subsidy, or protections. If somehow a straight forward explicit welfare program can replace all relatively more evil governments' interventions, then capitalists are probably better of not opposing welfare so much. Even Milton Friedman supports schemes called guaranteed minimum income, which is like welfare but with much less market distortion. That's not where the similarity ends. One of the main creeds of capitalism is that consent and competition should be preferred over force. Without that consent, anyone can simply make us choose to make our self worst of under the pretext that it is for our own good. In fact, most laws against consensual acts can be traced down to protection of some disgruntled competitors often done under the pretext of the consenting parties' own good. Anti prostitution and anti polygamy laws, for example, is there to ration females to poor dumb males under the pretext of protecting the consenting women. Of course, all natural resources tend to be rationed somewhat proportional to ones' voting power. And that does explain why democracy and anti polygamy laws go hand in hand too. One man one vote soon leads to one man one wife. Well, at least Matt Ridley agrees with me and he's a well known mainstream scientific researchers. I guess that's also why so many uncompetitive people want to ensure that evolution theory is not taught in school. You can also read a famous psikiatrist book, "The road less traveled," you'll see that life long monogamous marriage is just a trap to prevent highly desirable people from being available to those who they want more, and romance is just the lure to that trap. On the women side, anti pornography laws is really meant to prevent highly desirable women from advertising her assets and hence protecting less pretty women from the higher industry standard a public display of superior desirability might cause. Countries that embrace porn tend to have prettier women. Where did all the unsexy ones go? They're all shifting out of the gene pool, and hence are doing their best to oppose porn preaching religious doctrines that men should judge women based on any features but beauty, which they can't offer. Another issue is consent. Welfare program is not consensual; however, it's relatively more consensual then civil war. In ancient time, when we have different ideological opinions, we end up killing each other to proof who are "right." The Catholic would kill the Gnostic, the Sunni would kill the Shiah. One King would kill the other. A younger prince will argue that the older prince is demon. Might makes right. Such differences of opinions are of course solved with war, which is a very cost inefficient way to know who're "right." However it does work in some subjective practical sense. If we look in the past and try to figure out whether the Gnostic or the Catholic is the one that's heretical or "right" respectively, we need only to see who won. The Gnostics are slaughtered, so they must be the heretic, or do they? At least I bet there are way more people in the world that think that way than the other way around, excluding me actually. It doesn't matter how many books many institutionalized religions burned, how much restrictions of freedom of speech and irrationality they embraced, how many witnesses they snuffed outs and all other techniques that would not have stand the scrutiny of a peer reviewed scientific journal, or even a reasonable jury in the court of law. Too many people don't believe who are right and reasonable, they believe who are mighty. Right or wrong, the win will always become right anyway. Now, under democratic context, we don't kill those who oppose us, rather we try to persuade enough people to join our cause. How do we persuade them? By money of course. Welfare program is then a reasonably cost efficient method to buy votes. When too many people are on a side, we will sort of know that going to war will hurt the other side; hence we comply anyway with the whim of majority avoiding the costly alternatives. While not ideal, this is indeed how right and wrong is really decided, proper assessments of each sides' bargaining position and mutually cherished compromised line of war, plus a bunch of lies covering what's going on to safe each sides' face. No matter how noble the purpose, lies and prejudices lead to misunderstanding, that leads to more war. Hence, the best contribution is simply to unmask all lies. All in all, peaceful democracy is indeed a more cost efficient ways to measure ones' bargaining position. While democracy often lead to decisions opposites of freedom, like popularly supported victimless crime, income tax, and welfare, it's indeed relatively more cost efficient than civil war. That's not when the coherency end. Various natural laws restrict various possible political outcomes. We can't expect a stone will fly to the sky when we drop it as much as we cannot expect a human to be generally unselfish. If we want to kill our enemies, we'll do well dropping a big stone on top of our enemies head rather than dropping the stone on top of our own head expecting the stone to somewhat magically fly to the enemies head. The same way, we can't demand market distortion and expect that the best and brightest among us to still magically be a nice tax payer rather than dictators and corruptors. In a country where selling porn or building a good franchise chain is more difficult and less lucrative than becoming a dictator, guess what the smart would end up doing? Ask Saddam. If we want rich and prosperous countries, we must know that it will and only will happen when we properly align individuals' interests with productivity. Such coherency tends to make certain things come in package with another. We can expect that moving electric field will induce magnetic field. The same way, in life, we observe similar things. Communism and socialism, for example, always come in package with dictatorship and corruptions when smart people realize that being dictators pay more than building a business empire. To the opposite capitalistic countries comes in package with softer deals for losers, such as, guess what, welfare. We know from our economic classes that free market capitalism brings prosperity within market mechanism. However, it turns out that the prosperity that free market brings also profit the less successful beyond market mechanism. Capitalism and the prosperity that come with it tend to facilitate ideological changes in ways that benefit the less successful. One such ideological change is the popular support for losers' benefits. One such benefit is, guess what, welfare. The most obvious samples of such ideological shifts the free market bring are the elimination of slavery in US. What happened? As usual, the northern part of America is an industrial country. At that time, steel industries are relatively more modern than the farming industry. Higher tech industry increase labors' productivity. When labor's productivity goes up, entrepreneurs will want to hire as many workers as possible. Hence, labors' salary will go up. This will kill of industries with less labor's productivity. At the end, the marginal productivity of labors in the least productive industry will go up. That value is labors' salary. Under competitive equilibrium, the more productive and efficient a person is, the more he benefits everyone in the chain of productivity except those similar to him. Hence, an entrepreneurs coming up with ways to improve labors' productivity would benefit everyone, including workers and consumers, at the expense of other entrepreneurs and capitalists. Read that Karl Marx! Then what? When labors' salary goes up, obviously labors will move to the employers that pay them higher. Hence, farm labors in the south want to move to the north. They can't do so legally though because they were slaves. Hence, the northern capitalists in US want to free slaves so they can hire more workers. And then the southern capitalists in US want to keep slavery. This then results in war. The bigger the labors' productivity, the more intensive capitalists have to free slaves. The more supporters there will be on a cause the more likely the cause won. Hence, slaves were freed. Unfortunately, people still want to help losers and buy votes from those who are too expensive and too stubborn to switch. That explains why the farms in US gets subsidy. If losing means not as successful as the other, then there will always be losers. However, we see how free market shifts the worlds' system in ways that benefits the losers too. Unlike the commies' propaganda, capitalism does not cause or even enlarge disparity of wealth. Capitalism only changes the way such disparity are earned to the benefits of all. At the end of the warring states period in China, the king of Chin, Shih Huang Ti, and his prime minister, Li Si were the winner. Within one generation they have all their family slaughtered. If that's what winning means, what did losing means in pre-capitalistic countries? In ancient time, losing meant having all the males slaughtered, enslaved, or castrated and all the females raped and winning means risking your whole family slaughtered by rebels. In socialists countries the rich are corruptors and dictators that slice each other throats while the poor are starving. Now, thanks to the prosperity only free market can bring, losing means they can leave on welfare, with plenty of chance to climb back and proof their worth, like J. K. Rowling. Now, slaves are so free and highly paid thanks to increase in labors' productivity. In fact, when slave jobs are moving to China under globalization, slaves in US refused to be emancipated and want to keep their slave jobs in US rather than evolving into entrepreneurs. So, much for the land of the free and the place of the brave. Some people don't mind dying for what they believe in but are too scared to start a business. Evolutions will fix that I guess. Free market gives abundances to everyone. The benefits the free market brings benefit those less capable from being successful not only within the system but also through non market mechanism, like the ending of slavery and the start of reverse slavery we call welfare. But how do those really work? Is there a general principle? Each of us is greedy and selfish that we want as many as possible for us. Humans' greed and selfishness is an undisputable scientific facts, as sure as the sun rise in the east, as sure as a stone will fall to the ground pulled by gravity. We're not just greedy and selfish. Greed and selfishness doesn't explain all the war, suffering, and poverty we face. In fact, greed is good. Properly aligned, under free market, the greatest among us shall be the one productively providing the best service to the most customers. Blessed be the productive because they'll be rich. This will encourage higher and higher standard of living that we are currently enjoying. Free market allows those who serve more to grow richer. To those who have more profit, to those more capital are given. Even kingdom of heaven don't mind using this nice positive feedback effect. Who needs new deals to break up companies? Also, women prefer the rich. The next time you watch soap opera, make sure it's made in some country with the highest IQ in the world, like Hong Kong. Free sex means richer males will consensually attract and mate with more women producing more kids. That's the whole point of getting rich by the way. Duh? In fact, that's what being a living human male is all about: 1. Gain control ship of as much money or power as possible. 2. Attract or in anyway acquire as many females as possible. 3. Make kids. 4. Use that kids as tools to make grand children. You bet it's right because it's science. Of course, they don't teach this important fact in biology class because government interfere in education. Hence, when we're free, without genocide, without war, even with humanitarians aids given to appease enemies, the meek will indeed inherit the earth. More than greedy and selfish, some humans are simply not humans because they embrace the root of all evil, envy. That explains why we have so many laws against mutually beneficial consensual acts and governments regulations to protect us from our own choices. The truth is, all those laws and restrictions are more often not there to protect stupid people from making mistakes. All such laws are there to prevent the smart from making the right choices. That's why, for example, every body has to move equally slowly in school, to prevent the smart from moving faster. That's why various reproductive techniques are politically incorrect proportional to the expected quality of genetic material that will be duplicated. In particular, life long monogamous marriage, free sex, prostitution, polygamy, and cloning are sequences that both have increasingly expected value of genetic quality outcome and politically incorrectness. In Europe and China, the smart monks are encouraged not to get married. When some minority groups don't buy the bullshit and hence greatly improving their productively earned wealth and genetic quality, such minority groups somehow become victims of genocide. Life is like a real time strategy games. That means when we're not at war, we're in a race. That's simply how we evolve. Morality, religions, and ideologies, are stuffs created by really smart people to persuade us to run backward. Peace means we're in a race. Freedom means we are in a competition. Some people just don't want to compete. Hence, they craft lies and prejudices against those who are in front preventing progress to prosperity. I'll tell you the scientific truth. It's from the fruit we knows the tree. Anyone opposing free trades and globalization is more evil than Hitler or Nazi. If only Japan and German could have acquired natural resources through consensual peaceful trade, Nazism wouldn't have been popular there and Hitler wouldn't have risen to power. With his mass hypnotic skills, he may have ended up as seminar speaker I guess. If only those who had wanted to incite the Second World War see all the miracles and prosperity the free market brings, they would have repented and embrace free market. Yet, after all the prosperity and wealth the free market is bringing to all of us, still many people choose to oppose competition, and hence, miss-properly align our interests from productivity. That is the cause of all evil in the world. All causes opposing free market can be negotiated and appeased. However, if the very thing that a group of people want to prevent is the success of the others, then the situation is pretty much kill or be killed zero sum game. How does such situation usually end up? What would be our optimum solutions for such situation? Under normal circumstances, an optimum solution of any business decisions is a solution where the marginal revenue equals to the marginal costs. Hence, in a zero sum game, each party will try to maximize its benefit to that point. Sometimes, the marginal costs have a spike. There is a certain point where increasing a resources allocation beyond a certain point will create adverse costs. For example, increasing the number of labors will increase revenue. After a certain point, increasing one additional labor will mean buying a new machine or building a new factory. We may end up choosing to do it, we may not. In either case, discretions are the better part of the valor when it comes to that line. The same way, in most countries, each of us can increase our profits using property we own or consensually rent. When we maximize our profit that way, the public will, ideally and some times truly, not interfere, and defend us from being prevented to enjoy our "rights" by others. However, when we start using others' property to maximize our gain, say by stealing, public opinions may shift from protecting us to against us. Hence, the choice whether we should steal or not depends on the extra costs of crossing the politically correctness line of war. If a person sees that the potential gain justifies the increase costs of public support shifts, he'll still steal and make a great career out of it. Otherwise he'll stop stealing while coming up with a pretext to justify his cowardly decisions, such as morality. But what do the people choose their reaction to a specific act like stealing? They do so based on their sense of fairness, justice, and right-wrong discernment. How do people get that sense? From ideology. The ideology, religions, or whatever, then decides the line of war where the rest of us should consider before crossing. But how does the line gets drawn? By estimates of bargaining position. Let's examine an example. Is the King (or Queen?) of England the King of France? Don't know. How do we know? In the beginning, a ruling class from France went to England and become king of England. Then they lost control of France. Hence, king of England wanted to take back the controls they have lost. Well, such conflicts are solved by war. In this particular case, the war lasted 100 years. The British attacked France and successfully route knights with long bows. Then, the Frances stroke back driving the British back to their isolated islands. However, the France cannot move further and go all the way to attack British because of the Strait of Dover separating the two nations. Finally both sides realized that the straits somehow became the sacred line of war. It's not auspicious to cross the line of war for either side. The France, having more army and larger population would beat up the British on land, and the British being stronger at sea can always repulsed France sea invasion. Hence, we got peace. Such natural separators like straits and mountains explain why Europeans are divided into many different countries. The Chinese, not having that natural line of war, end up getting united all the time. Now, let's get back to the question whether welfare is part of capitalism. If all of us have just enough food, and some people don't work, what would we end up doing to those who are not productive? Humans' basic instincts and preferences lead to gene pool survival. When food is scarce, such as when the people demand centralized planning, it would serve ones' gene pool survival to slaughter the parasites rather than sharing food to them. That's because sharing food to those who do not earn it means starving ones own self. In fact, humans will kill each other to literally eat each other when food is scarce. Such is what happened in China and Rusia when centralized planning, governments' intervention in economy, and prejudices against successful capitalists became the norm. However, when food and money are abundance, such as when the people embrace free market, fighting the parasites might cause more gene pool survival lost than feeding them. On the other hand, simply giving and yielding toward threaten will motivate people to keep pushing us around. Moreover, giving in to those who can use force against us will motivate countries to build arms rather than say, better video games. Hence, one possible strategy to minimize open war while still properly aligning ones interest with other individuals around them is to give to those who ask nicely and ask less. As free market brings a lot of abundance, those who are needy can be appeased much more cheaply than those who are envy, and hence, we got welfare program. To be frank, I'd rather see the unproductive people have bigger TV rather than letting them make more kids. It's more humane, and cheaper. Guess what? Most people that know they're not very capable either would rather have that too. Back to the France vs British. If only both sides have realized the true bargaining positions of each, they wouldn't have to resort to such expensive 100 years war right? The thing is, the 100 years war are the most credible and accurate ways to measure ones' bargaining position. War shows which one is stronger, and hence leads to a mutual understanding of where the line of war might be. If only we can wave our gun and scare the enemies, it'll be great. However, the only threats that are credible are those actually done. How do we know a cause's bargaining position? Democracy might give some light by counting the number of those who are in favor or against what we consider lesser evil. However, number counting can be deceiving. We hold this truth with plenty of evidences, that humans are inherently different. We have difference capability and preferences, and hence different choices and outcome. It's useless to lay net in front of anything with wings. Those who are genetically predestined to be successful will get rich anyway whether through honest capitalistic means or through dictatorship. Those who are small in numbers can hence be quite strong. Preventing the smart from making money honestly will then turn them into corruptors and dictators. When the Chileans demand to prosecute their entrepreneurs, they end up getting a dictator, the way any country that demand slavery over freedom deserves. Fortunately, Pinochet are relatively benign compared to others dictator and embrace free market giving the miraculous prosperity that the Chilean now enjoy. Now, US government arrested his daughter for a crime of tax evasion. An act that wouldn't have been a crime if making honest money is free. The miracle of Chili becomes the model of China's moving to free market. It also helps to end communism all over the world peacefully. If capitalists fail to show thanks to Pinochet family, I don't know what would happen to all of us. So, beyond number counting, the more accurate ways are then through skirmishes. When people cross the public's opinion line of war and we don't strike back, the line of war will shift against the coward by precedence. By fighting back, we'll then have a more accurate knowledge of which one the public would agree with. Hence, it's very important to retaliate to what others do to us, either good or bad. It's a pleasure to serve my friends, it's also a pleasure to wipe out envy enemies that are on our ways, should my friends wish or don't mind. When a fraudster tricks my brother over $3,900, my main concern is not to get my money back. My main concern is to get the fraudster to jail even if that will costs far more money than the $3,900. When a thief steals my money on 2001, my concern is also not to get my property back. What's just is to encourage the whole world to post any thieves conviction records on the net to prevent further larcenies. It makes me wonder though. Why people consider it cruel to damage a thief or a fraudster' reputation? The mere acts of making honest money are punishable by income tax. When Everett O. Lasher makes an argument in court, the case leads to $5000 fine, and understandably, a suicide. The mere acts of successfully fending of ones' home from thieves lead to a life long jail term for Tony Martin. Thousands would march against WTO demanding harsh laws to punish those exercising consensual trades. In Iran, the mere acts of switching religions can lead to death penalty. In Indonesia, new laws are being drafted giving years in prison for kissing in public. Of course, public rape during May riot are still far from being punished. This while murderers of Vincent Chin went free without jail term. Thousands would march to end death penalty against murderers. In Indonesia, religious fundamentalists can come to a house and destroy properties from houses providing consensual entertainment with polices watching. Those people often get away or lightly punish. If consensual productive acts are punished while damaging inconsensual forces are not, soon, all highly productive people would end up in gas chamber after the next Cultural Revolution, or what ever. Those who are left are those smart enough to be dictators enslaving the rest of us. Prejudices reminds me of an envy old hag that's so determined to ruin my reputation for being friendly to her and her friends, after her own friendly communication. I never intended to fraud anyone or steal her money yet I got my reputation ruined. I am very disappointed to see that there are people in the world that want to bring me down more than they want to bring down a thief. I have tried to resolve the issue privately by suggesting to that thing that she's really not important enough for anyone to pretend to be her friend. Moreover, I didn't need her as a friend. All this was just a damage-less misunderstanding caused by her own friendly communication which I could simply publicly straighten out. At least, it used to be. However, that vermin really wished to get the issue public telling lies that she never communicated with me, possibly to boost that things' feeling of importance her genes deny her. Well, if she got so mad over a few friendly introductions, I can only wonder what that thing would do when it finds out that her true envy natures are revealed to 55000 newsgroups several times. It'll happen again and again whenever I feel like. Hence, just look for "envy vermin" on the net to find out what's really going on including what she said privatedly. Let the public decide who are more honest, rational, scientific, and straightforward. Let the market decides which one are worthy and who are worthless. It's a great mistake to ever consider such thing as a friend, a mistake no body should do. It's her kind that turns people of from making money productively. Hopefully we can undermine public opinions against all form of envy motivated lies and prejudices. At the end, we'll greatly weaken laws against victimless crime and easily out compete all envy people out of the gene pool. That'll ensure that the free fair market competition would reign over war when all lies and prejudices against those more successful are gone. Now that being said, I want to move all jobs that can be done online to Asia, especially, copy writers. Take advantage of the value difference and leverage like hell is how we all make money in any system. Who's with me? Free market is all merciful and all compassionate. At the end, even those that oppose free market will benefits from free trades. From invalidemail at aerojockey.com Tue May 9 17:56:56 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 May 2006 14:56:56 -0700 Subject: Can Python installation be as clean as PHP? In-Reply-To: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> Message-ID: <1147211815.312069.135140@u72g2000cwu.googlegroups.com> Jack wrote: > Then again, I do like the Python language. It would be great if > Python (or a variation of Python) can be made the PHP way, one > executable file, and you get everything. True, sometimes it can be a real convenience to have this. There are solutions that implement your solution to some degree. For instance, for Windows there's Moveable Python (it costs a scant 5 pounds): http://www.voidspace.org.uk/python/movpy/ I don't believe it's a single file, but it is "installationless". Py2exe and PyInstaller can let you distribute programs as single-file executables. PyInstaller works on Unix too, IIRC. If you're good at tweaking stuff and have some knowledge of Python internals; it's possible to make a minimal distro just by copying files out of a regular installation by hand (and maybe zipping some them up). This can be a security and bug risk, so be careful. Carl Banks From larry.bates at websafe.com Mon May 8 11:28:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 08 May 2006 10:28:46 -0500 Subject: connect file object to standard output? In-Reply-To: <1147101408.320069.12780@g10g2000cwb.googlegroups.com> References: <1147101408.320069.12780@g10g2000cwb.googlegroups.com> Message-ID: <445F63AE.3090702@websafe.com> beliavsky at aol.com wrote: > I want to write a function that writes to an output file if specified > and otherwise to standard output. How can I connect a file object to > standard output in the code below? I could use an if statement to > choose between print and print>>fp throughout the function, but this > seems awkward. I think there is a way to connect standard output to a > file, but I'd prefer not to do that, since I want to use plain print > statements to warn about errors in the function and have their output > appear on the screen. Thanks. > > def write_data(data,out_file=""): > if (out_file != ""): > fp = open(out_file,"w") > else > fp = # how to connect standard output to fp? > print>>fp,data > # more print>>fp statements follow > import sys def write_data(data, out_file=None): if out_file is None: fp = sys.stdout # how to connect standard output to fp? else fp = open(out_file,"w") fp.write(data) # more fp.write() statements follow -Larry Bates From mramos at montevideo.com.uy Fri May 12 18:14:55 2006 From: mramos at montevideo.com.uy (Marcelo Ramos) Date: Fri, 12 May 2006 19:14:55 -0300 Subject: having trouble importing a module from local directory In-Reply-To: <1147465295.213844.284100@y43g2000cwc.googlegroups.com> References: <1147465295.213844.284100@y43g2000cwc.googlegroups.com> Message-ID: <446508DF.4050003@montevideo.com.uy> vduber6er escribi?: > First off this is in unix. > > I have a C file that has python embedded in it. In the script I have > the following > > PyRun_SimpleString(code); > > where > code = "import mymodule" > > however I get this error > > Traceback (most recent call last): > File "<string>", line 1, in ? > ImportError: No module named mymodule > Object not found > Segmentation fault > > If i just run python from my local path then type "import mymodule" in > the python prompt this is fine. I'm guessing when I am embedding my > python script in the C code the local directory is no longer the > directory where my C code resides. How can i tell python to load the > module from my current local directory? > > Try adding the directory where your mymodule module lives to the PYTHONPATH environment variable before running your c program. -- Marcelo Ramos Fedora Core 5 | 2.6.16 Socio UYLUG Nro 125 From harry.g.george at boeing.com Fri May 19 01:15:36 2006 From: harry.g.george at boeing.com (Harry George) Date: Fri, 19 May 2006 05:15:36 GMT Subject: Programming language productivity References: <mailman.5923.1148009336.27775.python-list@python.org> <Xns97C7E9ACF911Bcastleamber@130.133.1.4> <1148030499.484778.8260@j33g2000cwa.googlegroups.com> Message-ID: <xqxlksya93b.fsf@cola3.ca.boeing.com> "malv" <malvert at telenet.be> writes: [snip] > Once you get involved in larger projects, the dynamic nature of the > programming tool becomes much more important. I mean by this, the > ability to stop running code, modify or add to it and continue without > having to re-establish the state of the program. This may sound trivial > to many, but in major applications setting up the state again can take > a considerable processing time. Such feature should be available from > within the debugging tools. > > In fact, languages like Smalltalk, Lisp and even VB offer this > possibility. > Ruby coming up strongly these days also has this dynamic reload > capability. > To sum up, I like Python very much but I don't understand how come this > basic flaw has not been taken care of. It is sufficient to search for > "reload" to see how many people have struggled with it over the years. > I hate the idea of having to take up Ruby to really find out how it > could serve me better in this most critical productivity area. > What is "major project"? We have 50 people working on a project, over 5 years, in Python. Much of the regresison test can be done by rebuilding context in RAM (no need to persist). That is immediate (whole test suite runs in a few seconds). Sometimes we have to reestablish context by clearing the database and then reloading objects from test_input XML files. That is slow (perhaps an over night job). I've yet to experience a context where language features are the rate limiting step. On the other hand, I have definitely experienced language as a rate limiting factor in a) peer code reviews, b) debugging, c) ramping up new team members. Python wins those battles everytime. -- Harry George PLM Engineering Architecture From matt.good at gmail.com Fri May 19 18:14:04 2006 From: matt.good at gmail.com (Matt Good) Date: 19 May 2006 15:14:04 -0700 Subject: Python sqlite and regex. In-Reply-To: <Wtobg.46855$CH2.42030@tornado.texas.rr.com> References: <mailman.5942.1148042842.27775.python-list@python.org> <1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> <hunbg.46845$CH2.29994@tornado.texas.rr.com> <m2u07lq2s5.fsf@unique.fqdn> <Wtobg.46855$CH2.42030@tornado.texas.rr.com> Message-ID: <1148076844.076382.129640@g10g2000cwb.googlegroups.com> Oops, sorry about the confusion regarding the built-in REGEXP. That's kind of disappointing. It would appear that the user-defined regexp function in the original post should work assuming the SQL and regex syntax errors are corrected. However, there *is* a GLOB built-in to SQLite 3 that has a default registered implementation (though it can be overriden by a user-defined "glob" method if necessary). From chris.cavalaria at free.fr Thu May 18 10:45:15 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 16:45:15 +0200 Subject: Question about exausted iterators In-Reply-To: <4d3f10F18q0d9U1@uni-berlin.de> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <mailman.5879.1147959939.27775.python-list@python.org> <446c7f44$0$7128$626a54ce@news.free.fr> <4d3f10F18q0d9U1@uni-berlin.de> Message-ID: <446c88a2$0$7121$626a54ce@news.free.fr> Diez B. Roggisch a ?crit : > Christophe wrote: > > >>Fredrik Lundh a ?crit : >> >>>Christophe wrote: >>> >>> >>>>Because I'm still waiting for a valid answer to my question. The >>>>answer "Because it has been coded like that" or is not a valid one. >>> >>> >>>it's been coded like that because that's what the specification says: >>> >>> http://www.python.org/dev/peps/pep-0234/ >> >>I didn't though I had to mention that "Because the spec has been writen >>like that" wasn't a valid answer either. > > > The important thing is: it _is_ specified. And what about code like this: > > > iterable = produce_some_iterable() > > for item in iterable: > if some_condition(item) > break > do_something() > > for item in iterable: > do_something_with_the_rest() > > > If it weren't for StopIteration raised if the iterable was exhausted, you'd > have to clutter that code with something like > > try: > for item in iterable: > do_something_with_the_rest() > except IteratorExhausted: > pass It would be ugly but you could do that instead : iterable = produce_some_iterable() for item in iterable: if some_condition(item) break do_something() else: iterable = [] for item in iterable: do_something_with_the_rest() I'll admit that the else clause in for/while loops isn't the most common and so some people might be a little troubled by that. There's also that : iterable = produce_some_iterable() for item in iterable: if some_condition(item) for item in iterable: do_something_with_the_rest() break do_something() > What makes you say that this is better than the above? Just because _you_ > had some cornercases that others seems not to have (at least that > frequently, I personally can't remember I've ever bitten by it) isn't a > valid reason to _not_ do it as python does. Maybe I've used more iterables than most of you. Maybe I've been doing that wrong. But I'd like to think that if I've made those mistakes, others will make it too and would benefit for some help in debugging that from the interpreter :) > Besides that: it would be a major change of semantics of iterators that I > seriously doubt it would make it into anything before P3K. So - somewhat a > moot point to discuss here I'd say. It wouldn't be such a big semantic change I think. You could add that easily[1] as deprecation warning at first and later on switch to a full blown error. [1] "Easily" provided you can easily code what I ask itself ;) From tjreedy at udel.edu Sat May 20 14:16:53 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 20 May 2006 14:16:53 -0400 Subject: Generating Cutter numbers References: <1148114166.590393.176250@u72g2000cwu.googlegroups.com><1148133784.844430.23130@38g2000cwa.googlegroups.com> <1148146441.412605.163750@j55g2000cwa.googlegroups.com> Message-ID: <e4nmek$kem$1@sea.gmane.org> "Gerard Flanagan" <grflanagan at yahoo.co.uk> wrote in message news:1148146441.412605.163750 at j55g2000cwa.googlegroups.com... > I'm cataloging a small library and want to generate a unique id (called > a 'call number') for each book. This id is composed of: > > * Dewey 3-digit Subject Classification Number > * Dewey Decimal (always 0 for the minute) > * Cutter Number > * Copy number (multiple copies or volumes) > > (That Celestial Emporium again...) > > I haven't researched it much but it seems the Cutter number is used to > distinguish between authors with the same name, and between different > books written by the same author - so you need last name, first name > and title. But it may be as much art as science. I seems you are mixing pieces of two cataloging systems. The link you gave was for creating Cutter numbers to represent subtopics of Library of Congress classes. For instance, 'algorithms' is .A43. From ddonato at unisa.it Wed May 31 09:47:20 2006 From: ddonato at unisa.it (ddonato at unisa.it) Date: Wed, 31 May 2006 15:47:20 +0200 Subject: os.popen3() - how to close cmd window automatically? Message-ID: <1149083240.447d9e683d7b1@webmail.unisa.it> > > # Script "shortcut.py" > > import os > > import webbrowser > > import win32api > > > > # open default web browser and display webbpage > > page = 'C:\\Temp\\Welcome.html' > > webbrowser.open(page) > > > > # path to application that is opened > > path = "C:\\Program Files\\ExternalApplication.exe" > > > > # get short name > > shortpath = win32api.GetShortPathName(path) > > > > # open external application > > stdin, stdout, stderr = os.popen3(shortpath) > > output = stdout.read() > > errors = stderr.read() > > stdin.close() > > stdout.close() > > stderr.close() > > print output > > print errors > > # ---------------------------------------------------------------------- > > > > > > In order to [...] In order to run this on a linux box? daniel ---------------------------------------------------------------- This message was sent using IMP, the Internet Messaging Program. From desale at india.com Fri May 26 04:43:13 2006 From: desale at india.com (sandip desale) Date: Fri, 26 May 2006 16:43:13 +0800 Subject: Parsing python dictionary in Java using JPython Message-ID: <20060526084313.564FF7B5EF@ws5-10.us4.outblaze.com> Hi, We have some tools which are developed in Python and using python dictionaries. Now for some new requirments we are using Java and want to use the existing dictionaries as both the tools are executed on the same platform. So we are trying to use the existing dictionaries only using JPython libraries. Also if u know some thing like sending back values from Python to Java then also it is ok. In this case we will use python to parse the dictionaries and send the values returned back to Java. Regards, Sandip > ----- Original Message ----- > From: Ant <antroy at gmail.com> > To: python-list at python.org > Subject: Re: Parsing python dictionary in Java using JPython > Date: 26 May 2006 01:13:35 -0700 > > > It really depends on how you are trying to pass the dictionary across > to Java, what sort of objects are in the dictionary etc. Could you > provide some more background? > > BTW the Java implementation of Python is now called Jython (and has > been for some years!). > > -- > http://mail.python.org/mailman/listinfo/python-list > -- India.com free e-mail - www.india.com. Check out our value-added Premium features, such as an extra 20MB for mail storage, POP3, e-mail forwarding, and ads-free mailboxes! From fredrik at pythonware.com Fri May 5 05:50:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 May 2006 11:50:39 +0200 Subject: Tuple assignment and generators? References: <mailman.5334.1146755400.27775.python-list@python.org><1146819662.519528.224530@e56g2000cwe.googlegroups.com><mailman.5358.1146821235.27775.python-list@python.org> <1146821724.732068.268960@g10g2000cwb.googlegroups.com> Message-ID: <e3f75f$c2h$1@sea.gmane.org> "vdrab" wrote: > Does the documentation mention that "x is y" returns True when they are > both 0 but not when they are 100001 ? language reference, comparisions (is operator): The operators is and is not test for object identity: x is y is true if and only if x and y are the same object language reference, objects: "Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after "a = 1; b = 1", a and b may or may not refer to the same object with the value one, depending on the implementation, but after "c = []; d = []", c and d are guaranteed to refer to two different, unique, newly created empty lists. (note the use of "may or may not" and "depending on the implementation") </F> From ptmcg at austin.rr._bogus_.com Mon May 8 02:28:26 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 08 May 2006 06:28:26 GMT Subject: New pyparsing wiki Message-ID: <eyB7g.12367$Qq.10289@tornado.texas.rr.com> I've converted the pyparsing project home page to a wiki, hosted at http://pyparsing.wikispaces.com/ Please come and visit the new pyparsing project site, and add your contributions to the public Tips and Documentation pages! Thanks! -- Paul From Serge.Orlov at gmail.com Thu May 11 09:39:44 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 May 2006 06:39:44 -0700 Subject: Install libraries only without the program itself References: <e3v660$jqt$1@newsreader1.utanet.at> Message-ID: <1147354784.387775.51270@i40g2000cwc.googlegroups.com> Gregor Horvath wrote: > Hi, > > My application is a client/server in a LAN. I want to keep my programs > .py files on a central File Server serving all clients. The clients > should load those over the LAN every time they start the program since I > expect that they are rapidly changing and I dont want to update each > client seperatly. Don't forget you can screw up running clients if you override old version with a new one. > On the clients there should only be python and the necessary libraries > and third party modules (sqlobject etc.) installed. I believe it's better to keep *everything* on the file server. Suppose your OS is windows and suppose you want to keep everything in s:/tools. The actions are: 1. Copy python with all 3rd party modules from c:/python24 to s:/tools/python24-win32 2. Grab exemaker from http://effbot.org/zone/exemaker.htm, copy exemaker.exe to s:/tools/win32/client.exe 3. Create little dispatcher s:/tools/win32/client.py: #!s:/tools/python24-win32/python.exe import sys sys.path[0] = "s:/tools/client-1.0.0" import client 4. Create your first version of s:/tools/client-1.0.0/client.py: print "I'm a client version 1.0.0" ----------------------------- That's it. Now s:/tools/win32/client.exe is ready to go. I guess it's obvious how to release version 1.0.1 If you need to support other architectures or operating systems you just need to create tiny dispatchers in directories s:/tools/linux, s:/tools/macosx ... From sybrenUSE at YOURthirdtower.com.imagination Tue May 9 02:59:48 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 9 May 2006 08:59:48 +0200 Subject: do "some action" once a minute References: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> Message-ID: <slrne60ff3.7vs.sybrenUSE@schuimige.stuvel.eu> Petr Jakes enlightened us with: > I would like to do "some action" once a minute. My code (below) > works, I just wonder if there is some more pythonic approach or some > "trick" how to do it differently. I'd use the Threading module, and the Timer object from that module to be more precise. There you can simply say "call this function in 60 seconds" or something similar. Then your program just sleeps until it's time to call the function. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From bucodi at yahoo.fr.invalid Thu May 18 12:09:30 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 18 May 2006 18:09:30 +0200 Subject: Tkinter Dialog Management problems: References: <mailman.5891.1147967578.27775.python-list@python.org> Message-ID: <mn.94417d65a9ca76a9.43626@yahoo.fr.invalid> If you need a beginners tutorial for Tkinter, try this one : http://www.pythonware.com/library/tkinter/introduction/ >> Hello: >> >> Below I have included a stripped down version of the GUI I am working >> on. >> It contains 2 dialog boxes - one main and one settings. It has the >> following >> problems, probably all related, that I am hoping someone knows what I am >> doing wrong: >> >> 1) Pressing the Settings.. Button multiple times, brings up many >> instances >> of the Settings Panel. I just want it to bring up one. Is there an >> easy >> way to do that? > > In fact, the two windows you created are not dialogs; they're just > windows. To turn a window into an actual "dialog", i.e basically to make > it modal, you have to do the following operations (supposing your dialog > window is named dlg and your main window in named root): > > ## Ensure only window can receive user events > dlg.grab_set() > ## Force Dialog to stay on top of main window > dlg.transient(root) > ## Wait for dialog to be destroyed > root.wait_window(dlg) > >> 2) Pressing the Done button in the Settings Panel, just erases the Done >> button >> (and any other widgets in the Panel). It does not dismiss the Panel. >> Pressing >> the X button does work. What callback is that? Can I make the Done >> button >> call >> that instead? How? > > This is not the way it works. In fact, what you did wrong is something > that has been around for years in some Tkinter tutorial(s): you made your > classes inherit from Frame. This is a Bad Idea: a Frame is not a window, > but only a generic container. There are 2 classes for windows: Tk for the > main window and Toplevel for all others. They both also act as containers, > so you can do in them everything you do in Frames. So make your > ScriptDialog inherit from Tk, your SettingsDialog inherit from Toplevel, > remove all explicit creations of Tkinter.Tk or Tkinter.Toplevel and > instantiate your classes instead. Then calling destroy on either on the > dialogs will actually close the window. > >> 3) Pressing the Done button from the Main Panel has no effect? Why not? >> It >> used >> to work (self.quit()). Again, I would like to call whatever is called >> when the >> X button (top Right corner) is pressed. > > This should work. BTW, your "done" method is not needed: creating the > Button with command=self.quit works without problem. > > > Thanks. That helped alot. > However it leaves a couple very minor problems which I think I can live > with. > 1) It brings up an empty additional 'main window'. > I have tried using the Tkinter.NoDefaultRoot() option, but run into > other problems with other things not defined. > NameError: global name '_default_root' is not defined > Exception exceptions.AttributeError: "IntVar instance has no attribute > '_tk'" in > <bound method IntVar.__del__ of <Tkinter.IntVar instance at 0x009C7990>> > ignored > > 2) By deriving the 'dialog' from Tk, existing calls to self.pack() no > longer are valid, but they don't appear to be necessary. > > My only 'Tkinter tutorial' is what is included in Orielly's "Programming > Python". Still looking for a good tutorial. I am not clear what the > difference > between Tk() and Toplevel() are. They seem totally interchangeable. -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From grante at visi.com Mon May 1 11:04:43 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 01 May 2006 15:04:43 -0000 Subject: How to efficiently read binary files? References: <zda5g.5247$nV4.1486@trnddc04> <125acgep357kbd8@corp.supernews.com> <mailman.5165.1146434636.27775.python-list@python.org> Message-ID: <125c8sbqsd7a952@corp.supernews.com> On 2006-04-30, Robert Kern <robert.kern at gmail.com> wrote: > Grant Edwards wrote: >> On 2006-04-30, David Lees <debl2NoSpam at verizon.net> wrote: >> >>>I want to process large binary files (>2GB) in Python. I have played >>>around with prototypes in pure Python and profiled the code. Most of >>>the time seems to be spent converting back and forth to and from strings >>>using the struct module. Is there a way to directly read into an array >>>of integers in Python? >> >> Perhaps the numarray module? > > numpy for new code, please. So numarray and numpy were both written to replace numeric? -- Grant Edwards grante Yow! I want to kill at everyone here with a cute visi.com colorful Hydrogen Bomb!! From fredrik at pythonware.com Fri May 5 11:12:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 May 2006 17:12:28 +0200 Subject: using urllib with ftp? References: <oqt6g.2048$No6.44127@news.tufts.edu><mailman.5347.1146776157.27775.python-list@python.org> <445abddd$0$9424$c3e8da3@news.astraweb.com> Message-ID: <e3fq0t$gm8$1@sea.gmane.org> John Salerno wrote: > Thanks. So the ftp:// is something different than actually using ftplib > to connect to an FTP server, right? I've used both urllib and ftplib, so > I know what they do, I just was a little unclear about whether they can > sometimes do each other's work as well. urllib uses ftplib under the hood, but all you can do is to fetch files or directory listings. </F> From phpbird at gmail.com Fri May 5 09:36:50 2006 From: phpbird at gmail.com (Ju Hui) Date: 5 May 2006 06:36:50 -0700 Subject: how to remove 50000 elements from a 100000 list? Message-ID: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> I want to remove about 50000 elements from a list,which has 100000 elements. sample code like below: >>> a=range(10) >>> b=range(4) >>> for x in b: ... a.remove(x) ... >>> a [4, 5, 6, 7, 8, 9] when a and b is small size, it will finished quickly, but when a and b have many elements. such as: >>> a=range(100000) >>> b=range(50000) >>> for x in b: ... a.remove(x) ... it will very slowly. Shall I change to another data structure and choos a better arithmetic? any suggestion is welcome. thanks a lot! From mwilson-to at sympatico.ca Fri May 26 10:17:11 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 26 May 2006 10:17:11 -0400 Subject: "Learning Python" 2nd ed. p479 error? In-Reply-To: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> References: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> Message-ID: <I5Edg.3308$%Z2.351404@news20.bellglobal.com> AbrahamLincolnIllinois at yahoo.com wrote: > Hello all. > > On page 479, the 2nd edition of the "Learning Python" book, this code > appears > > class Derived(Base): > def __init__(self, arg, *args, **kw): > self.__init__(self, *args, **kw) > > Surely self.__init__ should be > > Base.__init__ > > Everything else in the book has been crystal clear. Up to page 479! > It doesn't appear in the errata. What am I misunderstanding? Seems to be a typo: Python 2.4.2 (#1, Jan 23 2006, 21:24:54) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> class A(object): ... def __init__ (self): ... print 'Constructing A' ... >>> class B(A): ... def __init__ (self): ... self.__init__ (self) ... >>> B() Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in __init__ TypeError: __init__() takes exactly 1 argument (2 given) >>> class C(A): ... def __init__ (self): ... A.__init__ (self) ... >>> C() Constructing A <__main__.C object at 0x402cf5ac> Mel. From dawodu4fun at yahoo.com Mon May 29 15:38:30 2006 From: dawodu4fun at yahoo.com (glutepuppet) Date: Mon, 29 May 2006 19:38:30 GMT Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> Message-ID: <sbjm729loiv8t430392i8v8l5j6acv7uhv@4ax.com> On 29 May 2006 10:52:13 -0700, "Kriv" <kriv.john at gmail.com> wrote: >Hi friends, > >I found this eBook on the web. This book is very very good. >I refer to them. > >http://rapidshare.de/files/21704644/Apress.Beginning.Python.From.Novice.to.Professional.Sep.2005.rar.html > > >Thx >John WOW! What a great book! Thanks for the link. You RULE. From vipulagarwal.in at gmail.com Sat May 27 02:25:26 2006 From: vipulagarwal.in at gmail.com (vipulagarwal.in at gmail.com) Date: 26 May 2006 23:25:26 -0700 Subject: access serial port in python In-Reply-To: <0audnaDolMWd4erZRVn-jg@comcast.com> References: <1148678743.109181.259710@i40g2000cwc.googlegroups.com> <0audnaDolMWd4erZRVn-jg@comcast.com> Message-ID: <1148711126.061387.107220@j73g2000cwa.googlegroups.com> i can use the polling method to check for data on the serial port using pyserial...but i need to use the interrupt driven method .....am workin on a windows platform .... From fb at frank-buss.de Sun May 7 15:22:33 2006 From: fb at frank-buss.de (Frank Buss) Date: Sun, 7 May 2006 21:22:33 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <1vspxcmldcqa5.t1b4abyraqom.dlg@40tude.net> <1heytyi.lope5l1p029gfN%aleaxit@yahoo.com> Message-ID: <19qhkvgj0bdmg.1ex2haasqrgrj.dlg@40tude.net> Alex Martelli wrote: > Sorry, but I just don't see what lambda is buying you here. Taking just > one simple example from the first page you quote, you have: > > (defun blank () > "a blank picture" > (lambda (a b c) > (declare (ignore a b c)) > '())) You are right, for this example it is not useful. But I assume you need something like lambda for closures, e.g. from the page http://www.frank-buss.de/lisp/texture.html : (defun black-white (&key function limit) (lambda (x y) (if (> (funcall function x y) limit) 1.0 0.0))) This function returns a new function, which is parametrized with the supplied arguments and can be used later as building blocks for other functions and itself wraps input functions. I don't know Python good enough, maybe closures are possible with locale named function definitions, too. -- Frank Buss, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From jmcmonagle at velseis.com.au Wed May 24 22:09:12 2006 From: jmcmonagle at velseis.com.au (rimmer) Date: 24 May 2006 19:09:12 -0700 Subject: Unexpected extension module behaviour Message-ID: <1148522952.022925.229350@u72g2000cwu.googlegroups.com> I'm writing an extension module in C in which I'm passing an array of floats from C to python. The code below illustrates a simple C function designed to output an array of floats. --------- extTest.c --------- #include <stdio.h> double *testArray(int nsamp) { double nums[10000]; int i; double cumdata = 0.0; printf("%d\n", nsamp); for (i=0; i<=nsamp; i++) { printf("%d\n", i); nums[i] = cumdata; cumdata += 0.5; printf("%f\n", nums[i]); } return nums; } Then I write a wrapper function to pass the data back and forth between C and Python. ---------------- extTestWrapper.c ---------------- #include "/usr/include/python2.4/Python.h" #include <stdio.h> // external declarations extern float *testArray(int); // Python wrapper for the testArray function PyObject *extTest_testArray(PyObject *self, PyObject *args) { double *nums; int nsamp; int i; PyObject *pynums; if (!PyArg_ParseTuple(args, "i", &nsamp)) { return NULL; } // call the C function nums = testArray(nsamp); // build a Python list object containing the array values pynums = PyList_New(nsamp); for (i=0; i<=nsamp; i++){ PyList_SetItem(pynums, i, PyFloat_FromDouble(nums[i])); } return Py_BuildValue("O", pynums); } // method table mapping names to wrappers static PyMethodDef extTestMethods [] = { {"testArray", extTest_testArray, METH_VARARGS}, {NULL, NULL} }; //module init function void initextTest() { Py_InitModule("extTest", extTestMethods); } I then run the following setup.py script using python setup.py install --install-lib=. -------------------------------------------------------------------------------------------- # setup.py for extTest from distutils.core import setup, Extension setup(name="extTest", version="0.0.1", ext_modules=[Extension("extTest", ["extTest.c", "extTestWrapper.c"])]) -------------------------------------------------------------------------------------------- The library builds and installs ok. When I invoke the testArray function, it appears to work correctly (the output is as expected). For example, import extTest a = extTest.testArray(5) yields the following output: 5 0 0.000000 1 0.500000 2 1.000000 3 1.500000 4 2.000000 5 2.500000 Exception exceptions.IndexError: 'list assignment index out of range' in 'garbage collection' ignored Fatal Python error: unexpected exception during garbage collection Aborted Here is where I'm stumped. I must be doing something wrong during the PyList_SetItem or the Py_BuildValue. Any ideas on fixing this problem ? Regards, Rimmer From max at alcyone.com Mon May 8 02:42:55 2006 From: max at alcyone.com (Erik Max Francis) Date: Sun, 07 May 2006 23:42:55 -0700 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> Message-ID: <9L-dnd8uyrvydcPZnZ2dnUVZ_sednZ2d@speakeasy.net> ankyhe at gmail.com wrote: > L = [4,3,2,1] > L=L.sort() > L will refer to None, why L.sort() don't return the L? > I want to ask why the designer of Python do so? Because that's the convention that signifies that a Python method mutates the object rather than returns a new one. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Sitting in the den and / Looking at the phone as if it owed / Owed me a favor -- Blu Cantrell From Bobert at strasbourg.france Fri May 19 13:49:00 2006 From: Bobert at strasbourg.france (Bobert) Date: Fri, 19 May 2006 19:49:00 +0200 Subject: Daily python url archives Message-ID: <pan.2006.05.19.17.48.58.716100@strasbourg.france> Hi, Do you know by chance if someone has archives from the "daily python url" feed (http://www.pythonware.com/daily/rss2.xml) ? An archive of the last 3 or 6 months would be most useful to me. Many thanks in advance, Cheers From tjreedy at udel.edu Mon May 22 20:45:54 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 22 May 2006 20:45:54 -0400 Subject: Too big of a list? and other problems References: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> Message-ID: <e4tm0g$kdp$1@sea.gmane.org> "Brian" <bnblazer at gmail.com> wrote in message news:1148343552.037687.214420 at j55g2000cwa.googlegroups.com... > First off, I am sorry for cluttering this group with my inept > questions, but I am stuck again despite a few hours of hair pulling. > > I have a function (below) that takes a list of html pages that have > images on them (not porn but boats). This function then (supposedly) > goes through and extracts the links to those images and puts them into > a list, appending with each iteration of the for loop. The list of > html pages is 82 items long and each page has multiple image links. > When the function gets to item 77 or so, the list gets all funky. > Sometimes it goes empty, and others it is a much more abbreviated list > than I expect - it should have roughly 750 image links. This does not make much sense without actual examples. But ... > When I looked at it while running, it appears as if my regex is > actually appending a tuple (I think) of the results it finds to the > list. because that is what you said to do. So foundpics will have 1 items appended per page. I am sure you want to .extend the list with the sequence returned by findall, not append. > My best guess is that the list is getting too big and croaks. Almost certainly not, unless you are out of memory, in which case you should get appropriate exception. If suggested edit is not enough, print the results of findall and even of foundPics with every iteration to investigate further. Add input statement so you can step thru iterations (perhaps after 50th or so). Terry Jan Reedy From robert.kern at gmail.com Thu May 18 19:35:07 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 May 2006 18:35:07 -0500 Subject: WTF? Printing unicode strings In-Reply-To: <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> Message-ID: <e4j0b9$7a7$1@sea.gmane.org> Ron Garret wrote: > I'm using an OS X terminal to ssh to a Linux machine. Click on the "Terminal" menu, then "Window Settings...". Choose "Display" from the combobox. At the bottom you will see a combobox title "Character Set Encoding". Choose "Unicode (UTF-8)". > But what about this: > >>>>f2=open('foo','w') >>>>f2.write(u'\xFF') > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in > position 0: ordinal not in range(128) > > That should have nothing to do with my terminal, right? Correct, that is a different problem. f.write() expects a string of bytes, not a unicode string. In order to convert unicode strings to byte strings without an explicit .encode() method call, Python uses the default encoding which is 'ascii'. It's not easily changeable for a good reason. Your modules won't work on anyone else's machine if you hack that setting. > I just found http://www.amk.ca/python/howto/unicode, which seems to be > enlightening. The answer seems to be something like: > > import codecs > f = codecs.open('foo','w','utf-8') > > but that seems pretty awkward. <shrug> About as clean as it gets when dealing with text encodings. -- 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 wrffruntre at tznvy.pbz.ROT13 Tue May 2 15:07:48 2006 From: wrffruntre at tznvy.pbz.ROT13 (Jesse Hager) Date: Tue, 02 May 2006 15:07:48 -0400 Subject: stripping In-Reply-To: <1146550856.291511.5780@v46g2000cwv.googlegroups.com> References: <1146550856.291511.5780@v46g2000cwv.googlegroups.com> Message-ID: <125fbfiphjsdl78@corp.supernews.com> micklee74 at hotmail.com wrote: > hi > i have a file test.dat eg > > abcdefgh > ijklmn > <-----newline > opqrs > tuvwxyz > <---newline > > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break > #if not re.findall(r'^$',line): > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all..? > thanks > Change the 'break' statement to a 'continue'. -- Jesse Hager email = "wrffruntre at tznvy.pbz".decode("rot13") From roy at panix.com Sun May 21 17:32:21 2006 From: roy at panix.com (Roy Smith) Date: Sun, 21 May 2006 17:32:21 -0400 Subject: Iterators: Would "rewind" be a good idea? References: <4470C2E5.1020004@earthlink.net> <mailman.6042.1148244425.27775.python-list@python.org> <vM4cg.20452$Lm5.11170@newssvr12.news.prodigy.com> Message-ID: <roy-1BCCB1.17322121052006@reader1.panix.com> Edward Elliott <nobody at 127.0.0.1> wrote: > This is why the C++ STL has independent forward and backward iterator types. Let me see if I can paraphrase the difference between the Python design philosophy and the C++ design philosophy about most things. Python says, "Let's make things simple enough that it can be explained fully in a couple of paragraphs, even if it means there are some things you can't do". C++ says, "Let's make it possible to do anything, even if it makes it complicated enough that it takes a shelf full of books to explain it all". There may be value in restartable iterators, but comparing what we've got now to STL isn't the way to convince people it's a good idea :-) From fabiofz at gmail.com Wed May 17 14:35:14 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Wed, 17 May 2006 15:35:14 -0300 Subject: How to couple pyunit with GUI? In-Reply-To: <1147879480.640335.252950@y43g2000cwc.googlegroups.com> References: <1147879480.640335.252950@y43g2000cwc.googlegroups.com> Message-ID: <cfb578b20605171135q254b6e0fsfbe81a16bc4ab9ab@mail.gmail.com> On 17 May 2006 08:24:40 -0700, volcano <Mark.Geyzer at gmail.com> wrote: > > I am desperately looking for an info how to combine a testing > application with decent GUI interface - the way most xUnits do. I > believe I have seen something about using Tkinter, but I do not > remember - where. > I am working on a complex testing application built over unittest > module, and I need GUI interface that will alllow me to select tests at > different levels of test hierarchy tree. > I am new to python, so say everything slow and repeat it twice:) > > -- > http://mail.python.org/mailman/listinfo/python-list Have you checked http://pyguiunit.sourceforge.net/ -- it is for PyQt, but can probably be adapted for other GUIs. -- Fabio -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060517/6512908b/attachment.html> From claudio.grondi at freenet.de Wed May 24 10:59:25 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 24 May 2006 16:59:25 +0200 Subject: John Bokma harassment In-Reply-To: <1148470149.596188.18500@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> Message-ID: <e51sc9$atc$1@newsreader3.netcologne.de> Tim N. van der Leeuw wrote: > ilitzroth at gmail.com wrote: > >>I agree there are limits to you right to free speech, but I believe Xah >>Lee is not crossing >>any boundaries. If he starts taking over newspapers and TV stations be >>sure to notify me, >>I might revise my position. >>Immanuel > > > Perhaps he's not crossing boundaries of free speech, but he's > repeatedly crossing boundaries on usenet nettiquette, even though > repeatedly he's being asked not to do so. (Extensive crossposting to > various usenetgroups / mailing lists, for instance). > > If he would just post his stuff on a blog and find a way to get people > to visit his blog, without crossposting to 10 usenest groups for each > post he makes to his blog, then nobody would mind him expressing his > opinions, and those interested could discuss them wildly on the blog. > > But I've repeatedly seen people telling him not to crosspost his essays > to so many newsgroups, yet he continues doing it. > If that's enough to quit his subscription with his ISP I don't know, > but since I've stopped following threads originated by him I don't know > what other grounds there would be. > > Cheers, > > --Tim > Well said, Tim. Claudio From bborcic at gmail.com Tue May 2 15:44:21 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 21:44:21 +0200 Subject: simultaneous assignment In-Reply-To: <pan.2006.05.02.19.35.15.219815@hastings.org> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <I9O5g.2039$No6.43918@news.tufts.edu> <pan.2006.05.02.19.35.15.219815@hastings.org> Message-ID: <4457b69b$1_1@news.bluewin.ch> Steve R. Hastings wrote: > len([v for v in seq if v]) # builds a list, then feeds it to len() > len(v for v in seq if v) # gen obj feeds values to len one at a time note that generators have no defined length - precisely because they feed values one at a time while you need them all together to speak of a length. The second expression will raise a TypeError because of that. If you want to count objects with a generator expression, use sum(1 for v in seq if some_condition(v)) which is also clearer imho; summing ones for each item satisfying a condition - isn't that a definition of counting ? From mark.dufour at gmail.com Thu May 4 09:03:14 2006 From: mark.dufour at gmail.com (Mark Dufour) Date: Thu, 4 May 2006 15:03:14 +0200 Subject: Shed Skin Python-to-C++ Compiler - Summer of Code? Message-ID: <8180ef690605040603wd28625csd99049cd1369c32e@mail.gmail.com> Hello all, As Bearophile pointed out, I have just released Shed Skin 0.0.8. For those of you that do not know Shed Skin, it is an optimizing Python-to-C++ compiler, that allows for translation of pure (unmodified) Python programs into optimized machine language. The speed of generated code is typically 2-40 times, 12 on average, faster than when using Psyco, and 2-220 times, 45 on average, than when using CPython, for a sizeable set of benchmarks (such as a raytracer, chess player, othello player, neural network sim, sat solver, several sudoku solvers..) See http://mark.dufour.googlepages.com for a more detailed introduction to Shed Skin, its current limitations, and a link to my Master's Thesis, which contains more precise results and an explanation of how the compiler works. Now that I have released a fairly clean and stable (but still very much alpha!) version of my compiler, I would like to invite other people to join the project. Seeing that the SoC application deadline for this year is only in about a week (:P), this would be a nice way to help out and get started in SS development. Note that I did a SoC project on SS last year, which has improved it tremendously. Two important aspects that still need to be investigated are memory optimizations (e.g. transforming heap allocation into stack- and static preallocation), more efficient string support (rather than using the inefficient C++ STL string type) and looking at integration with the standard library and calling compiled code from Python. Note that especially memory optimizations would also be an interesting Master's Thesis topic. Again, see http://mark.dufour.googlepages.com for more details about possible ways to help out. Please let me know if you are even remotely interested :-) Otherwise, a simple way to also help out, is to send me bug reports of small code fragments that SS does not compile correctly, or you can just send me complete programs. Bug reports are always motivating, make my work more time-efficient, and are the best way to getting your own programs supported. Thanks. Mark. -- "How should I know if it works? That's what beta testers are for. I only coded it." - Linus Torvalds From larry.bates at websafe.com Thu May 25 13:05:09 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 25 May 2006 12:05:09 -0500 Subject: Modify one character in a string In-Reply-To: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> References: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> Message-ID: <4475E3C5.4040500@websafe.com> mp wrote: > X-No-Archive > How do I go about modifying one character in a string elegantly? > In other words, I want a function that will change 'aaaa' to 'aaza', > given the index 2 of the character in the string. > > Also, how do I do this when dealing with a file ; which file mode > should I use and what function should I use to modify a single > character once in that file mode? > > Thanks > MP > IMHO the most elegant method is something like: def switchchar(srcstring, position, character): b=list(srcstring) b[2]=character return ''.join(b) You should open file in binary 'b' mode. Use .seek() method to seek to the character you want to replace. use .write() method to write one character. -Larry From scott.daniels at acm.org Mon May 22 14:16:31 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 22 May 2006 11:16:31 -0700 Subject: performance difference between OSx and Windows In-Reply-To: <1148294382.741146.274830@j55g2000cwa.googlegroups.com> References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> <1148254182.824583.195370@i40g2000cwc.googlegroups.com> <1148255177.190455.217840@u72g2000cwu.googlegroups.com> <1148263521.205652.286240@j55g2000cwa.googlegroups.com> <1148267986.876892.123110@i40g2000cwc.googlegroups.com> <1148294382.741146.274830@j55g2000cwa.googlegroups.com> Message-ID: <4471fbe1$1@nntp0.pdx.net> Brian wrote: > As one additional question, can someone point me in the direction of a > resource that would explain how I could use Python to tell me what core > is actually handling the process? I am not even sure if something like > this exists, but it would be an interesting feature to explore. Since the GIL is released from time to time (on any system call that may wait, for example), it is a single core at any one instant, but is not necessarily the same core over time. --Scott David Daniels scott.daniels at acm.org From deets at nospam.web.de Tue May 30 13:35:33 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 May 2006 19:35:33 +0200 Subject: iterator? way of generating all possible combinations? References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <mailman.6282.1148767807.27775.python-list@python.org> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> Message-ID: <4e3e6hF1cp3p8U1@uni-berlin.de> akameswaran at gmail.com wrote: > > > Well thanks for the mathematical restatement of my problem. I had > forgotten the proper terms. Searching on those terms generates some > interesting results. > > However, none of the algo's I have checked will work with generated > sequences, or iterable classes, as posited in my first post. > > While appropriate to the current domain, ie dice. What if you want > combinations of extrememely large lists, say 3 sets of 10 mil items. > In such a case, I really do want my sets to be generators rather than > lists or set objects. > > This is what had me stumped before, and still has me stumped. def combinations(l, depth): if depth == 1: for element in l: yield (element,) else: for element in l: for rest in combinations(l, depth -1 ): yield (element,) + rest HTH, Diez From python.list at tim.thechases.com Thu May 18 18:32:09 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 18 May 2006 17:32:09 -0500 Subject: number of different lines in a file In-Reply-To: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> Message-ID: <446CF5E9.5030909@tim.thechases.com> > I have a million-line text file with 100 characters per line, > and simply need to determine how many of the lines are distinct. A few ideas: 1) the shell way: bash$ sort file.in | uniq | wc -l This doesn't strip whitespace...a little sed magic would strip off whitespace for you: bash$ sed 'regexp' file.in | sort | uniq | wc -l where 'regexp' is something like this atrocity 's/^[[:space:]]*\(\([[:space:]]*[^[:space:]][^[:space:]]*\)*\)[[:space:]]*$/\1/' (If your sed supports "\s" and "\S" for "whitespace" and "nonwhitespace", it makes the expression a lot less hairy: 's/^\s*\(\(\s*\S\S*\)*\)\s*$/\1/' and, IMHO, a little easier to read. There might be a nice/concise perl one-liner for this too) 2) use a python set: s = set() for line in open("file.in"): s.add(line.strip()) return len(s) 3) compact #2: return len(set([line.strip() for line in file("file.in")])) or, if stripping the lines isn't a concern, it can just be return len(set(file("file.in"))) The logic in the set keeps track of ensuring that no duplicates get entered. Depending on how many results you *expect*, this could become cumbersome, as you have to have every unique line in memory. A stream-oriented solution can be kinder on system resources, but would require that the input be sorted first. -tkc From li19104 at yahoo.com Mon May 15 20:39:01 2006 From: li19104 at yahoo.com (Shirley Li) Date: Mon, 15 May 2006 17:39:01 -0700 (PDT) Subject: Python modules Message-ID: <20060516003901.11507.qmail@web53815.mail.yahoo.com> Dear Python experts, I'm a beginner of Python programming. I have a question about Python modules. With the following: ================= import sys, os, string, math from Numeric import * from Matrix import * ================= at the beginning of my Python script, it complained that "ImportError: No module named Numeric" when I run the script. Could someone tell me what's wrong? Any help/info will be greatly appreciated. Shirley --------------------------------- Yahoo! Messenger with Voice. Make PC-to-Phone Calls to the US (and 30+ countries) for 2?/min or less. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060515/9dd72b9d/attachment.html> From nogradi at gmail.com Sun May 21 15:52:25 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Sun, 21 May 2006 21:52:25 +0200 Subject: getattr for modules not classes Message-ID: <5f56302b0605211252k79b642efl5ff4653fe7d17768@mail.gmail.com> Is there something analogous to __getattr__ for modules? I know how to create a class that has attributes from a list and nothing else by overloading __getattr__ and making sure that the accessed attribute appears in my list. Now I would like to do the same with a module, say x.py, in which I have a list, say mylist, and after importing x from another module I would like to be able to say x.one( ) or x.two( ) if 'one' and 'two' are in mylist and raise an exception if they aren't. Is this possible? From dadapapa at googlemail.com Thu May 11 09:45:06 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 11 May 2006 06:45:06 -0700 Subject: scientific libraries for python Message-ID: <1147355105.972329.115480@y43g2000cwc.googlegroups.com> Hi all, I want to use the current need for a Levenberg-Marquardt least squares fitting procedure for my long term desire to dive into scientific libraries for python. However, I am always confused by the shear sheer variety of available packages and the fact that some of them (Numeric, Numarray) seem to be outdated. http://wiki.python.org/moin/NumericAndScientific gives a nice overview of the most popular packages. According to this listing, ScientificPython and PyDSTool seem most appropriate for what I generally work on (simulations of dynamical systems and data analysis). Before I start to dive into one of these packages (I would go for ScientificPython from what I know so far), I want to ask about your experiences. Is there a good reason to choose one instead of the other? Or do they even work together, in the sense that I can use PyDSTool to generate data to be later analyzed by ScientifPython without much timeconsuming conversion a.s.o. in between? Thanks for any suggestions! - harold - From cookedm+news at physics.mcmaster.ca Wed May 17 21:49:07 2006 From: cookedm+news at physics.mcmaster.ca (David M. Cooke) Date: Wed, 17 May 2006 21:49:07 -0400 Subject: ANN: NumPy 0.9.8 released References: <mailman.5856.1147912897.27775.python-list@python.org> Message-ID: <qnk8xp0je5o.fsf@arbutus.physics.mcmaster.ca> "Travis E. Oliphant" <oliphant.travis at ieee.org> writes: > NumPy 0.9.8 has been released. It can be downloaded from > > http://numeric.scipy.org > > The release notes are attached. > > Best regards, > > -Travis Oliphant > NumPy 0.9.8 is a bug-fix and optimization release with a > few new features. The C-API was changed so that extensions compiled > against NumPy 0.9.6 will need re-compilation to avoid errors. > > The C-API should be stabilizing. The next release will be 1.0 which > will come out in a series of release-candidates during Summer 2006. > > There were many users and developers who contributed to the fixes for > this release. They deserve much praise and thanks. For details see > the Trac pages where bugs are reported and fixed. > > http://projects.scipy.org/scipy/numpy/ > > > * numpy should install now with easy_install from setuptools Note that you'll need to use the latest setuptools (0.6b1). The hacks I added to get easy_install and numpy.distutils to get along are hard enough without trying to be backward compatible :-( -- |>|\/|< /--------------------------------------------------------------------------\ |David M. Cooke |cookedm(at)physics(dot)mcmaster(dot)ca From NA at NA.com Sat May 13 04:13:23 2006 From: NA at NA.com (N/A) Date: Sat, 13 May 2006 16:13:23 +0800 Subject: plot data from Excel sheet by Matplotlib, how? Message-ID: <e444f4$ecj$1@enyo.uwa.edu.au> Hi all, Can any1 please guide me how to plot data from Excel by Matplotlib? Let's say, I have 78(rows) x 8(cols) data in an Excel sheet. I would like to plot data for all 78(rows) at 4th column against data for all 78(rows) at 7th column. How to plot it? Thank u! From DirkHagemann at gmail.com Fri May 19 05:45:02 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 19 May 2006 02:45:02 -0700 Subject: Windows Registry Dump In-Reply-To: <4d3hepF185ne6U1@uni-berlin.de> References: <1147964415.540190.47480@i40g2000cwc.googlegroups.com> <4d3hepF185ne6U1@uni-berlin.de> Message-ID: <1148031902.238612.250810@g10g2000cwb.googlegroups.com> @Diez: I'm not trying to hack into somebody's computer - it is about collecting data from my company's anti-virus-parent-server. And all the information is only available in the registry (thanks Symantec...). @Tim, olso and Fredrik: THANKS - I will have a closer look at these modules. regards Dirk From johnjsal at NOSPAMgmail.com Tue May 9 13:10:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 17:10:57 GMT Subject: Python editor recommendation. In-Reply-To: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <B248g.2069$No6.45840@news.tufts.edu> DeepBlue wrote: > Hi all, > > Can any one please recommend me an editor for coding Python. Thank u. > I have Komodo (www.activestate.com) in my mind. Is the editor any good? > > regards. As a newbie (referring to myself), I recommend typing everything by hand first, so you will learn all the little things that need to be done. I find that IDEs, and even some editors that have auto-complete, etc., necessarily cause your mind to skip over some things that, while you are new to the language, you should do manually. Of course, if you aren't new, ignore this post entirely! :) From eurleif at ecritters.biz Mon May 8 00:35:51 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Mon, 08 May 2006 00:35:51 -0400 Subject: which is better, string concatentation or substitution? In-Reply-To: <445ec45e$0$1965$c3e8da3@news.astraweb.com> References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> Message-ID: <445ec9f6$0$3686$4d3efbfe@news.sover.net> John Salerno wrote: > My initial feeling is that concatenation might take longer than > substitution Doesn't look that way: leif at ubuntu:~$ python -m timeit "'<p>%s</p>\n\n' % 'foobar'" 1000000 loops, best of 3: 0.6 usec per loop leif at ubuntu:~$ python -m timeit "'<p>' + 'foobar' + '</p>\n\n'" 1000000 loops, best of 3: 0.358 usec per loop > but that it is also easier to read: I prefer string formatting for readability, but it's a matter of personal preference. From knowledge at world.net Sat May 20 00:42:04 2006 From: knowledge at world.net (Knowledge) Date: Sat, 20 May 2006 05:42:04 +0100 Subject: Find Your Soul Mate Message-ID: <newscache$cbrkzi$8x6$1@newsfront4.netvisao.pt> Find Your Soul Mate ! Cheat Your Wife/Husband! Try New Things! Or Just Met Friends! http://affiliatecash.designerlove.com/idevaffiliate.php?id=3537 From santosh.pandey at gmail.com Thu May 4 16:24:48 2006 From: santosh.pandey at gmail.com (san) Date: 4 May 2006 13:24:48 -0700 Subject: Can I use python for this .. ?? In-Reply-To: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> Message-ID: <1146774288.904851.278130@i39g2000cwa.googlegroups.com> btw i got the firefox to open and access some webpage and winamp running .. code below ---------- import os import os.path import subprocess # Web pages ffox_exe = r'C:\Program Files\Mozilla Firefox\firefox.exe' assert os.path.exists(ffox_exe) # open gmail url = "http://www.gmail.com" child = subprocess.Popen( (ffox_exe, url), executable = ffox_exe) rc = child.wait() # Winamp wamp_exe = r'C:\Program Files\Winamp\winamp.exe' assert os.path.exists(wamp_exe) url = "http://64.236.34.97:80/stream/1040" child = subprocess.Popen( (wamp_exe, url), executable = wamp_exe) ------------ now is there anyway i can enter user name and password and then click okay .. (not for gmail but for other similar webpages which require loggin) .. ?? how to open pages in tabs .. ?? San From aahz at pythoncraft.com Fri May 19 22:57:52 2006 From: aahz at pythoncraft.com (Aahz) Date: 19 May 2006 19:57:52 -0700 Subject: DO NOT USE file() (was Re: altering an object as you iterate over it?) References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <e4la8j$od9$1@daisy.noc.ucla.edu> Message-ID: <e4m0jg$o3t$1@panix3.panix.com> In article <e4la8j$od9$1 at daisy.noc.ucla.edu>, James Stroud <jstroud at ucla.edu> wrote: >Paul McGuire wrote: >> >> 1. open("xxx") still works - not sure if it's even deprecated or not - but >> the new style is to use the file class > >Python 2.3.4 (#4, Oct 25 2004, 21:40:10) >[GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. >py> open is file >True Python 2.5a2 (trunk:46052, May 19 2006, 19:54:46) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> open is file False Per the other comments in this thread, Guido agreed that making open() a synonym of file() was a mistake, and my patch to split them was accepted. Still need to do more doc update (per Uncle Timmy complaint), but that shouldn't be too hard. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From usenet at local.machine Thu May 25 10:03:54 2006 From: usenet at local.machine (=?ISO-8859-2?Q?Dra=BEen_Gemi=E6?=) Date: Thu, 25 May 2006 16:03:54 +0200 Subject: John Bokma harassment In-Reply-To: <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> Message-ID: <e54crf$5lp$1@magcargo.vodatel.hr> Larry Elmore wrote: > No shit. Lately it seems that for every "spam" post of Xah's, there's > at three or more by John *to all the same newsgroups* bitching about > Xah's use of bandwidth. Pot, meet kettle. I'm killfiling Xah for being > a useless twit and killfiling John for being a prick about it. There is a person on USENET, particularly in hr. hierarchy that posts under three different accounts. Sometimes he argues with himself, and sometimes event supports himself :-) Maybe we have the similar case here. DG From alanalan at newsgroup.nospam Wed May 31 13:29:22 2006 From: alanalan at newsgroup.nospam (A.M) Date: Wed, 31 May 2006 13:29:22 -0400 Subject: Are ActivePython scripts compatible with Linux? References: <Knjfg.1106$Su3.100610@news20.bellglobal.com> <SYCdnZBPbu0GTeDZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <Ckkfg.1120$Su3.101476@news20.bellglobal.com> Thanks alot Larry for your comprehensive answer. "Larry Bates" <larry.bates at websafe.com> wrote in message news:SYCdnZBPbu0GTeDZnZ2dneKdnZydnZ2d at comcast.com... > Short answer: yes > > Things to watch out for: > > 1) Versions on both Windows/Linux need to be compatible. If Linux > has same or later version, you are normally OK. If Linux version > is older, you will have to use only Python Libraries and functions > that are in the oldest version. > > 2) Don't use OS-specific constructs. Things like backslashes > in filenames, etc. Use os.path.join, os.path.basename, etc. to work > with paths. Linux has OS-specific code that handles all the > cross-OS problems for you if you use these methods. Don't hard > code drive letters in your code, Linux/Mac don't have drive letters. > > 3) Obviously you can't use Python Windows extensions, which won't > port. You can't move something that is written as COM object or > as a Windows service (sorry those were probably too obvious ;-). > > 4) If you use GUI, use something that is cross-platform (like > wxWindows, TK, etc.). You can't use Windows-specific GUI calls. > > 5) You can be affected by word length issues if you move from > 32-bit Windows to 64-bit Linux. Normally this is only only > a problem if you use struct module to pack/unpack buffers or if > you do bit shift operations (e.g. <<, >>). > > 6) Don't depend on Windows line endings in files. Linux/Mac > use different ones than Windows. > > 7) Some Linux machine have different endian storage of bytes. > If you do bit shifting or struct pack/unpack you will need to > take that into account. > > 8) If you have OS-specific "things" in your code, put them in > a function or class that can easily be rewritten for the > specific OS you are porting to. Don't spread them out all > through your code. It is much easier to rewrite a couple of > functions/classes that are OS-specific than it is to try to > find problems all over your program. > > Hope info helps at least a little. > > -Larry > > > A.M wrote: >> Hi, >> >> >> >> I am planning to develop python applications on windows and run them on >> Linux. Are ActivePython scripts compatible with Linux? Is there any >> guideline that explains the compatibility issues between python in >> different >> platforms? >> >> >> >> What would be the best approach for what I am trying to do? >> >> >> >> Any help would be appreciated, >> >> Alan >> >> From email at christoph-haas.de Tue May 9 08:07:15 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 9 May 2006 14:07:15 +0200 Subject: installing numpy In-Reply-To: <873bfj5sp5.fsf@localhost.localdomain> References: <877j4v5ukc.fsf@localhost.localdomain> <mailman.5505.1147174470.27775.python-list@python.org> <873bfj5sp5.fsf@localhost.localdomain> Message-ID: <20060509120715.GB20063@torf.workaround.org> On Tue, May 09, 2006 at 09:43:50PM +1000, Gary Wessle wrote: > Christoph Haas <email at christoph-haas.de> writes: > > > On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote: > > > I am trying to install NumPy in my debian/testing linux > > > 2.6.15-1-686. > > > > > > with no numpy for debian/testing, I am left alone, since the > > > experimental version available by debian will result in a dependency > > > nightmares, > > > > What about "python-numeric"? Found through "apt-cache search numpy". > > is no longer maintained, notice my previous post titled "Numerical > Python Tutorial errors" Are you sure? The last update of the Debian package was slightly over a month ago (http://packages.qa.debian.org/p/python-numeric.html). And the description text reads: """ Description: Numerical (matrix-oriented) Mathematics for Python The Numeric Extensions to Python (NumPy) ... """ And finally the /usr/share/doc/python-numeric/copyright.Debian reads: "It was downloaded from http://numpy.sourceforge.net/" Kindly Christoph P.S.: Your mail client seems break the references. Your reply doesn't show up as a proper followup to my posting. -- Please reply to the list - not to me personally. Personal replies are ignored. From jeremy at emperorlinux.com Fri May 26 17:10:23 2006 From: jeremy at emperorlinux.com (Jeremy L. Moles) Date: Fri, 26 May 2006 17:10:23 -0400 Subject: chop() and empty() functions In-Reply-To: <44776377.7090304@lexicon.net> References: <mailman.6253.1148664337.27775.python-list@python.org> <44776377.7090304@lexicon.net> Message-ID: <1148677823.14341.14.camel@localhost.localdomain> On Sat, 2006-05-27 at 06:22 +1000, John Machin wrote: > On 27/05/2006 2:54 AM, Jeremy L. Moles wrote: > > ["chop" snipped] > > > > > Furthermore, what do people think about the idea of adding a truly > > empty, no-op global lambda somewhere in Python? I use them a lot > > What is the use case? Why write something like """empty(foo, 42, > cmd="xyzzy")""" when you could merely write "pass" or nothing at all? Well, in a lot of the libraries I use, there is often a need for a callback of some sort. Sure, I--and most other people--often define an empty, no-op function of some sort when you want to at least have "something" there, but I thought it might be kinda' neat to be able to have a builtin called empty() or noop() that returned a (possibly optimized?) function that just did nothing. :) It probably is a dumb idea, hehe... the chop() was the big one I thought people might comment on. For example, I often do stuff like this for handling "input events" in soya: evhandlers = [emptyfunc for i in range(MAX_NUM_EVENTS)] evhandlers[EVENT_NUMBER] = self.my_handler_function ...and then in the actual input loop I'll come along and say... evhandlers[ev](*args) In this way I don't have to test the value of any event and behave accordingly--I just send it on it's way. It's just an iterative way to say, "Okay, give me some default behavior for everything, and I'll come back around later and set the explicit handlers later." This same design is probably used in other areas too... that's why I brought up the "truly empty noop" thing; it would give me fuzzy feeling to know that in those cases where empty() is defined, nothing is happening (although, this could currently be the case in Python, I'm not sure--I don't know a lot about Python internals). Again, it's not a big deal. Just wondered what people thought. :) > > (usually defining a: empty = lambda *a, **k: None somewhere at the > > topmost module space), but if enough people did too, it might be worth > > adding an empty() builtin to much later versions of Python. > > From me at privacy.net Fri May 19 14:37:30 2006 From: me at privacy.net (Dan Sommers) Date: Fri, 19 May 2006 14:37:30 -0400 Subject: Python sqlite and regex. References: <mailman.5942.1148042842.27775.python-list@python.org> <1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> <hunbg.46845$CH2.29994@tornado.texas.rr.com> Message-ID: <m2u07lq2s5.fsf@unique.fqdn> On Fri, 19 May 2006 17:44:45 GMT, "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote: > "Gerhard H?ring" <gh at ghaering.de> wrote in message > news:mailman.5966.1148057291.27775.python-list at python.org... >> """ >> The REGEXP operator is a special syntax for the regexp() user >> function. No regexp() user function is defined by default and so use >> of the REGEXP operator will normally result in an error message. If a >> user-defined function named "regexp" is defined at run-time, that >> function will be called in order to implement the REGEXP operator. >> """ > This is very interesting. So I *could* define my own regexp function > that processes not regular expressions, but say, glob-like strings, > which are usually much easier for end users to work with (very basic > wild-carding where '*' matches one or more characters, and '?' matches > any single character - maybe add '#' to match any single digit and '@' > to match any single alpha character). Doesn't SQL already have lightweight wildcards? SELECT somefield FROM sometable WHERE someotherfield LIKE '%foo%' Regards, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From onurb at xiludom.gro Wed May 17 08:02:40 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 17 May 2006 14:02:40 +0200 Subject: assignment in a for loop In-Reply-To: <1147843606.982432.269470@38g2000cwa.googlegroups.com> References: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> <mailman.5781.1147842350.27775.python-list@python.org> <1147843606.982432.269470@38g2000cwa.googlegroups.com> Message-ID: <446b1147$0$24865$626a54ce@news.free.fr> MackS wrote: (snip) >>What's preventing the use of list comprehensions? >> >> new_list = [x+1 for x in old_list] > > Suppose I want to do anything as trivial as modify the values of the > list members _and_ print their new values. Then it's a sure design smell IMHO. Don't mix presentation with logic. > List comprehensions must not > contain statements, I think. You're right. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From ibr at radix50.net Tue May 30 17:41:52 2006 From: ibr at radix50.net (ibr at radix50.net) Date: Tue, 30 May 2006 23:41:52 +0200 Subject: logging In-Reply-To: <1149005605.819519.242350@j55g2000cwa.googlegroups.com> References: <mailman.6101.1148366215.27775.python-list@python.org> <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <mailman.6143.1148460752.27775.python-list@python.org> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> <mailman.6265.1148690064.27775.python-list@python.org> <1149005605.819519.242350@j55g2000cwa.googlegroups.com> Message-ID: <20060530214151.GA3913@radix50.net> Hello Vinay, On Tue, May 30, 2006 at 09:13:25AM -0700, Vinay Sajip wrote: > [snip] > > [handlers] > > keys=console > [snip] > > [logger_root] > > level=CRITICAL > > handlers=console > > > > [logger_l01] > > level=DEBUG > > qualname=l01 > > handlers=console > > > > [logger_l02] > > level=CRITICAL > > qualname=l02 > > handlers=console > [snip] ... > > When I run the script, zzz is printed twice, and qqq isn't. I want that > > zzz is printed once. ... > Did you try removing the handler from l01, as I suggested in an earlier > reply? I had removed the whole line, and it complained about the missing handlers line. Now I've tried with 'handlers=', this seems to work. Thanks much! > The reason that zzz is printed twice is that when a logger decides to > process an event, it is passed to handlers attached to ancestor > loggers (unless propagate is set to 0 - but this is not the normal > situation). So, log1 is deciding to process the event (based on the > level), and passing it to its own handlers (l01->console) and then to > its ancestor loggers' handlers (root->console). Hmm, log1 decides once whether to print an event, and after that it gets printed in log1 and all its ancestors, regardless of their level? I find this quite counter-intuitive. I'd instead expect that each logger decides whether to print an event according to its own level. Could you give an example why one would want the python behavior? With kind regards, Baurzhan. From johnzenger at gmail.com Wed May 3 15:15:20 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 3 May 2006 12:15:20 -0700 Subject: Gettings subdirectories In-Reply-To: <e3au5u$drm$1@news.in.tum.de> References: <e3au5u$drm$1@news.in.tum.de> Message-ID: <1146683720.748769.36490@g10g2000cwb.googlegroups.com> It's a bit overkill, but consider using os.walk. root, dirnames, filenames = os.walk(r"C:\").next() # (in real code, you'd want to catch exceptions here) print dirnames Florian Lindner wrote: > Hello, > how can I get all subdirectories of a given directories? os.listdir() gives > me all entries and I've found no way to tell if an object is a file or a > directory. > > Thanks, > > Florian From kkylheku at gmail.com Thu May 11 13:05:27 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 11 May 2006 10:05:27 -0700 Subject: Multi-line lambda proposal. In-Reply-To: <slrne662c4.9qk.sybrenUSE@schuimige.stuvel.eu> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <slrne63ahp.dac.apardon@rcpc42.vub.ac.be> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> <1147333696.789718.189050@v46g2000cwv.googlegroups.com> <slrne662c4.9qk.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1147367127.569933.213710@i39g2000cwa.googlegroups.com> Sybren Stuvel wrote: > yairchu at gmail.com enlightened us with: > > this is how I think it should be done with multi-line lambdas: > > > > def arg_range(inf, sup, f): > > return lambda(arg): > > if inf <= arg <= sup: > > return f(arg) > > else: > > raise ValueError > > This is going to be fun to debug if anything goes wrong. Ever seen > such a traceback? I'm looking at various tracebacks now. I don't see any special problems with lambdas. Inner functions are inadequately identified, so that the file and line number has to be used, which works just as well as for lambdas. > A function decorator is supposed to add something to a function. The > syntax that sticks the closest to that of defining a function seems > most Pythonic to me. Which proposed lambda syntax is closest in this sense? > I can already foresee that I'll have a tougher time explaining your > lambda-based "decorators", than the current decorators, to people > learning Python. Is it unusual to have a tougher time explaining X than Y to people who are learning a language, where X and Y are different features? For instance, an assignment statement is easier to explain than a metaclass. Therefore, assignment statements are probably going to be covered in an earlier lecture of a Python course than metaclasses. In what language are features equally easy to explain? It's possible to use Python while pretending that lambdas don't exist at all. (That's true of the lambda in its current form, as well as the proposed forms). From johnjsal at NOSPAMgmail.com Tue May 16 16:41:02 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 20:41:02 GMT Subject: calling upper() on a string, not working? In-Reply-To: <mailman.5767.1147811690.27775.python-list@python.org> References: <Ayqag.2108$No6.45797@news.tufts.edu> <mailman.5767.1147811690.27775.python-list@python.org> Message-ID: <yNqag.2109$No6.46071@news.tufts.edu> Felipe Almeida Lessa wrote: > Em Ter, 2006-05-16 ?s 20:25 +0000, John Salerno escreveu: >> it doesn't seem to work. The full code is below if it helps to understand. > > Why doesn't it work? What does it do, what did you expect it to do? If you run the whole script with the first line (the one not commented), you get output similar to this, which is correct: >>> ["AMN RIPQ LP WOQ SNIS. BW VIDQ, LQ'P WOQ NHNW RIPQ.", 'ULJJLIY TIZJXWNE'] >>> But if you use the line with the upper() call, you get this: >>> ["Bhe past is not dead. Dn fact, it's not even past.", 'Killiam Qaulkner'] >>> Now, I know the actual upper() function works, but I can't understand if there's a problem with *when* it's being called, or what's being done with it to get the second result above. From funkyj at gmail.com Fri May 19 13:19:51 2006 From: funkyj at gmail.com (funkyj) Date: 19 May 2006 10:19:51 -0700 Subject: how to suppress the "source code echo" output by warnings.warn("x")? Message-ID: <1148059191.067419.112040@38g2000cwa.googlegroups.com> I've been googling around trying to find the answer to this question but all I've managed to turn up is a 2 year old post of someone else asking the same question (no answer though). http://groups.google.com/group/comp.lang.python/browse_frm/thread/8004c690b8c4db53/81e460a0ee8b03a5?lnk=st&q=python+warnings+echo&rnum=6#81e460a0ee8b03a5 jh> In the following jh> jh> import warnings jh> warnings.warn('change me') jh> jh> The warning is issued: jh> jh> hunter:~/python/test> python test.py jh> test.py:3: UserWarning: change me jh> warnings.warn('change me') jh> jh> I want to supress the line echo. Eg, I just want jh> jh> hunter:~/python/test> python test.py jh> test.py:3: UserWarning: change me jh> jh> How do I configure warnings to do this? Perhaps this can't be done without rewriting the warning module? From perlefar at gmail.com Thu May 25 03:43:26 2006 From: perlefar at gmail.com (Zameer) Date: 25 May 2006 00:43:26 -0700 Subject: Best way to handle exceptions with try/finally In-Reply-To: <1148513110.914528.121280@i40g2000cwc.googlegroups.com> References: <mailman.6122.1148413632.27775.python-list@python.org> <pan.2006.05.24.11.59.47.24496@thomas-guettler.de> <1148481073.976420.316970@j55g2000cwa.googlegroups.com> <mailman.6152.1148486485.27775.python-list@python.org> <1148511177.319796.228280@g10g2000cwb.googlegroups.com> <1148513110.914528.121280@i40g2000cwc.googlegroups.com> Message-ID: <1148543006.392324.74040@j33g2000cwa.googlegroups.com> I wonder where the "else" goes in try..except..finally... From fabianosidler at gmail.com Tue May 2 14:35:05 2006 From: fabianosidler at gmail.com (Fabiano Sidler) Date: Tue, 2 May 2006 20:35:05 +0200 Subject: unable to resize mmap object In-Reply-To: <1146423993.105177.182420@v46g2000cwv.googlegroups.com> References: <mailman.5159.1146398546.27775.python-list@python.org> <1146423993.105177.182420@v46g2000cwv.googlegroups.com> Message-ID: <200605022035.05164.fabianosidler@gmail.com> On Sunday 30 April 2006 21:06, Serge Orlov wrote: > Fabiano Sidler wrote: >> Now, when I try to resize mm to 10 byte >> --- snip --- >> mm.resize(10) >> --- snap --- >> I get an EnvironmentError:[Errno 22] Invalid argument. > > Just a guess: try a new size argument that is multiple of page size. No, doesn't work neitzer. :( Thank you anyway for the idea! From kentilton at gmail.com Wed May 10 10:58:36 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 10 May 2006 10:58:36 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147252695.346762.20020@y43g2000cwc.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147252695.346762.20020@y43g2000cwc.googlegroups.com> Message-ID: <xcn8g.11$FO5.5@fe08.lga> sross wrote: >>I do wonder what would happen to Cells if I ever want to support >>multiple threads. Or in a parallel processing environment. > > > AFAIK It should be fine. > In LW, SBCL and ACL all bindings of dynamic variables are thread-local. > Ah, I was guilty of making an unspoken segue: the problem is not with the *dependent* special variable, but with the sequentially growing numeric *datapulse-id* ("the ID") that tells a cell if it needs to recompute its value. The ID is not dynamically bound. If threads T1 and T2 each execute a toplevel, imperative assignment, two threads will start propagating change up the same dependency graph... <shudder> Might need to specify a "main" thread that gets to play with Cells and restrict other threads to intense computations but no Cells? Actually, I got along quite a while without an ID, I just propagated to dependents and ran rules. This led sometimes to a rule running twice for one change and transiently taking on a garbage value, when the dependency graph of a Cell had two paths back to some changed Cell. Well, Cells have always been reengineered in the face of actual use cases, because I am not really smart enough to work these things out in the abstract. Or too lazy or something. Probably all three. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From chris.van.bael at gmail.com Tue May 23 09:55:51 2006 From: chris.van.bael at gmail.com (Chris_147) Date: 23 May 2006 06:55:51 -0700 Subject: can't figure out error: module has no attribute... Message-ID: <1148392551.118437.255680@i39g2000cwa.googlegroups.com> but it seems to depend on from where I start the Python shell. so I've got a module selfservicelabels.py with some variables defined, like this: BtnSave = "link=label.save" DeliveryAutomaat = "//input[@id='deliveryMethod' and @value='AU']" This module is in the Lib directory. Now when I do import selfservicelabels selfservicelabels.BtnSave -> link=nmbs.label.save selfservicelabels.DeliveryAutomaat -> AttributeError: 'module' object has no attribute 'DeliveryAutomaat' to make it more strange: PyCrust and Idle recognise DeliveryAutomaat perfectly. Everything above is done with Python 2.4.3 on Windows XP SP2 So after some testing it seems to depend on from which partition I start Python. So open commandline and navigate to a dir on C: everything works perfectly. Close python shell en navigate to D: some variables in selfservicelabels.py are not known. What is going on here? Is this a known error? From aum at spam.me.please Mon May 29 03:30:20 2006 From: aum at spam.me.please (aum) Date: Mon, 29 May 2006 19:30:20 +1200 Subject: saving settings References: <e5e6g2$nbv$1@ss408.t-com.hr> Message-ID: <pan.2006.05.29.07.30.20.70376@spam.me.please> On Mon, 29 May 2006 09:05:36 +0200, SuperHik wrote: > Hi, > > I was wondering how to make a single .exe file, say some kind od clock, > and be able to save some settings (alarm for example) into the same > file? Basically make code rewrite it self... > > thanks! Yikes!!! I'd strongly suggest you read the doco for ConfigParser, and load/save your config file to/from os.path.join(os.path.expanduser("~")). Another option - save your stuff in the Windows Registry -- Cheers aum From robin at reportlab.com Fri May 26 05:06:42 2006 From: robin at reportlab.com (Robin Becker) Date: Fri, 26 May 2006 10:06:42 +0100 Subject: John Bokma harassment In-Reply-To: <e55660$r9q$1@sea.gmane.org> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148484597.410529.219960@j33g2000cwa.googlegroups.com> <e9e3813b0605240847g6e21dcdeyc3c8d50cc093b3f7@mail.gmail.com> <e55660$r9q$1@sea.gmane.org> Message-ID: <4476C522.6060104@chamonix.reportlab.co.uk> Steve Holden wrote: ...... > I too wrote to XL's hosting company pointing out that while he might be > an irritant he wasn't particularly abusive. Bokma, on the other hand, > can be. I don't like either of them much, but at least Xah Lee insults > everyone while Bokma appears to resort to ad hominem attacks frequently. It seems strange to me that XL gets such a bad rep. It takes at least two to make a flame war/troll work so why do others jump in with both feet. It's like many approaches to narcotics control ie try to stem the source, the proper approach is to halt the demand. Just stay silent. Trying to call XL a net abuser is just silly and wrong. Many people have ideas which others consider wrong, blasphemous, dangerous, stupid etc etc etc, but freedom of expression is important. -- Robin Becker From stijndesaeger at gmail.com Fri May 5 05:35:24 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 02:35:24 -0700 Subject: Tuple assignment and generators? In-Reply-To: <mailman.5358.1146821235.27775.python-list@python.org> References: <mailman.5334.1146755400.27775.python-list@python.org> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> <mailman.5358.1146821235.27775.python-list@python.org> Message-ID: <1146821724.732068.268960@g10g2000cwb.googlegroups.com> > so anything you don't understand, and cannot be bothered to look up in > the documentation, just has to be an inconsistent ad-hoc weird-gotcha > design ? Does the documentation mention that "x is y" returns True when they are both 0 but not when they are 100001 ? If so, I stand corrected. *plonk* away ... s. From rcs at bgoark.no Wed May 24 05:59:25 2006 From: rcs at bgoark.no (baalbek) Date: Wed, 24 May 2006 11:59:25 +0200 Subject: Using python for a CAD program In-Reply-To: <mailman.6079.1148309846.27775.python-list@python.org> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <e4ham3$1td$1@sea.gmane.org> <446C8950.3070107@anansispaceworks.com> <mailman.6000.1148109587.27775.python-list@python.org> <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> <mailman.6062.1148282177.27775.python-list@python.org> <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> <mailman.6079.1148309846.27775.python-list@python.org> Message-ID: <44742eef$0$22970$c83e3ef6@nn1-read.tele2.net> David Cuthbert wrote: > baalbek wrote: > >> David Cuthbert wrote: >> >>> This does not mean the design itself should be stored as an RDBMS. >>> As I've stated previously, CAD data (both electrical and, it appears, >>> mechanical) does not lend itself to RDBMS relationship modeling. >> >> >> I simply do not agree with this. >> >> A CAD program (like Autocad) is nothing >> but an advanced database editor: the program loads data from a binary >> file and creates its object (in memory) from the tables that it reads >> from the file on the disk. > > > Well, then, good luck with this. Let us know when you've rediscovered > that simply structuring data in a table does not make an RDBMS. Remember, a CAD binary file (at least most of them) stores its data in tables that are already in a (first?) normal form, similar to that of a RDBMS. The CAD program parses the data, and the CAD objects are created by database joins between the different tables (one table for layers, one table for colors, one table for geometrical data of the CAD entities, etc etc). I never said it would be easy, but remember, the O/R mapping of today is far ahead of what one had only 10 years ago. Of course, I would not have the CAD client talk directly to the RDBMS, with constantly updating the database, but through a O/R layer (Hibernate is a good one for this) that the CAD client connects to (either through CORBA, ICE or similar), and have the application server do batch update/fetching of the data. I think that those that shy away from a RDBMS CAD solution exaggerates the complexity of the CAD structure, and underestimates the technologies we have available today. Regards, Baalbek From fuzzyman at gmail.com Tue May 30 11:39:03 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 30 May 2006 08:39:03 -0700 Subject: Python Version Testing Tool? In-Reply-To: <mailman.6162.1148501945.27775.python-list@python.org> References: <1148495974.975395.12920@i40g2000cwc.googlegroups.com> <mailman.6162.1148501945.27775.python-list@python.org> Message-ID: <1149003543.861707.95700@y43g2000cwc.googlegroups.com> Michael Yanowitz wrote: > Hello: > > Is there a version testing tool available for Python > such that I can check to see if my code will still run in > versions 2.2, 2.3, 2.4.3, and 1.1 (for example) (or whatever) > without having to install all these different versions on my > computer? > This is one of the things Movable Python is good at. (For Windows only currently). http://www.voidspace.org.uk/python/movpy/ You can test your code with multiple versions of Python (currently 2.2, 2.3 & 2.4) without having to install them. The next update will allow you to switch which version you run your code with just by selecting hte interpreter from the menu. All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml > Thanks in advance: > Michael Yanowitz From fredrik at pythonware.com Thu May 18 18:26:07 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 00:26:07 +0200 Subject: Which is More Efficient? In-Reply-To: <1147990753.406649.80150@y43g2000cwc.googlegroups.com> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> <1147990753.406649.80150@y43g2000cwc.googlegroups.com> Message-ID: <e4is9u$rn0$2@sea.gmane.org> Dustan wrote: >> 2. Measure it. > > Tell me how and I will; I'm not nearly that much of a geek > unfortunately. do you have to be a geek to be able to measure how much time something takes? </F> From eriol at huine.org Sun May 28 21:50:19 2006 From: eriol at huine.org (Eriol) Date: Mon, 29 May 2006 01:50:19 GMT Subject: Best way to check that a process is running on a Unix system? References: <mailman.6286.1148792733.27775.python-list@python.org> Message-ID: <vrseg.16189$jP5.407070@twister1.libero.it> Arthur Pemberton wrote: > What is the best way to check that a process is running (or better yet > number of instances) based on the name of the process? Would have to > work on a unix/linux system. Did you try pidof? Bye, Eriol From nobody at 127.0.0.1 Fri May 12 02:29:15 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 06:29:15 GMT Subject: syntax for -c cmd References: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> <bVM8g.85722$dW3.77269@newssvr21.news.prodigy.com> <3g8862ligej5fm49rjjkro05v7qunqnrjg@4ax.com> Message-ID: <%WV8g.75682$H71.69129@newssvr13.news.prodigy.com> Dennis Lee Bieber wrote: > On Thu, 11 May 2006 20:12:55 GMT, Edward Elliott <nobody at 127.0.0.1> > declaimed the following in comp.lang.python: > >> If putting the else in a separate arg unbinds it from the if, I would >> expect a syntax error. If OTOH naked elses are allowed on the command >> line for some odd reason, then this shouldn't happen: >> > More likely, the -C never processed anything after the first quoted > statement. Yep you are correct. Odd, I could've sworn I've done that before. Here's what the man page has to say: "when called with -c command, it executes the Python statement(s) given as command. Here command may contain multiple statements separated by newlines. ... following options are passed as arguments to the command." So the following works: $ python -c 'if 0 == 1: print "foo" # arg is unterminated $$ else: print "bar"' # now we close it bar -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From miki.tebeka at gmail.com Thu May 18 03:22:01 2006 From: miki.tebeka at gmail.com (Miki) Date: 18 May 2006 00:22:01 -0700 Subject: Job Offer (Herzelia, Israel) Message-ID: <1147936921.124832.296680@38g2000cwa.googlegroups.com> Job Title: Python Application Expert Company: Logia (http://www.logiamobile.com) Contact: Lior Rudnik (liorr at logia.co.il) Job Description: * Design & Development of our leading product's PC client application * Development in Python Job Requirements: * At least 4 years of experience developing client applications * Extensive knowledge and experience in Object Oriented and design methodologies * Fast learner, able to study the impact of new technologies and adapt accordingly * Excellent communication skills, ability to handle multiple interfaces * High problem analysis and solving skills * Ability to work in a very challenging & dynamic environment Advantage (nice to have) * Experience developing python * Experience with wxPython and/or wxWidgets * Experience with open source * Experience with content - Video, Audio * Experience with VoIP From rwrii at charter.net Wed May 24 21:56:28 2006 From: rwrii at charter.net (rwr) Date: 24 May 2006 18:56:28 -0700 Subject: Compiling Python from Sources In-Reply-To: <1148521050.907555.312320@j55g2000cwa.googlegroups.com> References: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> <1148509057.542733.217230@i39g2000cwa.googlegroups.com> <1148509487.448417.294690@j33g2000cwa.googlegroups.com> <1148512998.732842.258430@j33g2000cwa.googlegroups.com> <1148518265.135570.39890@i39g2000cwa.googlegroups.com> <1148521050.907555.312320@j55g2000cwa.googlegroups.com> Message-ID: <1148522188.487395.166820@u72g2000cwu.googlegroups.com> Thank YOU ever soooooooooooooooooooo much as it worked my friend!!! Thank you. Sincerely, rwr From blair.bethwaite at gmail.com Mon May 8 03:11:10 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 8 May 2006 00:11:10 -0700 Subject: Getting HTTP responses - a python linkchecking script. In-Reply-To: <3vqt52hb9b1k1ddk1pkqu9k1qb0kalcmor@4ax.com> References: <1147056628.354150.116120@y43g2000cwc.googlegroups.com> <3vqt52hb9b1k1ddk1pkqu9k1qb0kalcmor@4ax.com> Message-ID: <1147072270.475178.321030@v46g2000cwv.googlegroups.com> Rene Pijlman wrote: > blair.bethwaite at gmail.com: > >with urllib2 it doesn't seem possible to get HTTP status codes. > > except urllib2.HTTPError, e: > if e.code == 403: Thanks. Is there documentation for this available somewhere online, I can't see it to obviously in the library reference? Cheers, -Blair From seeker1001 at lycos.com Tue May 2 04:03:06 2006 From: seeker1001 at lycos.com (seeker) Date: Tue, 02 May 2006 11:03:06 +0300 Subject: stripping blanks In-Reply-To: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> References: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> Message-ID: <4457123a$1_1@news.estpak.ee> micklee74 at hotmail.com wrote: > hi > i have a file test.dat eg > > abcdefgh > ijklmn > <-----newline > opqrs > tuvwxyz > <---newline > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break > #if not re.findall(r'^$',line): > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all..? > thanks > Hi, this should work better: f = open("test.dat") while 1: line = f.readline().rstrip("\n") if line == '': continue #if not re.findall(r'^$',line): print line From scott.daniels at acm.org Mon May 1 13:48:01 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 01 May 2006 10:48:01 -0700 Subject: Add file to zip, or replace file in zip In-Reply-To: <ka95g.65983$F_3.36061@newssvr29.news.prodigy.net> References: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> <1146257509.963417.250250@g10g2000cwb.googlegroups.com> <4455010f@nntp0.pdx.net> <ka95g.65983$F_3.36061@newssvr29.news.prodigy.net> Message-ID: <4456464c$1@nntp0.pdx.net> Edward Elliott wrote: > Scott David Daniels wrote: >>... > ... You windows kids and your crazy data formats. There were a few oth OS's than Linux and Windows. Maybe you should call me "you crazy Tenex kid." Knuth says, "the fastest way to search is to know where to go." -- Zips have locations of files, and you needn't read in a lot of a huge zip to find and extract a couple of files. >> Any error >> (or raised exception like Control-C) during this process is likely >> to leave you with an inconsistent and therefore unreadable zip file. > > Isn't that true of any modifications to the zip archive, e.g. appending a > new file rather than replacing an existing one? Nope. There is enough info in the zip to rebuild the directory with a forward scan of the zip. (Each entry has a file descr). "appending" is really replacing backing up before the zip archive directory and writing another entry, followed by a new directory. >> in one pass, copy all non-deleted files to a new zip (which you can then >> swap for the original zip). Shortcutting this process puts all data in >> your zip file at risk. > > Again, isn't this true of any substantive change to any file whatsoever? > Errors during write can always leave your data in an inconsistent state, > unless your data uses a structured append format like journaled > filesystems. That seems like an orthogonal issue to replacing a file in > the archive. --Scott David Daniels scott.daniels at acm.org From deets at nospam.web.de Fri May 5 10:51:24 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 16:51:24 +0200 Subject: Tuple assignment and generators? References: <mailman.5334.1146755400.27775.python-list@python.org> <1146826136.746268.4060@i40g2000cwc.googlegroups.com> <445b3960$1_3@news.bluewin.ch> <1146831804.396839.316070@v46g2000cwv.googlegroups.com> <syi*BxTfr@news.chiark.greenend.org.uk> <1146839183.981537.216320@y43g2000cwc.googlegroups.com> Message-ID: <4c174hF13bbpoU1@uni-berlin.de> > ... I had no clue. We figured that.... > I guess the take-away lesson is to steer clear from any reliance on > object identity checks, if at all possible. You've been told that quite a few times before that "is" is not intended for what you used it. Some people actually listen to what others tell. Others seem to be driven by the deep desire to make even the tiniest bit of getting-a-grasp a public affair. Diez From peter.maas at somewhere.com Sun May 21 15:19:53 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Sun, 21 May 2006 21:19:53 +0200 Subject: Programming language productivity In-Reply-To: <Xns97C7E9ACF911Bcastleamber@130.133.1.4> References: <mailman.5923.1148009336.27775.python-list@python.org> <Xns97C7E9ACF911Bcastleamber@130.133.1.4> Message-ID: <e4qeh9$l27$1@online.de> John Bokma wrote: > Also note that Python programmers write more lines/hour which they need to > finish in the same time as Perl programmers :-D. You probably want to say that a Python program tends to have more lines than an equivalent Perl program. I think that a LOC comparison between a language that enforces line breaks and another language that enables putting an lots of code in one line doesn't make much sense. I wonder why comparisons aren't made in terms of word count. Word count would include literals, constants, variables, keywords, operators, bracket- and block delimiter pairs. Python indent/unindent would of course also count as block delimiters. I think this would be a more precise measure for software size. Peter Maas, Aachen. From prikryl at skil.cz Wed May 10 02:09:26 2006 From: prikryl at skil.cz (Petr Prikryl) Date: Wed, 10 May 2006 08:09:26 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> Message-ID: <e3s02m$9jo$1@news.contactel.cz> "Alex Martelli" wrote... > Joe Marshall wrote: > ... > > If you language allows unnamed integers, unnamed strings, unnamed > > characters, unnamed arrays or aggregates, unnamed floats, unnamed > > expressions, unnamed statements, unnamed argument lists, etc. why > > *require* a name for trivial functions? Event the trivial function can have a name. Does it make the trivial function more understandable if I do not give a name? I understand what lambda means, but it is clearer for me to see something like (with more meaningful name than shown here): >>> def fn(x): ... return x + 5 and to use it like... >>> fn(3) 8 Still, I can anonymize it later, if I really need >>> a = [fn] or I can give it another name >>> z = fn In my opinion, the cry for lambda in Python comes from people used to functional languages, because they are not used to the procedural style and it does not fit them at the beginning. Frankly, functional style seems "more strange" to me (i.e. the counter example). Still, I do not say it is bad. But it never came to my mind to say "Please, rewrite the LISP so that it looked more like Pascal. I do not like the lambda." Also, Python is compiled (to bytecode), imperative language, and the form of definition of the chunks of code is more natural to the compiler and to the customs how the procedural program is written and how its parts are referenced and put together to form bigger chunks of code. > I think it's reasonable to make a name a part of functions, classes and > modules because they may often be involved in tracebacks (in case of > uncaught errors): to me, it makes sense to let an error-diagnosing > tracebacks display packages, modules, classes and functions/methods > involved in the chain of calls leading to the point of error _by name_. I agree with Alex here. I USUALLY do not need debugger, but sometimes it is exremely handy to discover what happens (through debugger or few print commands, its a matter of taste). And Python is very fine here: >>> dir(fn) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> fn.__name__ 'fn' and even the anonymized function still knows its original name and type >>> a[0].__name__ 'fn' >>> type(a[0]) <type 'function'> If lambda functions in Python are tweaked internally into normal Python functions... >>> z = lambda x: x * 3 >>> dir(z) ['__call__', '__class__', '__delattr__', '__dict__', '__doc__', '__get__', '__getattribute__', '__hash__', '__init__', '__module__', '__name__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__', 'func_closure', 'func_code', 'func_defaults', 'func_dict', 'func_doc', 'func_globals', 'func_name'] >>> z.__name__ '<lambda>' >>> type(z) <type 'function'> ... what makes them better, than the named function? If I do not loose anything by simplification, I want to have it simpler. pepr From aylwyn at cantab.net Wed May 17 15:25:07 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 12:25:07 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <mailman.5826.1147889037.27775.python-list@python.org> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <mailman.5826.1147889037.27775.python-list@python.org> Message-ID: <1147893907.862337.299750@y43g2000cwc.googlegroups.com> Andy Sy wrote: >def sqlcall(): > cursor.execute('select id, item, amount, field4, field5, field6'+ > 'from table1 where amount>100') Lines two and three (a continuation line) are both at a syntactic indentation level of 1. Therefore they should both start with a tab. (Though actually indentation is ignored for continuation lines so you only need to preserve the indentation if you want alignment.) Then you can add spaces to align the function arguments. def sqlcall(): <tab>cursor.execute('select id, item, amount, field4, field5, field6'+ <tab><---spaces---->'from table1 where amount>100') I prefer not to bother with alignment like this, but if you do want to align things, you use spaces. Indenting is done with tabs; alignment with spaces. From chrisBrat at gmail.com Fri May 26 12:46:52 2006 From: chrisBrat at gmail.com (chris brat) Date: 26 May 2006 09:46:52 -0700 Subject: how to clear up a List in python? In-Reply-To: <44772de5.0@entanet> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <e54gtn$grs$1@ulysses.news.tiscali.de> <1148653059.381151.113360@j73g2000cwa.googlegroups.com> <44772de5.0@entanet> Message-ID: <1148662012.600336.113660@j33g2000cwa.googlegroups.com> Doesnt this do what the original poster is try accomplish? Linnorms example - >>> list1 = [0,1,2,3] >>> list1 [0, 1, 2, 3] >>> list1 = [] >>> list1 [] >>> From andymac at bullseye.apana.org.au Sat May 13 08:59:45 2006 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Sat, 13 May 2006 23:59:45 +1100 Subject: Slow network reading? In-Reply-To: <e433ll$ao$1@news2.carnet.hr> References: <e3u5lf$m1$1@news2.carnet.hr> <mailman.5603.1147374962.27775.python-list@python.org> <e433ll$ao$1@news2.carnet.hr> Message-ID: <4465D841.2060408@bullseye.apana.org.au> Ivan Voras wrote: > Andrew MacIntyre wrote: > >> Comparative CPU & memory utilisation statistics, not to mention platform >> and version of Python, would be useful hints... > > During benchmarking, all versions cause all CPU to be used, but Python > version has ~1.5x more CPU time allocated to it than PHP. Python is 2.4.1 A pretty fair indication of the Python interpreter doing a lot more work... >> Note that the file-like object returned by makefile() has significant >> portions of heavy lifting code in Python rather than C which can be a >> drag on ultimate performance... If on a Unix platform, it may be worth >> experimenting with os.fdopen() on the socket's fileno() to see whether >> the core Python file object (implemented in C) can be used in place of >> the lookalike returned from the makefile method. > That's only because I need the .readline() function. In C, I'm using > fgets() (with the expectation that iostream will buffer data). The readline method of the file object lookalike returned by makefile implements all of the line splitting logic in Python code, which is very likely where the extra process CPU time is going. Note that this code is in Python for portability reasons, as Windows socket handles cannot be used as file handles the way socket handles on Unix systems can be. If you are running on Windows, a fair bit of work will be required to improve performance as the line splitting logic needs to be moved to native code - I wonder whether psyco could do anything with this?. >> Even without that, you are specifying a buffer size smaller than the >> default (8k - see Lib/socket.py). 16k might be even better. > > The benchmark is such that all of data is < 200 bytes. I estimate that > in production almost all protocol data will be < 4KB. A matter of taste perhaps, but that seems to me like another reason not to bother with a non-default buffer size. >> Although they're only micro-optimisations, I'd be interested in the >> relative performance of the query method re-written as: > > The change (for the better) is minor (3-5%). Given your comments above about how much data is actually involved, I'm a bit surprised that the tweaked version actually produced a measurable gain. ------------------------------------------------------------------------- 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 DirkHagemann at gmail.com Fri May 19 06:29:33 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 19 May 2006 03:29:33 -0700 Subject: Windows Registry Dump In-Reply-To: <mailman.5932.1148032463.27775.python-list@python.org> References: <mailman.5932.1148032463.27775.python-list@python.org> Message-ID: <1148034573.408628.118320@j73g2000cwa.googlegroups.com> Hi Tim! I want to do some analysis (as always ;-) ) and for that reason I think it's more practical to go trough a text-file. I can produce this text-file also by right-click on the key (the folder) in the registry and select "Export". There one can select Text-File and the place where to save the text-file. This I want to be done by python automatically. Dirk From http Thu May 25 13:16:24 2006 From: http (Paul Rubin) Date: 25 May 2006 10:16:24 -0700 Subject: Modify one character in a string References: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> <4475E3C5.4040500@websafe.com> Message-ID: <7xodxmgh3r.fsf@ruckus.brouhaha.com> Larry Bates <larry.bates at websafe.com> writes: > IMHO the most elegant method is something like: > > def switchchar(srcstring, position, character): > b=list(srcstring) > b[2]=character > return ''.join(b) If the strings or large or you're doing it a lot, the array module is likely more efficient. From rpdooling at gmail.com Thu May 4 19:22:27 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 4 May 2006 16:22:27 -0700 Subject: Can I use python for this .. ?? References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146774288.904851.278130@i39g2000cwa.googlegroups.com> <1146779044.307500.50810@u72g2000cwu.googlegroups.com> <1146780593.481020.272500@g10g2000cwb.googlegroups.com> Message-ID: <1146784947.397927.38500@j73g2000cwa.googlegroups.com> san, Take a look at this thread which features some smart and helpful people and good links. http://tinyurl.com/ggn5e I'm wagering you'll make more sense of it than I did. I have my hands full just making my way through tutorials and books at the moment. rick From kentilton at gmail.com Mon May 8 00:51:57 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 08 May 2006 00:51:57 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <yfshd41yeaj.fsf@oc.ex.ac.uk> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> <yfshd41yeaj.fsf@oc.ex.ac.uk> Message-ID: <O7A7g.59$sC4.54@fe09.lga> Alexander Schmolck wrote: > [trimmed groups] > > Ken Tilton <kentilton at gmail.com> writes: > > >>yes, but do not feel bad, everyone gets confused by the /analogy/ to >>spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief >>period I swore off the analogy because it was so invariably misunderstood. >>Even Graham misunderstood it. > > > Count me in. <g> But looking at what it says: "Think of the slots as cells in a spreadsheet (get it?), and you've got the right idea. ", if you follow the analogy (and know that slot means "data member" in other OO models) you also know that Serge's Spreadsheet example would have scored a big fat zero on the Miller Analogy Test. Serge in no way made slots in Python classes behave like cells in a spreadsheet. He simply started work on a Spreadsheet application, using Python classes along the way. Bzzt. While everyone makes the mistake, it is only because few of us (me included) read very carefully. Especially if they are more interested in flaming than learning what someone is saying. C'mon, people. I linked to Adobe's betting the ranch on such an idea. I linked to Guy Steele's paper on the same idea. In which he marvelled that it had not caught on. I could also link you to COSI over at STSCI, presented at a Lisp Users Group Meeting in 1999 where they were jumping up and down about the same thing. One of my users gets Cells because he loved the KR system in Garnet. Look it up. I have more citations of prior art. And, again, it has gone mainstream: Adobe has adopted the paradigm. Y'all might want to ease up on the pissing contest and learn something. or not, I have been on Usenet before. :) > > >>But it is such a great analogy! <sigh> >> >>>but what's the big deal about PyCells? >>>Here is 22-lines barebones implementation of spreadsheet in Python, >>>later I create 2 cells "a" and "b", "b" depends on a and evaluate all >>>the cells. The output is >>>a = negate(sin(pi/2)+one) = -2.0 >> >>>b = negate(a)*10 = 20.0 >> >>Very roughly speaking, that is supposed to be the code, not the output. So you >>would start with (just guessing at the Python, it has been years since I did >>half a port to Python): >> >> >> v1 = one >> a = determined_by(negate(sin(pi/2)+v1) >> b = determined_by(negate(a)*10) >> print(a) -> -2.0 ;; this and the next are easy >> print(b) -> 20 >> v1 = two ;; fun part starts here >> print(b) -> 40 ;; of course a got updated, too >> > > > do you mean 30? > > I've translated my interpretation of the above to this actual python code: > > from math import sin, pi > v1 = cell(lambda: 1) > a = cell(lambda:-(sin(pi/2)+v1.val), dependsOn=[v1]) > b = cell(lambda: -a.val*10, dependsOn=[a], > onChange=lambda *args: printChangeBlurp(name='b',*args)) > print 'v1 is', v1 > print 'a is', a # -2.0 ;; this and the next are easy > print 'b is', b # 20 > v1.val = 2 # ;; fun part starts here > print 'v1 now is', v1 > print 'b now is', b # 30 ;; of course a got updated, too > > > I get the following printout: > > v1 is 1 > a is -2.0 > b is [cell 'b' changed from <__main__.unbound object at 0xb4e2472c> to 20.0, > it was not bound]20.0 > [cell 'b' changed from 20.0 to 30.0, it was bound ] v1 now is 2 > b now is 30.0 > > Does that seem vaguely right? <g> You have a good start. But you really have to lose the manual wiring of dependencies, for several reasons; -- it is a nuisance to do -- it will be a source of bugs -- it will be kind of impossible to do, because (in case you missed it), the rule should be able to call any function and establish a dependency on any other cell accessed. So when coding a change to a function, one would have to go track down any existing rule to change its dependsOn declaration. never mind the pain in th first place of examining the entire call tree to see what else gets acessed. -- it gets worse. I want you to further improve your solution by handling rules such as this (I will just write Lisp): (if (> a b) c ;; this would be the "then" form d)) ;; this is the 'else' The problem here is that the rule always creates dependencies on a and b, but only one of c and d. So you cannot write a dependsOn anyway (never mind all the other reasons for that being unacceptable). > > >>The other thing we want is (really inventing syntax here): >> >> on_change(a,new,old,old-bound?) print(list(new, old, old-bound?) > > > Is the above what you want (you can also dynamically assign onChange later > on, as required or have a list of procedures instead)? Your onChange seems to be working fine. One thing we are glossing over here is that we want to use this to extend the object system. In that case, as I said and as no one bothered to comprehend, we want /slots/ to behave like spreadsheet cells. Not globals. And I have found that these onChane deals are most sensibly defined on slots, not cell by cell. That said, if you did work something up similar for Python classes, i have no doubt you could do that. Again, if anyone is reading and not looking to just have a flamewar, they will recall i have already done once a partial port of Cells to python. (I should go look for that, eh? It might be two computer systems back in the closet though. <g>) > > >>Then the print statements Just Happen. ie, It is not as if we are just hiding >>computed variables behind syntax and computations get kicked off when a value >>is read. Instead, an underlying engine propagates any assignment throughout >>the dependency graph before the assignment returns. > > > Updating on write rather than recalculating on read does in itself not seem > particularly complicated. <heh-heh> Well, there are some issues. B and C depend on A. B also depends on C. When A changes, you have to compute C before you compute B, or B will get computed with an obsolete value of C and be garbage. And you may not know when A changes that there is a problem, because as you can see from my example (let me change it to be relevant): (if (> a d) c e) It may be that during the prior computation a was less= d and did /not/ depend on c, but with the new value of a is > d and a new code branch will be taken leading to c. It was not that hard to figure all that out (and it will be easier for you given the test case <g>) but I would not say propagation is straightforward. There are other issues as well, including handling assignments to cells within observers. This is actually useful sometimes, so the problem needs solving. > > >>My Cells hack does the above, not with global variables, but with slots (data >>members?) of instances in the CL object system. I have thought about doing it >>with global variables such as a and b above, but never really seen much of >>need, maybe because I like OO and can always think of a class to create of >>which the value should be just one attribute. > > > OK, so in what way does the quick 35 line hack below also completely miss your > point? What is that trash talking? I have not seen your code before, so of course I have never characterized it as completely missing the point. Spare me the bullshit, OK? Alexander, you are off to a, well, OK start on your own PyCells. You have not made a complete mess of the low-hanging fruit, but neither have you done a very good job. Requiring the user to declare dependencies was weak -- I never considered anything that (dare I say it?) unscaleable. Like GvR with Python, I knew from day one that Cells had to very simple on the user. Even me, their developer. But do not feel too bad, the GoF Patterns book described more prior art (I might have mentioned) and they had explicit (and vague) subscribe/unsubscribe requirements. As for the rest of your code, well, propagation should stop if a cell recomputes the same value (it happens). And once you have automatic dependency detection, well, if the rule is (max a b) and it turns out that b is just 42 (you had cell(lambda 1)... why not just cell(1) or just 1), then do not record a dependency on b. (Another reason why the user cannot code dependsOn -- it is determined at run time, not by examination of the code. Now we need to talk about filters on a dependency.... kenny (expecting more pissing and less reading of the extensive on-line literature on constraints) -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From duncan.booth at invalid.invalid Sun May 14 09:22:52 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 May 2006 13:22:52 GMT Subject: any plans to make pprint() a builtin? References: <44669e46$0$5337$c3e8da3@news.astraweb.com> Message-ID: <Xns97C3667B2DA19duncanbooth@127.0.0.1> John Salerno wrote: > Just wondering if this will ever happen, maybe in 3.0 when print becomes > a function too? It would be a nice option to have it available without > importing it every time, but maybe making it a builtin violates some > kind of pythonic ideal? There are so many things which *could* be builtins, and it really is better not to pollute the global namespace with more than absolutely necessary. Personally I'd just like to see 'python' a builtin shorthand for importing a name you aren't going to use much e.g. python.pprint.pprint(x) From bugs at almad.net Thu May 11 15:56:31 2006 From: bugs at almad.net (Almad) Date: 11 May 2006 12:56:31 -0700 Subject: FTP filename escaping In-Reply-To: <1147375459.332757.212570@u72g2000cwu.googlegroups.com> References: <1147375459.332757.212570@u72g2000cwu.googlegroups.com> Message-ID: <1147377391.521967.26730@j33g2000cwa.googlegroups.com> OK, after some investigation...problem is in non-latin characters in filenames on ftp. Yes, users should be killed for this, but I would like to handle it somehow... I can't figure out how it's handled by protocol, ftplib seems to just strip those characters... Thank You, Almad From sjmachin at lexicon.net Wed May 31 06:52:01 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 May 2006 20:52:01 +1000 Subject: An algorithm problem In-Reply-To: <mailman.6357.1149067240.27775.python-list@python.org> References: <mailman.6350.1149058719.27775.python-list@python.org> <slrne7qiso.5k5.sybrenUSE@schuimige.stuvel.eu> <mailman.6357.1149067240.27775.python-list@python.org> Message-ID: <447D7551.2040702@lexicon.net> On 31/05/2006 7:20 PM, Bo Yang wrote: > I am sorry , and thanks for your friendliness . > I have change my source code for more meaningful variable name and more > comments follow the instructions > John has writen . I think that is useful for you to look my code . > > And this time I put the code in the attachment . Indeed , I write that > in the Eclipse Pydev , I don't know why > it lose its idention in the mailing list . > > Also , I forget an example for the question , and I compensate for it : > > Given the integer 2 for instance : > what we exapct from the algorithm is a list of 0 or 1 , for this > instance it is 1 1 0 0 . > We can take it as a ring , and fetch any continuous 2 numbers from it , > finally get four combinations : > 11 , 10 , 00 , 01 > and they are 3 , 2 , 0 , 1 . > > > I hope this time it is clear for all to understand what problem confront > me . > And again I am sorry for the trouble , thanks for you again ! > OK, it was able to be run this time. The algorithm is recursive. For input == n, it needs stack of depth 2**n. The default limit is 1000, and 2**9 < 1000 < 2**10 -- so it fails when n >= 10. You can change this with sys.setrecursionlimit. Please take careful note of the warnings in the documentation: """ setrecursionlimit( limit) Set the maximum depth of the Python interpreter stack to limit. This limit prevents infinite recursion from causing an overflow of the C stack and crashing Python. The highest possible limit is platform-dependent. A user may need to set the limit higher when she has a program that requires deep recursion and a platform that supports a higher limit. This should be done with care, because a too-high limit can lead to a crash. """ I tried it with sys.setrecursionlimit(2**n+10) -- that worked up to 13 on my Windows XP box, throwing a MemoryError (and a long stack trace!) for n == 14. Be careful; yours may crash more horribly than that. Can your algorithm be expressed non-recursively? Best of luck, John From tbrkic at yahoo.com Sat May 13 14:45:32 2006 From: tbrkic at yahoo.com (glomde) Date: 13 May 2006 11:45:32 -0700 Subject: compiling module from string and put into namespace In-Reply-To: <UW89g.5100$fb2.3962@newssvr27.news.prodigy.net> References: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> <4464754a$0$306$626a54ce@news.free.fr> <1147474282.618115.60590@u72g2000cwu.googlegroups.com> <UW89g.5100$fb2.3962@newssvr27.news.prodigy.net> Message-ID: <1147545932.917599.217970@j73g2000cwa.googlegroups.com> > I dont want the caller to call import but a function. come again? >>> type (__builtins__.__import__) <type 'builtin_function_or_method'> I didnt mean that __import__ isnt a function, but that I want to make a function called ImoprtFile that actually does something very similar that what __import__. So to rephrsase the questin how does __import__ load a module into the callers namespace. Example: file1 def ImportFile(fileName): parsedCode = Parser(fileName).Parse() module = new.module(name) exec parsedCode in module.__dict__ sys.modules[name] = module import name #!!!!!!! This doesn't work. Imports in file1 namespace!!!!! file2 import file1 file1.ImportFile(fileName) fileName.function() #This wont work because the import happened locally in file1!!!!!!!!!!!!! Now the import in file1 doesnt take effect in file2. So what do I have to do to make that work. And I dont want to do a custom hook to import. So how does __import__ do? From john at castleamber.com Thu May 18 23:58:16 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 03:58:16 GMT Subject: Programming language productivity References: <mailman.5923.1148009336.27775.python-list@python.org> Message-ID: <Xns97C7E9ACF911Bcastleamber@130.133.1.4> Connelly Barnes <connellybarnes at yahoo.com> wrote: > http://barnesc.blogspot.com/2006/05/programming-language-productivity.h > tml C: 3 hours to write the program, 5 hours to track down the memory leaks Java: 4 hours to write the program, 6 hours to get all the exception handling right C++ 5 hours to write the program after reading Stroustrup for 6 hours Just kidding, of course. Also note that Python programmers write more lines/hour which they need to finish in the same time as Perl programmers :-D. -- 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 rupole at hotmail.com Fri May 5 22:33:53 2006 From: rupole at hotmail.com (Roger Upole) Date: Fri, 5 May 2006 22:33:53 -0400 Subject: Can Python kill a child process that keeps on running? References: <g0x5g.104639$7a.102977@pd7tw1no> Message-ID: <1146882617_5787@sp6iad.superfeed.net> Using Pywin32 (obviously not cross platform): import win32api,win32con h=win32api.OpenProcess(win32con.PROCESS_TERMINATE,False, <pid>) win32api.TerminateProcess(h, <exit code>) Roger "I. Myself" <No.Spam at Spam.none> wrote in message news:g0x5g.104639$7a.102977 at pd7tw1no... > Suppose we spawn a child process with Popen. I'm thinking of an executable file, like a compiled C program. > Suppose it is supposed to run for one minute, but it just keeps going and going. Does Python have any way to kill it? > > This is not hypothetical; I'm doing it now, and it's working pretty well, but I would like to be able to handle this run-on > condition. I'm using Windows 2000, but I want my program to be portable to linux. > > Thanks > > Mitchell Timin > > -- > I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, > or articles, or do testing or research for ANNEvolve, let me know. > > Humans may know that my email address is: (but remove the 3 digit number) > zenguy at shaw666 dot ca > > > ----== 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 wrstuden at wasabisystems.com Tue May 16 14:17:39 2006 From: wrstuden at wasabisystems.com (William Studenmund) Date: Tue, 16 May 2006 11:17:39 -0700 Subject: Subclassing types in C Message-ID: <AB7F4F6D-C2CB-4115-A330-14C65A244B3E@wasabisystems.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 I used the embedding python guide to embed python in an application to let me easily script the app. It's all working rather well, and I've added a number of types which expose the internals to python. However I've gotten to the point where I want to add classes for part of the interface, and these class really should be subclasses of another one of my types. Well, subtypes. The Embedding guide doesn't cover this. I found PEP 253, which partially covers this. It indicates that I should be able to do this. However: 1) the "Creating a subtype of a built-in type in C" section has an "XXX there should be a paragraph or two about argument passing here" comment, and 2) the PEP's abstract has an editor's note indicating that the PEP no longer describes the implementation. So what do I need to do? Are the instructions in the PEP still correct? Take care, Bill -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (Darwin) iD8DBQFEahdIDJT2Egh26K0RAuJIAJ406DDdXTu6VEfcW1yWa2Hg4wIIQACfVuCH SBrwJOCqHIHZdFndfzJBMbo= =aPMN -----END PGP SIGNATURE----- From tjreedy at udel.edu Wed May 17 15:43:05 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 May 2006 15:43:05 -0400 Subject: How to add columns to python arrays References: <1147882432.166728.207820@j55g2000cwa.googlegroups.com><e4fri0$khm$1@sea.gmane.org> <e4ft0l$356$1@sea.gmane.org> Message-ID: <e4fuc8$vlm$1@sea.gmane.org> "Michael Spencer" <mahs at telcopartners.com> wrote in message news:e4ft0l$356$1 at sea.gmane.org... > If you're just looking for a multi-dimensional array type, and don't need > maximum speed or the vast range of array-processing that numpy offers, > then > *pyarray* provides a pure-python single module solution. > > the latest pyarray is available with tests and documentation at: > http://svn.brownspencer.com/pyarray/trunk/ Nice. I downloaded and expect to give it a try sometime. I suggest putting the url in the module file itself to make it easier to search for updated versions ;-) tjr From sjmachin at lexicon.net Sat May 27 19:52:20 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 28 May 2006 09:52:20 +1000 Subject: Serializing / Unserializing datetime In-Reply-To: <1148751427.204676.238100@g10g2000cwb.googlegroups.com> References: <1148751427.204676.238100@g10g2000cwb.googlegroups.com> Message-ID: <4478E634.8060001@lexicon.net> On 28/05/2006 3:37 AM, Brendan wrote: > Hi All > > I can't find the "Python Way" of writing a datetime instance to a > string so that it can be easily parsed back again. time.strptime is > apparantly not supported on some platforms, and time.time <==> > datetime.utcfromtimestamp will cause problems come 2038. Unfortunately > there don't seem to be "fromstring" equivalents for datetime.ctime or > datetime.isoformat. > > Ideally the serialized datetime should be human readable, and > potentially parseable from other languages. Any suggestions? > > It's not that hard to DIY; the simple code at the end of this posting (1) handles fractions of a second [which you may or may not want] without burdening the network or the readers' eyeballs with excess trailing zeroes (2) doesn't handle TZs [which you may or may not want]. Some further validation on input strings may be a good idea, if you need to eat other software's strings as well as yours. E.g. check that where the '-' characters should be that you find nothing stranger than '.' or '/'; certainly not digits. HTH, John 8<--- import datetime def datetime_from_str(s): # YYYY-MM-DD HH:MM:SS.TTT # 01234567890123456789012 year = int(s[0:4]) month = int(s[5:7]) day = int(s[8:10]) hour = int(s[11:13]) minute = int(s[14:16]) microseconds = int(float(s[17:]) * 1000000.0) second, microsecond = divmod(microseconds, 1000000) return datetime.datetime(year, month, day, hour, minute, second, microsecond) def datetime_as_str(dtm): part1 = dtm.strftime("%Y-%m-%d %H:%M:%S") micros = dtm.microsecond if not micros: return part1 part2 = (".%06d" % micros).rstrip('0') return part1 + part2 if __name__ == "__main__": tests = [ '1999-12-31 23:59:59.999999', '1999-12-31 23:59:59.99999999', '1999-12-31 23:59:59.999', '1999-12-31 23:59:59', '2000-01-01 00:00:00.000', '2000-01-01 00:00:00', '2000-01-01 00:00:00.000001', '2000-01-01 00:00:00.001', ] for test in tests: dtm = datetime_from_str(test) print "input str: ", repr(test) print "datetime: ", repr(dtm) round_trip = datetime_as_str(dtm) print "output str:", repr(round_trip), ["not same", ""][round_trip == test] print 8<--- From bnblazer at gmail.com Sun May 21 19:46:17 2006 From: bnblazer at gmail.com (Brian) Date: 21 May 2006 16:46:17 -0700 Subject: performance difference between OSx and Windows In-Reply-To: <1148254182.824583.195370@i40g2000cwc.googlegroups.com> References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> <1148254182.824583.195370@i40g2000cwc.googlegroups.com> Message-ID: <1148255177.190455.217840@u72g2000cwu.googlegroups.com> Thanks for the response. I was unaware that the G5 was only using one core. Can I ask why that is, and if there is a way to take advantage of all 4 within python? Thanks, Brian From bignose+hates-spam at benfinney.id.au Thu May 18 18:26:49 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 May 2006 08:26:49 +1000 Subject: Which is More Efficient? References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> <1147990753.406649.80150@y43g2000cwc.googlegroups.com> Message-ID: <87ejyrklzq.fsf@benfinney.id.au> "Dustan" <DustanGroups at gmail.com> writes: > John Machin wrote: > > 2. Measure it. > > Tell me how and I will; I'm not nearly that much of a geek > unfortunately. You've already been told. Here it is again: <URL:http://docs.python.org/lib/profile.html> -- \ "I don't know half of you half as well as I should like, and I | `\ like less than half of you half as well as you deserve." -- | _o__) Bilbo Baggins | Ben Finney From duncan.booth at invalid.invalid Tue May 16 06:37:04 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 10:37:04 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> <roy-765731.09112115052006@reader1.panix.com> <1147751294.699031@teuthos> <1147774322.797789.132510@y43g2000cwc.googlegroups.com> Message-ID: <Xns97C574CD09E52duncanbooth@127.0.0.1> John Machin wrote: >> (my dictionary values are all None). > > So in fact all you need is a set. Have you experimented with the Python > 2.5 alpha? > I don't think that will help him: my timings work out about the same on 2.4.2 or 2.5a2. As I pointed out, the bottleneck is creating the tuples. Creating either a dictionary or a set from 5 million tuples takes a similar amount of time (about 6 seconds on my system). BTW, a string key is quite a bit faster than the tuples, even though you end up with as many temporary tuples during the process: >>> scale = 2**32 >>> data = [ "%d:%d" % (i*scale,i) for i in range(5000000) ] >>> d = set(data) takes about 18 seconds to create the data list and 5 for the set. From rzantow at gmail.com Sat May 20 10:43:40 2006 From: rzantow at gmail.com (Rick Zantow) Date: Sat, 20 May 2006 10:43:40 -0400 Subject: Generating Cutter numbers References: <1148114166.590393.176250@u72g2000cwu.googlegroups.com> <1148133784.844430.23130@38g2000cwa.googlegroups.com> Message-ID: <Xns97C96D21C8CE2rzed@208.49.80.253> skryskalla at gmail.com wrote in news:1148133784.844430.23130@ 38g2000cwa.googlegroups.com: > Gerard Flanagan wrote: >> All >> >> would anyone happen to have code to generate Cutter Numbers: >> >> eg. http://www1.kfupm.edu.sa/library/cod-web/Cutter-numbers.htm >> [...] > > I wrote a script to see if I could capture what the table is doing on > the page you linked to. It gets the Cutter number right about 50% of > the time, otherwise its off by a few digits. > > I am stumped about what to do when the first letter is Q not followed > by U. It says to use numbers 2-29 for the second letters a-t, but that > is obviously not right (for one thing t would be 21, not 29). > > Since you seem a little bit more experienced in library science could > you explain what is going on? :) > > you can find the script here: > http://lost-theory.org/python/cutter.txt > I found another page <http://ublib.buffalo.edu/libraries/units/cts/codes/cutter.html> that expresses the letter codes more fully than the one the OP posted. But nothing I've seen so far accounts for an example like " Chertok (.C48)". This page <http://www.itsmarc.com/crs/cutr0020.htm> shows essentially the same information the OP posted, including the Chertok example, which is linked to another page that says this (and only this): "These Cutters reflect the adjustments made to allow for a range of letters on the table, e.g., l-m, or for letters not explicitly stated, e.g., h after an initial consonant." Given that some unnamed adjustment is made, it's not clear how one would go about programming it. I mean, Python's good, but it only has a serpent brain. -- rzed From bborcic at gmail.com Tue May 2 07:49:34 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 13:49:34 +0200 Subject: set partitioning In-Reply-To: <1146530789.867089.75160@i39g2000cwa.googlegroups.com> References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> <1146522121.798317.206180@i39g2000cwa.googlegroups.com> <1146523373.778624.142510@y43g2000cwc.googlegroups.com> <mailman.5197.1146525436.27775.python-list@python.org> <1146530789.867089.75160@i39g2000cwa.googlegroups.com> Message-ID: <44574755$1_5@news.bluewin.ch> hymort at hotmail.com wrote: > For the list [1,2,3,4], I'm looking for the following for k = 2: > > [[1,2], [3,4]] > [[1,3], [2,4]] > [[1,4], [2,3]] > > for k = 3: > > [[1,2,3], [4]] > [[1,2,4], [3]] > [[1,3,4], [2]] > [[2,3,4], [1]] > def pickk(k,N,m=0) : if k==1 : return ((n,) for n in range(m,N)) else : return ((n,)+more for more in pickk(k-1,N,m+1) for n in range(m,more[0])) def partitionN(k,N) : subsets = [frozenset(S) for S in pickk(k,N)] def exhaust(rest,bound=0) : if len(rest) < k : if rest : yield [sorted(rest)] else : yield [] for newbound in range(bound,len(subsets)) : S = subsets[newbound] if rest >= S : sS = [sorted(S)] for restpart in exhaust(rest-S,newbound+1) : yield sS+restpart return exhaust(set(range(N))) partition = lambda k,S : [[[S[j] for j in S0] for S0 in P0] for P0 in partitionN(k,len(S))] >>> partition(2,[1,2,3,4]) [[[1, 2], [3, 4]], [[1, 3], [2, 4]], [[2, 3], [1, 4]]] >>> partition(3,[1,2,3,4]) [[[1, 2, 3], [4]], [[1, 2, 4], [3]], [[1, 3, 4], [2]], [[2, 3, 4], [1]]] CAVEAT : insufficiently tested, not proved correct, uncommented, provided as is From invalidemail at aerojockey.com Thu May 11 19:51:27 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 11 May 2006 16:51:27 -0700 Subject: Time to bundle PythonWin In-Reply-To: <1147388148.406918.76040@q12g2000cwa.googlegroups.com> References: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> <1147388148.406918.76040@q12g2000cwa.googlegroups.com> Message-ID: <1147391487.429326.310940@i40g2000cwc.googlegroups.com> Robert Hicks wrote: > No it isn't. It is a Windows only package. It needs to stay a separate > download. The latest Python Library Reference has a section called "MS Windows Specific Services", where it has several packages that work only on Windows. There's also a section for SGI IRIX modules, and IRIX support is scheduled to be dropped in Python 3000. There might be a good reason why win32 isn't in Python base distro, but that it's Windows-only isn't it. Carl Banks From OlafMeding at gmail.com Mon May 8 10:13:44 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 8 May 2006 07:13:44 -0700 Subject: hyperthreading locks up sleeping threads Message-ID: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Below are 2 files. The first is a Python program that isolates the problem within less than 1 hour (often just a few minutes). The second is a C++ program that shows that the Win32 Sleep() function works as expected (ran from Friday afternoon until Monday morning). Note, the Python programs hangs (stops responding) with hyper-threading turned on (a BIOS setting), but works as expected with hyper-threading turned off. This problem happens on Windows only (not on Linux for days). Variations of the Python program also lock up: Tried importing win32api instead of time and using the win32api.GetTickCount() and win32api.Sleep() methods. Tried using lock = threading.Event() and lock.wait() instead of time.sleep(). Tried import Queue using q = Queue.Queue() and q.get(True, self.t). Note, the Windows task manager shows 2 CPUs on the Performance tab with hyper-threading is turned on. Both Python 2.3.5 and 2.4.3 (downloaded from python.org) have this problem. The operating system is MS Windows XP Professional. winmsd.exe shows: 2CPUs: x86 Family 15 Model 4 Stepping 1 GenuineIntel ~3000 MHz Version: 5.1.2600 Service Pack 2 Build 2600 Could someone with a hyper-threading (or dual core or multi processor) CPU please confirm this bug? Many Thanks Olaf Here is the expected output of both programs (the progam has locked up if the numbers stop printing): python testsleep.py thread 1 started, sleep time 0.010 thread 2 started, sleep time 0.003 1 1 1 2 1 1 1 2 1 1 1 2 1 1 1 1 2 1 1 1 # testsleep.py import threading import time class Task(threading.Thread): def __init__(self, n, t): threading.Thread.__init__(self) self.n = n # thread id self.t = t # sleep time def run(self): print 'thread %d started, sleep time %.3f' % (self.n, self.t) count = 0 printCount = int(10 / self.t) while True: start = time.clock() time.sleep(self.t) stop = time.clock() if stop - start > 1.0: print 'thread', self.n, stop - start count += 1 if count > printCount: count = 0 print self.n, # print sign of live def test(): thread1 = Task(1, 0.01) # thread 1, sleep 10 ms thread2 = Task(2, 0.003) # thread 2, sleep 3 ms thread1.start() thread2.start() test() ---------------------------------------------------------------------------------- // testsleep.cpp // Compiled with Visual C++ version 6 as a Win32 console application. #include <windows.h> #include <stdio.h> #include <time.h> typedef struct { int id; int ms; } param_s; DWORD WINAPI threadFunction(LPVOID param) { param_s* p = (param_s*)param; long elapsedTime; long time1, time2; long printCount = long(10000 / p->ms); // loop iterations in 10 seconds long count = 0; printf("thread %d started, sleep time: %d ms" "\n", p->id, p->ms); while(true) { time1 = GetTickCount(); Sleep(p->ms); time2 = GetTickCount(); elapsedTime = time2 - time1; if(elapsedTime > 1000) printf("thread %d slept for %d ms" "\n", p->id, elapsedTime); count++; if(count > printCount) { count = 0; printf("%d ", p->id); // print sign of live } } return 0; } int main(int argc, char* argv[]) { long time1, time2; param_s p1, p2; p1.id = 1; p1.ms = 10; p2.id = 2; p2.ms = 3; time1 = GetTickCount(); while(true) { time2 = GetTickCount(); if (time1 != time2) { printf("clock resolution: %d ms" "\n", time2 - time1); break; } } CreateThread(NULL, 0, threadFunction, (void*)&p1, 0, NULL); CreateThread(NULL, 0, threadFunction, (void*)&p2, 0, NULL); getchar(); // wait until the user presses the enter key. return 0; } From roy at panix.com Wed May 17 17:50:55 2006 From: roy at panix.com (Roy Smith) Date: Wed, 17 May 2006 17:50:55 -0400 Subject: How to tell if function was passed a list or a string? References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> Message-ID: <roy-4EE50D.17505517052006@reader1.panix.com> In article <1147900957.466840.192390 at i40g2000cwc.googlegroups.com>, "rh0dium" <steven.klass at gmail.com> wrote: > The question is how do you tell that the data you were passed is a list > or not? >>> x = [] >>> isinstance (x, list) True From rpdooling at gmail.com Sun May 14 01:35:57 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 May 2006 22:35:57 -0700 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> Message-ID: <1147584957.646822.213960@g10g2000cwb.googlegroups.com> Thanks! And thanks for the Cookbook. rd "There is no abstract art. You must always start with something. Afterward you can remove all traces of reality."--Pablo Picasso From jantod at gmail.com Tue May 16 08:16:37 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 16 May 2006 05:16:37 -0700 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <mailman.5711.1147697881.27775.python-list@python.org> Message-ID: <1147781797.407160.54740@u72g2000cwu.googlegroups.com> BTW why are python dicts implemented as hash tables and not judy arrays? From funkyj at gmail.com Fri May 19 17:03:57 2006 From: funkyj at gmail.com (funkyj) Date: 19 May 2006 14:03:57 -0700 Subject: how to suppress the "source code echo" output by warnings.warn("x")? In-Reply-To: <e4l0pf$rcu$00$1@news.t-online.com> References: <1148059191.067419.112040@38g2000cwa.googlegroups.com> <e4l0pf$rcu$00$1@news.t-online.com> Message-ID: <1148072637.730879.265270@i40g2000cwc.googlegroups.com> Peter Otten wrote: > funkyj wrote: > > > I've been googling around trying to find the answer to this question > > but all I've managed to turn up is a 2 year old post of someone else > > asking the same question (no answer though). > How about monkey-patching? > > import warnings > > def formatwarning(message, category, filename, lineno): > return "%s:%s: %s: %s\n" % (filename, lineno, > category.__name__, message) > > warnings.formatwarning = formatwarning > > warnings.warn("so what") Thanks, that did the trick! From fredrik at pythonware.com Tue May 2 03:13:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 May 2006 09:13:49 +0200 Subject: blank lines representation in python References: <1146552795.151721.25380@g10g2000cwb.googlegroups.com> Message-ID: <e370rl$u32$1@sea.gmane.org> micklee74 at hotmail.com wrote: > what is the correct way to represent blank lines in python (while > iterating a file) without regexp? I know one way is to use > re.search((line,r'^$') to grab a blank line, but i wanna try not to use > regexp... > is it > 1) if line == ''": dosomething() (this also means EOF right? ) > 2) if line is None: dosomething() > 3) if not line: dosomething() > thanks if line == "\n": # look for a single newline dosomething() or if not line: ... end of file ... elif not line.strip(): # look for lines with nothing but whitespace dosomething() </F> From phillipsd at cromwell.co.uk Wed May 3 06:04:44 2006 From: phillipsd at cromwell.co.uk (Fuzzydave) Date: 3 May 2006 03:04:44 -0700 Subject: Calling a Postgres Function using CGI written in Python References: <1146648602.110172.191810@g10g2000cwb.googlegroups.com> <e39tpn$ktk$1@ucsnew1.ncl.ac.uk> Message-ID: <1146650684.089258.316120@i39g2000cwa.googlegroups.com> I did do a google search i have looking through the one python book i have and there are plenty of references for how to write a function in Python but not as many on how to call a function stored in postgres using python I have tried the conn.execute(cmi_grn_cost(productCode)) and also the conn.callproc(cmi_grn_cost(productCode)) commands where conn is the connection object and cmi_grn_cost() is the the function getting called from Postgres and productCode is the variable to passed. From richardjones at optushome.com.au Tue May 9 19:29:58 2006 From: richardjones at optushome.com.au (Richard Jones) Date: Wed, 10 May 2006 09:29:58 +1000 Subject: Python Game Challenge results (and new hosting) UP! Message-ID: <446125f5$0$25132$afc38c87@news.optusnet.com.au> After some problems with hosting which were solved thanks to the PSF the PyWeek site is back. http://www.pyweek.org/ Go see the results of the challenge, in particular the outstanding Nelly's Rooftop Garden and Trip on the Funny Boat. PyWeek challenges entrants to develop a complete game in Python in a week. Inspired by similar programming challenges and National Novel Writing Month, the event capitalises on the extraordinary work people can produce under the combined influence of a very short deadline and a community of like-minded people. This year there were approximately 100 entries, of which about 35 were completed. The next PyWeek will be in about 6 months. From python.list at tim.thechases.com Wed May 3 09:25:35 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 03 May 2006 08:25:35 -0500 Subject: Sorting a list of dictionaries by dictionary key In-Reply-To: <e3a9v3$kia$1@sea.gmane.org> References: <4458A61F.3010004@gmail.com> <e3a9v3$kia$1@sea.gmane.org> Message-ID: <4458AF4F.9060008@tim.thechases.com> > assuming that DateTime returns something that compares correctly, you can > do something like: > > def sortkey(item): > return item.get("from_datetime") > > data.sort(key=sortkey) > > (assuming Python 2.4 or later) Building on Fredrik's solution, for 2.3 (or earlier?), you can use data.sort(lambda a,b: cmp(a['from_datetime'], b['from_datetime'])) -tkc From smithj at rpath.com Sat May 13 10:35:03 2006 From: smithj at rpath.com (Jonathan Smith) Date: Sat, 13 May 2006 10:35:03 -0400 Subject: How to pass variables between scripts In-Reply-To: <5290E77B1FE2FE40B82AA54158825F0601F2C94C@hqosex01.fao.org> References: <5290E77B1FE2FE40B82AA54158825F0601F2C94C@hqosex01.fao.org> Message-ID: <4465EE97.9030903@rpath.com> Gross, Dorit (SDRN) wrote: > [snip] > for f in fileList: > try: > globvars = {'infile' : f} > locvars = {} > execfile('/scripts/second.py', globvars(), locvars) > except IOError: > exit(0) > print locvars > > > And this is what happens when calling test_exec.py > > ./test_exec.py > Traceback (most recent call last): > File "./test_exec.py", line 19, in ? > execfile('/scripts/second.py', vars(), results) > TypeError: 'dict' object is not callable > Why do you try to call globevars as if it was a function? As the traceback states, dictionaries can't be called like that. Just take the () out and try again. -smithj From diffuser78 at gmail.com Tue May 9 21:41:22 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 9 May 2006 18:41:22 -0700 Subject: Memory leak in Python In-Reply-To: <44605dd1$0$2056$626a54ce@news.free.fr> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <44605dd1$0$2056$626a54ce@news.free.fr> Message-ID: <1147225282.478996.134910@i39g2000cwa.googlegroups.com> The amount of data I read in is actually small. If you see my algorithm above it deals with 2000 nodes and each node has ot of attributes. When I close the program my computer becomes stable and performs as usual. I check the performance in Performance monitor and using "top" and the total memory is being used and on top of that around half a gig swap memory is also being used. Please give some helpful pointers to overcome such memory errors. I revisited my code to find nothing so obvious which would let this leak happen. How to kill cross references in the program. I am kinda newbie and not completely aware of the finetuning such programming process. Thanks bruno at modulix wrote: > diffuser78 at gmail.com wrote: > > I have a python code which is running on a huge data set. After > > starting the program the computer becomes unstable and gets very > > diffucult to even open konsole to kill that process. What I am assuming > > is that I am running out of memory. > > > > What should I do to make sure that my code runs fine without becoming > > unstable. How should I address the memory leak problem if any ? I have > > a gig of RAM. > > > > Every help is appreciated. > > Just a hint : if you're trying to load your whole "huge data set" in > memory, you're in for trouble whatever the language - for an example, > doing a 'buf = openedFile.read()' on a 100 gig file may not be a good > idea... > > > > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From me+python at modelnine.org Thu May 18 12:30:49 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 18 May 2006 18:30:49 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147958226.200557.264850@j33g2000cwa.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <mailman.5873.1147952119.27775.python-list@python.org> <1147958226.200557.264850@j33g2000cwa.googlegroups.com> Message-ID: <200605181830.49133.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 15:17 schrieb glomde: > > nothing general the OP is trying to achieve here > > Define general :-). I do think I solve something and make it more > readable. > You could also argue that list comprehension doesnt solve anything > general. Sure, a list comprehension solves something general. It's syntactic sugar for a recurring pattern in a for loop. What you are trying to achieve is to make syntactic sugar for making namespace definitions look nicer. But: the way you are trying to do so isn't pythonic, because there isn't one obvious way how your proposal works; you're not even specifying a proper semantic interpretation of your syntax (and use "magic" markers, which is even more a NoNo). For a better thought out proposal (IMHO) for stacking and defining namespaces (based on the current metaclass behaviour), look for the PEP on the "make" keyword (which was sent to Py-Dev some weeks ago). > > By the way: the language you (the OP) are trying to implement here goes > > strictly against the MVC model of application programming. You know that, > > right? > > ???. I cant see how this breaks MVC. MVC depends on how you parition > your application > this doesnt put any constraint on how you should do your application. Sure it does. In case you implement a templating language that simply contains the "full" power of the Python language, you create a (somewhat) cripled PHP, basically. The View part of MVC shouldn't do branching (well, in the strict sense of MVC), shouldn't do looping, shouldn't do modification of the data, all that stuff is up to the controller. If you empower the template writer with the full power of the Python programming language by integrating your proposal with Python itself, you're bound to water down the split between the three, and to create a maintenance nightmare (as I said, PHP comes to mind, where you basically can't split controller from model properly). For a proper (and pretty strict) MVC templating language, have a look at Nevow. --- Heiko. From apa7hy.spam at gmail.com Wed May 3 03:21:43 2006 From: apa7hy.spam at gmail.com (apa7hy.spam at gmail.com) Date: 3 May 2006 00:21:43 -0700 Subject: audio on os x using python, mad, ao Message-ID: <1146640903.629524.170150@u72g2000cwu.googlegroups.com> this message was originally posted by someone else and closed without a proper answer. i'm reposting it in hopes that someone will provide a solution. Begin Quote: "I'm attempting to play an mp3 file on OSX, but am running into some difficulty. When using py-mad and py-ao, I only get static with the following code (which is derived off another mailing that I found from this list's archives): #!/usr/bin/env python '''Requires: py-mad (mp3 ability) py-ao (system audio ability) ''' import mad, ao, sys mf = mad.MadFile(sys.argv[1]) dev = ao.AudioDevice('macosx')#osx device, linux: use "oss" or "alsa" while 1: buf = mf.read() if buf is None: break dev.play(buf, len(buf)) Does anyone know why this produces static, or whether there's a better method of producing audio output that's also cross-platform (OSX, linux)? I've looked at pymedia, but they do not support OSX at the moment. Thanks!" From fdu.xiaojf at gmail.com Sun May 7 23:25:44 2006 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Mon, 08 May 2006 11:25:44 +0800 Subject: How can I do this with python ? Message-ID: <445EBA38.7000609@gmail.com> Dear all, In a shell script, I can run a command which need interactive input like this, #!/bin/sh A_Command<<-EOF a b c EOF But, how can I do this with python ? Thanks in advance. From jstroud at ucla.edu Thu May 11 22:51:34 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 11 May 2006 19:51:34 -0700 Subject: which windows python to use? In-Reply-To: <mailman.5608.1147380021.27775.python-list@python.org> References: <mailman.5589.1147359382.27775.python-list@python.org> <e406rp$dvt$1@daisy.noc.ucla.edu> <mailman.5608.1147380021.27775.python-list@python.org> Message-ID: <e40t7m$ull$1@daisy.noc.ucla.edu> Robert Kern wrote: > James Stroud wrote: > > >>Enthought does not play well with cygwin, I've noticed. > > > In what way? Does the mingw gcc that we distribute interfere with Cygwin's gcc? > One can not run the enthought python interactive interpreter from a cygwin x-window session, it locks up. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From nobody at 127.0.0.1 Wed May 3 18:31:50 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 22:31:50 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <mailman.5241.1146613795.27775.python-list@python.org> <44580270$0$4903$626a54ce@news.free.fr> <mailman.5285.1146693145.27775.python-list@python.org> Message-ID: <qba6g.67188$F_3.3510@newssvr29.news.prodigy.net> Ben Finney wrote: > My basis for rejecting the proposal is that it claims to offer net > simplicity, yet it breaks at least two of the admonishments that > simplify Python. As do other features of Python. Or did you forget the follow-up to the special cases "rule"? Special cases aren't special enough to break the rules. Although practicality beats purity. From mblume at socha.net Fri May 12 10:05:52 2006 From: mblume at socha.net (Martin Blume) Date: Fri, 12 May 2006 16:05:52 +0200 Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> <44644a76$0$290$626a54ce@news.free.fr> Message-ID: <4464959f$1$13578$5402220f@news.sunrise.ch> "bruno at modulix" schrieb > > What Python 2.4 adds is only syntactic sugar for decorators. > You can do the same - somewhat more explicitely - in 2.3. > > > What is the decorator useful for? > > > The whole things looks like this: > > def deco(func): > print "decorating %s" % func.__name__ > def _wrapper(*args, **kw): > print "%s called " % func.__name__ > res = func(*args, **kw) > print "%s returned %s" % (func.__name__, str(res)) return res ^^^^^^^^^^ Shouldn't here be a return res, so that wrapper behaves like the original function? > return _wrapper > > # python < 2.4 > def somefunc(): > print "in somefunc" > return 42 > > somefunc = deco(somefunc) > Thanks for the explanation. Another question: Isn't decorating / wrapping usually done at runtime, so that the @deco notation is pretty useless (because you'd have to change the original code)? What do I miss here? Martin From robert.kern at gmail.com Wed May 24 20:26:51 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 24 May 2006 19:26:51 -0500 Subject: Why can't timedeltas be divided? In-Reply-To: <200605250025.46476.maric@aristote.info> References: <1148508445.853563.170030@i39g2000cwa.googlegroups.com> <200605250025.46476.maric@aristote.info> Message-ID: <e52tka$ft7$1@sea.gmane.org> Maric Michaud wrote: > Le Jeudi 25 Mai 2006 00:07, Dan Bishop a ?crit : > >>If I try to write something like: >> >> num_weeks = time_diff / datetime.timedelta(days=7) > > because it has no meaning, Yes, it does. > what you want is : > > num_weeks = time_diff.days / 7 > or > num_weeks = (time_diff / 7).days Uh, no. Besides the integer division problem in your first line, keep in mind that the .days attribute does not give you the time interval measured in days. It gives you the number of *whole* days in the interval. The first method will be incorrect if time_diff is not an even multiple of 1 day. The latter will be incorrect if time_diff is not an even multiple of 7 days. -- 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 ask at me Thu May 11 08:05:24 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 08:05:24 -0400 Subject: python equivalent of the following program Message-ID: <FbWdnZazBY8Aqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> Hi, What would by a python equivalent of following shell program: #!/bin/sh prog1 > file1 & prog2 > file2 & As you see, I need to spawn a few processes and redirect stdout to some files. Thx, A. From jamesthiele.usenet at gmail.com Thu May 11 14:04:34 2006 From: jamesthiele.usenet at gmail.com (James Thiele) Date: 11 May 2006 11:04:34 -0700 Subject: Reg Ex help References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> Message-ID: <1147370674.603873.193520@j73g2000cwa.googlegroups.com> don wrote: > I have a string from a clearcase cleartool ls command. > > /main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT > from /main/parallel_branch_1/release_branch_1.0/4 > > I want to write a regex that gives me the branch the file was > checkedout on ,in this case - 'dbg_for_python' > > Also if there is a better way than using regex, please let me know. > > Thanks in advance, > Don Not regex, but does this do what you want? >>> s = "/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT" >>> s = s + " from /main/parallel_branch_1/release_branch_1.0/4" >>> s.split('/')[4] 'dbg_for_python' From onurb at xiludom.gro Fri May 12 04:40:51 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 10:40:51 +0200 Subject: Decorator In-Reply-To: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> Message-ID: <44644a76$0$290$626a54ce@news.free.fr> Lad wrote: > I use Python 2.3. > I have heard about decorators in Python 2.4. What Python 2.4 adds is only syntactic sugar for decorators. You can do the same - somewhat more explicitely - in 2.3. > What is the decorator useful for? FWIW, I'm not sure the name 'decorator' is such a great idea. A decorator (read 'function decorator') is mainly a callable that takes a callable as param and returns another callable, usually wrapping the passed callable and adding some responsabilities (tracing, logging, pre-post condition checks, etc). Two well-known examples are classmethod and staticmethod. The whole things looks like this: def deco(func): print "decorating %s" % func.__name__ def _wrapper(*args, **kw): print "%s called " % func.__name__ res = func(*args, **kw) print "%s returned %s" % (func.__name__, str(res)) return _wrapper # python < 2.4 def somefunc(): print "in somefunc" return 42 somefunc = deco(somefunc) The syntactic sugar added in 2.4 allows you to avoid the explicit call to deco(): # python >= 2.4 @deco def someotherfunc(): return "the parrot is dead" As you see, apart from the syntactic sugar, there's nothing new here. It's just plain old higher order function, well known in any functional language. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From thomas at eforms.co.nz Tue May 9 23:55:46 2006 From: thomas at eforms.co.nz (Thomas Thomas) Date: Wed, 10 May 2006 15:55:46 +1200 Subject: Reading Soap struct type References: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz><1146620207.56.7672@mint-julep.mondoinfo.com><002901c66e57$05a69090$346ea8c0@tintz.co.nz><1146624295.41.7841@mint-julep.mondoinfo.com><003501c66e64$316deb30$346ea8c0@tintz.co.nz> <1146677203.2.7870@mint-julep.mondoinfo.com> Message-ID: <00f701c673e5$a3af0860$346ea8c0@tintz.co.nz> Hi All, I am receiving a hash below from my Soap Interface <SOAPpy.Types.structType item at 34661160>: {'Field12value': ':C F3Value', 'Field8': 'Price Text:price_text', 'Field9': 'Text with File:file_text ', 'Field11value': ':CF2Value', 'Field7': 'Product Code:product_code', 'Field7va lue': ':product_values', 'Field2': 'Job Reference:job_reference', 'Field3': 'Job Description:job_description', 'Field6': 'Campaign Name:campaign_name', 'Field10 value': ':CF1Value', 'Field6value': ':campaign_values', 'Field5': 'Keywords:keyw ords', 'Field10': 'CF1Title:custom_field1', 'Field11': 'CF2Title:custom_field2', 'Field12': 'CF3Title:custom_field3', 'Field13': 'CF4Title:custom_field4', 'Fiel d14': 'Name:meta_filename', 'Field4': 'Display Name:display_name', 'Field13value ': ':CF4Value'} How can i iterarte through it bcz when do try do something like myHash.values() I am getting the error AttributeError: structType instance has no attribute 'values' any help Thomas From aleaxit at yahoo.com Thu May 4 10:59:22 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 4 May 2006 07:59:22 -0700 Subject: Subclassing array References: <1146747096.623101.122510@j73g2000cwa.googlegroups.com> Message-ID: <1heszg6.1q17bgp1jwua35N%aleaxit@yahoo.com> TG <girodt at gmail.com> wrote: ... > When I call Vector.__init__() in Stimulus, doesn't it also call __new__ > ? I don't understand the detail of callings to __new__ and __init__ in > python inheritance ... Calling a (new-style) class does __new__ first, THEN calls the class's __init__ on the resulting instance -- and the arguments you're passing when calling the class go to both __new__ and __init__. Alex From claird at lairds.us Mon May 1 12:08:01 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 01 May 2006 16:08:01 GMT Subject: An Atlas of Graphs with Python References: <4455e186$0$14794$4fafbaef@reader4.news.tin.it> Message-ID: <7dmhi3-emr.ln1@lairds.us> In article <4455e186$0$14794$4fafbaef at reader4.news.tin.it>, Giandomenico Sica <nospam at nospam.nospam> wrote: > Call for Cooperation >An Atlas of Linguistic Graphs > >I'm a researcher in graph theory and networks. >I'm working about a project connected with the theory and the applications >of >linguistic graphs, which are mathematical structures useful to represent >languages and consequently to manage the organization of data in different >kinds of scientific fields. >At the present I'm developing an application of these graphs to medicine, >specifically related to the ontology of clinical diseases. >And now to the purpose of this message, which is to ask if someone in this >list >can be interested in collaborating with me about the construction of an open >source software useful to represent, to analyse and to compare linguistic >graphs. >I've developed the project but don't have the necessary programming skills >to >proceed with the creation of the code. >The software would be distributed in public domain and the collaboration is >free >and voluntary. . . . Much as I'd love personally to take up this opportunity, previous commitments preclude it. I wonder whether it might attract someone at Google? They certainly have an interest in analytic linguistics and familiarity with high-level languages; while Summer of Code might appear superficially to be a vehicle of some sort, I believe it's already closed to new project ideas ... I'd ask also among the practitioners of ML, Lisp, J, Snobol, and other high-level languages that I believe are likeliest to host interest in graph theory. It's certainly true, though, that Python boasts at least a couple. From linuxnow at gmail.com Mon May 8 02:58:56 2006 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: 7 May 2006 23:58:56 -0700 Subject: why _import__ only works from interactive interpreter? In-Reply-To: <1147068903.306169.52130@i40g2000cwc.googlegroups.com> References: <1147041996.232232.165820@i39g2000cwa.googlegroups.com> <1147043686.558715.124540@j73g2000cwa.googlegroups.com> <1147044060.998898.140740@i40g2000cwc.googlegroups.com> <pan.2006.05.08.00.17.20.44832@gmail.com> <1147068903.306169.52130@i40g2000cwc.googlegroups.com> Message-ID: <1147071536.693454.264300@v46g2000cwv.googlegroups.com> Sorry to follow up myself, I've finally used the execfile approach, passing an empty dict for capturing locals and then just processing it: new_settings = {} execfile(self.SETTINGS_MODULE, new_settings) # returns its locals in new_settings # assign UPPER_CASE vars for setting in new_settings.keys(): setting_value = new_settings[setting] # do what you want with the vars It looks like a better solution than polluting the namespace and allows to use any file as a config file withou the need to have it on sys.path. From None at none.none Tue May 30 15:50:38 2006 From: None at none.none (WIdgeteye) Date: Tue, 30 May 2006 14:50:38 -0500 Subject: TIming References: <pan.2006.05.30.01.24.04.677340@none.none> <ecin725eh7mk1teolpfi2ulj349ogptdir@4ax.com> <pan.2006.05.30.05.23.09.936650@none.none> <mailman.6326.1148969845.27775.python-list@python.org> Message-ID: <pan.2006.05.30.19.50.38.152274@none.none> On Tue, 30 May 2006 16:15:44 +1000, John McMonagle wrote: > Tue, 2006-05-30 at 00:23 -0500, WIdgeteye wrote: >> On Tue, 30 May 2006 04:34:03 +0000, Tim Roberts wrote: >> >> > WIdgeteye <None at none.none> wrote: >> >>HI, >> >>I am trying to write a little program that will run a program on >> >>scedule. I am having trouble understanding the datetime, time, sched >> >>modules. What I would like is something like this: >> >> >> >>If date&time = 06-13-2006:18:00:00 >> >>Then run this program >> >> >> >>I am not sure how to enter a future date in this equation using any of >> >>the modules mentioned above. I have figured out how to get the date >> >>and time from the modules above but not the future and then compare >> >>the two. >> > >> > What operating system are you using? Both Linux and Windows have >> > commands that can do this for you. It's more efficient to use >> > existing operating system services than to invent your own. >> > >> > Also, remember to take into account the possibility that your program >> > might not check the time at the exact second. In your example, you >> > need to be prepared to start your app if the time is just PAST 6 PM on >> > June 13. >> >> I am using Linux and could use cron. But I want to be able to schedule >> and record television shows on her. And yeah I know about freevo but >> it's way to complicated than it needs to be. >> >> So back to the question: How can I get a 9 position tuple from the time >> functions in Python based on a future date. > > Tim Roberts is right. As you are on linux, I suggest you investigate the > at command - very user friendly and not at all complicated. I have been using Slackware for over 10 years I know all about the commands on the OS. If you guys don't have an answer to the question just say so. But don't give me suggestions on how to use an OS I have been using most likely longer than 90% of the people using linux today. This is the comp.lang.python news group not the linux news group. If I didn't want to write the Python code and I wanted to use the OS commands instead I would. Python is cross platform. Linux is not. I intend to release the software to the general public someday when it is done. I want it cross platform. BTW in the time it took me NOT to get an answer for my question in this so called Python NG, I figured it out for myself. This PYTHON NG blows to high heaven. Whats worse, the answers I got were most likely from people who know SQUAT about Python scripting. That's why they gave me such lame fucking answers. Idiots. From skip at pobox.com Fri May 19 13:16:23 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 19 May 2006 12:16:23 -0500 Subject: WTF? Printing unicode strings In-Reply-To: <e4kruq$19o$1@sea.gmane.org> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <RFkbg.2124$No6.46433@news.tufts.edu> <e4kruq$19o$1@sea.gmane.org> Message-ID: <17517.64871.44237.790358@montanaro.dyndns.org> Robert> Because sys.stdout.encoding isn't determined by your Python Robert> configuration, but your terminal's. Learn something every day. I take it "646" is an alias for "ascii" (or vice versa)? % python Python 2.4.2 (#1, Feb 23 2006, 12:48:31) [GCC 3.4.1] on sunos5 Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.stdout.encoding '646' >>> import codecs >>> codecs.lookup("646") (<built-in function ascii_encode>, <built-in function ascii_decode>, <class encodings.ascii.StreamReader at 0x819aa4c>, <class encodings.ascii.StreamWriter at 0x819aa1c>) Skip From robert.kern at gmail.com Mon May 15 21:59:38 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 15 May 2006 20:59:38 -0500 Subject: Python modules In-Reply-To: <20060516003901.11507.qmail@web53815.mail.yahoo.com> References: <20060516003901.11507.qmail@web53815.mail.yahoo.com> Message-ID: <e4bbma$8ed$1@sea.gmane.org> Shirley Li wrote: > Dear Python experts, > > I'm a beginner of Python programming. I have a question about Python > modules. > > With the following: > ================= > import sys, os, string, math > from Numeric import * > from Matrix import * > ================= > at the beginning of my Python script, it complained that "ImportError: > No module named Numeric" when I run the script. > > Could someone tell me what's wrong? You didn't install the Numeric module or didn't install it correctly. Also, please note that the Numeric module (and the Matrix module that comes with it) have been replaced with the numpy package. Since you are just getting started, please start with numpy. http://numeric.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 rpdooling at gmail.com Wed May 10 23:29:13 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 May 2006 20:29:13 -0700 Subject: reusing parts of a string in RE matches? In-Reply-To: <1147315665.449631.136650@y43g2000cwc.googlegroups.com> References: <YMm8g.2077$No6.45935@news.tufts.edu> <1147306546.383277.11820@j33g2000cwa.googlegroups.com> <1147313413.738430.121890@g10g2000cwb.googlegroups.com> <1147315665.449631.136650@y43g2000cwc.googlegroups.com> Message-ID: <1147318153.362423.247180@v46g2000cwv.googlegroups.com> Thanks, Ben. Quite an education! rick From steve at holdenweb.com Thu May 18 01:27:30 2006 From: steve at holdenweb.com (Steve Holden) Date: Thu, 18 May 2006 06:27:30 +0100 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <m2u07rwu44.fsf@ordesa.lan> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> <m2irobbjtf.fsf@ordesa.lan> <WE49g.86156$dW3.50737@newssvr21.news.prodigy.com> <m2u07rwu44.fsf@ordesa.lan> Message-ID: <e4h0ju$41r$1@sea.gmane.org> Piet van Oostrum wrote: >>>>>>Edward Elliott <nobody at 127.0.0.1> (EE) wrote: > > >>EE> Piet van Oostrum wrote: >> >>>>>>>>>tsaar2003 at yahoo.com (T) wrote: >>>> >>T> As you can see, the "constant" A can be modified this easily. But if >>T> there were an intuitive mechanism to declare a symbol to be immutable, >>T> then there won't be this problem. >> >>>>Mutability is not a property of symbols but of values. So it doesn't make >>>>sense to declare an identifier to be immutable. And mutability is tied to >>>>the object's type, not to individual instances. > > >>EE> I think he meant immutable binding, not immutable symbol. So >>EE> rebinding/overshadowing a "constant" A would raise an error, but >>EE> mutating the underlying object A refers to would not (unless it too >>EE> were immutable). > > > The way I understood it was that he meant both. The way I understood it was that he didn't understand it. But then he was gracious enough to admit that under questioning. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From aleaxit at yahoo.com Sun May 7 14:57:58 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 11:57:58 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <1vspxcmldcqa5.t1b4abyraqom.dlg@40tude.net> Message-ID: <1heytyi.lope5l1p029gfN%aleaxit@yahoo.com> Frank Buss <fb at frank-buss.de> wrote: > Alex Martelli wrote: > > > I cannot conceive of one. Wherever within a statement I could write the > > expression > > lambda <args>: body > > I can *ALWAYS* obtain the identical effect by picking an otherwise > > locally unused identifier X, writing the statement > > def X(<args>): body > > and using, as the expression, identifier X instead of the lambda. > > This is true, but with lambda it is easier to read: > > http://www.frank-buss.de/lisp/functional.html > http://www.frank-buss.de/lisp/texture.html > > Would be interesting to see how this would look like in Python or some of > the other languages to which this troll thread was posted :-) Sorry, but I just don't see what lambda is buying you here. Taking just one simple example from the first page you quote, you have: (defun blank () "a blank picture" (lambda (a b c) (declare (ignore a b c)) '())) which in Python would be: def blank(): " a blank picture " return lambda a, b, c: [] while a named-function variant might be: def blank(): def blank_picture(a, b, c): return [] return blank_picture Where's the beef, really? I find the named-function variant somewhat more readable than the lambda-based variant, but even if your preferences are the opposite, this is really such a tiny difference that I can't see why so many bits should gets wasted debating it (perhaps it's one of Parkinson's Laws at work...). Alex From Serge.Orlov at gmail.com Tue May 2 10:18:25 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 2 May 2006 07:18:25 -0700 Subject: py2app, pythoncard build problems In-Reply-To: <1146576615.234047.196110@v46g2000cwv.googlegroups.com> References: <1146576615.234047.196110@v46g2000cwv.googlegroups.com> Message-ID: <1146579505.274009.3130@j73g2000cwa.googlegroups.com> loren.davie at gmail.com wrote: > Hi, > > I'm attempting to build a small app that uses pythoncard for a gui > layer. The intention is to use py2app to construct an .app bundle for > the Mac. I'm running OS 10.4 on an Intel MacBook Pro. I'm using the > default installed Python 2.3 > > The .app bundle appears to build, but when I start up it fails - > checking the console reveals that it can't find the "wx" package, as > its called from some pythoncard code. (The app launches just fine in > non-bundled form when I run it from the command line using pythonw). > > Not sure where to go with this. Any help would be greatly appreciated Most likely py2app analyzes code of pythoncard and cannot find dependance on wx. As a quick workaround you can just insert "import wx" in the beginning of your program where you import pythoncard. For a more flexible solution you will need to read py2app docs how to force bunding of a package from setup.py From scott.daniels at acm.org Sun May 21 18:21:24 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 21 May 2006 15:21:24 -0700 Subject: Name conflict in class hierarchy In-Reply-To: <mailman.6014.1148158078.27775.python-list@python.org> References: <mailman.6014.1148158078.27775.python-list@python.org> Message-ID: <4470e3cd$1@nntp0.pdx.net> Jeffrey Barish wrote: > Suppose that there are two classes defined as follows: > > class A(object): > def f1(self): > print 'In A.f1, calling func' > self.func() > > def func(self): > print 'In A.func' > > class B(A): > def func(self): > print 'In B.func, calling A.f1' > A.f1(self) > > Class A was defined by someone else or it comes from a library, so I have no > prior information about what is in it. I subclass A to add some new > functionality, and I call the new function "func". The function B.func > uses A.f1, but unbeknownst to me, A.f1 uses A.func. Unfortunately, class B > overrides func, so the call in A.f1 to self.func actually invokes B.func, > resulting in this case in an infinite loop. Is there a way from B to > specify that A should use its own version of func and ignore the version in > B? I know that I could rename A.func to avoid the name clash, but since A > is actually in a library, I will lose that change when I upgrade the > library. I could rename B.func, but there is already a bunch of code that > calls it so I would have to update all the calls. That seems like the > correct solution, though. The other possibility is to use composition > rather than subclassing: > > class B: > def func(self): > print 'In B.func, calling A.f1' > a = A() > a.f1() > > but then B does not inherit other functions of A that I would like to use. > It struck me that this must be a common problem in OOP, so I'm wondering > whether there is a simple solution that I am missing. If you insist on this (I find silly) version, I'd suggest you want to use "has-a" rather than "is-a" relationship between B and A class A(object): def f1(self): print 'In A.f1, calling func' self.func() def func(self): print 'In A.func' class B(object): def __init__(self, *args, **kwargs): self._a = A(*args, **kwargs) def func(self): print 'In B.func, calling A.f1' self._a.f1() But, you could use this (I think ill-advised) technique if you need a special-case work-around: class Bb(A): def __init__(self, *args, **kwargs): super(Bb, self).__init__(*args, **kwargs) self._recursed_func = 0 def f1(self): self._recursed_func += 1 try: return super(Bb, self).f1() finally: self._recursed_func -= 1 def func(self): if self._recursed_func: return super(Bb, self).func() print 'In B.func, calling A.f1' self.f1() --Scott David Daniels scott.daniels at acm.org From phddas at yahoo.com Fri May 12 13:11:43 2006 From: phddas at yahoo.com (Gary Wessle) Date: 13 May 2006 03:11:43 +1000 Subject: TkTable for info gathering Message-ID: <877j4ri2wg.fsf@localhost.localdomain> Hi I just finished with 1.5 tutorials about Tkinter, my thought is to use a table "maybe TkTable" to gather info from the user as to what file to chart data from, as well as info provided by the TkTable properties. each cell of the table will be either empty or contains a file path, let x=1 be the x-index of the cells on the first col and y=1 be the y-index of the cells on the first row. the position of the cell with the max-x and max-y will determine how many frames will be displayed, grid with x columns corresponding to max-x and x rows corresponding to max-y. i.e, the look of the table will resemble the gui, empty cell -> empty frame, cell with filepth -> frame with canvas. is TkTable or NovaGrid suitable for this? thanks From jantod at gmail.com Sun May 28 19:50:41 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 28 May 2006 16:50:41 -0700 Subject: itertools.count() as built-in References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> Message-ID: <1148860241.048549.269330@j73g2000cwa.googlegroups.com> I have a project of around 6000 lines where I used count() 20 times. It has 14 modules, 10 of which I needed an explicit import. Many of the usages are of the form: for item, n in zip(items, count(N)): dostuff Around half of these are due to using pylab.subplot(x,y.n), which requires values for n>=1. So I want N=1. The enumerate builtin starts from 0. I also write out textual reports that start with n=1. I also have things like for n, component, rotations in zip(count(), sorted(tools.component_files().keys()), all_symbol_rotations) where the enumerate version just looks even more confusing and easy to mess up for n, component, rotations in enumerate(sorted(tools.component_files().keys()), all_symbol_rotations) Some more examples follow. Note that I find it more natural to specify the count last as it's usually less important than the other values. This is different from the order given by enumerate, so I'm more inclined to use count(). mutated_symbols_and_names = zip(mutated_symbols, (("<%s mutation %s>" % (component, m)) for m in count())) edge_weight=dict(zip(Intersection.types, count(1))) for (component, filename), n in zip(components, count()): for (component, filename), component_count in zip(tools.component_files().items(), count()): From tim.golden at viacom-outdoor.co.uk Mon May 15 08:47:00 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 15 May 2006 13:47:00 +0100 Subject: Formmating excel cells with PyExcelerator or COM Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1BE@vogbs009.gb.vo.local> [Mauricio Tellez] | Hi, I just want that a number like 1234.123 appear in excel | as 1,234.12 | In excel I just select some cells, then right click on them | and select "Cell Formatting" then select Number, and check | "Use thounsands separator" and 2 decimal places. I can't find | how to do this with PyExcelerator neither with COM. Any clue? Nearly always, a good starting point for doing this kind of thing with COM (obviously doesn't apply for PyExcelerator) is to record a Macro in Excel itself which does what you want, and then to translate the code that macro uses into Python -- usually trivial. Here, I stuck a number into Excel, applied formatting as you described, and the result was: Selection.NumberFormat = "#,##0.00" Obviously you have to do whatever you need around that to apply the formatting to the range of values you're interested in, but a (negligible) working example might be: <code> import win32com.client xl = win32com.client.gencache.EnsureDispatch ("Excel.Application") xl.Visible = 1 wb = xl.Workbooks.Add () ws = wb.ActiveSheet range = ws.Range (ws.Cells (1, 1), ws.Cells (1, 3)) range.Value = [1234, 2345, 3456] range.NumberFormat = "#,##0.00" </code> 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 wahab at chemie.uni-halle.de Thu May 11 17:40:50 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Thu, 11 May 2006 23:40:50 +0200 Subject: calling perl modules from python In-Reply-To: <1690502.fNiZoSDNhf@teancum> References: <1690502.fNiZoSDNhf@teancum> Message-ID: <e40b7u$llg$1@mlucom4.urz.uni-halle.de> Hi David > I have a hash function written by another organization that I need to use. > It is implemented in perl. I've been attempting to decode what they are > doing in their hash function and it is taking way too long. I've > identified two functions in a perl module that I would like to 'call' from > a python program. I found the following: > http://www.annocpan.org/~GAAS/pyperl-1.0/perlmodule.pod > > and wondered if anyone had any comments. This thing implements a perl > interpreter inside python. That seems like overkill to me. > > I wonder what wisdom this group can offer. Why not the other way around. Use their .pl-program and use the functions inside it - then cross-call in to your python module: [--- someperl.pl ---] py_prepare $result1 = hash_proc_1($whatever); $result2 = hash_proc_2($whatever); py_calculate( $result1, $result2 ); # - - - - - - - - - - - - - - - - - - # use Inline Python => <<'END_OF_PYTHON_CODE'; def py_calculate (r1, r2): do_something(r1 * r2) def do_something(result): return x - y END_OF_PYTHON_CODE [/--- someperl.pl ---] This approach ensures that the strange perl functions run clean int their native environment. You have access to all your py- Modules, as in a normal python- environment (Python globals are directly imported, afaik). [--- someperl.pl ---] use Inline Python; doit(); __END__ __Python__ from mylibrary import doit ... ... [/--- someperl.pl ---] (http://search.cpan.org/~neilw/Inline-Python-0.22/Python.pod) I use this sometimes, it is quite nice. Regards M. From vbgunz at gmail.com Wed May 24 08:43:24 2006 From: vbgunz at gmail.com (vbgunz) Date: 24 May 2006 05:43:24 -0700 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> Message-ID: <1148474604.279491.71090@j55g2000cwa.googlegroups.com> Learning Python by Mark Lutz will be the most perfect book to get you started! Perhaps there are others aimed at the non-programmer but after getting through that book (2 times) I finally left it with wings... It is a great book for the n00b in my humble opinion. After that, you'll pretty much start flying higher on your own as long as you always keep the python docs handy along with the addresses to comp.lang.python and it's IRC channel #python on irc.freenode.net... Good luck, welcome to Python! From robert.kern at gmail.com Wed May 10 19:55:40 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 10 May 2006 18:55:40 -0500 Subject: Best form when using matrices and arrays in scipy... In-Reply-To: <1147304301.787642.309380@v46g2000cwv.googlegroups.com> References: <1147304301.787642.309380@v46g2000cwv.googlegroups.com> Message-ID: <e3tuht$ah0$1@sea.gmane.org> conor.robinson at gmail.com wrote: > Using large arrays of data I found it is MUCH faster to cast arrays to > matricies and then multiply the two matricies togther > (scipy.matrix(ARRAY1)*scipy.matrix(ARRAY2)) in order to do a matrix > multipy of two arrays vs. scipy.matrixmultipy(ARRAY1, ARRAY2). > > Are there any logical/efficiency errors with this train of thought and > is there a valid reason for the speed increase? matrixmultiply is a backwards-compatibility alias. You should be using dot() instead. When an optimized BLAS is available dot() is replaced with an optimized version. numpy.matrix uses dot() to implement its multiplication operation. Unfortunately, the code that does the replacement does not seem to handle matrixmultiply correctly. Also, there are better fora for asking questions about numpy and scipy: http://www.scipy.org/Mailing_Lists -- 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 onurb at xiludom.gro Thu May 4 04:48:52 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 10:48:52 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <k_a6g.21491$4L1.14831@newssvr11.news.prodigy.com> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <pan.2006.05.03.20.57.05.32060@gmx.net> <Sda6g.67189$F_3.50022@newssvr29.news.prodigy.net> <mailman.5289.1146697051.27775.python-list@python.org> <k_a6g.21491$4L1.14831@newssvr11.news.prodigy.com> Message-ID: <4459c050$0$3552$626a54ce@news.free.fr> Edward Elliott wrote: > Ben Finney wrote: > >>As I understand it, the point was not what the code does, but to give >>a sample input (a Python program) for the "simple text processor" you >>described to wade through. > > > Ah, well then, there's no need for a full-blown parser. It should suffice > to recognize a class definition and modify the parameter list of every def > indented one level further than that. won't do : class CounterExample(object): if compute_some_const_according_to_phase_of_moon(): def meth(...): do_something(self, 42) else: do_something_else(self) > Then pick out the static methods and > 'undo' those. don't forget classmethods... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From __peter__ at web.de Tue May 16 11:44:06 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 May 2006 17:44:06 +0200 Subject: regex help References: <4469eba9$0$61166$ae4e5890@news.nationwide.net> Message-ID: <e4crsb$tc8$02$1@news.t-online.com> Lance Hoffmeyer wrote: > I have the following table and I am trying to match percentage the 2nd > column on the 2nd Tiger line (9.0). > > I have tried both of the following. I expected both to match but neither > did? Is there a modifier > I am missing? What changes do I need to make these match? I need to keep > the structure of the regex the same. > > TIGER.append(re.search("TIGER\s{10}.*?(?:(\d{1,3}\.\d)\s+){2}", > target_table).group(1)) > TIGER.append(re.search("^TIGER.*?(?:(\d{1,3}\.\d)\s+){2}", > target_table).group(1)) You can try the re.DOTALL flag (prepend the regex string with "(?s)"), but I'd go with something really simple: instream = iter(target_table.splitlines()) # or: instream = open(datafile) for line in instream: if line.startswith("TIGER"): value = instream.next().split()[1] # or ...[0]? they are both '9.0' TIGER.append(value) break Peter From steven.bethard at gmail.com Sat May 20 01:39:20 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 19 May 2006 23:39:20 -0600 Subject: Using metaclasses to inherit class variables In-Reply-To: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> Message-ID: <-JednSk_j70VNvPZRVn-sg@comcast.com> telesphore4 at gmail.com wrote: > I want to inherit fresh copies of some class variables. So I set up a > metaclass and meddle with the class variables there. > > Now it would be convenient to run thru a dictionary rather than > explicitly set each variable. However getattr() and setattr() are out > because they chase the variable thru the class hierarchy. getattr() does, setattr() doesn't. > Is there an easy way around this? Or am I stuck listing out the > variables one per line? > > class SetClassVars(type): > cvars = dict(name=None, desc=None, required=True, minlen=1, > maxlen=25, idDown=999999999, idNext=0) > def __init__(cls, name, bases, dict): > if not cls.__dict__.has_key('name'): cls.name = None > if not cls.__dict__.has_key('desc'): cls.desc = None > if not cls.__dict__.has_key('required'): cls.required = True > if not cls.__dict__.has_key('minlen'): cls.minlen = 1 > if not cls.__dict__.has_key('maxlen'): cls.maxlen = 25 > if not cls.__dict__.has_key('idDown'): cls.idDown = 999999999 > if not cls.__dict__.has_key('idNext'): cls.idNext = 0 Does this do what you want? Note that I don't even bother with __dict__ since the class dict is already available as the final argument to __init__. >>> class SetClassVars(type): ... cvars = dict(name=None, desc=None, required=True) ... def __init__(cls, name, bases, classdict): ... for name, value in SetClassVars.cvars.iteritems(): ... if not name in classdict: ... setattr(cls, name, value) ... >>> class C(object): ... __metaclass__ = SetClassVars ... name = 'foo' ... >>> class D(C): ... __metaclass__ = SetClassVars ... desc = 'bar' ... >>> print C.name, C.desc, C.required foo None True >>> print D.name, D.desc, D.required None bar True STeVe From usenet at local.machine Sun May 21 12:18:22 2006 From: usenet at local.machine (=?ISO-8859-2?Q?Dra=BEen_Gemi=E6?=) Date: Sun, 21 May 2006 18:18:22 +0200 Subject: Software Needs Philosophers In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <e4q37v$ipo$2@magcargo.vodatel.hr> Xah Lee wrote: > Software Needs Philosophers > Welcome to my junk filters !!!! DG From deets at nospam.web.de Wed May 24 16:04:07 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 May 2006 22:04:07 +0200 Subject: Bind an instance of a base to a subclass - can this be done? In-Reply-To: <pecoraREMOVE-120DFE.15351024052006@ra.nrl.navy.mil> References: <pecoraREMOVE-120DFE.15351024052006@ra.nrl.navy.mil> Message-ID: <4djshnF1asdovU1@uni-berlin.de> Lou Pecora schrieb: > I've been scanning Python in a Nutshell, but this seems to be either > undoable or so subtle that I don't know how to do it. > > I want to subclass a base class that is returned from a Standard Library > function (particularly, subclass file which is returned from open). I > would add some extra functionality and keep the base functions, too. > But I am stuck. > > E.g. > > class myfile(file): > def myreadline(): > #code here to return something read from file > > Then do something like (I know this isn't right, I'm just trying to > convey the idea of what I would like) > > mf=myfile() > > mf=open("Afile","r") > > s=mf.myreadline() # Use my added function > > mf.close() # Use the original file function > > > Possible in some way? Thanks in advance for any clues. Nope, not in that way. But you might consider writing a proxy/wrapper for an object. That looks like this (rouch sketch from head): class FileWrapper(object): def __init__(self, f): self._f = f def __getattr__(self, name): return getattr(self._f, name) def myreadline(self): .... Then you do f = FileWrapper(open(name, mode)) Diez From claird at lairds.us Thu May 18 10:19:21 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 18 May 2006 14:19:21 +0000 Subject: how to make the program notify me explicitly References: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> <1147939268.619806.147550@j73g2000cwa.googlegroups.com> <1147941537.039418.316340@j73g2000cwa.googlegroups.com> <1147946759.180928.316090@j33g2000cwa.googlegroups.com> Message-ID: <9ccuj3-0pa.ln1@lairds.us> In article <1147946759.180928.316090 at j33g2000cwa.googlegroups.com>, alex23 <wuwei23 at gmail.com> wrote: >hankssong wrote: >> may be message dialog is the best way to let me be informed! > >EasyGui is possibly the simplest and fastest way to get message >dialogue boxes in Python: > >http://www.ferg.org/easygui/ > >- alex23 > No. That's sure not how I see it, at any rate. While there are many, MANY things to say in comparing GUIs, popping up a message dialogue is generally a one-liner with any toolkit, so, if that's the only requirement, what's really pertinent is "ease of set-up" or a similar dimension. And standard Python includes Tkinter, so Tkinter can't be beat for simplicity and availability, at least as I under- stand them. From steve at hastings.org Tue May 2 23:24:34 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 02 May 2006 20:24:34 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4457b115$1_6@news.bluewin.ch> Message-ID: <pan.2006.05.03.03.24.34.99762@hastings.org> On Tue, 02 May 2006 21:20:48 +0200, Boris Borcic wrote: > Steve R. Hastings wrote: >> So, don't test to see if something is equal to True or False: >> >> if 0 == False: >> pass # never executed; False and 0 do not directly compare > > of course they do - ie isinstance(False,int) is True and False == 0 I stand corrected. I tested most of my examples; I thought I had tested that example, but clearly I did not. I just tried "0 == False" in Python and it does evaluate True. "[] == False" still does not, of course... Thank you for the correction. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From hannu at skype.net Tue May 16 15:57:21 2006 From: hannu at skype.net (Hannu Krosing) Date: Tue, 16 May 2006 22:57:21 +0300 Subject: Using python for a CAD program In-Reply-To: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Message-ID: <1147809441.3818.1.camel@localhost.localdomain> ?hel kenal p?eval, E, 2006-05-15 kell 23:49, kirjutas 63q2o4i02 at sneakemail.com: > 2. GUI. Yes, I know you can do guis with qt, gtk, tkinter, etc. I'm > talking of fancy guis that do alpha blending, animations, nice > shading/gradients, etc. in a quick, smooth, and slick way, such that > moving a scroll bar or jiggling the mouse yields fast game-like > response time, and which gives this program the feeling that you're > actually in the 21st century... ie this is an *interactive* > environment, and I f***king hate crass-hatching, so real colors is a > must. Can this be portable between linux and windows? Is it possible > to "do the whole thing" in opengl, even the 2d stuff? I guess I dont > know enough about guis here. My fear is that my app will turn into > x-hell if I try to do more than 8-bit colors in linux, with flashing > background windows and complaints from the server about bit planes. > Maybe I need to play with linux a bit more from the development side > before commenting on this, since I get the feeling I'm working on old > information here... for a nice fast corel-draw clone written in python see http://www.skencil.org/ ------------- Hannu From Bob at bob.com Thu May 4 15:40:41 2006 From: Bob at bob.com (Bob) Date: Thu, 04 May 2006 21:40:41 +0200 Subject: regex to exctract informations Message-ID: <445a58ba$0$18262$636a55ce@news.free.fr> Dears, I am trying to search and replace strings with regex. The string is identified by a keyword : IDImage("1M234567"); DescriptionImage("Desc of the Image 1"); I want to exctract the IDImage (1M234567 ) and the Description. The ID are characters and numbers, the description too. Thx, Bertrand From jcb at iteris.com Wed May 31 18:53:30 2006 From: jcb at iteris.com (Metalone) Date: 31 May 2006 15:53:30 -0700 Subject: ctypes pointers and SendMessage Message-ID: <1149116010.351538.258990@g10g2000cwb.googlegroups.com> I would like to call windll.user32.SendMessageA(hwnd, win32con.WM_COMMAND, wParam, lParam) where lParam represents a pointer to an object. And also convert this pointer back to an object reference inside of wnd_proc def wnd_proc(hwnd, msg, wParam, lParam): So something like this: class X(Structure): def __init__(self, x): self.v = x x = X(1) windll.user32.SendMessageA(hwnd, WM_COMMAND, 4000, addressof(x)) def wnd_proc(hwnd, msg, wParam, lParam): if msg == WM_COMMAND and wParam == 4000): x = X.from_address(lParam) print x.v Unfortunately, this does not work. Also to my surprise the following does not work: x1 = X(1) x2 = X.from_address(addressof(x1)) addressof(x1) == addressof(x2) --> True but x2.v --> 'object has no attribute v' x1.v --> 1 Also this does not work as I expect. p = pointer(x) p[0].v --> 'object has no attribute v'. What am I doing wrong? From phddas at yahoo.com Wed May 3 18:25:01 2006 From: phddas at yahoo.com (Gary Wessle) Date: 04 May 2006 08:25:01 +1000 Subject: scope of variables References: <874q06bz4c.fsf@localhost.localdomain> <pan.2006.05.03.21.37.01.804277@hastings.org> Message-ID: <87zmhyagqq.fsf@localhost.localdomain> "Steve R. Hastings" <steve at hastings.org> writes: > On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote: > > b = 3 > > def adding(a) > > print a + b > > > > it seams not to see the up-level scope where b is defined. > > Assuming you put a ':' after the "def adding(a)", this should work in > recent versions of Python. In Python 2.0 and older, this will not work. the example was an in-accuretlly representation of a the problem I am having. my apologies. a = [] def prnt(): print len(a) >>> prnt <function prnt at 0xb7dc21b4> I expect to get 0 "the length of list a" From akameswaran at gmail.com Wed May 31 10:14:16 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 31 May 2006 07:14:16 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <447cc1d8$1@nntp0.pdx.net> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <mailman.6282.1148767807.27775.python-list@python.org> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> <447c8c6e$1@nntp0.pdx.net> <1149016823.214610.258930@r44g2000cwb.googlegroups.com> <447cadf6$1@nntp0.pdx.net> <1149024847.655949.227290@38g2000cwa.googlegroups.com> <447cc1d8$1@nntp0.pdx.net> Message-ID: <1149084856.590738.123940@j55g2000cwa.googlegroups.com> Scott David Daniels wrote: > akameswaran at gmail.com wrote: > > Scott David Daniels wrote: > >> Sorry, "re-iterables". A file re-iterable is: > >> > >> class FileReIterable(object): ... > >> def __iter__(self): > >> self.file.seek(0) > >> return iter(self.file) > >> > >> This works if-and-only-if it is only in use once at a time. > >> If you have multiple simultaneous accesses, you need to do > >> something like: > >> > >> class FileReIterable2(object): ... > >> def __iter__(self): > >> self.file.seek(0) > >> for line in self.file: > >> nextpos = self.file.tell() > >> yield line > >> self.file.seek(nextpos) > > > > Since I was doing this as a self education excercise. When you say is > > in use once and only once, you mean I can only use a single instance of > > the class? > No. This works: > > f1 = FileReIterable("one.file") > f2 = FileReIterable("another.file") > ... free uses of ... > > This does not "work": > > gen = FileReIterable("one.file") > > for a in gen: > for b in gen: > print a, b > > This does "work": > > gen = FileReIterable2("one.file") > > for a in gen: > for b in gen: > print a, b > > That is, any instance of FileReIterable must not be used in a > context where it may be in the midst of iterating a file, gets > used to produce a result, and then must produce a result from > the original iteration. > > If you think about what must happen to the file read pointer, > the reason for all of this should become clear. > > --Scott David Daniels > scott.daniels at acm.org Thanks for the explanation, the issue of the file pointer was pretty clear - it's why I created multiple files. I just misunderstood what you meant by use only one. What I did miss at first was the fact that the file object is not re-iterable. Just plain dumb oversite. Of course in the end I'm actually more concerned with writing my own iterators or generators. I was to busy thinking my errors were in the recursion to look at the iterable/reiterable issue. This is a working version of the die class I started this thread with. class die(object): def __init__(self,sides): self.sides=sides self.next = 1 def next(self): if self.next <= self.sides: current = self.next self.next +=1 return current else: self.next=1 raise StopIteration def __iter__(self): return self From mscottschilling at hotmail.com Fri May 26 16:48:03 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Fri, 26 May 2006 20:48:03 GMT Subject: OT: Quote ? [was: John Bokma harassment] References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> <Xns97CE807F1ADC6castleamber@130.133.1.4> <Zpmdg.2874$%Z2.298786@news20.bellglobal.com> <4476efed$2$649$bed64819@news.gradwell.net> <Xns97CF757E136D6castleamber@130.133.1.4> Message-ID: <7QJdg.17594$fb2.11320@newssvr27.news.prodigy.net> "John Bokma" <john at castleamber.com> wrote in message news:Xns97CF757E136D6castleamber at 130.133.1.4... > "Chris Uppal" <chris.uppal at metagnostic.REMOVE-THIS.org> wrote: > >> [apologies to the whole flaming crowd for sending this to the whole >> flaming crowd...] >> >> Geoffrey Summerhayes wrote: >> >>> After you kill Navarth, will it be nothing but gruff and deedle >>> with a little wobbly to fill in the chinks? >> >> Where does that come from ? It sounds like a quote, and Navarth is a >> Jack Vance name (and /what/ a character), but I don't remember the >> rest of it occurring in Vance. > > Navarth is very present in "the palace of dreams" (Demon princes series) Nitpick: _The Palace of Love_ From johnjsal at NOSPAMgmail.com Sat May 13 22:58:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 13 May 2006 22:58:57 -0400 Subject: any plans to make pprint() a builtin? Message-ID: <44669e46$0$5337$c3e8da3@news.astraweb.com> Just wondering if this will ever happen, maybe in 3.0 when print becomes a function too? It would be a nice option to have it available without importing it every time, but maybe making it a builtin violates some kind of pythonic ideal? From nospam at nospam.nospam Tue May 16 03:12:23 2006 From: nospam at nospam.nospam (Nic) Date: Tue, 16 May 2006 09:12:23 +0200 Subject: Python and Combinatorics Message-ID: <44697b5c$0$14794$4fafbaef@reader4.news.tin.it> Hello, I've a problem in defining a good Python code useful to articulate the following algorithm. Can you help me please? Thanks a bunch, Nic 1. Insert a number "n". Example: 3 2. List all the numbers < or = to n. Example: 1,2,3. 3. Combine the listed numbers each other. Example: 12 13 23 4. For each combination associate two letters a and b. Example: 12a 12b 13a 13b 23a 23b 5. Combine the new combinations each other, provided that combinations including the same couple of numbers (e.g. 12a and 12b) cannot be combined. Example: 12a 13a 23a 12a 13b 23a 12a 13b 23b 12b 13a 23a 12b 13b 23a 12b 13b 23b PS 12a 13a 23a and13a 23a 12a are the same thing. From cvanarsdall at mvista.com Thu May 11 19:53:37 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Thu, 11 May 2006 16:53:37 -0700 Subject: Threads In-Reply-To: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> Message-ID: <4463CE81.8090106@mvista.com> placid wrote: > Hi all, > > In Python, Threads cannot be paused, i remember reading this somewhere, > so is there a way around this ? > When you say paused do you mean paused by an external source or paused by a call internal to the thread? There are plenty of synchronization constructs for making threads wait: Check out Events and Conditions -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From nicogrubert at gmail.com Wed May 3 09:44:22 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Wed, 03 May 2006 15:44:22 +0200 Subject: Sorting a list of dictionaries by dictionary key In-Reply-To: <mailman.19720.1146662103.27774.python-list@python.org> References: <mailman.19720.1146662103.27774.python-list@python.org> Message-ID: <4458B3B6.10606@gmail.com> > assuming that DateTime returns something that compares correctly, you can > do something like: > > def sortkey(item): > return item.get("from_datetime") > > data.sort(key=sortkey) > > (assuming Python 2.4 or later) Thank you very much, Frederik. Unfortunately, I can only use Python 2.3.5. From tim.leeuwvander at nl.unisys.com Mon May 8 05:03:06 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 8 May 2006 02:03:06 -0700 Subject: How can I do this with python ? In-Reply-To: <mailman.5460.1147060043.27775.python-list@python.org> References: <mailman.5460.1147060043.27775.python-list@python.org> Message-ID: <1147078986.624152.14770@u72g2000cwu.googlegroups.com> Your question is insufficiently clear for me to answer. Do you want to know how to read from standard-input in a Python program? Do you want to know how to start an external program from Python, and then connect something to that programs standard input? Do you want to know something else? Please specify! Cheers, --Tim From dfj225 at gmail.com Tue May 23 17:54:21 2006 From: dfj225 at gmail.com (dfj225 at gmail.com) Date: 23 May 2006 14:54:21 -0700 Subject: performance difference between OSx and Windows In-Reply-To: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> Message-ID: <1148421261.164171.3310@g10g2000cwb.googlegroups.com> Hi Brian, You may have already considered this, but since I didn't see it mentioned in your post, I'll reply anyway. I believe the Python binaries that Apple includes with OS X are always slightly behind the latest that you can get from the official sources. I'm not infront of my Mac right now, so I can't tell you the disparity. One thing I would suggest would be to normalize the versions of Python accross the two machines. I find that using Fink (http://fink.sourceforge.net/) on OS X is the easiest way to install a new version of Python (as well as much other open source software). There are often speed improvements between older and newer Python releases, so this might be the source of the execution time differences. cheers, ~doug Brian wrote: > While the CPU speed on the G5 was faster the total execution time was > much quicker on the MS box. Can anyone give some suggestions as to why > this is? > > Thanks, > Brian From eval.apply at gmail.com Mon May 8 12:44:26 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 8 May 2006 09:44:26 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> Message-ID: <1147106666.402541.114270@g10g2000cwb.googlegroups.com> Alex Martelli wrote: > Ken Tilton <kentilton at gmail.com> wrote: > ... > > But the key in the whole thread is simply that indentation will not > > scale. Nor will Python. > > Absolutely. That's why firms who are interested in building *seriously* > large scale systems, like my employer (and supplier of your free mail > account), would never, EVER use Python, So how much Python code runs when I check my gmail? > nor employ in prominent > positions such people as the language's inventor and BDFL, the author of > the most used checking tool for it, and the author of the best-selling > reference book about that language; and, for that matter, a Director of > Search Quality who, while personally a world-renowned expert of AI and > LISP, is on record as supporting Python very strongly, and publically > stating its importance to said employer. Doesn't Google also employ such people as the inventor of Limbo programming language, one of the inventors of Dylan, and a Smalltalk expert? From steve at hastings.org Tue May 2 23:29:48 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 02 May 2006 20:29:48 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <1146599894.090292.69590@e56g2000cwe.googlegroups.com> Message-ID: <pan.2006.05.03.03.29.48.871651@hastings.org> On Tue, 02 May 2006 12:58:14 -0700, Roger Miller wrote: > Steve R. Hastings wrote: > >> a = 0 >> b = 0 >> a is b # always true > > Is this guaranteed by the Python specification, or is it an artifact of > the current implementation? I believe it's an artifact of the current implementation. And I only tested that on CPython; I don't know if it will work like that on Jython, IronPython, etc. I can't imagine why the Python spec would guarantee such a thing anyway. :-) > My understanding has been that an > implementation is free to share integer objects or not, so using 'is' > as an equality test takes you into undefined territory, regardless of > the size of the value. This sounds correct to me. (Note: I do not claim to be an authority on Python! But there are several authorities here who will no doubt correct this if I am wrong.) -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From andrew.arobert at gmail.com Thu May 18 09:34:55 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Thu, 18 May 2006 09:34:55 -0400 Subject: Conversion of perl unpack code to python - something odd Message-ID: <126ou0iapdasl8d@corp.supernews.com> Hey everyone, Maybe you can see something I don't. I need to convert a working piece of perl code to python. The perl code is: sub ParseTrig { # unpack the ibm struct that triggers messages. my $struct = shift; my %data; @data{qw/StructID Version QName ProcessName TriggerData ApplType ApplId EnvData UserData QMgrName/} = unpack("A4A4A48A48A64A4A256A128A128A48", $struct); return undef unless $data{StructID} eq 'TMC'; return \%data; Taking away the fact that it is a function, the base code sets a 732 element structure with the ascii pattern derived above. I wrote a simple test script that accepts the command argument at position 1. #!C:\Python24\python import sys, string, struct # From the language declarations in manual, the following format was derived format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' size=struct.calcsize(format) # Extract list item out for convenience/readability data=sys.argv[1] # Calculated size of the struct format is 732 # Length of data string is 732 print len(data) print size d1,d2=struct.unpack(format,data) print d1 sys.exit(0) When I run it, it says there are too many values to unpack. Traceback ( most recent call last) File "m:\mq\mq\scripts\format.py", line 32, in ? d1, d2 = struct.unpack(format,data) ValueError: too many values to unpack Error starting triggered application I checked the manual on the structure used to pack the code and it appears correct. # # MQTMC2 Language declarations as defined chapt 22 of programmers ref # http://publibfp.boulder.ibm.com/epubs/pdf/csqzak09.pdf # # CHAR4 Struct ID # CHAR4 Version # CHAR48 QName # CHAR48 ProcessName # CHAR64 TriggerData # CHAR4 ApplType # CHAR256 ApplID # CHAR128 EnvData # CHAR128 UserData # CHAR48 QMgrName Any help you can provide on this would be greatly appreciated. From girodt at gmail.com Thu May 4 08:51:36 2006 From: girodt at gmail.com (TG) Date: 4 May 2006 05:51:36 -0700 Subject: Subclassing array Message-ID: <1146747096.623101.122510@j73g2000cwa.googlegroups.com> Hi. i've already something about inheriting from array a few weeks ago and had my answer. But again, there is something that I don't understand. Here is my vector class, which works quite well : class Vector(array): def __new__(cls,length,data=None): return super(Vector,cls).__new__(cls,'f') def __init__(self,length,data=None): if data == None: for _ in xrange(length): self.append(0.0) else: for i in xrange(length): self.append(data[i]) Now, i want to inherit from this vector class : class Stimulus(Vector): def __init__(self,width,height,label,data=None): Vector.__init__(self,width*height,data) self.width = width self.height = height self.label = label This doesn't seem to work : >>> s = Stimulus(10,10,"data") TypeError: __new__() takes at most 3 arguments (4 given) In order to make it work, it seems that I have to redefine __new__ again, like this. def __new__(cls,width,height,label,data=None): return super(Stimulus,cls).__new__(cls,width*height) Why is that ? When I call Vector.__init__() in Stimulus, doesn't it also call __new__ ? I don't understand the detail of callings to __new__ and __init__ in python inheritance ... From lance at augustmail.com Wed May 17 21:39:52 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Wed, 17 May 2006 20:39:52 -0500 Subject: excel centering columns In-Reply-To: <1147908177.262141.61460@g10g2000cwb.googlegroups.com> References: <446ba8bd$0$61161$ae4e5890@news.nationwide.net> <1147908177.262141.61460@g10g2000cwb.googlegroups.com> Message-ID: <446bd067$0$61170$ae4e5890@news.nationwide.net> I did read the error message. I did not understand why 'constant' was not defined. In perl I did not have to run anything like 'makepy' to get constants to work. And no, I don't want to go back to perl. Python appears to integrate with packages more readily than perl does. I was unaware of 'makepy' until you mentioned it. Spent 3 hours searching the web and google groups under python excel column | 'centering columns' to find a solution. Never saw anything mentioned about 'makepy'. Thanks. I will do some searches on 'makepy'. Lance John Machin wrote: >> from win32com.client import constants >> sh2.Columns(lastcol).HorizontalAlignment = constant.xlCenter >> NameError: name 'constant' is not defined > > 1. So why not try reading the error message and fixing the problem > instead of thrashing about madly? > > 2. You have run makepy on your Excel library, haven't you? > From noway at sorry.com Wed May 31 04:12:01 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 31 May 2006 08:12:01 GMT Subject: genexp performance problem? References: <SC5fg.18764$jP5.469405@twister1.libero.it> <mailman.6348.1149057920.27775.python-list@python.org> Message-ID: <ldcfg.19033$cX1.294388@twister2.libero.it> Fredrik Lundh wrote: >> I found this strange: >> >> python -mtimeit "sum(int(L) for L in xrange(3000))" >> 100 loops, best of 3: 5.04 msec per loop >> >> python -mtimeit "import itertools; sum(itertools.imap(int, >> xrange(3000)))" 100 loops, best of 3: 3.6 msec per loop >> >> I thought the two constructs could achieve the same speed. > > hint: how many times to the interpreter have to look up the names > "int" > and "L" in the two examples ? Ah right, thanks! -- Giovanni Bajo From fredrik at pythonware.com Thu May 4 08:26:35 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 14:26:35 +0200 Subject: about the implement of the PyString_InternFromString References: <000301c66f70$1f0995e0$3500a8c0@kyom> Message-ID: <e3crtr$rrb$1@sea.gmane.org> Kyo Guan wrote: > I have a question about the this API. > > PyObject * > PyString_InternFromString(const char *cp) > { > PyObject *s = PyString_FromString(cp); > if (s == NULL) > return NULL; > PyString_InternInPlace(&s); > return s; > } > > > Why it always try to call PyString_FromString first? if char* cp is already in the > interned dict, this PyString_FromString call is waster. so I think this API should > implement as: > > 1. check the interned dict > 2. if cp is not in the dict, then call PyString_FromString, and insert the new string in > the dict > 3. else : call Py_INCREF and return. > > Is this right? Python dictionaries contains Python objects, not C strings, and it's a bit difficult to look for an object if you don't have it. </F> From chris.uppal at metagnostic.REMOVE-THIS.org Fri May 26 07:29:28 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Fri, 26 May 2006 12:29:28 +0100 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <OLadnbkovJLJj-vZnZ2dneKdnZydnZ2d@insightbb.com> <u7irntdbob.fsf@snapdragon.csl.sri.com> Message-ID: <4476efed$1$649$bed64819@news.gradwell.net> Fred Gilham wrote: > BTW, one time I tried a little social engineering to get rid of an > irrelevant cross-posted thread. I replied to the messages in the > thread (an irrelevant political thread posted in rec.audio.tubes) with > (somewhat) inflammatory replies but deleted my newsgroup from the > follow-up line. I kept doing this for a day or two to every message > that showed up in rec.audio.tubes. The result was that the threads > actually died out pretty fast in that newsgroup. Clever idea. Evil, but clever ;-) -- chris From tfb at conquest.OCF.Berkeley.EDU Mon May 8 05:04:06 2006 From: tfb at conquest.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 08 May 2006 02:04:06 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> <1hew3d4.1x2eems1pb7o5N%aleaxit@yahoo.com> <1147030835.498512.314110@u72g2000cwu.googlegroups.com> Message-ID: <xcv7j4wevll.fsf@conquest.OCF.Berkeley.EDU> olsongt at verizon.net writes: > Alex Martelli wrote: > > Steve R. Hastings <steve at hastings.org> wrote: > > ... > > > > But the key in the whole thread is simply that indentation will not > > > > scale. Nor will Python. > > > > > > This is a curious statement, given that Python is famous for scaling well. > > > > I think "ridiculous" is a better characterization than "curious", even > > if you're seriously into understatement. > > When you consider that there was just a big flamewar on comp.lang.lisp > about the lack of standard mechanisms for both threading and sockets in > Common Lisp (with the lispers arguing that it wasn't needed) I find it > "curious" that someone can say Common Lisp scales well. You really need to get better at distinguishing between reality and usenet flamewars. While some comp.lang.lispers were bitching back and forth about this, others of us were in Hamburg listening to Martin Cracauer from ITA talking about "Common Lisp in a high-performance search environment". In case you aren't aware, ITA is the company that makes the search engine behind Orbitz. From llothar at web.de Fri May 12 06:59:03 2006 From: llothar at web.de (llothar) Date: 12 May 2006 03:59:03 -0700 Subject: Is there any pure python webserver that can use FCGI Message-ID: <1147431543.658099.106310@j73g2000cwa.googlegroups.com> Hello, as the subject says, for an embedded application i need a 100% pure python webserver that can talk to a FCGI process (which runs ruby on rails). Of couse it also must be able to use simple CGI. Please don't ask why i want a python webserver for a ruby application. I just need it. From bbands at gmail.com Mon May 1 11:28:12 2006 From: bbands at gmail.com (BBands) Date: 1 May 2006 08:28:12 -0700 Subject: list*list Message-ID: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> There must be a better way to multiply the elements of one list by another: a = [1,2,3] b = [1,2,3] c = [] for i in range(len(a)): c.append(a[i]*b[i]) a = c print a [1, 4, 9] Perhaps a list comprehension or is this better addressed by NumPy? Thanks, jab From pmartin at snakecard.com Tue May 2 08:06:27 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 02 May 2006 07:06:27 -0500 Subject: wxPython, wxcombobox opening References: <mn.e4727d64aaab276c.43626@yahoo.fr.invalid> <9cL4g.4233$B42.2019@dukeread05> Message-ID: <7XH5g.9939$9c6.3212@dukeread11> Hi, >From the wxPython list: > Hi, > > Which event must I catch to be called when the user clicks on the combo > "button" to make the drop down list to appear ? No, there isn't a specific event for the opening of the drop-down box. Regards, Philippe Philippe Martin wrote: > Hi, > > I do not have the answer but am very interested in the issue. I tried > this: > > l_ev = wx.MouseEvent(wx.wxEVT_LEFT_DOWN) > l_ev.SetEventObject(self.GetCombo()) > self.GetEventHandler().ProcessEvent(l_ev) > > Which did send the event to the combo (which is in a pannel in my case) .. > but that is apparently not the event that triggers the dropping of the > list. > > I posed elsewhere and will forward here any hint. > > Philippe > > > > Rony Steelandt wrote: > >> Hi, >> >> Does somebody knows a way to automaticely open the list part of a >> wxCombobox when it gets the focus ? >> >> tia, >> >> Rony From onurb at xiludom.gro Tue May 16 10:52:23 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 16 May 2006 16:52:23 +0200 Subject: Questions about the event loop In-Reply-To: <mailman.5750.1147789001.27775.python-list@python.org> References: <mailman.5750.1147789001.27775.python-list@python.org> Message-ID: <4469e78d$0$7052$636a55ce@news.free.fr> egbert wrote: > What does a gui_event_loop know ? > > My gui is based on pygtk, > but i suppose the mechanism is the same everywhere. > > The gui is created within a class-instance within a function. > Normally, ie without a gui, everything that happens within > a function is forgotten as soon the function ends. > > But in a gui_event_loop the callback-method within the function > can be called, and this callbacks calls another function > also within the same first function. > And that function already stopped. s/stopped/returned/ I guess that what bother you has to do with closures. def foo(bar): buu = "buu" def baaz(baak): print bar, buu, baak print "foo(%s") return..." % bar return baaz dodo = Foo('parrot') dudu = Foo('dead') dodo(42) dudu("ni") As you can see, after foo() has returned, dodo() and dudu() 'remember' the environment in which they where created. A closure is a function that carries it's environment with it. > > Maybe somebody can explain what is going on, or where I can find > further explanations. > http://en.wikipedia.org/wiki/Closure_(computer_science) http://www.python.org/dev/peps/pep-0227/ http://docs.python.org/ref/naming.html#naming HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From deets at nospam.web.de Tue May 30 08:40:37 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 30 May 2006 14:40:37 +0200 Subject: Beginner Python OpenGL difficulties References: <1148833256.751748.291270@j55g2000cwa.googlegroups.com> <mailman.6322.1148939452.27775.python-list@python.org> <1148979397.531861.316140@y43g2000cwc.googlegroups.com> Message-ID: <4e2stdF1cjj9iU1@uni-berlin.de> jg.campbell.ng at gmail.com wrote: > > Mike C. Fletcher wrote: >> jg.campbell.ng at gmail.com wrote: >> > I'm beginning learning Python and OpenGL in Python. >> > > [...] >> > ImportError: No module named OpenGL.GLUT >> > >> > jc at localhost~/etc/python>$ echo $PYTHONPATH >> > /usr/lib/python2.2/site-packages/OpenGL >> > >> You should already have site-packages in your PythonPath. You want the >> directory *above* OpenGL in the path, not OpenGL itself. > > Yes, tried that: > > $ echo $PYTHONPATH > /usr/lib/python2.2/site-packages/ > > and no improvement. Should there be a file or directory named GLUT* in > /usr/lib/python2.2/site-packages/OpenGL/ ? All I can see are GL, GLU > and GLX directories. > > I'm unsure why >> you're running a Python 2.2 instance on a modern Linux. > > jc at localhost~/etc/python>$ python2 > Python 2.4.2 (#1, Feb 12 2006, 03:59:46) > [GCC 4.1.0 20060210 (Red Hat 4.1.0-0.24)] on linux2 > > The OpenGL stuff was from an RPM that I sound on the web. Go compile it yourself then - the RPM seems to be for python2.2, but you run 2.4. That means more happened than just changing the PYTHONPATH - so don't expect you come away so cheap :) Diez From Serge.Orlov at gmail.com Sat May 13 22:50:56 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 13 May 2006 19:50:56 -0700 Subject: cx_freeze and matplotlib In-Reply-To: <1147561396.641012.139940@y43g2000cwc.googlegroups.com> References: <1147561396.641012.139940@y43g2000cwc.googlegroups.com> Message-ID: <1147575056.469276.156200@y43g2000cwc.googlegroups.com> Flavio wrote: > I am trying to freeze an application which imports matplotlib. It all > works fine on the machine where it was frozen. The executable runs > without a glitch. > > But when I move the directory containing the frozen executable and > other libs to a new machine, I get the following error: > > Traceback (most recent call last): > File > "/home/fccoelho/Downloads/cx_Freeze-3.0.2/initscripts/Console.py", > line 26, in ? > File "epigrass.py", line 5, in ? > File "Epigrass/manager.py", line 7, in ? > File "Epigrass/simobj.py", line 4, in ? > File "/usr/lib/python2.4/site-packages/matplotlib/__init__.py", line > 457, in ? > try: return float(s) > File "/usr/lib/python2.4/site-packages/matplotlib/__init__.py", line > 245, in wrapper > if level not in self.levels: > File "/usr/lib/python2.4/site-packages/matplotlib/__init__.py", line > 319, in _get_data_path > Return the string representing the configuration dir. If s is the > RuntimeError: Could not find the matplotlib data files > > Matplotlib can't find its data files. I'm not familiar with cx_freeze, but have you told cx_freeze that you don't want to bundle matplotlib or cx_freeze has decided that matplotlib is not going to be bundled? That fact that matplotlib is loaded from site-package is pretty strange, standalone application are not supposed to depend on non-system packages. From fredrik at pythonware.com Thu May 18 17:31:55 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 23:31:55 +0200 Subject: WTF? Printing unicode strings In-Reply-To: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> Message-ID: <e4ip4a$hsj$1@sea.gmane.org> Ron Garret wrote: >>>> u'\xbd' > u'\xbd' >>>> print _ > Traceback (most recent call last): > File "<stdin>", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > position 0: ordinal not in range(128) so stdout on your machine is ascii, and you don't understand why you cannot print a non-ascii unicode character to it? wtf? </F> From brad.beveridge at gmail.com Wed May 24 10:57:59 2006 From: brad.beveridge at gmail.com (bradb) Date: 24 May 2006 07:57:59 -0700 Subject: John Bokma harassment In-Reply-To: <R_Zcg.248$LO3.40@fe11.lga> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> Message-ID: <1148482679.779623.211680@g10g2000cwb.googlegroups.com> > C'mon, John Bokma (and everyone else dumb enough to crosspost their > shushing to every group on the crosspost list -- why do they do that? So > Xah will hear them six times? No, they want everyone to see how witty > they are when they tell Xah off. Now /that/ is spam) is the problem. > > kenny I agree. It is not Xah who is the problem, but the 200 replies to him telling him to go away. Look at Xah's posting to replies ratio, it is enormous - Xah is the ultimate troll and everything he posts turns into huge threads. At c.l.l at least his threads are almost certainly the longest by far. The answer is easy, don't respond to his posts. Cheers Brad (sigh, now I am one of the crossposting Xah repliers) From camfarnell at cogeco.ca Tue May 23 15:06:09 2006 From: camfarnell at cogeco.ca (Cam) Date: 23 May 2006 12:06:09 -0700 Subject: Don't wish to give up on a Tkinter GUI Builder :( References: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> <1148371674.932205.83160@j55g2000cwa.googlegroups.com> <1148382609.644438.267020@j55g2000cwa.googlegroups.com> <A6qdnQFPrLgDzO7ZnZ2dnUVZ_uidnZ2d@nmt.edu> Message-ID: <1148411169.830384.149330@g10g2000cwb.googlegroups.com> > > What are you building? I routinely do things like these by hand > > www.greschke.com/unlinked/images/changeo.jpg > www.greschke.com/unlinked/images/pocus.jpg > www.greschke.com/unlinked/images/pis.jpg > www.greschke.com/unlinked/images/petm.jpg > > and I can't imagine using a builder for anything 'simpler'. If you are just > starting out I'd go the long-hand route first until you really have a good > grasp of Tkinter, then go the easier route. Once you find your own "style" > it becomes easier to just do it rather than try to get some other program > to do it for you. > > I tried rapyd today, too. Started it, drug a button to the frame, but then > couldn't figure out how to set the text of the button. Deleted it. :) > > Bob While it's possible to do things like this by hand I find it's royal pain when it comes time to make revisions or move things around. What I like about Rapyd-TK (warning warning, I wrote Rapyd-Tk, put bias detector on high) is that you can, after the fact, move widgets and frames around and all the gory code to generate them is automatically regenerated. As for the code to actually make the application go, well, if there is some automatic way to make that happen it hasn't dawned on me yet. Lots of hits on the Rapyd-Tk web site as a result of this thread :) From softwindow at gmail.com Thu May 18 23:12:23 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 20:12:23 -0700 Subject: Script to make Windows XP-readable ZIP file In-Reply-To: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> Message-ID: <1148008343.257795.139230@u72g2000cwu.googlegroups.com> i am in win2000 "z.write(a_path,a_path)" may change to "z.write(a_path)" but the dirpath is not in zipfile who can tell me? From stijndesaeger at gmail.com Fri May 5 10:26:24 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 07:26:24 -0700 Subject: Tuple assignment and generators? In-Reply-To: <syi*BxTfr@news.chiark.greenend.org.uk> References: <mailman.5334.1146755400.27775.python-list@python.org> <1146826136.746268.4060@i40g2000cwc.googlegroups.com> <445b3960$1_3@news.bluewin.ch> <1146831804.396839.316070@v46g2000cwv.googlegroups.com> <syi*BxTfr@news.chiark.greenend.org.uk> Message-ID: <1146839183.981537.216320@y43g2000cwc.googlegroups.com> oh wow... it gets better... >>> x = "test!" >>> y = "test!" >>> x is y False >>> x = "test" >>> y = "test" >>> x is y True >>> ... I had no clue. I guess the take-away lesson is to steer clear from any reliance on object identity checks, if at all possible. Are there any other such "optimizations" one should like to know about? v. From mrmakent at cox.net Thu May 25 13:24:44 2006 From: mrmakent at cox.net (Mike Kent) Date: 25 May 2006 10:24:44 -0700 Subject: Anyone compiling Python 2.3 on an SCO OpenServer 5 box? Message-ID: <1148577884.528595.157910@j33g2000cwa.googlegroups.com> If anyone is successfully compiling Pyton 2.3 on an SCO OpenServer 5 box, I'd appreciate hearing from you on how you managed to do it. So far, I'm unable to get a python that doesn't coredump. From aleaxit at yahoo.com Mon May 8 01:09:35 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 22:09:35 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1146990071.634244.83380@i39g2000cwa.googlegroups.com> <871wv6b3y0.fsf@rpi.edu> <1146996240.867564.139490@u72g2000cwu.googlegroups.com> <1heyqxs.4dbeogv9o591N%aleaxit@yahoo.com> <mailman.5457.1147051292.27775.python-list@python.org> Message-ID: <1hezmbn.q0klh1o9mo4oN%aleaxit@yahoo.com> Chris Lambacher <chris at kateandchris.net> wrote: > On Sun, May 07, 2006 at 11:57:55AM -0700, Alex Martelli wrote: > > > [1] I'm considering introducing bugs or misdesigns that have to be > > > fixed > > > as part of training for the purposes of this discussion. Also the > > > > Actually, doing it _deliberately_ (on "training projects" for new people > > just coming onboard) might be a good training technique; what you learn > > by finding and fixing bugs nicely complements what you learn by studying > > "good" example code. I do not know of this technique being widely used > > in real-life training, either by firms or universities, but I'd love to > > learn about counterexamples. > > When I was learning C in university my professor made us fix broken programs. > He did this specifically to teach us to understand how to read compiler > warnings/errors and also how to debug software. The advantage of this in the > tutorial setting was that the TAs knew what the error was and could assist the > people in finding bugs in a controlled environment. When I later worked with > people who did not go through this training I found many of them had no clue > how to decipher the often cryptic C/C++ compiler warnings/errors (think > Borland Turbo C or MS Visual C++, GCC is pretty good in comparison) or where > to start looking for a bug (an affliction I do not possess). Great to hear that SOME teachers use this technique. I think it would be about just as valuable with any language (or other similar piece of technology). Alex From vipulagarwal.in at gmail.com Fri May 26 17:25:43 2006 From: vipulagarwal.in at gmail.com (vipulagarwal.in at gmail.com) Date: 26 May 2006 14:25:43 -0700 Subject: access serial port in python Message-ID: <1148678743.109181.259710@i40g2000cwc.googlegroups.com> hi i hav written a code in python to send an SMS from a nokia 3310 connected to my PC... i wanted to receive a msg on my PC. In order to do so, the PC must know when it has to read data frm the serial port ...thus an interrupt must be generated when the serial port receives data frm the phone .....HOW CAN I DO THIS IN PYTHON ?? can anyone help me with this INTERRUPT HANDLING thing in PYTHON ??? thanks From cvanarsdall at mvista.com Wed May 17 15:26:25 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 17 May 2006 12:26:25 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> Message-ID: <446B78E1.7080901@mvista.com> Dave Hansen wrote: > On Wed, 17 May 2006 12:02:46 -0700 in comp.lang.python, "Carl J. Van > Arsdall" <cvanarsdall at mvista.com> wrote: > > >> Andy Sy wrote: >> >>> Carl J. Van Arsdall wrote: >>> >>> >>> >>>>> Next major objection then, how can one practically use 'tabs as >>>>> semantic indentation' without screwing up formatting of code like >>>>> the below?? >>>>> >>>>> >>>>> def sqlcall(): >>>>> cursor.execute('select id, item, amount, field4, field5, field6'+ >>>>> 'from table1 where amount>100') >>>>> >>>>> >>>>> >>>>> >>>> Why couldn't you tab your third line over as close as possible to the >>>> start of the quote then use a couple spaces? Then the tabs would work >>>> just fine and you could still have your pretty line. >>>> >>>> >>> This will break if someone tries to view my code using different >>> tab settings from the one I'm using >>> >>> >> Uh, no it won't. It should be read in as "one tab and two spaces" >> regardless of the tabstop setting. >> > > Think about it a little harder. What does that "one tab" mean? > > Assume the code was written by someone using 4-space tabs. To them, > the code is: > > def sqlcall(): > --->cursor.execute('select id, item, amount, field4, <etc> > --->--->--->--->...'from table1 where amount>100') > > (where -------> represents an 4-space tab and . represents a space) > > Which looks fine. But if I then load the code into my editor with > 3-space tabs, it looks like: > > def sqlcall(): > -->cursor.execute('select id, item, amount, field4, <etc> > -->-->-->-->...'from table1 where amount>100') > > Then my colleage loads it into his editor with 8-space tabs, and it > looks like (assuming I didn't change it to make it look reasonable): > > def sqlcall(): > ------->cursor.execute('select id, item, amount, field4, <etc> > ------->------->------->------->...'from table1 where amount>100') > > Ah, good point. I was referring to it "breaking code". It may look different (which I know invalidates my original point), but it certainly doesn't break code. I don't really use multiline strings in my code, but I find when working with other people I prefer the tab method. For nothing else other than "my indent is 2 whereas my coworker's is 4" and the use of tabs allows us to throw things around much more easily without either of us having to compromise on personal preference. .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From ullrich at math.okstate.edu Wed May 31 08:01:05 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Wed, 31 May 2006 07:01:05 -0500 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <mailman.6345.1149049261.27775.python-list@python.org> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <otpq72t7c1n3puh4omc42k3f98db968lhs@4ax.com> <slrne7qr97.8hm.sybrenUSE@schuimige.stuvel.eu> Message-ID: <4b1r7296fjngt6saj7t61iv7dlplseglel@4ax.com> On Wed, 31 May 2006 12:17:11 +0200, Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> wrote: >David C Ullrich enlightened us with: >> I thought that the fact that you could use the same trick for >> _shuffling_ a list was my idea, gonna make me rich and famous. I >> guess I'm not the only one who thought of it. Anyway, you can use >> DSU to _shuffle_ a list by decorating the list with random numbers. > >This is often done in database queries that need to randomize the data >;-) Huh. Gotta find a good patent attorney<g>. >Sybren ************************ David C. Ullrich From roy at panix.com Thu May 11 07:54:19 2006 From: roy at panix.com (Roy Smith) Date: Thu, 11 May 2006 07:54:19 -0400 Subject: unittest: How to fail if environment does not allow execution? References: <44622274.5040907@verizonbusiness.com> <e3t9hv$4a6$1@reader1.panix.com> <44631FFB.9040700@verizonbusiness.com> Message-ID: <roy-04D5D3.07541911052006@reader1.panix.com> Kai Grossjohann <kai.grossjohann at verizonbusiness.com> wrote: > I am trying to figure out whether a message is logged by syslog. > Not sure how I would do that except require the user to configure syslog > to log foo messages to the /var/log/foo file and to then check that > the message is written. Well, I suppose that depends on what exactly it is that you're trying to test. Are you testing the operation of the syslog system itself, or are you testing that *your program* calls syslog at the appropriate time? If the latter, then you might consider writing your own test stub replacement for the syslog module that looks something like this: history = [] def clearHistory(): global history history = [] def syslog (arg1, args=None): history.append ((time.ctime(), arg1, arg2)) Arrange to have this module be found in your PYTHONPATH before the standard one. Have your setUp() method call clearHistory(). Each test case that should write something to syslog can interrogate syslog.history to see if the appropriate thing was added to the list. There is so much that can go wrong with syslog that it's hard to do any deterministic testing using it. The syslogd could crash. It could be configured wrong (or in a way which forwards all local syslog messages to another machine). Or, the UDP messages could just plain get dropped by the network without a trace. This is not the kind of stuff you want to be trusting for a unit test. > Why did you use the open/IOError combination, instead of > os.stat/OSError? I am using the latter. But I don't know what I'm doing... I simply tried opening a non-existent file and saw what exception I got: >>> open ("/dev/foo") Traceback (most recent call last): File "<stdin>", line 1, in ? IOError: [Errno 2] No such file or directory: '/dev/foo' >>> I suppose it would have been smarter to have read the docs, but I'm lazy. Larry Wall says that's a good thing in programmers :-) From aahz at pythoncraft.com Thu May 25 13:38:50 2006 From: aahz at pythoncraft.com (Aahz) Date: 25 May 2006 10:38:50 -0700 Subject: NEWB: how to convert a string to dict (dictionary) References: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> <mailman.6141.1148453462.27775.python-list@python.org> <1148514268.491292.276670@38g2000cwa.googlegroups.com> Message-ID: <e54q3a$hji$1@panix1.panix.com> In article <1148514268.491292.276670 at 38g2000cwa.googlegroups.com>, manstey <manstey at csu.edu.au> wrote: > >Thanks. I didn't know eval could do that. But why do many posts say >they want a solution that doesn't use eval? Because it is a security risk! eval("os.system('rm -rf /')") -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From levub137 at wi.rr.com Tue May 9 20:52:33 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Wed, 10 May 2006 00:52:33 GMT Subject: installing numpy In-Reply-To: <mailman.5533.1147209024.27775.python-list@python.org> References: <877j4v5ukc.fsf@localhost.localdomain> <6Y%7g.11622$EC.10694@tornado.rdc-kc.rr.com> <8764kfkkhb.fsf@localhost.localdomain> <mailman.5533.1147209024.27775.python-list@python.org> Message-ID: <lPa8g.3970$WP5.1983@tornado.rdc-kc.rr.com> Robert Kern wrote: > Gary Wessle wrote: > >>"Raymond L. Buvel" <levub137 at wi.rr.com> writes: > > >>>When installing from source on a Debian system, you want the installed >>>package to wind up in /usr/local/lib/python2.x/site-packages (where x >>>represents the version of Python you are running the installer from). >>>This allows you to keep it separate from the apt managed directories and >>>allows for easy removal/upgrade. So the command you want to execute >> >>>from root is >> >>>python setup.py install --prefix=/usr/local >> >>sorry if this is boring since I am not a seasoned Linux user. >> >>setup.py isn't located at the root, do you mean, execute the command above >>from root, as to do this >>:~$ cd / >>:/$ python setup.py install --prefix=/usr/local >>or >>:/$ python home/fred/numpy-0.9.6/setup.py install --pref... >>or AS root >>:/# python setup.py install --prefix=/usr/local >>or >>:/# python home/fred/numpy-0.9.6/setup.py install --pref... > > > I think he meant "as the root user". You will probably want to build numpy as a > regular user and then only install as the root user. You will probably want to > use sudo(1) to gain root privileges. You can read the sudo man-page for more > information on how to do that. > > ~$ cd numpy-0.9.6 > ~/numpy-0.9.6$ python setup.py build > ~/numpy-0.9.6$ sudo python setup.py install --prefix=/usr/local > > However, instead of setting --prefix every time you execute setup.py for every > Python package, it will be easier for you to create the file ~/.pydistutils.cfg > with the contents > > [install] > prefix=/usr/local > > See http://docs.python.org/inst/config-syntax.html for more information. > > Then, you can just do > > ~$ cd numpy-0.9.6 > ~/numpy-0.9.6$ python setup.py build > ~/numpy-0.9.6$ sudo python setup.py install > > >>>By the way, to get NymPy to use the high-performance libraries, you must >>>install these libraries and the associated -dev packages before running >>>the Python install. >> >>I wish to know the debian names for those packages, my first guess >>would be refblas3 under testing since blas is not available for >>debian/testing, there is also >>refblas3-dev Basic Linear Algebra Subroutines 3, static library >>which I don't have installed. >> >>would refblas3 be all what NymPy need to the high-performance? > > > No. refblas3 provides the reference (unoptimized) implementation of the BLAS. In > Ubuntu (a Debian-based distribution) the package that you would want is > atlas3-base-dev. It should have a similar name in your version of Debian > (possibly atlas-dev or atlas3-dev or some other variant). > > If you need more help, you will probably get more focused help on the > numpy-discussion mailing list. > > http://lists.sourceforge.net/lists/listinfo/numpy-discussion > Since you are a new Linux user, you should definitely follow Robert's advice about building as an ordinary user separately from the install. I sometimes take a shortcut and just do the install as user root. However, I then wind up cleaning out the build directory as user root (not a very safe thing to do). The Debian/testing package you want to install is indeed atlas3-base-dev. This package contains the header files needed to build against the optimized blas library. Note that the dependancies listed in this package will cause the library package to be installed as well. There are packages that are optimized for the extended instruction sets available on some processors. If you want to try and install one of these instead of atlas3-base, just search the package list for anything with atlas3 in the name. Then carefully read the package descriptions to find one that is optimized for your hardware. Make sure you install the -dev package or you will wind up using the unoptimized default in NumPy. From reply.in.the.newsgroup at my.address.is.invalid Tue May 9 16:05:12 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 09 May 2006 22:05:12 +0200 Subject: Upgrading Class Instances Automatically on Reload References: <1147196712.192606.75160@g10g2000cwb.googlegroups.com> <24p1625coseqi7imip7f6nssi9feu400j3@4ax.com> <1147203260.211710.14890@v46g2000cwv.googlegroups.com> Message-ID: <49t1625fkhhkrca8l2u015tums1b0r8c9j@4ax.com> malv: >At the statement b = Bar(), the following error occurs: >The debugged program raised the exception unhandled AttributeError >"type object 'Bar' has no attribute '__instance_refs__'" I haven't studied it at all, but the code on http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 seems to run fine with Python 2.4.2 in WingIDE on Windows XP. There's no exception and it prints: 1 2 3 Are you perhaps using an older dead tree version of the Cookbook? -- Ren? Pijlman From wahab at chemie.uni-halle.de Thu May 25 18:36:58 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Fri, 26 May 2006 00:36:58 +0200 Subject: Go "help" the perl list instead Fredrik Lundh In-Reply-To: <jbednXMRKL1RgOvZRVn-qQ@comcast.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <jbednXMRKL1RgOvZRVn-qQ@comcast.com> Message-ID: <e55bpa$a2j$1@mlucom4.urz.uni-halle.de> Thus spoke D H (on 2006-05-25 23:12): > Fredrik Lundh wrote: >> if you don't know how to do things, you don't need to post. > > He already posted ... Based on your Text, you can (in Perl, of course ;-) extract the Goedel-Number sequence (prime number sequence) of it: use Acme::Goedelize; my $goed = new Acme::Goedelize; my $rant = do { local $/; (<DATA>) }; $rant = ~s/[.\n]//mg; print join "\n", $goed->to_number($rant)=~/(\d{64})/g; __DATA__ He already posted before your post that he made a mistake. You obviously ignored that and invented some argument that he posted with malicious intentions. That better describes most of your thousands of annoying posts. This prints a (64 char blocked) "Version" of your text, which can be retranslated to your text by 'degoedelization'. How'd you do *that* in Python ;-) Regards Mirco f'up c.l.python From rpdooling at gmail.com Thu May 18 17:05:30 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 May 2006 14:05:30 -0700 Subject: Strange error In-Reply-To: <446c8c4c$0$14894$626a54ce@news.free.fr> References: <1147962206.900840.19130@38g2000cwa.googlegroups.com> <mailman.5883.1147962743.27775.python-list@python.org> <1147963014.880378.44270@i39g2000cwa.googlegroups.com> <446c8c4c$0$14894$626a54ce@news.free.fr> Message-ID: <1147986330.103990.181120@i39g2000cwa.googlegroups.com> >> This type of bug commonly bites neophyte programmers. That IS weird. I'm new. I read it, I see how it works, but how come in between calls of the function, you can't access the values being stored? Or I guess you can, but I don't see the way. How come you can't do something like : >>>wtf.args It doesn't give you the list with the values it's storing between function calls. From bruno at modulix.org Fri May 26 08:37:47 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 26 May 2006 05:37:47 -0700 Subject: Accessing object parent properties In-Reply-To: <mailman.6121.1148412463.27775.python-list@python.org> References: <af3c42f10605230527o75d06818x42a177f41e480d6e@mail.gmail.com> <Xns97CC5F55ECF8Bmaxericksongmailcom@80.91.229.5> <af3c42f10605231127w4af23544ob52e877e9292a117@mail.gmail.com> <mailman.6121.1148412463.27775.python-list@python.org> Message-ID: <1148647066.931498.157490@38g2000cwa.googlegroups.com> (answering to the op) Cloudthunder wrote: > How can I set up method delegation so that I can do the following: > A.run() > and have this call refer to the run() method within the boo instance? Also, > what if I have tons of functions like run() within the boo instance and I > want all them to be directly accessible as if they were part of their > parent > (the Foo instance)? class Foo(object): def __init__(self, delegate): self._delegate = delegate def __getattr__(self, name): try: return getattr(self._delegate, name) except AttributeError: msg = "object '%s' has no attribute '%s' % (self.__class__.__name__, name) raise AttributeError(msg) class Boo(object): # your code here def run(self): print "This is a job for SuperBicycleRepairMan" f = Boo(Foo()) f.run() HTH From grante at visi.com Wed May 31 11:09:18 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 31 May 2006 15:09:18 -0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <1148998176.105881.156310@g10g2000cwb.googlegroups.com> <127olia8pnldl90@corp.supernews.com> <mailman.6347.1149052455.27775.python-list@python.org> Message-ID: <127rccueg04oie5@corp.supernews.com> On 2006-05-31, Sergei Organov <osv at javad.com> wrote: > It seems that sniff on a real tty device could be implemented using the > same technique strace uses to intercept and show syscalls, though I'm > not aware of any sniffer application that does it. Using strace you can indeed trace read/write calls on user-specified file descriptors. Figuring out which file descriptors to trace is the tricky part. -- Grant Edwards grante Yow! I was making donuts at and now I'm on a bus! visi.com From kent at kentsjohnson.com Sun May 7 13:07:36 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sun, 07 May 2006 13:07:36 -0400 Subject: the print statement In-Reply-To: <1146960978.564533.59730@j73g2000cwa.googlegroups.com> References: <1146950481.610645.39710@j33g2000cwa.googlegroups.com> <mailman.5435.1146958332.27775.python-list@python.org> <1146960978.564533.59730@j73g2000cwa.googlegroups.com> Message-ID: <445e28e1$1_1@newspeer2.tds.net> mirandacascade at yahoo.com wrote: > Thank you. Yes, that post answers most of the questions. I now have a > bit of an understanding of the \xhh pattern. It's still unclear to me, > however, how one can go from the \x92 pattern and arrive at the > apostrophe character. Is \x92 theh apostrophe character in another > character set? If so, which character set? \x92 is a right single quote in Windows cp1252. http://www.microsoft.com/globaldev/reference/sbcs/1252.mspx Kent From phddas at yahoo.com Sun May 14 14:07:00 2006 From: phddas at yahoo.com (Gary Wessle) Date: 15 May 2006 04:07:00 +1000 Subject: continue out of a loop in pdb Message-ID: <87mzdkwke3.fsf@localhost.localdomain> Hi using the debugger, I happen to be on a line inside a loop, after looping few times with "n" and wanting to get out of the loop to the next line, I set a break point on a line after the loop structure and hit c, that does not continue out of the loop and stop at the break line, how is it down, I read the ref docs on pdb but could not figure it out. thanks From jes at nl.demon.net Wed May 31 10:32:01 2006 From: jes at nl.demon.net (Jim Segrave) Date: Wed, 31 May 2006 14:32:01 -0000 Subject: iterator? way of generating all possible combinations? References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <447c8c6e$1@nntp0.pdx.net> <1149016823.214610.258930@r44g2000cwb.googlegroups.com> <447cadf6$1@nntp0.pdx.net> Message-ID: <127ra71smt8mgd3@corp.supernews.com> In article <447cadf6$1 at nntp0.pdx.net>, Scott David Daniels <scott.daniels at acm.org> wrote: > >This works if-and-only-if it is only in use once at a time. >If you have multiple simultaneous accesses, you need to do >something like: > > class FileReIterable2(object): > def __init__(self, file): > if isinstance(file, basestring): > self.file = open(file, 'rU') > else: > self.file = file > def __iter__(self): > self.file.seek(0) > for line in self.file: > nextpos = self.file.tell() > yield line > self.file.seek(nextpos) Hmm - I tried this with 'one.file' being just the lower case letters, one per line: class FileReIterable2(object): def __init__(self, file): if isinstance(file, basestring): self.file = open(file, 'rU') else: self.file = file def __iter__(self): self.file.seek(0) for line in self.file: nextpos = self.file.tell() yield line self.file.seek(nextpos) gen = FileReIterable2("one.file") for a in gen: for b in gen: print " ", a.strip(), b.strip() gen = FileReIterable2("one.file") for a in gen: for b in gen: print a.strip(), b.strip() which didn't produce lines 'a a', 'a b', etc. It produced the single line 'a a', then stopped. A judicious proint or two showed that after the first execution of 'for line in self.file:', the file pointer was at EOF, not at 2, as one would expect. Rewriting the __iter__ method to not internally iterate over the file object, as follows, works - it now generates a a ... a z b a ... z z class FileReIterable2(object): def __init__(self, file): self.file = open(file, 'rU') def __iter__(self): self.file.seek(0) while True: line = self.file.readline() if line == '': raise StopIteration nextpos = self.file.tell() yield line self.file.seek(nextpos) -- Jim Segrave (jes at jes-2.demon.nl) From theller at python.net Mon May 15 05:00:28 2006 From: theller at python.net (Thomas Heller) Date: Mon, 15 May 2006 11:00:28 +0200 Subject: Making all string literals Unicode In-Reply-To: <e1gg625ci6792r2g3a337d6h5mrpcusm46@4ax.com> References: <e1gg625ci6792r2g3a337d6h5mrpcusm46@4ax.com> Message-ID: <4468432C.3030102@python.net> Richie Hindle wrote: > Hi, > > Am I imagining it, or is there a switch or an environment variable to > make Python treat all string literals as unicode? I seem to recall > seeing it mentioned somewhere, but now I can't find it anywhere. > > Thanks, > python -U From aleaxit at yahoo.com Sun May 7 02:05:58 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 23:05:58 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <slrne5qu42.9lp.tomasz.zielonka@tomekz.gem.lan> Message-ID: <1hextts.o0uihlttzk47N%aleaxit@yahoo.com> Tomasz Zielonka <tomasz.zielonka at gmail.com> wrote: > Alex Martelli wrote: > > Having to give functions a name places no "ceiling on expressiveness", > > any more than, say, having to give _macros_ a name. > > And what about having to give numbers a name? Excellent style, in most cases; I believe most sensible coding guides recommend it for most numbers -- cfr <http://en.wikipedia.org/wiki/Magic_number_(programming)> , section "magic numbers in code". > > Yes, we are, because the debate about why it's better for Python (as a > > language used in real-world production systems, *SCALABLE* to extremely > > large-scale ones) to *NOT* be insanely extensible and mutable is a > > separate one -- Python's uniformity of style allows SCALABILITY of > > teams, and teams-of-teams > > I think this kind of language scalability is most important for Google, > see below. It's definitely very important for Google, just as for most organization doing software development on a large scale. > > if your need SCALE, well then, PYTHON IS SCALABLE, and will remain a > > *SIMPLE, CLEAN, LITTLE AND POWERFUL LANGUAGE* (letting nobody do > > anything INSANE to it;-) while scaling up to whatever size of project(s) > > you need (including systems so large... > > But honestly, isn't this scalability a result of the data processing > model you use, which is language independent? My point is that when you > have such a well scaling data processing model, most languages scale > well on the "data" and "load" axes, so you pick your language based on > how well it scales on the "teams" and "features" axes. There's one more axis, the "size of software project" one (in some unit of measure such as function points). That is partly related to "language level", but it's not _just_ about that -- e.g., Ruby's language level is basically the same as Python, but (in my modest experience) it doesn't scale up quite as well to very large software projects, as it's more prone to subtle coupling between modules (as it makes it easy for one module to affect others indirectly, by making modifications to fundamental globals such as "Object" and other built-in types). > You seem to claim that there is something in Python that lets it scale > well on "data" and "load", and is not related to "teams" and "features", > and also not related to Google's data processing model. Can you tell > me what it is? I don't think that (apart from whatever infrastructure Google may have developed, and partly published in various whitepapers while partly deciding to not discuss it publically) Python's scaling on "data" and "load", to use your terminology, should be intrinsically different (i.e., due to language differences) from that of other languages with similar characteristics, such as, say, Ruby or Smalltalk. Alex From kairosenthal at tiscali.de Fri May 5 12:31:41 2006 From: kairosenthal at tiscali.de (kai) Date: 5 May 2006 09:31:41 -0700 Subject: [ConfigParser] value with ; and the value blank Message-ID: <1146846701.912321.202730@u72g2000cwu.googlegroups.com> Hello, how can I use/save/read values with ";" (start comment) and the value blank? When I write (set) my config file often the part behind the ";" disappears. e.g. myKey = startMyValue ; endMyValue Thank's for your hints, Kai From jdsalt_AT_gotadsl.co.uk Thu May 18 11:01:31 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Thu, 18 May 2006 10:01:31 -0500 Subject: [silly] Does the python mascot have a name ? References: <e4c59e$tqg$1@emma.aioe.org> <mailman.5791.1147860411.27775.python-list@python.org> <Xns97C6BF618E3A9BaldHeadedJohn@216.196.109.145> <Xns97C6ADE23FCAcastleamber@130.133.1.4> Message-ID: <Xns97C79C8584F71BaldHeadedJohn@216.196.109.145> John Bokma <john at castleamber.com> wrote in news:Xns97C6ADE23FCAcastleamber@ 130.133.1.4: > John D Salt <jdsalt_AT_gotadsl.co.uk> wrote: > >> Andy Sy <andy at neotitans.com> wrote in >> news:mailman.5791.1147860411.27775.python-list at python.org: >> >>> http://mail.python.org/pipermail/python-list/2003-September/185612.html >> >> "Odi" must be the Dutch for "Monty". > > Nope. If it was Dutch it would probably be Odie Damn. All the best, John. From carlosperezs at alumnos.uvigo.es Wed May 24 10:55:25 2006 From: carlosperezs at alumnos.uvigo.es (carlosperezs at alumnos.uvigo.es) Date: Wed, 24 May 2006 16:55:25 +0200 Subject: No subject Message-ID: <1148482525.447473dd5f772@correoweb.uvigo.es> hello together !!! I would like to know if it is available the com component for wmeditor in python language? This program is called windows media file editor, lets users to create marks into a movie and belongs to installation packet of windows encoder. thank you --oOo-----------------------------------------------------------------oOo-- Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo Servicios Inform?ticos [ http://si.uvigo.es ] Universidade de Vigo [ http://www.uvigo.es ] URL: https://correoweb.uvigo.es From sjmachin at lexicon.net Sat May 27 04:55:25 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 27 May 2006 18:55:25 +1000 Subject: chop() and empty() functions In-Reply-To: <mailman.6260.1148678121.27775.python-list@python.org> References: <mailman.6253.1148664337.27775.python-list@python.org> <44776377.7090304@lexicon.net> <mailman.6260.1148678121.27775.python-list@python.org> Message-ID: <447813FD.9000506@lexicon.net> On 27/05/2006 7:10 AM, Jeremy L. Moles wrote: > On Sat, 2006-05-27 at 06:22 +1000, John Machin wrote: >> On 27/05/2006 2:54 AM, Jeremy L. Moles wrote: >> >> ["chop" snipped] >> >>> Furthermore, what do people think about the idea of adding a truly >>> empty, no-op global lambda somewhere in Python? I use them a lot >> What is the use case? Why write something like """empty(foo, 42, >> cmd="xyzzy")""" when you could merely write "pass" or nothing at all? > > Well, in a lot of the libraries I use, there is often a need for a > callback of some sort. Sure, I--and most other people--often define an > empty, no-op function of some sort when you want to at least have > "something" there, but I thought it might be kinda' neat to be able to > have a builtin called empty() or noop() that returned a (possibly > optimized?) function that just did nothing. :) It probably is a dumb > idea, hehe... the chop() was the big one I thought people might comment > on. > > For example, I often do stuff like this for handling "input events" in > soya: > > evhandlers = [emptyfunc for i in range(MAX_NUM_EVENTS)] > > evhandlers[EVENT_NUMBER] = self.my_handler_function > > ...and then in the actual input loop I'll come along and say... > > evhandlers[ev](*args) > > In this way I don't have to test the value of any event and behave > accordingly--I just send it on it's way. > > It's just an iterative way to say, "Okay, give me some default behavior > for everything, and I'll come back around later and set the explicit > handlers later." If you intend to set explicit handlers later, wouldn't it be better for the default event handler to raise an exception, just in case your intention is waylaid or sidetracked? > > This same design is probably used in other areas too... that's why I > brought up the "truly empty noop" thing; it would give me fuzzy feeling > to know that in those cases where empty() is defined, nothing is > happening (although, this could currently be the case in Python, I'm not > sure--I don't know a lot about Python internals). It would give you a fuzzy feeling to know that nothing is happening -- instead of *what* happening? What do you dread? If, when you do evhandlers[ev](*args), evhandlers[ev] can't be evaluated to a callable object (for one of several possible reasons), Python will raise the appropriate exception. It won't "do nothing". Python will not assume that you meant to supply a no-op function. Python refuses to guess what you had in mind. This is part of the language philosophy, and is not implementat(ion|er)-dependant. I suggest that you fire up a Python interactive prompt, and type import this Cheers, John From leo at lspace.org Fri May 5 18:33:48 2006 From: leo at lspace.org (Leo Breebaart) Date: 5 May 2006 22:33:48 GMT Subject: How to doctest if __name__ already used? Message-ID: <4c226cF13sh8vU1@individual.net> I have a simple question (I hope), but one I'd love to get some feedback on in case I am missing something obvious: If I have a Python script that is executable, and therefore already uses '''if __name__ == "__main__"''' to call a function of its own, what is then the easiest yet still most Pythonic way to run doctest on the docstrings in the file? Trigger doctest.testmod() via a "--test" command-line option, is what I'm thinking. But is that really the best way? -- Leo Breebaart <leo at lspace.org> From godoy at ieee.org Sat May 6 20:29:02 2006 From: godoy at ieee.org (Jorge Godoy) Date: Sat, 06 May 2006 21:29:02 -0300 Subject: Python Eggs Just install in *ONE* place? Easy to uninstall? References: <1146936395.028140.15640@i39g2000cwa.googlegroups.com> Message-ID: <2199622.7zKjNmN3Qs@jupiter.g2ctech> seberino at spawar.navy.mil wrote: > It appears that apps distributed as Python Eggs are either a single > compressed > blob in site-packages directory or a directory under site-packages > directory. > > Is this ALWAYS true? So by just erasing stuff under site-packages > I can do a COMPLETE uninstallation of an Egg? They might have been added to some ".pth" file there as well, so you'd have to remove the egg reference from it. Also, they don't need to be installed only in one place, you can install them somewhere else. There are uninstall instructions at the documentation: http://peak.telecommunity.com/DevCenter/setuptools For other Python Eggs information you might want to check: http://peak.telecommunity.com/DevCenter/PythonEggs -- Jorge Godoy <godoy at ieee.org> "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From fairwinds at eastlink.ca Sat May 13 13:12:18 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Sat, 13 May 2006 14:12:18 -0300 Subject: Package that imports with name of dependent package In-Reply-To: <e450ua$q1a$01$1@news.t-online.com> References: <mailman.5657.1147530941.27775.python-list@python.org> <e44vvm$nvh$01$1@news.t-online.com> <e450ua$q1a$01$1@news.t-online.com> Message-ID: <44661372.10602@eastlink.ca> Hi Peter. Thank you for this warning. I'll document this in the code. I plan on importing only from dependentpackage for portability. Also, much in the framework relies upon it. This approach is primarily for maintenance purposes and would also allow me to package the modified dependentpackage (with just the __init__.py ) along with mypackage if I plan to distribute it. It allows it to be a drop in replacement. I am hoping with packaging utilities, I can easily remove the dependentpackage if it is encountered in site-packages to replace it with my own. Regards, David Peter Otten wrote: > Peter Otten wrote: > >>> I'd appreciate hearing of what I can do in an __init__ file or what >>> other strategy could make this work. Many thanks. >> I think fixing the imports is the better long-term approach. But putting >> >> from pkgutil import extend_path >> import mypackage >> __path__ = extend_path(mypackage.__path__, __name__) >> >> into dependentpackage/__init__.py might work. > > One big caveat: If you are mixing both > > import mypackage.somemodule > > and > > import dependentpackage.somemodule > > in the same application, mypackage.somemodule and > dependentpackage.somemodule are *not* the same module instance. This may > have surprising effects when global variables in somemodule.py are > updated... > > Peter From john at castleamber.com Mon May 29 23:35:41 2006 From: john at castleamber.com (John Bokma) Date: 30 May 2006 03:35:41 GMT Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> <Xns97D2956C291F0castleamber@130.133.1.4> <1148952542.615043.94410@g10g2000cwb.googlegroups.com> Message-ID: <Xns97D2E5D7F71FCcastleamber@130.133.1.4> "Luis M. Gonz?lez" <luismgz at gmail.com> wrote: > I didn't know it wasn't a free ebook. I realized it once I downloaded > it. > But it's such a good book that I decided to buy a hard copy. > This way I will support its author, while getting a very good book on > Python. :-D Sounds much better. -- 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 larry.bates at websafe.com Mon May 22 10:04:09 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 22 May 2006 09:04:09 -0500 Subject: problem with writing a simple module In-Reply-To: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> References: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> Message-ID: <4471C4D9.8020806@websafe.com> nephish at xit.net wrote: > ello there. i am having a problem getting a module to work right. > > i wrote a class that is going to be used in a few different scripts in > the same directory. > > it looks like this: > > #!/usr/bin/python > > import MySQLdb > > class DbConnector(object): > """ > Database Connection object. > class receives the db argument to specify the database. > """ > > def __init__(self, db='test_db', host="10.10.10.16",user="me", > passwd="mypass"): > self.host = host > self.user = user > self.passwd = passwd > self.db = db > # Unpack Other Database Arguments Here > self.CreateConnection() > > def createConnection(self): > self.connection = MySQLdb.connect(self.host, self.user, self.passwd, > self.db) > > def killConnection(self): > self.connection.close() > > def getMany(self, sql_statement): > cursor = self.connection.cursor() > try: > cursor.execute(sql_statement) > result = cursor.fetchall() > self.connection.close() > return result > except: > self.connection.close() > > the file is saved as DbConnector.py and made executable. > then i get this in idle > >>> import DbConnector >>> x = DbConnector() > > then it tells me that the module object is not callable. > > this works though >>> import DbConnector >>> x = DbConnector >>> x.db = 'other_db' >>> results = x.getOne("SELECT * FROM `stuff`") > > it tells me that the module has no attribute getOne. > > i am really not trying for an attribute, but a method. > > anyone know what i am doing wrong? > > thanks > You can do either: from DbConnector import * x=DbConnector() or (preferred method these days) import DbConnector x=DbConnector.DbConnector() When you zay x=DbConnector all you are doing is setting a variable (pointer) x that points to the class DBconnector, which is basically an alias. x in fact would not have a getOne method as it hasn't been instantiated yet. -Larry Bates From timr at probo.com Tue May 30 00:34:03 2006 From: timr at probo.com (Tim Roberts) Date: Tue, 30 May 2006 04:34:03 GMT Subject: TIming References: <pan.2006.05.30.01.24.04.677340@none.none> Message-ID: <ecin725eh7mk1teolpfi2ulj349ogptdir@4ax.com> WIdgeteye <None at none.none> wrote: >HI, >I am trying to write a little program that will run a program on >scedule. I am having trouble understanding the datetime, time, sched >modules. What I would like is something like this: > >If date&time = 06-13-2006:18:00:00 >Then run this program > >I am not sure how to enter a future date in this equation using any >of the modules mentioned above. I have figured out how to get the date >and time from the modules above but not the future and then compare >the two. What operating system are you using? Both Linux and Windows have commands that can do this for you. It's more efficient to use existing operating system services than to invent your own. Also, remember to take into account the possibility that your program might not check the time at the exact second. In your example, you need to be prepared to start your app if the time is just PAST 6 PM on June 13. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From nobody at 127.0.0.1 Wed May 3 12:54:48 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 16:54:48 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <mailman.5241.1146613795.27775.python-list@python.org> <44580270$0$4903$626a54ce@news.free.fr> Message-ID: <sf56g.81313$dW3.5801@newssvr21.news.prodigy.com> Bruno Desthuilliers wrote: > IOW, let's give Edward some time to come up with enough rope so we can > hang him to the nearest (AS) Tree !-) That's all I ask. ;) From sybrenUSE at YOURthirdtower.com.imagination Wed May 3 17:56:40 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 3 May 2006 23:56:40 +0200 Subject: Python & SSL References: <e38c66$r2t$1@zinnia.noc.ucla.edu> <4457B74A.2000208@benjiyork.com> <mailman.5284.1146693115.27775.python-list@python.org> Message-ID: <slrne5i9oo.ijc.sybrenUSE@schuimige.stuvel.eu> John J. Lee enlightened us with: > Of course, remembering that the first thing to ask in response to > "is it secure?" is "against what?", for lots of purposes it just > doesn't matter that it ignores certificates. I'm curious. Can you give me an example? AFAIK you need to know who you're talking to before transmitting sensitive information, otherwise you could be talking to anybody - and that's just what you wanted to prevent with the encryption, right? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From haraldarminmassa at gmail.com Sun May 28 12:57:44 2006 From: haraldarminmassa at gmail.com (GHUM) Date: 28 May 2006 09:57:44 -0700 Subject: propose extension of mimetypes Message-ID: <1148835464.948019.247070@y43g2000cwc.googlegroups.com> Hello, mimetypes lacks the guessing of .svg as image/svg+xml mimetypes.add_type("image/svg+xml",".svg", True) maybe this can be added to python 2.5 standard library Harald From deets at nospam.web.de Tue May 9 06:42:43 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 May 2006 12:42:43 +0200 Subject: do "some action" once a minute References: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> <tjl062lu3m6d96d8e67ve2h1m7kleijakh@4ax.com> <1147165909.579147.216030@g10g2000cwb.googlegroups.com> Message-ID: <4cba1bF14iqt8U1@uni-berlin.de> Petr Jakes wrote: > Thanks for your comment. It is mainly English issue (I am not native > English speaker). > > OK, to be more specific, I would like to run the code, when the value > of seconds in the timestamp become say "00". > The whole code will run in the infinitive loop and other actions will > be executed as well, so it can not "sleep" for 60 seconds :). The you have to go for a thread, as otherwise you'd have to create all sorts of checks in your program to check for the current date. That therad then could wait like this: import time def seconds(): return time.localtime()[5] def wait_for_seconds(secs=0): while seconds() != secs: time.sleep(.5) def foo(): # initial wait wait_for_seconds() do_something() while True: time.sleep(50) wait_for_seconds do_something() Diez From peace.is.our.profession at gmx.de Tue May 9 04:02:28 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Tue, 09 May 2006 10:02:28 +0200 Subject: Python's regular expression? In-Reply-To: <Xns97BDA5543F8B1duncanbooth@127.0.0.1> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> <e3ndsm$rfa$1@mlucom4.urz.uni-halle.de> <Xns97BD8F2E0EE6Eduncanbooth@127.0.0.1> <e3nh1h$saa$1@mlucom4.urz.uni-halle.de> <slrne5ukoj.4ob.nick@irishsea.home.craig-wood.com> <Xns97BDA5543F8B1duncanbooth@127.0.0.1> Message-ID: <e3pih1$hsb$1@mlucom4.urz.uni-halle.de> Hi Duncan > Nick Craig-Wood wrote: >> Which translates to >> match = re.search('(blue|white|red)', t) >> if match: >> else: >> if match: >> else: >> if match: > > This of course gives priority to colours and only looks for garments or > footwear if the it hasn't matched on a prior pattern. If you actually > wanted to match the first occurrence of any of these (or if the condition > was re.match instead of re.search) then named groups can be a nice way of > simplifying the code: A good point. And a good example when to use named capture group references. This is easily extended for 'spitting out' all other occuring categories (see below). > PATTERN = ''' > (?P<c>blue|white|red) > ... This is one nice thing in Pythons Regex Syntax, you have to emulate the ?P-thing in other Regex-Systems more or less 'awk'-wardly ;-) > For something this simple the titles and group names could be the > same, but I'm assuming real code might need a bit more. Non no, this is quite good because it involves some math-generated table-code lookup. I managed somehow to extend your example in order to spit out all matches and their corresponding category: import re PATTERN = ''' (?P<c>blue |white |red ) | (?P<g>socks|tights ) | (?P<f>boot |shoe |trainer) ''' PATTERN = re.compile(PATTERN , re.VERBOSE) TITLES = { 'c': 'Colour', 'g': 'Garment', 'f': 'Footwear' } t = 'blue socks and red shoes' for match in PATTERN.finditer(t): grp = match.lastgroup print "%s: %s" %( TITLES[grp], match.group(grp) ) which writes out the expected: Colour: blue Garment: socks Colour: red Footwear: shoe The corresponding Perl-program would look like this: $PATTERN = qr/ (blue |white |red )(?{'c'}) | (socks|tights )(?{'g'}) | (boot |shoe |trainer)(?{'f'}) /x; %TITLES = (c =>'Colour', g =>'Garment', f =>'Footwear'); $t = 'blue socks and red shoes'; print "$TITLES{$^R}: $^N\n" while( $t=~/$PATTERN/g ); and prints the same: Colour: blue Garment: socks Colour: red Footwear: shoe You don't have nice named match references (?P<..>) in Perl-5, so you have to emulate this by an ordinary code assertion (?{..}) an set some value ($^R) on the fly - which is not that bad in the end (imho). (?{..}) means "zero with code assertion", this sets Perl-predefined $^R to its evaluated value from the {...} As you can see, the pattern matching related part reduces from 4 lines to one line. If you wouldn't need dictionary lookup and get away with associated categories, all you'd have to do would be this: $PATTERN = qr/ (blue |white |red )(?{'Colour'}) | (socks|tights )(?{'Garment'}) | (boot |shoe |trainer)(?{'Footwear'}) /x; $t = 'blue socks and red shoes'; print "$^R: $^N\n" while( $t=~/$PATTERN/g ); What's the point of all that? IMHO, Python's Regex support is quite good and useful, but won't give you an edge over Perl's in the end. Thanks & Regards Mirco From sybrenUSE at YOURthirdtower.com.imagination Sun May 21 17:20:34 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 21 May 2006 23:20:34 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> Message-ID: <slrne71md2.q5u.sybrenUSE@schuimige.stuvel.eu> foxtree at gmail.com enlightened us with: > None of you seem to know what you are talking about. That's not a way to make friends. I very well know what I'm talking about. None of the issues I've raised are negated by what you say, so every single one still stands. > Flash also behaves consistently cross-browser, cross/platform That's where you are wrong. Flash on Mac/MSIE behaves differently than other platform/browser combinations. There are also many browsers and platforms that can't use Flash. Even though Flash is available for Linux, it isn't available for my Zaurus, for instance. > -- and most features cannot be disabled by the user. (compare that > to a user being able to turn off JS, or Java -- something often > mandated in a corporate environment.) It's either "all on" or "all > off." And in many corporate environments, it's off. > Flash has such a large install base, that it could be argued it is > the most widely available platform for delivering media-rich > "applications" over the web. True, but 99.9% of all Flash usage is more an annoyance than truely useful and "rich". > (And code does not involve anywhere near the same level of attention > to kludges and workarounds that one would have to use to replicate > similar feature -- where possible -- in different browsers and > browser *versions.*) -- ActionScript is a horrible klidge it itself. Don't try to portrait it as something else. > Not to sound like I work for MM/Adobe, but, here's what the Flash > Player can do at *run time*: When should it do that if not at run time? At compile time? > Flash can render text -- w/ custom-defined and packaged fonts. (not > possible in a browser!) It can apply a limited set of CSS to the > rendered text, BTW. But when using my scrollwheel to scroll the page it is used on, my browser stops scrolling when the mouse is over such a flash file. Very annoying! > Flash can load/parse/serialize/send XML. So can JavaScript. > Flash can POST and GET a variety of data (true, it may access > browser controls to manage this.) So can HTML. > Flash can access you webcam, allowing you to create your own video > chat/IM app. So can NetMeeting and many others. > Flash can load and render jpegs, gifs(v8), and pngs(v8) -- and in > version 8, composite all that w/ vector graphics (+video?) -- *and,* > sample the resulting display pixel by pixel. (passing that data > back to a server would allow dynamic creation of a jpeg or gif.) But version 8 is not even available for Linux. > Flash 8 has a new "file upload" ability that goes beyond what a > browser is capable of: You can *multi-select* files, filter files > by type or size, and have programatic access to the state of the > upload. It accesses an Operating System GUI control to do this -- > and I have tested that these features work in MSIE, Moz FF, and > Safari on OSX. *** But version 8 is not even available for Linux. > Flash can #animate# stuff!!! So can GIF and MNG. > Flash is like a 2 MB download that works in almost *every* browser > out there. Not on Linux/x86, nor Liinux/ARM, nor Linux/MIPS, .... > (like: a built-in interpreter for a > late-version-EcmaScript-compliant scripting language -- that, in > many ways, is far more capable than what is available w/ JavaScript > in most browsers!) But it is horrible to work with. I can know, I've had to develop quite a few advanced Flash websites for my work. My work even went to the high folks at Disney. I don't need to brag, but apparently I do need to show you I *do* know what I'm talking about. > *** This feature can be used for a web-based CMS! It would > blow-away anything (non-Java) now available for managing and > uploading assets. LOL I can write an application that runs circles around Flash. And it would have the advantage it isn't web-based either - yes, I see that as an advantage. Web-based is overrated. I ask of you to take a look at the serious issues many people have with Flash. It's not just geeks and nerds that are annoyed by non-functioning scrollwheels, badly designed GUIs, and badly searchable websites. People that are less familiar with the web are even more annoyed, but are less capable of expressing that in a structured and well-defined way, because they simply lack the jargon. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From alastair at gotadsl.co.uk Wed May 24 18:40:59 2006 From: alastair at gotadsl.co.uk (Alastair Alexander) Date: Wed, 24 May 2006 23:40:59 +0100 Subject: COM Server crashing when returning large arrays References: <mailman.6105.1148382878.27775.python-list@python.org> Message-ID: <162dnUS2C_OxQunZRVnyjw@pipex.net> Bingo! Downloaded release 208 and the problem is solved! "Stefan Schukat" <SSchukat at dspace.de> wrote in message news:mailman.6105.1148382878.27775.python-list at python.org... Hello Alistair, which version of pythoncom you are using? In the newer versions there is an support for a "native" safearray (the data type Excel is providing). In older versions the complete array was converted to a tuple which is very time and memory consuming. during this conversion you could run out of memory since you have the Python objects and the COM data in your process. I think in 207 the patch was included. 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 Alastair Alexander > Sent: Monday, May 22, 2006 6:27 PM > To: python-list at python.org > Subject: COM Server crashing when returning large arrays > > Hi ... I'm using pythoncom to create a python COM server > application that needs to be able to return large arrays to > COM client apps. For example, I need to be able to return an > array to Excel that is 500 by 10, with each element of the > array holding a 32 byte string. > > If I run the code for smaller arrays, say 10 by 10, it works > fine. If I allow the server to try to return the entire 500 > by 10 array, pythonw.exe causes a memory access violation and > dies and I get an "automation exception" error message in the > client app. > > I assume I'm violating some upper limit for data transfer > from pythoncom into COM. Anyone know if such limitations > exist? Is there a way around them? > Can anyone point me in the right direction? > > Thanks > > Alastair > > > p.s. 1st message on comp.lang.python, indeed 1st message on > any news group > > > -- > http://mail.python.org/mailman/listinfo/python-list > From vys at renet.ru Tue May 16 06:20:03 2006 From: vys at renet.ru (Vladimir 'Yu' Stepanov) Date: Tue, 16 May 2006 14:20:03 +0400 Subject: Large Dictionaries In-Reply-To: <1147774466.391591@teuthos> References: <1147699064.107490@teuthos> <1147738318.330346.231310@j33g2000cwa.googlegroups.com> <1147774466.391591@teuthos> Message-ID: <4469A753.7030005@renet.ru> Chris Foote wrote: > lcaamano wrote: > >> Sounds like PyTables could be useful. >> >> http://www.pytables.org >> > > In browsing their excellent documentation, it seems that all concepts > are built around storing and reading HDF5 format files. > > Not suitable for this project unfortunately. > > Cheers, > Chris > > How many values accept long and int in pairs ? It is possible to try to use the dictionary of dictionaries: d = {} for long_val, int_val in list_vals: d.setdefault(long_val, {})[int_val] = None From nogradi at gmail.com Fri May 5 06:16:57 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Fri, 5 May 2006 12:16:57 +0200 Subject: Tuple assignment and generators? In-Reply-To: <4c0mi2F13miioU1@uni-berlin.de> References: <mailman.5334.1146755400.27775.python-list@python.org> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <e-idndayO-NancbZRVn-sQ@speakeasy.net> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> <e3f5p6$7jn$1@sea.gmane.org> <mailman.5360.1146822522.27775.python-list@python.org> <4c0mi2F13miioU1@uni-berlin.de> Message-ID: <5f56302b0605050316h7dbddb74n84d0ef60dd1c83da@mail.gmail.com> > > I was just at a point when I thought I learned something but got > > confused again after trying the following and unfortunately didn't > > find an answer in the docs. > > > >>>> a = 10 > >>>> b = 10 > >>>> id(a) > > 134536516 > >>>> id(b) > > 134536516 > > > > So the two memory addesses are the same, but > > > >>>> a = 10000 > >>>> b = 10000 > >>>> id(a) > > 134604216 > >>>> id(b) > > 134604252 > > > > and they are not the same (I restarted the interpreter between the two > > cases). So how is this now? Sorry if it's too trivial, but I simply > > don't get it. > > It's an optimization scheme that will cache number objects up to a certain > value for optimized reuse. However this is impractical for larger numbers - > you only hold a table of lets say 1000 or so objects. Then the look up of > one of those objects is extremely fast, whereas the construction of > arbitrary numbers is somewhat more expensive. > > And as "is" is the operator for testing if objects are identical and _not_ > the operator for testing of equality (which is ==), the above can happen. > And is totally irrelevant from a practical POV (coding-wise that is - it > _is_ a relevant optimization). Thanks a lot! So after all I really learned something :) From larry.bates at websafe.com Fri May 26 16:56:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 26 May 2006 15:56:46 -0500 Subject: hide python window, con'td In-Reply-To: <mailman.6245.1148656971.27775.python-list@python.org> References: <mailman.6245.1148656971.27775.python-list@python.org> Message-ID: <nuidnfgKW6EU9urZRVn-gw@comcast.com> Something that runs all day in the background is a perfect candidate for being turned into a Service. That and servicemanager has a good way of managing the task so that it doesn't take up lots of excess CPU cycles that a "normal" application would take while sleeping or unnecessarily looping. Pick up a copy of Mark Hammond's Python Programming on Win32 book for example services in Python. You could then start/stop the service with service manager or with net start/ net stop commands. -Larry Bates Bell, Kevin wrote: > Great! And now that it's hiding w/ .pyw, how would I kill it if I want? > Just log off, or is there a better way? > > Kevin > > From kentilton at gmail.com Mon May 15 14:19:16 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 15 May 2006 14:19:16 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <MD2ag.777$8K5.396@fe09.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> <d6lu07r7u0u.fsf@vipunen.hut.fi> <44681F95.9040400@gmail.com> <1147689991.541829.129550@u72g2000cwu.googlegroups.com> <MD2ag.777$8K5.396@fe09.lga> Message-ID: <dE3ag.34$RM1.15@fe12.lga> Ken Tilton wrote: > > > Ben wrote: > >> >> Nothing you have described sounds that complicated, and you never come >> up with concrete objections to other peoples code (apart that it took >> 10 years to write in Lisp, so it must be really hard) > > > Oh, now I have to spend an hour dissecting any code you people toss-off > that does no more than pick the low-hanging fruit? I do not spend enough > time on Usenet already? :) I want to clarify something. I did look at the code. It was the same thing we had with Cells after four-five hours. Yet the author admitted he had looked at the Cells source, so he should have known he had not implemented, inter alia, synapses, kid-slotting, ephemerals, optional laziness, and worst of all he had omitted the data integrity mechanism encapsulated by with-integrity. In the next exchange we discover he missed the ability to author Python instances individually while mistakenly thinking it was impossible. Exactly how much time am I supposed to spend on someone not willing to spend enough time to understand Cells? I recognize, tho, a kindred spirit more interested in writing their own code than reading and understanding someone else's. :) You too are more eager to flame me over misperceived slights to The Sacred Python than in Python having a wicked cool constraints package, and I am wasting too much time on you. I recognize, tho, a fellow Usenet dlamewar enthusiast. :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From steven.klass at gmail.com Fri May 19 11:41:34 2006 From: steven.klass at gmail.com (rh0dium) Date: 19 May 2006 08:41:34 -0700 Subject: Subprocess or Process or OMG!! In-Reply-To: <1148000976.455456.11800@i40g2000cwc.googlegroups.com> References: <1147992479.110490.41960@i40g2000cwc.googlegroups.com> <1148000976.455456.11800@i40g2000cwc.googlegroups.com> Message-ID: <1148053294.727937.221490@38g2000cwa.googlegroups.com> ROTFLMAO - Thanks --- I "meant" has anyone done the wrapper approach before!! Not has anyone used the code.. hahah nice!! subprocess also has the wait object. I think I like this better than popen2 (which I have used in the past) for a number of reasons but primarily it's simplicity. Having said that, I don't think I want to use the wait object because I am afraid the db query in some cases may take longer than the command.. That would leave the user wondering what's going on.. Only testing will tell though.. Thanks Robert - yeah I checked the docs and figured out that it takes a list shortly after I sent the post. From webmaster at net4xbox360.com Wed May 17 21:46:52 2006 From: webmaster at net4xbox360.com (net4xbox360) Date: Wed, 17 May 2006 18:46:52 -0700 Subject: CGI errror in (only in) IIS 6.0 server 2003 References: <1136764730.157479.286130@o13g2000cwo.googlegroups.com> Message-ID: <ZOadna_PWuE3TPbZRVn-pA@comcast.com> You have to enable the correct web extensions. Whatever you do, do not ever enable all as that is a huge security risk. I'll be adding a "how-to" for enabling it for IIS 5.1 which runs on windows xp. I put together a tutorial here: http://python.markrowsoft.com/iiswse.asp <nonamehkg at hotmail.com> wrote in message news:1136764730.157479.286130 at o13g2000cwo.googlegroups.com... > Hi, I've been using ActivePython 2.3 (cgi) on IIS on win xp, 2000 and > they work fine. > Until I upgrade the system the server 2003. The ASP script engine is ok > but not the CGIs. > > I got these errors: > > HTTP Error 403.1 - Forbidden: Execute access is denied. > > > > I already have execute access on the directory. > > > > Can anyone help me? > > > ========= > kychan > From inyeol.lee at siliconimage.com Tue May 30 17:33:19 2006 From: inyeol.lee at siliconimage.com (Inyeol Lee) Date: Tue, 30 May 2006 14:33:19 -0700 Subject: Strange behavior with iterables - is this a bug? In-Reply-To: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> References: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> Message-ID: <20060530213319.GB817@siliconimage.com> On Tue, May 30, 2006 at 01:11:26PM -0700, akameswaran at gmail.com wrote: [...] > >>> ================================ RESTART > >>> f1 = open('word1.txt') > >>> f2 = open('word2.txt') > >>> f3 = open('word3.txt') > >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in f1 for i2 in f2 for i3 in f3] > [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')] > >>> l1 = ['a\n','b\n','c\n'] > >>> l2 = ['a\n','b\n','c\n'] > >>> > >>> l3 = ['a\n','b\n','c\n'] > >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for i3 in l3] > [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), > ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), > ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), > ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), > ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), > ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), > ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')] > > explanation of code: the files word1.txt, word2.txt and word3.txt are > all identical conataining the letters a,b and c one letter per line. > The lists I've added the "\n" so that the lists are identical to what > is returned by the file objects. Just eliminating any possible > differences. You're comparing file, which is ITERATOR, and list, which is ITERABLE, not ITERATOR. To get the result you want, use this instead; >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in open('word1.txt') for i2 in open('word2.txt') for i3 in open('word3.txt')] FIY, to get the same buggy(?) result using list, try this instead; >>> l1 = iter(['a\n','b\n','c\n']) >>> l2 = iter(['a\n','b\n','c\n']) >>> l3 = iter(['a\n','b\n','c\n']) >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for i3 in l3] [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')] >>> -Inyeol Lee From apavluck at gmail.com Wed May 17 14:57:20 2006 From: apavluck at gmail.com (Alex Pavluck) Date: 17 May 2006 11:57:20 -0700 Subject: \t not working In-Reply-To: <slrne6mo92.hpk.sybrenUSE@schuimige.stuvel.eu> References: <1147883344.070704.127080@g10g2000cwb.googlegroups.com> <slrne6mo92.hpk.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1147892240.277333.49110@i40g2000cwc.googlegroups.com> ha ha...good point. I didn't realize that you could run it all together. I guess the "single string" part should have been a tip off. Anyway, more questions to come soon. Thanks everyone! From f.braennstroem at gmx.de Thu May 11 01:38:57 2006 From: f.braennstroem at gmx.de (Fabian Braennstroem) Date: Thu, 11 May 2006 07:38:57 +0200 Subject: problem with array and for loop Message-ID: <slrne65jfh.53j.f.braennstroem@node1.ut.TU-Berlin.DE> Hi, I have a 'simple' problem with a multidimension array in a for loop. It looks like this: wert= zeros([127,2]) wert1= zeros(127) m=1 l=1 for pos in [pos1,pos2,pos3]: for i in range(1,125): wert[l,m]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i); # wert1[i]= probe1.GetOutput().GetPointData().GetScalars().GetTuple1(i); m=m+1; l=l+1; It works for the 1D 'wert1'. Does anyone have an idea? Greetings! Fabian From thirsteh at gmail.com Thu May 25 12:31:09 2006 From: thirsteh at gmail.com (Patrick M. Nielsen) Date: Thu, 25 May 2006 18:31:09 +0200 Subject: Telnet linebreaks In-Reply-To: <28dc07920605231549g56cfdc4fi9d995a0e1fb4cf0b@mail.gmail.com> References: <28dc07920605231548w6fd48d25t463f510338044da8@mail.gmail.com> <28dc07920605231549g56cfdc4fi9d995a0e1fb4cf0b@mail.gmail.com> Message-ID: <28dc07920605250931w4d8dfa00p2e31dc00795b8876@mail.gmail.com> *bump* :) On 5/24/06, Patrick M. Nielsen <thirsteh at gmail.com> wrote: > > Oh, and, apologies for the "inpythonic" nature of this issue. > > > On 5/24/06, Patrick M. Nielsen <thirsteh at gmail.com > wrote: > > > > Hey guys. > > > > I have begun playing with the Simple MUD server example from the > > Stackless website > > ( http://www.stackless.com/Members/rmtew/code/mud.py ) > > and it's all good so far, however, I've come to notice something that I > > remember from back > > in the days (some old mud code), but I don't remember what I did to fix > > it. > > > > While the MUD reads lines from Telnet clients just fine, clients such as > > Gmud are practically ignored, > > probably because Gmud doesn't send Telnet-valid data ('\x08'?). > > > > However, a MUD that is not accessible to one such client or others isn't > > much good, so I'd appreciate > > some help in pinpointing the problem. > > > > These are the code blocks that need modification (I believe) > > > > def read(self): # TELNET > > ret = self.readChannel.receive() > > if self.echo: > > if ret == '\x08': > > self.send(ret+" ") > > self.send(ret) > > return ret > > > > def readline(self): # TELNET > > buf = self.readBuffer > > > > while True: > > if buf.find('\r\n') > -1: # MUD clients that aren't using > > the telnet protocol > > i = buf.index('\r\n') # need to be able to do stuff. > > ret = buf[:i+2] > > self.readBuffer = buf[i+2:] > > while '\x08' in ret: > > i = ret.index('\x08') > > if i == 0: > > ret = ret[1:] > > else: > > ret = ret[:i-1]+ret[i+1:] > > return ret > > > > buf += self.read() > > > > I'm suspecting that Gmud doesn't send '\x08', since from looking at some > > old DIKU code, > > I see that the if '\n' || '\r' are there as well, but there is no check > > for '\x08'. If this is indeed > > the cause of my problem, how would I go about doing it? > > > > Thanks in advance. > > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060525/71533b3e/attachment.html> From jarrod.roberson at gmail.com Mon May 8 01:15:51 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 7 May 2006 22:15:51 -0700 Subject: which is better, string concatentation or substitution? In-Reply-To: <445ec45e$0$1965$c3e8da3@news.astraweb.com> References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> Message-ID: <1147065351.819566.140900@j73g2000cwa.googlegroups.com> niether .join() is the fastest From deets at nospam.web.de Thu May 4 08:31:38 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 04 May 2006 14:31:38 +0200 Subject: HTMLParseError: EOF in middle of construct error References: <1146745753.568267.166130@v46g2000cwv.googlegroups.com> Message-ID: <4buai4F12pcheU1@uni-berlin.de> Mike wrote: > Me again. > > I'm getting this error when parsing an external URL - I understand that > a common cause of this is badly formed HTML (or XHTML) and that's fair > enough, but is there any way to turn the parser into forgiving mode? > > As I'm getting this error from documents over which I have no control, > I need to be able to recover from this situation. Is there a way to > clean the document before parsing it, or have the parser ignore the > issue and proceed (which would probably be ok in my case)? google:BeatifulSoup Diez From jstroud at ucla.edu Tue May 9 20:35:34 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 09 May 2006 17:35:34 -0700 Subject: do "some action" once a minute In-Reply-To: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> References: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> Message-ID: <e3rcgm$qt0$1@daisy.noc.ucla.edu> Petr Jakes wrote: > I would like to do "some action" once a minute. My code (below) works, > I just wonder if there is some more pythonic approach or some "trick" > how to do it differently. > > minutes=time.localtime()[4] > while 1: > min, sec = time.localtime()[4:6] > if sec==0 and minutes!=min: # first occur of sec==0 only!! polling > 10x a second > minutes=min > print "Eureca" > time.sleep(0.1) > > Regards > > Petr Jakes > This may be what you want: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/464959 James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From kentilton at gmail.com Sun May 7 11:37:13 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sun, 07 May 2006 11:37:13 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <r8n7g.10$Q17.3@fe08.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> Message-ID: <Juo7g.6$sC4.4@fe09.lga> Ken Tilton wrote: > >> >> a = negate(sin(pi/2)+one) = -2.0 >> b = negate(a)*10 = 20.0 > > > Very roughly speaking, that is supposed to be the code, not the output. > So you would start with (just guessing at the Python, it has been years > since I did half a port to Python): > > v1 = one Sorry, only later did I realize "one" was going in as a named spreadsheet Cell. I thought maybe Python was a bit of a super-cobol and had one as a keyword. <g> kenny From fredrik at pythonware.com Fri May 12 04:29:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 May 2006 10:29:39 +0200 Subject: deleting texts between patterns References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> Message-ID: <e41h1p$kft$1@sea.gmane.org> <micklee74 at hotmail.com> skrev i meddelandet news:1147420279.664699.181200 at i40g2000cwc.googlegroups.com... > hi > say i have a text file > > line1 > line2 > line3 > line4 > line5 > line6 > abc > line8 <---to be delete > line9 <---to be delete > line10 <---to be delete > line11 <---to be delete > line12 <---to be delete > line13 <---to be delete > xyz > line15 > line16 > line17 > line18 > > I wish to delete lines that are in between 'abc' and 'xyz' and print > the rest of the lines. Which is the best way to do it? Should i get > everything into a list, get the index of abc and xyz, then pop the > elements out? or any other better methods? what's wrong with a simple emit = True for line in open("q.txt"): if line == "xyz\n": emit = True if emit: print line, if line == "abc\n": emit = False loop ? (this is also easy to tweak for cases where you don't want to include the patterns in the output). to print to a file instead of stdout, just replace the print line with a f.write call. </F> From me+python at modelnine.org Fri May 12 09:02:03 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Fri, 12 May 2006 15:02:03 +0200 Subject: linking with math.so In-Reply-To: <1147366190.436903.315380@g10g2000cwb.googlegroups.com> References: <1147366190.436903.315380@g10g2000cwb.googlegroups.com> Message-ID: <200605121502.03331.me+python@modelnine.org> Am Donnerstag 11 Mai 2006 18:49 schrieb imdognuts at yahoo.com: > "importing math" as far as I can tell right now, invokes a shared > library (math.so). Now I have a shared library dependency that I dont > want. Is there a way to get the math functionality from a dot a or a > dot o, so I dont have to make my app dependent on a shared library? > cos, sin, and pi which is what I need do not live in the libpython2.4.a > - I did an nm on it.... I'm on linux. bonifats modelnine # ls -la /usr/lib/libm.a -rw-r--r-- 1 root root 1194744 May 9 02:23 /usr/lib/libm.a bonifats modelnine # You have to link statically against that part of libc. --- Heiko. From bignose+hates-spam at benfinney.id.au Thu May 25 01:15:11 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 25 May 2006 15:15:11 +1000 Subject: python __import__ question References: <87psi3wjai.fsf@adm.dn.bus.com.ua> Message-ID: <87lksq1y8w.fsf@benfinney.id.au> Evgeniy Zamriy <codebuger at gmail.com> writes: > I have this code: > try: > empty_mod = __import__(some_empty_module) > except ImportError: > print "test" > raise > > But python doesn't work with this except: > ImportError: No module named .... Your example is incomplete. >>> try: ... empty_mod = __import__(some_empty_module) ... except ImportError: ... print "test" ... raise ... Traceback (most recent call last): File "<stdin>", line 2, in ? NameError: name 'some_empty_module' is not defined Can you post a minimal, complete example that shows the behaviour? -- \ "As we enjoy great advantages from the inventions of others, we | `\ should be glad to serve others by any invention of ours." -- | _o__) Benjamin Franklin | Ben Finney From john at castleamber.com Wed May 24 11:15:43 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:15:43 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <XRZcg.6994$8G3.6399@twister.nyroc.rr.com> Message-ID: <Xns97CD686303698castleamber@130.133.1.4> Eli Gottlieb <eligottlieb at gmail.com> wrote: > Who reads blogs? They're well known for housing crackpots far worse > than Xah, and I estimate he doesn't want to associate himself with that > sort. Yup, he seems to be quite happy as a Usenet Kook -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From onurb at xiludom.gro Fri May 5 10:46:53 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 16:46:53 +0200 Subject: Is this a legal / acceptable statement ? In-Reply-To: <2AI6g.10201$9c6.5375@dukeread11> References: <2AI6g.10201$9c6.5375@dukeread11> Message-ID: <445b65ba$0$26228$626a54ce@news.free.fr> Philippe Martin wrote: > Hi, > > This code works, but is it "appropriate" ? appropriate for what ?-) > l_init = False > # corrected typo, cf other post in this thread > if True == l_init and 1234 == l_value: > print 'l_value is initialized' Do this in production code, and have one of the first Python entry in the Daily WTF !-) What are you trying to do, exactly ? I've been scratching my head for at least 5 minutes without finding any sensible reason to write such code. > I know I can do this with a try but ... ??? <ot> Slightly ot, but since you ask for idioms: 1/ Since binding (so-called 'assignment') is a statement (not an expression), you can as well write your equality test the 'normal' way: >>> if l_init == True and l_value == 1234: ... pass the "litteral value == variable" idiom comes from languages where assignement being an expression, one could 'typo' '=' for '==', usually leading to unwanted result !-) 2/ also, testing for equality against True or False is a bad idea, since there are some things that will eval to false in a boolean context without actually being equal to False: >>> for item in [[], (), {}, None, '']: ... print item, " == False ?", item == False ... if not item: ... print "but still evals to False..." ... [] == False ? False but still evals to False... () == False ? False but still evals to False... {} == False ? False but still evals to False... None == False ? False but still evals to False... == False ? False but still evals to False... >>> so : >>> if l_init and l_value == 1234: ... pass This still doesn't make sense to me, but it's at least a bit more readable !-) </ot> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From None at none.none Tue May 30 01:23:10 2006 From: None at none.none (WIdgeteye) Date: Tue, 30 May 2006 00:23:10 -0500 Subject: TIming References: <pan.2006.05.30.01.24.04.677340@none.none> <ecin725eh7mk1teolpfi2ulj349ogptdir@4ax.com> Message-ID: <pan.2006.05.30.05.23.09.936650@none.none> On Tue, 30 May 2006 04:34:03 +0000, Tim Roberts wrote: > WIdgeteye <None at none.none> wrote: >>HI, >>I am trying to write a little program that will run a program on scedule. >>I am having trouble understanding the datetime, time, sched modules. What >>I would like is something like this: >> >>If date&time = 06-13-2006:18:00:00 >>Then run this program >> >>I am not sure how to enter a future date in this equation using any of >>the modules mentioned above. I have figured out how to get the date and >>time from the modules above but not the future and then compare the two. > > What operating system are you using? Both Linux and Windows have commands > that can do this for you. It's more efficient to use existing operating > system services than to invent your own. > > Also, remember to take into account the possibility that your program > might not check the time at the exact second. In your example, you need > to be prepared to start your app if the time is just PAST 6 PM on June 13. I am using Linux and could use cron. But I want to be able to schedule and record television shows on her. And yeah I know about freevo but it's way to complicated than it needs to be. So back to the question: How can I get a 9 position tuple from the time functions in Python based on a future date. Thanks. From chris.cavalaria at free.fr Fri May 19 05:01:01 2006 From: chris.cavalaria at free.fr (Christophe) Date: Fri, 19 May 2006 11:01:01 +0200 Subject: Question about exausted iterators In-Reply-To: <mailman.5914.1147992246.27775.python-list@python.org> References: <446b48e2$0$5293$626a54ce@news.free.fr><mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <mailman.5914.1147992246.27775.python-list@python.org> Message-ID: <446d8971$0$6053$626a54ce@news.free.fr> Terry Reedy a ?crit : > "Christophe" <chris.cavalaria at free.fr> wrote in message > news:446c2dea$0$5306$626a54ce at news.free.fr... > >>Instead of saying that all works as intended could you be a little >>helpful and tell me why it was intended in such an obviously broken way >>instead ? > > > I answered both your explicit and implied questions in good faith. But you > seem to be too attached to your pre-judgment to have benefited much, so I > won't waste my time and yours saying more. Instead I suggest that you try > this: > > 1. Write a specification for your an alternate, more complicated, iterator > protocol. Specification : same as now except iterators raise once StopIteration and any subsequent call to next raises ExaustedIteratorError. > 2. Write a simple class with .next method that implements your > specification. class ExaustedIteratorError(Exception): pass class safe_iter(object): def __init__(self, seq): self.it = iter(seq) def __iter__(self): return self def next(self): try: return self.it.next() except StopIteration: del self.it raise except AttributeError: raise ExaustedIteratorError > 3. Test your class with your example. >>> it = safe_iter(range(10)) >>> print list(it) [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] >>> print list(it) Traceback (most recent call last): File "safe_iter_test.py", line 20, in ? print list(it) File "safe_iter_test.py", line 13, in next raise ExaustedIteratorError __main__.ExaustedIteratorError > 4. Consider how you would persuade people to add the extra machinery > needed. Well, the main reason for such change is and will always be to catch bugs. The fact is, using duct typing is something very common with the Python language. And as such, considering a lot of functions which take sequences as parameters work as well with an iterator instead, you can say that it's an application of duct typing. The problem is of course the same as for cases. Even if those two objets ( iterator and container ) look alike from a certain point of view, they have some fundamental differences. So, we have quite a few functions which take freely either a container or an iterator, until someone changes that function a little. At that point there are three kind errors which happen : - the function expected a sequence and tries to access it's [] operator which fails. Standard duct typing behaviour. - the function uses the iterator more than once and so, sometimes it works without errors but produces an incorrect result. - the function uses the iterator more than once but never exhausts it's values. Same result as above but much harder to catch. In the sake of avoiding behaviour which lets obvious errors pass and produces incorrect results, I propose to change the standard behaviour of all the iterators in the standard Python. The change will be so that they refuse to be used anymore once they have been exausted. Thus it'll help catch the second class. The other procedure used to catch such bugs would require explicit typing of the function parameters but this is for some other proposal. > 5. Consider what you would do when people don't. I'm already doing it. Cleaning up the code, changing parameters names around so that it is clear such parameter is an iterator and that other one is not, making some functions explicitly refuse iterators etc ... It should not that that last feature will be useful even without the exhausted iterator guard I propose. > If you want, post a report on your experiment, and I will read it if I see > it. I suppose I could add safe_iter to the builtins in my project and use it around. It would be easy to catch all usages of that one once we settle on something different then. From bignose+hates-spam at benfinney.id.au Tue May 16 18:57:10 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 08:57:10 +1000 Subject: arrays, even, roundup, odd round down ? References: <446a4891$0$61165$ae4e5890@news.nationwide.net> Message-ID: <871wutr321.fsf@benfinney.id.au> Lance Hoffmeyer <lance at augustmail.com> writes: > So, I have using the following to grab numbers from MS Word. I > discovered that that there is a "special" rule being used for > rounding. > > If a ??.5 is even the number is to rounded down (20.5 = 20) > if a ??.5 is odd the number is to rounded up (21.5 = 22) This sounds specific enough that I'd want it in a separate function. def specially_rounded_integer(num): """ Round a number using our special rules """ rounded_num = num * phase_of_moon() # or whatever else you need to do return rounded_num > Brands = ["B1","B2"] > A1 = [] > A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, target_table).group(1) for i in Brands ] > A1 = [int(float(str(x))+0.5) for x in A1 ] > print A1 original_nums = however_you_get_them() rounded_nums = [specially_rounded_integer(n) for n in original_nums] If it's not quickly obvious on a single line, express it more fully. Future readers, including yourself, will thank you. -- \ "Nothing in life is so exhilarating as to be shot at without | `\ result." -- Winston Churchill | _o__) | Ben Finney From johnjsal at NOSPAMgmail.com Fri May 19 10:32:17 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 14:32:17 GMT Subject: WTF? Printing unicode strings In-Reply-To: <mailman.5904.1147987926.27775.python-list@python.org> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> Message-ID: <RFkbg.2124$No6.46433@news.tufts.edu> Fredrik Lundh wrote: > Ron Garret wrote: > >>>>> u'\xbd' >> u'\xbd' >>>>> print _ >> Traceback (most recent call last): >> File "<stdin>", line 1, in ? >> UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in >> position 0: ordinal not in range(128) > > so stdout on your machine is ascii, and you don't understand why you > cannot print a non-ascii unicode character to it? wtf? > > </F> > AFAIK, I'm all ASCII (at least, I never made explicit changes to the default Python install), so how am I able to print out the character? From me at privacy.net Wed May 17 22:10:22 2006 From: me at privacy.net (Dan Sommers) Date: Wed, 17 May 2006 22:10:22 -0400 Subject: MySQLdb - parameterised SQL - how to see resulting SQL ? References: <1147916515.511332.214660@j33g2000cwa.googlegroups.com> Message-ID: <m27j4kqe0h.fsf@unique.fqdn> On 17 May 2006 18:41:55 -0700, shearichard at gmail.com wrote: > Hi - I've got SQL that looks like this ... > cursor = > self.MySQLDb_conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) > sqlQuery = "SELECT * FROM T1 WHERE C1 = %s and C2 = %s" > sql = cursor.execute(sqlQuery,(strURLAlias,strSessionID)) > rows = cursor.fetchall() > cursor.close ITYM cursor.close() > ... i would be interested in seeing what the actual SQL used by the > .execute looks like after the replacements have been done. Is there a > way of doing this ? Taking a quick peek at pysqlite and the API spec, I'd say no, not a standard way. OTOH, eventually, mysqldb has to create that SQL in order to pass it to the database for execution, so it's probably as simple as finding the right place to put a "print" statement and/or to store the finished SQL in the cursor object. HTH, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From manstey at csu.edu.au Tue May 2 23:28:36 2006 From: manstey at csu.edu.au (manstey) Date: 2 May 2006 20:28:36 -0700 Subject: Recommended data structure for newbie Message-ID: <1146626916.066395.206540@y43g2000cwc.googlegroups.com> Hi, I have a text file with about 450,000 lines. Each line has 4-5 fields, separated by various delimiters (spaces, @, etc). I want to load in the text file and then run routines on it to produce 2-3 additional fields. I am a complete newbie to Python but I have the docs and done some experimenting. But I'm not sure what sort of data structure I should be creating. Example: gee fre asd[234 ger dsf asd[243 gwer af as.:^25a what i want is 'gee' 'fre' 'asd' '[' '234' 'ger' dsf' asf' '[' '243' 'gwer' 'af 'as.:' '^' '25a etc for 450,000 lines. Then on the basis of information in 1 or more lines, I want to append to each line new data such as 'gee' 'fre' 'asd' '[' '234' 'geefre2' '2344f' 'ger' dsf' asf' '[' '243' 'gerdsd' '2431' 'gwer' 'af 'as.:' '^' '25a 'gweraf' 'sfd2' What do you recommend? I think it is some sort of list inside a list, but I'm not sure. I know how to generate the new data but not how to store everything both in memory and on disk. Regards, Matthew From skip at pobox.com Wed May 17 13:23:35 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 May 2006 12:23:35 -0500 Subject: Using python for a CAD program In-Reply-To: <1147884651.321088.230740@g10g2000cwb.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <mailman.5766.1147809690.27775.python-list@python.org> <1147884651.321088.230740@g10g2000cwb.googlegroups.com> Message-ID: <17515.23575.322479.897983@montanaro.dyndns.org> >> 1. Databases. Assuming I roll my own, does python have any >> performance issues for this sort of thing? Most databases are written in a compiled language (gadfly being an exception). Even so, in my apps that use databases (mostly SQL-based), the database is the bottleneck, not Python. >> 5. Threads and parallelism. Should I even bother? I've read that >> it's possibly more tricky with python than with normal dev tools. Threads help if you're going to be I/O-bound. If you're going to be CPU-bound I wouldn't bother unless it provides some major structural advantage to your code. If you think you need more than a couple CPUs, you probably want a multi-process model anyway so you can leverage multiple computers on a LAN (think Beowulf-style multiprocessing). Skip From steven.klass at gmail.com Wed May 17 17:22:37 2006 From: steven.klass at gmail.com (rh0dium) Date: 17 May 2006 14:22:37 -0700 Subject: How to tell if function was passed a list or a string? Message-ID: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> Hi All, I have the nice little function (below) which used to work great assuming the data[key] passed to it was a list. Well now I want to update this a bit. I want this function to be smart enough to tell if it's a list and do the funky concatonation otherwise don't. def insert(self, table=None, data=None): insert1=[] insert2=[] for key in data.keys(): insert1.append(key) self.logger.debug("Key: %s Data: %s" % ( key,data[key])) try: an = [] for a in data[key]: an.append(re.sub(",","", str(a))) ans = string.join(an, ", ") except: ans = None insert2.append(ans) self.logger.info( "Insert command %s" % insert ) self.cursor.execute(insert) The question is how do you tell that the data you were passed is a list or not? Thanks so much! From kentilton at gmail.com Wed May 10 12:13:25 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 10 May 2006 12:13:25 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <sddwtcuc4wo.fsf@shell01.TheWorld.com> References: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> <NUP7g.17$G22.12@fe11.lga> <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> <ubn362tg2ft4la26hq4so0ron8lsj7fvqe@4ax.com> <sddwtcuc4wo.fsf@shell01.TheWorld.com> Message-ID: <Fio8g.7$CQ6.0@fe11.lga> Chris F Clark wrote: > David C Ullrich asked: > >>Q: How do we ensure there are no loops in the dependencies? >> >>Do we actually run the whole graph through some algorithm >>to verify there are no loops? > > > The question you are asking is the dependency graph a "directed > acyclic graph" (commonly called a DAG)? One algorithm to determine if > it is, is called "topological sort". That algorithm tells you where > there are cyclces in your graph, Yep. But with Cells the dependency graph is just a shifting record of who asked who, shifting because all of a sudden some outlier data will enter the system and a rule will branch to code for the first time, and suddenly "depend on" on some new other cell (new as in never before used by this cell). This is not subject to static analysis because, in fact, lexically everyone can get to everything else, what with closures, first-class functions, runtime branching we cannot predict... fuggedaboutit. So we cannot say, OK, here is "the graph" of our application model. All we can do is let her rip and cross our fingers. :) kenny From miki.tebeka at gmail.com Sun May 14 09:32:17 2006 From: miki.tebeka at gmail.com (Miki) Date: 14 May 2006 06:32:17 -0700 Subject: distutils and binding a script to a file extension on windows In-Reply-To: <1147566720.618224.150810@j73g2000cwa.googlegroups.com> References: <1147566720.618224.150810@j73g2000cwa.googlegroups.com> Message-ID: <1147613537.624737.60690@y43g2000cwc.googlegroups.com> Hello Alex, Not really an answer but if you use InnoSetup (http://www.jrsoftware.org/) you can set file type association (see http://www.jrsoftware.org/isfaq.php) HTH, Miki From jiangchanghao at hotmail.com Sat May 20 00:54:48 2006 From: jiangchanghao at hotmail.com (Changhao) Date: Fri, 19 May 2006 23:54:48 -0500 Subject: performance problem of streaming data over TCP In-Reply-To: <e4luqj$d0h$1@news.ks.uiuc.edu> References: <e4luqj$d0h$1@news.ks.uiuc.edu> Message-ID: <e4m7eo$fkm$1@news.ks.uiuc.edu> I figured out the reason. It was because of asyncore.dispatcher's inefficient implementation of messange sending. Instead of using its 'push' method. I directly call the underlying 'socket.send' and got the problem solved. Sorry about the spam. Thanks Changhao wrote: > Hi, friends, > > I am implementing a protocol on top of 'asyncore.dispatcher' to send > streaming multimedia data over TCP socket. However, I found that the > throughput of my current implementation is surprisingly low. > > Below is a snippet of my code with a note that: the packet sent over > the socket is of variable length, of which the first a couple bytes > indicates the length of the packet. I implemented a 'var_str_to_int' > function to get the 'length' and the offset of the payload. > > ############################################### > def handle_read(self): > self.socket.setblocking(1) > while (True) : > > > data = > self.assemble_msg() > if (not data) : > self.socket.setblocking(0) > return > (length,index) = var_str_to_int(data) > self._dispatch_cmd(data[index:]) > if (not self.recv_buffer) : > break > self.socket.setblocking(0) > > def assemble_msg(self) : > if (self.recv_buffer) : > data = self.recv_buffer > else : > data = self.socket.recv(self.BUFFER_SIZE) > if (len(data) == 0) : > return None > length,index = var_str_to_int(data) > while (length +index > len(data)) : > data += self.socket.recv(self.BUFFER_SIZE) > if (length + index == len(data)) : > self.recv_buffer = '' > else : > self.recv_buffer = data[length+index:] > data = data[:length+index] > return data > ############################################### > > I found it took around 7 seconds to receive a packet of 40KB sent > from localhost. The throughput is even not enough to support any > streaming multimedia file for live playback in a LAN. > > I read some threads in the group. It sounds like the problem might > have to do with the TCP option, setting TCP_NODELAY probably could solve > the problem. But I tried the following on both a Linux and a windows XP > machine. Neither of them worked: > > ############################################## > self.socket.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) > ############################################## > > Any comments or suggests is highly appreciated. > > Thanks, > Changhao From kent at kentsjohnson.com Fri May 26 07:02:30 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 26 May 2006 07:02:30 -0400 Subject: Parsing python dictionary in Java using JPython In-Reply-To: <mailman.6220.1148632998.27775.python-list@python.org> References: <mailman.6220.1148632998.27775.python-list@python.org> Message-ID: <4476df6d$1_2@newspeer2.tds.net> sandip desale wrote: > Hi, > > We have some tools which are developed in Python and using python dictionaries. Now for some new requirments we are using Java and want to use the existing dictionaries as both the tools are executed on the same platform. So we are trying to use the existing dictionaries only using JPython libraries. How do you access the dictionary files from Python? The same thing may work in Jython. For example importing the file, if it is Python syntax, should work in Jython; also I think format 0 (text) and format 1 pickles are compatible with Jython. Kent From george.sakkis at gmail.com Wed May 17 13:54:44 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 17 May 2006 10:54:44 -0700 Subject: Beautiful parse joy - Oh what fun References: <1147813885.337318.141070@g10g2000cwb.googlegroups.com> Message-ID: <1147888484.388949.97980@j55g2000cwa.googlegroups.com> Here's one way to do it: import re _any_re = re.compile('.+') d = {} for row in BeautifulSoup(html).fetch('tr'): columns = row.fetch('td') field = columns[1].firstText(_any_re).rstrip(' \t\n:') value = ' '.join(text.rstrip() for text in columns[2].fetchText(_any_re)) d[field] = value print d George From onurb at xiludom.gro Fri May 19 15:24:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 21:24:27 +0200 Subject: Modifying a variable in a non-global outer scope? In-Reply-To: <-tKdnSU7GKuPhPPZRVn-rg@comcast.com> References: <-tKdnSU7GKuPhPPZRVn-rg@comcast.com> Message-ID: <446e1bd4$0$26898$626a54ce@news.free.fr> Edward C. Jones wrote: > #! /usr/bin/env python > """ > When I run the following program I get the error message: > > UnboundLocalError: local variable 'x' referenced before assignment > > Can "inner" change the value of a variable defined in "outer"? Not this way > Where > is this explained in the docs? IIRC, http://www.python.org/doc/2.4.2/ref/naming.html > """ > def outer(): > def inner(): > x = x + 1 > > x = 3 > inner() > print x > > outer() What are functions arguments and return values for ? def outer(): def inner(x): return x+1 x = 3 x = inner(x) print x outer() Using side-effects - specially this way - is a Very Bad Thing(tm). It makes code that is hard to read and hard to maintain. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jstroud at ucla.edu Tue May 2 16:27:52 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 02 May 2006 13:27:52 -0700 Subject: Python & SSL In-Reply-To: <mailman.5219.1146599247.27775.python-list@python.org> References: <e38c66$r2t$1@zinnia.noc.ucla.edu> <mailman.5219.1146599247.27775.python-list@python.org> Message-ID: <e38fc8$t5q$1@zinnia.noc.ucla.edu> Benji York wrote: > James Stroud wrote: > >> I have been trying to make an https client with python > > > You probably don't want to use the standard library for HTTPS; here's a > quote from the socket module docs about SSL: > > Warning: This does not do any certificate verification! > > I'd recommend M2Crypto instead: > http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto > -- > Benji York Thank you, I will give M2Crypto a try. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From jerry.levan at gmail.com Tue May 30 23:49:13 2006 From: jerry.levan at gmail.com (jerry.levan at gmail.com) Date: 30 May 2006 20:49:13 -0700 Subject: Tktable, WinXP and ActiveState Python 2.4.3,x Message-ID: <1149047353.883167.18100@i39g2000cwa.googlegroups.com> Hi, I have a python app that runs fine on MacOS X and Fedora Core 5. This evening I dragged the folder over to my windows partition and tried to run the rascal. The program starts up fine but at the first call to create a Table object I get 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:\Documents and Settings\Jerry\Desktop\PyPgBrowseUni\PyPgExplorer.py", line 7, in ? obj.main() File "C:\Documents and Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line 72, in main self.build_ui( info) File "C:\Documents and Settings\Jerry\Desktop\PyPgBrowseUni\Resources\PyPgBrowse.py", line 187, in build_ui rowtagcommand=self.rowproc File "C:\Documents and Settings\Jerry\Desktop\PyPgBrowseUni\Resources\Tktable.py", line 64, in __init__ master.tk.call('load', '', 'Tktable' ) TclError: package "Tktable" isn't loaded statically : I get the same error if I try to create a Table object from the command line in a console. I tried waving a dead chicken at my laptop but it did no good. Is there some special magic to get Tktable.py to play nice? I do have the latest Tcl from Active State loaded on my box and the Tktable in my Tk programs work well... Thanks for any insight.... Jerry From msrainess at comcast.net Mon May 1 12:14:01 2006 From: msrainess at comcast.net (Mark rainess) Date: Mon, 01 May 2006 12:14:01 -0400 Subject: Multi-Monitor Support Message-ID: <-uGdnYcAYvZarsvZnZ2dnUVZ_s-dnZ2d@comcast.com> Hello, Does Python or wxPython include any support for multiple monitors. In my application multiple monitors are located at a distance. It is not convenient to move a window from the main monitor to one of the others. I want to have the option to open an an application on any connected monitor. I am using wxPython. Does anyone know how to do it? Thanks Mark Rainess From Florian.Lindner at xgm.de Tue May 2 12:43:12 2006 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Tue, 02 May 2006 18:43:12 +0200 Subject: RFC 822 continuations Message-ID: <e3827a$dtd$1@news.in.tum.de> Hello, http://docs.python.org/lib/module-ConfigParser.html writes: "with continuations in the style of RFC 822; " what is meant with these continuations? Thanks, Florian From ms at cerenity.org Sat May 6 06:27:12 2006 From: ms at cerenity.org (Michael) Date: Sat, 06 May 2006 11:27:12 +0100 Subject: Kamaelia & Summer of Code (was Re: Google's Summer of Code - Students coding on MoinMoin ) References: <mailman.5266.1146665961.27775.python-announce-list@python.org> Message-ID: <445c795b$0$5915$ed2e19e4@ptn-nntp-reader04.plus.net> Alexander Schremmer wrote: ... > Just as a sidenote, there are also at least the organisations BBC R&D ( > Kamaelia) and Python Software Foundation (including Python, PyPy, ...) > which offer work on Python software. I only just had a chance to check c.l.p.a - thanks for posting the reference above - it's VERY much appreciated :) For those interested in Kamaelia for summer of code, please see our main overview page here: * http://kamaelia.sourceforge.net/SummerOfCode2006.html We have a template for applications describing what we're interested in here: * http://kamaelia.sourceforge.net/SummerOfCode2006Template.html The main discussion area for projects is here: * http://kamaelia.sourceforge.net/cgi-bin/projects/blog.cgi However there's been *a lot* of discussion on IRC over the past few days on this subject, so looking in the logs might be a good idea: * http://koala.ilog.fr/twikiirc/bin/irclogger_logs/kamaelia We've had a few very good applications so far, but one thing I would like to say is this: Please note: For summer of code, we're interested in anyone who can code, not PhD candidates (they're nice and welcome though :). We're rating applications based on enthusiasm, approach and project they want to do as much as we are on people's innate ability. Anyone with sufficient talent OR determination can produce something wonderful. The reason for this note is someone made the comment that they thought we're interested only in PhD candidates which is unfortunate. Whilst Dirac is pretty hardcore, Kamaelia is written in python for a very specific reason - to lower the barrier to entry. Summer of Code for us is as much about testing whether that really is the case, as it is about producing useful tools. After all, we're serious when we say that Kamaelia /should/ be accessible even to novice programmers. Also, Whilst the front page of the website hasn't seen much action recently it's probably worth mentioning that we've now got significantly better documentation of individual components, a cookbook of examples, etc. The best starting point at the moment is probably here: * http://kamaelia.sourceforge.net/Docs/ If you've got no idea what Kamaelia is, two ways to describe it: * Rack mountable software (currently trying this description for size :) * Toys for programmers A way to describe its ethos (paraphrasing Doug McIlroy): "Write components that do one thing and do it well. Write components to work together. Write components to handle object streams, because that is a universal interface." We're in the final stages of an optimisation phase, so this is a good time to get involved. The current release will soon be replaced with something with a lot of new components and greatly improved performance. (when *that* happens that would be a good time to be a user of the system :) Anyway, this message is really targetted at people who are interested in doing something FUN and useful for summer of code :-) (apologies to those who might view it as spam...) Have fun! Michael -- Michael Sparks, Senior Research Engineer, BBC Research, Technology Group ms_ at users.sourceforge.net, Kamaelia Project Lead, http://kamaelia.sf.net/ Summer of Code: http://kamaelia.sf.net/SummerOfCode2006.html From pas at despam Mon May 8 16:54:05 2006 From: pas at despam (p-d-p=pas-de-spam) Date: Mon, 08 May 2006 22:54:05 +0200 Subject: Getting HTTP responses - a python linkchecking script. In-Reply-To: <1147056628.354150.116120@y43g2000cwc.googlegroups.com> References: <1147056628.354150.116120@y43g2000cwc.googlegroups.com> Message-ID: <445fafe8$0$6678$8fcfb975@news.wanadoo.fr> blair.bethwaite at gmail.com a ?crit : > Hi Folks, > > I'm thinking about writing a script that can be run over a whole site > and produce a report about broken links etc... > > I've been playing with the urllib2 and httplib modules as a starting > point and have found that with urllib2 it doesn't seem possible to get > HTTP status codes. > > I've had more success with httplib... > Firstly I create a new HTTPConnection object with a given hostname and > port then I try connecting to the host and catch any socket errors > which I can assume mean the server is either down or doesn't exist at > this place anymore. > If the connection was successful I try requesting the resource in > question, I then get the response and check the status code. > > So, I've got the tools I need to do the job sufficiently. Just > wondering whether anybody can recommend any alternatives. > > Cheers, > -Blair > have a look at urllib2 - The Missing Manual http://www.voidspace.org.uk/python/articles/urllib2.shtml From andrew at acooke.org Mon May 22 18:11:05 2006 From: andrew at acooke.org (andrew at acooke.org) Date: 22 May 2006 15:11:05 -0700 Subject: system(...) and unicode References: <1148331460.400964.158420@u72g2000cwu.googlegroups.com> Message-ID: <1148335865.001493.13320@38g2000cwa.googlegroups.com> Hmmm. After reading http://kofoto.rosdahl.net/trac/wiki/UnicodeInPython I tried: system(cmd.encode(getfilesystemencoding())) which works (nothing else changed). But that seems odd - is this a bug (the asymmetry - I read files with os.listdir with no explicit unicode handling, but need to do something explicitly on output - seems wrong), or am I going to be bitten by other errors later? Thanks, Andrew From jweida at gmail.com Tue May 9 12:37:00 2006 From: jweida at gmail.com (Jerry) Date: 9 May 2006 09:37:00 -0700 Subject: Python editor recommendation. In-Reply-To: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1147192620.064152.184670@u72g2000cwu.googlegroups.com> I have used Eclipse+PyDev in the past. I don't use the debugger though and don't find the outline all that useful, so now I just use the PythonWin interface that comes with the ActiveState Python distribution. Another one that I've heard lots of people seem to like is Stani's Python Editor (SPE). You can find it at http://stani.be/python/spe/blog/ From defcon8 at gmail.com Sun May 14 04:39:42 2006 From: defcon8 at gmail.com (defcon8) Date: 14 May 2006 01:39:42 -0700 Subject: Cellular automata and image manipulation In-Reply-To: <i4OdnQZa45PQ7_vZUSdV9g@ptd.net> References: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> <i4OdnQZa45PQ7_vZUSdV9g@ptd.net> Message-ID: <1147595982.184878.25800@d71g2000cwd.googlegroups.com> It seemed to work with a 1d list but not with 2d. From sybrenUSE at YOURthirdtower.com.imagination Tue May 2 06:31:44 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 2 May 2006 12:31:44 +0200 Subject: strip newlines and blanks References: <1146551463.451811.266960@j73g2000cwa.googlegroups.com> <e370gn$415$02$1@news.t-online.com> <1146555493.669199.217990@j73g2000cwa.googlegroups.com> Message-ID: <slrne5ed8g.gen.sybrenUSE@schuimige.unrealtower.org> micklee74 at hotmail.com enlightened us with: > thanks..and sorry, i am using the web version of google groups and > didn't find an option i can edit my post It's usenet, you can't edit posts. > so i just removed it.. Which doesn't work at all. Stupid thing they allow you to try and delete something on Google Groups, since removal of Usenet posts is ignored by most Usetnet carriers. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From max at alcyone.com Thu May 18 16:50:36 2006 From: max at alcyone.com (Erik Max Francis) Date: Thu, 18 May 2006 13:50:36 -0700 Subject: Question about exausted iterators In-Reply-To: <446c8f5e$0$7153$626a54ce@news.free.fr> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <mailman.5879.1147959939.27775.python-list@python.org> <446c7f44$0$7128$626a54ce@news.free.fr> <4d3f10F18q0d9U1@uni-berlin.de> <446c88a2$0$7121$626a54ce@news.free.fr> <mailman.5886.1147964579.27775.python-list@python.org> <446c8f5e$0$7153$626a54ce@news.free.fr> Message-ID: <q-KdnTMpBMuAQ_HZRVn-ig@speakeasy.net> Christophe wrote: > Yes, I know perfectly well that the bugs were my fault. But this doesn't > prevent me from asking for a feature that will have ( in my opinion ) a > negligible effect of current valid code and will help all of us catch > errors earlier. ... and apparently choosing to ask in such a way that guarantees practically no one will take your suggestion seriously. -- Erik Max Francis && max at alcyone.com && http://www.alcyone.com/max/ San Jose, CA, USA && 37 20 N 121 53 W && AIM erikmaxfrancis Chance favors the trained mind. -- Louis Pasteur From webraviteja at gmail.com Fri May 5 00:12:46 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 4 May 2006 21:12:46 -0700 Subject: cross platform libraries In-Reply-To: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> References: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> Message-ID: <1146802366.107685.299870@i40g2000cwc.googlegroups.com> No! That's not the way things work. Such code needs to run locally (in this case, Windows). You can run this program as a daemon on Windows with some nice simple remote interface (Eg: xmlrpc) and send a message to trigger the shutdown. From aristotelian at onet.eu Sat May 20 19:42:16 2006 From: aristotelian at onet.eu (aristotelian at onet.eu) Date: 20 May 2006 16:42:16 -0700 Subject: buffers readlines and general popen2 confusion... In-Reply-To: <126v8d1cpk0ci8a@corp.supernews.com> References: <1148162219.463249.155680@j33g2000cwa.googlegroups.com> <126v8d1cpk0ci8a@corp.supernews.com> Message-ID: <1148168536.774853.99200@y43g2000cwc.googlegroups.com> That's just it. I was hoping to have python listening for events and responding continually according to the demaons stdout. That's why I mention popen2. From fyleow at gmail.com Fri May 5 19:46:55 2006 From: fyleow at gmail.com (fyleow) Date: 5 May 2006 16:46:55 -0700 Subject: Elegent solution to replacing ' and " ? Message-ID: <1146872815.237738.57590@j73g2000cwa.googlegroups.com> I'm trying to replace the ' and " characters in the strings I get from feedparser so I can enter it in the database without getting errors. Here's what I have right now. self.title = entry.title.encode('utf-8') self.title = self.title.replace('\"', '\\\"') self.title = self.title.replace('\'', '\\\'') This works just great but is there a more elegent way to do this? It looks like maybe I could use the translate method but I'm not sure. From http Sun May 7 13:29:51 2006 From: http (Paul Rubin) Date: 07 May 2006 10:29:51 -0700 Subject: md5 from python different then md5 from command line References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> <just-5DE763.12245007052006@news1.news.xs4all.nl> <1146999187.874299.40390@j33g2000cwa.googlegroups.com> Message-ID: <7xhd41eoa8.fsf@ruckus.brouhaha.com> "Marius Ursache" <ursache.marius at gmail.com> writes: > > >>> import md5 > > >>> test = md5.new("marius\n") > > >>> print test.hexdigest() > > 0f0f60ac801a9eec2163083a22307deb > > Thanks, that was it ;) Also, the -n option suppresses the newline from echo: $ echo -n marius | md5sum 242aa1a97769109065e3b4df359bcfc9 - From ptmcg at austin.rr._bogus_.com Fri May 19 13:47:37 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 17:47:37 GMT Subject: Python sqlite and regex. References: <mailman.5942.1148042842.27775.python-list@python.org><1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> <hunbg.46845$CH2.29994@tornado.texas.rr.com> Message-ID: <Zwnbg.46846$CH2.28826@tornado.texas.rr.com> "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message news:hunbg.46845$CH2.29994 at tornado.texas.rr.com... > where '*' matches one or more characters, and '?' matches any single oops, I meant '*' matches zero or more characters. In many applications, these tests are sufficient for most user queries. And this eliminates the problem of teaching application users how to create queries using the full regular expression syntax. -- Paul From paddy3118 at netscape.net Fri May 19 14:38:55 2006 From: paddy3118 at netscape.net (Paddy) Date: 19 May 2006 11:38:55 -0700 Subject: number of different lines in a file References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> Message-ID: <1148063935.859890.173230@u72g2000cwu.googlegroups.com> If the log has a lot of repeated lines in its original state then running uniq twice, once up front to reduce what needs to be sorted, might be quicker? uniq log_file | sort| uniq | wc -l - Pad. From aleaxit at yahoo.com Sun May 7 14:57:57 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 11:57:57 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <pan.2006.05.07.08.35.04.362248@gmail.com> Message-ID: <1heytan.zl0xgh9v134kN%aleaxit@yahoo.com> I V <wrongbad at gmail.com> wrote: ... > >> higher level languages. There are useful programming techniques, like > >> monadic programming, that are infeasible without anonymous functions. > >> Anonymous functions really add some power to the language. > > > > Can you give me one example that would be feasible with anonymous > > functions, but is made infeasible by the need to give names to > > functions? In Python, specifically, extended with whatever fake syntax > > you favour for producing unnamed functions? > > Monads are one of those parts of functional programming I've never really > got my head around, but as I understand them, they're a way of > transforming what looks like a sequence of imperative programming > statements that operate on a global state into a sequence of function > calls that pass the state between them. Looks like a fair enough summary to me (but, I'm also shaky on monads, so we might want confirmation from somebody who isn't;-). > So, what would be a statement in an imperative language is an anonymous > function that gets added to the monad, and then, when the monad is run, > these functions get executed. The point being, that you have a lot of > small functions (one for each statement) which are likely not to be used > anywhere else, so defining them as named functions would be a bit of a > pain in the arse. It seems to me that the difference between, say, a hypothetical: monad.add( lambda state: temp = zipper(state.widget, state.zrup) return state.alteredcopy(widget=temp) ) and the you-can-use-it-right now alternative: def zipperize_widget(state): temp = zipper(state.widget, state.zrup) return state.alteredcopy(widget=temp) monad.add(zipperize_widget) is trivial to the point of evanescence. Worst case, you name all your functions Beverly so you don't have to think about the naming; but you also have a chance to use meaningful names (such as, presumably, zipperize_widget is supposed to be here) to help the reader. IOW, monads appear to me to behave just about like any other kind of HOFs (for a suitably lax interpretation of that "F") regarding the issue of named vs unnamed functions -- i.e., just about like the difference between: def double(f): return lambda *a: 2 * f(*a) and def double(f): def doubled(*a): return 2 * f(*a) return doubled I have no real problem using the second form (with a name), and just don't see it as important enough to warrant adding to the language (a language that's designed to be *small*, and *simple*, so each addition is to be seen as a *cost*) a whole new syntaxform 'lambda'. ((The "but you really want macros" debate is a separate one, which has been held many times [mostly on comp.lang.python] and I'd rather not repeat at this time, focusing instead on named vs unnamed...)) Alex From me+python at modelnine.org Thu May 18 03:04:51 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 18 May 2006 09:04:51 +0200 Subject: Python - Web Display Technology In-Reply-To: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> Message-ID: <200605180904.51164.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 08:51 schrieb SamFeltus: > I am trying to figure out why so little web development in Python uses > Flash as a display technology. It seems most Python applications > choose HTML/CSS/JS as the display technology, yet Flash is a far more > powerful and elegant display technology. On the other hand, HTML/JS > seems clunky and antiquated. I am a gardener, and not a coder by > trade, but Flash seems to integrate just fine with Python. Anyways, > what are the technical reasons for this? There no Python specific reason, but I refrain from using Flash because it requires more than just the usual browser (which is available everywhere). Using HTML/CSS/JS, I can make it so that the information I want to give to the user displays right on pretty much every computer that's available out there (think PS3), when I resort to techniques such as Flash or Java, I limit the number of people I can reach. Take me for example: I'm running Linux on AMD64, and there's no proper Flash implementation yet which I can plug into my Firefox. So, I'm out on any Flash page. If you want to exclude me from viewing the information you want to present, fine, use Flash. If you don't, don't use it. And: the web is a platform to offer _information_. Not to offer shiny graphics/sound, which is the only benefit Flash has to offer. To sum it up: Flash/Java considered evil here. But that's just my 5 cents. --- Heiko. From sjmachin at lexicon.net Mon May 29 21:19:55 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 May 2006 11:19:55 +1000 Subject: why not in python 2.4.3 In-Reply-To: <1148913877.508686.266060@g10g2000cwb.googlegroups.com> References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> <r94k725bfor7ssate10bd5veld2v6q6mm0@4ax.com> <1148851375.148311.320780@g10g2000cwb.googlegroups.com> <1148870627.058561.12800@y43g2000cwc.googlegroups.com> <1148897123.135779.91870@j33g2000cwa.googlegroups.com> <1148906849.894298.323790@g10g2000cwb.googlegroups.com> <1148913877.508686.266060@g10g2000cwb.googlegroups.com> Message-ID: <447B9DBB.4080102@lexicon.net> On 30/05/2006 12:44 AM, Rocco wrote: > Thanks Serge. > It's a gzip string. Look, Ma, no gzip!!! C:\junk>rocco_rss.py '<?xml version="1.0" encoding="UTF-8"?><rss version="2.0"><channel><generator>NF E/1.0</generator><tit' C:\junk>type rocco_rss.py import urllib2 def takefeed(url): request=urllib2.Request(url) request.add_header('User-Agent', 'Mozilla/4.0 (compatible; MSIE 5.5; Win dows NT') opener = urllib2.build_opener() data=opener.open(request).read() return data url='http://news.google.it/?output=rss' d=takefeed(url) print repr(d[:100]) From mcfletch at vrplumber.com Sun May 21 11:06:41 2006 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 21 May 2006 11:06:41 -0400 Subject: Using python for a CAD program In-Reply-To: <1147884651.321088.230740@g10g2000cwb.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <mailman.5766.1147809690.27775.python-list@python.org> <1147884651.321088.230740@g10g2000cwb.googlegroups.com> Message-ID: <44708201.8010108@vrplumber.com> 63q2o4i02 at sneakemail.com wrote: > Thanks for this. I'm enjoying this discussion and I'm learning a lot > about people's views and how they differ from mine. > > However, I'm still wondering about my original post. > > Can the experts please comment on python's usage for the following: > > 1. Databases. Assuming I roll my own, does python have any > performance issues for this sort of thing? > CAD software has generally proven to be somewhat less than amenable to relational database models. Relational databases are good for storing and querying large numbers of same-structure things. CAD models tend to be large numbers of different-structure things. An object database is likely to give you less of an impedance mismatch. With either approach, expect your database operations to be slow compared to running in memory. Storing the model in memory while working (if you can fit it) is going to be a lot snappier than keeping things out in a database. There are OO databases that have decent caching (e.g. ZODB) that can give you some of the benefits of storing in the database without needing to have everything loaded up at once. But keep in mind that most OO databases are *not* optimised for this type of use-case, you may need to rather heavily customise a standard package if you decide to use one. You'll have to handle the partition of the data such that you can run your simulations with partial data-sets if you want to take advantage of that (possible with architecture, interior design, game design, etceteras, not sure if it's possible with electrical engineering). > 2. GUI. Can Python command the various gui libraries fast enough to > qualify as game-quality, with transparency, anti-aliasing, animations, > etc? > While it might be possible to do this fast enough with Python, you will almost certainly want to use a retained-mode engine for the graphics display. There are quite a few retained-mode engines for Python, most are built on OpenGL. Some of those engines are written in Python, more in C or C++. Basically what the retained mode engine does for you is it allows you to simply describe what's supposed to be there and let something else deal with the problem of how to display it. Retained mode engines tend to be written by fairly experienced 3D programmers who are somewhat obsessed by performance issues. You can readily setup the node-graph in (slower) Python code and then have the engine handle the heavy per-frame rendering. The retained mode engine will (should) take care of things such as caching intermediate rendering data (such as simple data-pointers for rendering entire swaths of your drawings with a single GL call). They will only update those structures when you actually change something that affects the rendering. Their formality of operation allows them to make quite a few optimisations even though some are quite general platforms (the more general, the fewer optimisations they can easily make). (For simple drawings it's easy for you to make your own, better, optimisations, but with more complex scenes such optimisations become more and more cumbersome without introducing formal structures). > 3. Computational stuff like simulations and rules-checking. I'm just > going to assume this needs to be in C++ or pyrex or SciPy or something. > Numpy will often be sufficient for many scientific simulations, but it's all about what algorithms you need to implement. > 4. Programmability. How do I embed an interpreter which has some > custom CLI commands and knowledge of the graphical conext and which has > exposure to the API used in the main application, such that to the user > all the necessary things are exposed by default, and so that it doesn't > feel like it's just a disconnected console window that he/she needs to > set up manually each time? > Most Python GUI libraries have a console widget into which you can pass context. Doesn't particularly require a lot of work, just follow along in the docs for the GUI widget. You can see how it's done with wxPython and OpenGLContext here: http://pyopengl.cvs.sourceforge.net/pyopengl/OpenGLContext/bin/visualshell.py?view=markup > 5. Threads and parallelism. Should I even bother? I've read that > it's possibly more tricky with python than with normal dev tools. I've > never done it, but I'd like to at least think about it up front so > if/when this goes MT it's not a complete rewrite from the ground up. > Threads aren't any more complex with Python than other tools, if anything they're easier (Python has a good basic API for threading). The problem is that they are far less *useful* than in C or the like, because the global interpreter lock means they don't let you take advantage of multiple processors in the box in most cases. That said, threading is always tricky, particularly during debugging. If you can avoid it for most operations and only put things in threads that are largely disconnected from other processes you'll likely be happier. The big win would be if you are doing all of your simulation in C with an event-based update such that the simulation generates changes as a queued list of updates to the model. You could then have the simulation yield the interpreter lock and seldom block the rest of the process (save when it touches a Python object (i.e. the updates coming from or going to the queue)). Have fun, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From caseyhHAMMER_TIME at istar.ca Fri May 12 16:31:06 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Fri, 12 May 2006 20:31:06 GMT Subject: New tail recursion decorator References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <Xns97BF8E839A8D1duncanbooth@127.0.0.1> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> <1147437656.779139.54840@d71g2000cwd.googlegroups.com> <1147441799.331677.88460@d71g2000cwd.googlegroups.com> <Xns97C19C18C76A4duncanbooth@127.0.0.1> <yfsy7x7tb9q.fsf@oc.ex.ac.uk> Message-ID: <der9621q7ugch74fkcgulq4qmiont3vb0g@4ax.com> Your examples are not tail recursive because an extra step is needed before returning from the function call and that step cannot be thrown away! Alexander Schmolck <a.schmolck at gmail.com> wrote: >def even(n): > return n == 0 or not odd(n-1) > >def odd(n): > return n == 1 or not even(n-1) > -- Regards, Casey From ask at me Thu May 11 19:12:35 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 19:12:35 -0400 Subject: Chicago Python Users Group Thurs May 11 at 7pm In-Reply-To: <mailman.5556.1147271554.27775.python-list@python.org> References: <mailman.5556.1147271554.27775.python-list@python.org> Message-ID: <24-dnWYg5IRnTf7ZnZ2dnUVZ_tKdnZ2d@comcast.com> Brian Ray wrote: > This will be our best meeting yet! ChiPy's Monthly meeting this Thurs. > May 11, 2006. 7pm. > I will miss it. When the next is planed? From h.b.furuseth at usit.uio.no Wed May 3 04:20:09 2006 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Wed, 03 May 2006 10:20:09 +0200 Subject: Dispatching operations to user-defined methods References: <hbf.20060502stiz@bombur.uio.no> Message-ID: <hbf.20060503sln5@bombur.uio.no> I wrote: > I'm wondering how to design this: > (...) > One obvious implementation would be to provide a class Operation, > let the user define a single subclass of this, and have the server > call request_search(), response_search(), request_modify(), > check_access() etc in that subclass. > > Then I suppose the server would turn individual operations into > instance of internal subclasses of the user's subclass - class > SearchOperation(<user's class>), ModifyOperation(<user's class>) > etc. Begins to look a bit messy now. > (...) <Slap head> Or two classes - one operation class and one class subclassed by the user. Still need some way to let the user provide both general and more specialized methods though. -- Hallvard From no-spam at no-spam-no-spam.com Sat May 20 07:19:48 2006 From: no-spam at no-spam-no-spam.com (robert) Date: Sat, 20 May 2006 13:19:48 +0200 Subject: Simple DAV server? In-Reply-To: <10ddj3-qhb.ln1@snout.lairds.com> References: <e22ngm$ipq$1@ulysses.news.tiscali.de> <e23v7e$4uq$1@news1.carnet.hr> <e25ib0$12hc$1@ulysses.news.tiscali.de> <e26hrl$dfc$1@news1.carnet.hr> <e27p5p$1ehi$1@ulysses.news.tiscali.de> <e285ur$obt$1@news1.carnet.hr> <e2isqu$ckm$1@ulysses.news.tiscali.de> <1fg0i3-7pc.ln1@snout.lairds.com> <e2rkq0$g7s$1@news1.carnet.hr> <10ddj3-qhb.ln1@snout.lairds.com> Message-ID: <e4mu0m$18g1$1@ulysses.news.tiscali.de> Kyler Laird wrote: > Ivan Voras <ivoras at __-fer.hr-__> writes: > > >>Most of the problems are probably because I didn't mean it to be a >>fully-compliant WebDAV server, but to serve my need at the time :) > > > I am *so* close to having a WebDAV solution. Unfortunately when I finally > moved to using HTTPS, it all broke in MS Windows. (Konqueror handles it > beautifully.) > > If I make a Web Folder with HTTP, Windows displays it (as "\\hostname\") > in Windows Explorer. If I make it with HTTPS, it throws me into Internet > Explorer (where WebDAV isn't used - I can't even launch files). > > WTF?! It looks like other people are using WebDAV over HTTPS. > http://www.mydocsonline.com/info_webfolders.html > Why is Windows kicking me into IE for HTTPS??? > > (I'm tired and frustrated. I hate being forced to deal with proprietary > software.) > The Windows Web Folder mapping service is also "proprietary" : MS It can't handle HTTPS in XP so far. That HTTPS example on this page is from a Mac. -robert From aisaac0 at verizon.net Tue May 2 13:49:11 2006 From: aisaac0 at verizon.net (David Isaac) Date: Tue, 02 May 2006 17:49:11 GMT Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> Message-ID: <rYM5g.13332$O_6.7670@trnddc08> "John Salerno" <johnjsal at NOSPAMgmail.com> wrote in message news:8dM5g.2031$No6.43874 at news.tufts.edu... > Is there a way to assign multiple variables to the same value, but so > that an identity test still evaluates to False? Make sure the value is not a singleton. Assign them one at a time. >>> w=1000 >>> x=1000 >>> w==x True >>> w is x False >>> w=2 >>> x=2 >>> w==x True >>> w is x True Hope that helps, Alan Isaac From dale at riverhall.nospam.co.uk Tue May 9 03:40:23 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Tue, 09 May 2006 08:40:23 +0100 Subject: Enumerating Regular Expressions References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> Message-ID: <IHX7g.55413$hD6.14115@fe25.usenetserver.com> Any regular expression that has an asterisk in it has an infinite number of possible matches. If it has two asterisks, that's an infinite number squared and that's a really big number. You wouldn't want to print them out. blair.bethwaite at gmail.com wrote: > Hi all, > > Does anybody know of a module that allows you to enumerate all the > strings a particular regular expression describes? > > Cheers, > -Blair -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From struggleyb at gmail.com Wed May 10 11:13:57 2006 From: struggleyb at gmail.com (Bo Yang) Date: Wed, 10 May 2006 23:13:57 +0800 Subject: reusing parts of a string in RE matches? In-Reply-To: <YMm8g.2077$No6.45935@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> Message-ID: <44620335.6050204@gmail.com> John Salerno ??: > I probably should find an RE group to post to, but my news server at > work doesn't seem to have one, so I apologize. But this is in Python > anyway :) > > So my question is, how can find all occurrences of a pattern in a > string, including overlapping matches? I figure it has something to do > with look-ahead and look-behind, but I've only gotten this far: > > import re > string = 'abababababababab' > pattern = re.compile(r'ab(?=a)') > Below from the python library reference *|(?=...)|* Matches if ... matches next, but doesn't consume any of the string. This is called a lookahead assertion. For example, Isaac (?=Asimov) will match |'Isaac '| only if it's followed by |'Asimov'|. > m = pattern.findall(string) > > This matches all the 'ab' followed by an 'a', but it doesn't include the > 'a'. What I'd like to do is find all the 'aba' matches. A regular > findall() gives four results, but really there are seven. > > I try the code , but I give seven results ! > Is there a way to do this with just an RE pattern, or would I have to > manually add the 'a' to the end of the matches? > > Thanks. > From fredrik at pythonware.com Tue May 2 18:02:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 00:02:20 +0200 Subject: search file for tabs References: <1146606666.249084.12810@j73g2000cwa.googlegroups.com> Message-ID: <e38kte$v30$1@sea.gmane.org> beliavsky at aol.com wrote: > The following code to search a file for tabs does not work, at least on > Windows XP. Could someone please tell me what's wrong? Thanks. > > xfile = "file_with_tabs.txt" > for text in open(xfile,"r"): > text = text.strip() > if ("\t" in text): > print text since you're stripping away all leading and trailing whitespace from each line, you'll only find lines that have tabs "in the middle". (your code is only five lines long. don't you think you could have double- checked each line a couple of times, asking yourself "what exactly is this line doing", in less time than it took you to compose the mail ?) </F> From onurb at xiludom.gro Wed May 17 08:17:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 17 May 2006 14:17:05 +0200 Subject: Help System For Python Applications In-Reply-To: <1147837905.880754.145450@u72g2000cwu.googlegroups.com> References: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> <1147837905.880754.145450@u72g2000cwu.googlegroups.com> Message-ID: <446b14a8$0$7989$626a54ce@news.free.fr> BartlebyScrivener wrote: > At the commandline, run: > > pydoc -g > > In the interpreter: > > help("modulename") > > or help () > > for interactive. This is developper doc. I think the OP's talking about end-user doc. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From andrea at rediff.com Wed May 3 23:00:33 2006 From: andrea at rediff.com (andrea at rediff.com) Date: 4 May 2006 03:00:33 -0000 Subject: ISSPR2006_School_etc.:NEW_EXTENDED_Deadline Message-ID: <20060504030033.20276.qmail@rediff.com> REGISTER NOW FOR PATTERN RECOGNITION EVENTS THIS SUMMER, 2006 _______________________ 4TH INTERNATIONAL SUMMER SCHOOL ON PATTERN RECOGNITION (ISSPR, 2006) 23-28 JULY, UK http://www.PatternRecognitionSchool.com NEW...EXTENDED Early Bird Deadline for Registration. New Deadline 25th May 2006! and payments can be made Online CALL FOR PARTICIPATION The 4th International Summer School on Pattern Recognition will be organised at the University of Plymouth, UK (23-28 July, 2006). The school programme is listed below. Please pass on this email to your interested colleagues and students. This is a great summer school which I would recommend for everyone to attend. DEADLINE: Register BEFORE 01 MAY, 2006 through the website to get a discount on the fee. More than 100 participants in 2005! Speakers at the Summer School (ISSPR'2006) Dr. Sam Roberts Mathworks, UK (Introduction to Matlab) Prof. Wojtek Krzanowski University of Exeter, UK (Multivariate Statistics: Data Description) Dr. Mike Tipping, Microsoft Research, UK (Bayesian Pattern Recognition: Principles and Practice) Prof. Chris Bishop, Microsoft Research, UK (Latent Variables, Mixture Models and EM) Dr. Richard Everson, University of Exeter, UK (Dimensionality Reduction) Dr. Peter Tino University of Birmingham, UK (Probabilistic framework for model-based topographic map formation) Prof. Chris Williams, University of Edinburgh, UK (Neural Networks and Kernel Machines) Dr. Colin Campbell, University of Bristol, UK (Support Vector Machines and Kernel Methods: An Introduction and Review) Prof. John Shawe- Taylor, University of Southampton, UK (Kernel Based Methods) Dr. Steve Gunn, University of Southampton, UK (Matlab for Support Vector Machines) Prof. Mahesan Niranjan, University of Sheffield, UK (Classifier Performance Particle Filters for Tracking and Sequential Problems) Dr. Andrew Webb Qinetiq, UK (Decision TreesData Clustering) Prof. Xin Yao, University of Birmingham, UK (A Gentle Introduction to Evolutionary Computation; ATutorial on Evolutionary Multi-objective Optimisation) Dr. Richard Deardon, University of Birmingham, UK (Sequential Decision Making; Markov Chains Monte Carlo Methods) Dr. Jeremy Wyatt, University of Birmingham, UK (An Introduction to Reinforcement Learning) Dr. Ludmila Kuncheva, University of Wales, UK (Classifier Combination) Prof. Joseph Kittler, University of Surrey, UK (Feature Selection and Extraction) Prof. Sameer Singh, Loughborough University, UK (Multiresolution Pattern Recognition) Prof. Susan Craw, Robert Gordon University, UK (Case Based Reasoning) SUPPORTED BY: Microsoft, Springer, British Computer Society, and Mathworks. _______________________ IEEE CVPR CONFERENCE www.CVPR.org/2006 17-22 June, 2006 Registration Deadline is now 2nd of June, 2006 _______________________ 18th INTERNATIONAL CONFERENCE ON PATTERN RECOGNITION www.comp.hkbu.edu.hk/~icpr06 August 20-24, 2006 Early Bird Registration: 31 May, 2006 ______________________ Please see the event websites to get FULL information. Compiled by: Dr. Heather Mclleland From mblume at socha.net Fri May 12 14:01:32 2006 From: mblume at socha.net (Martin Blume) Date: Fri, 12 May 2006 20:01:32 +0200 Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> <44644a76$0$290$626a54ce@news.free.fr> <4464959f$1$13578$5402220f@news.sunrise.ch> <slrne69c7k.l3g.sybrenUSE@schuimige.stuvel.eu> <4464c789$1$13566$5402220f@news.sunrise.ch> <4464ca81$0$10968$626a54ce@news.free.fr> Message-ID: <4464ccda$1$13568$5402220f@news.sunrise.ch> "bruno at modulix" schrieb > > > > Well, if you're changing the original module, > Who's talking about "changing the original module" ? > Well, you have to apply @deco in the module where func_to_decorated is placed. > > > Isn't the point of a decorator to change the > > behavior externally, at runtime, possibly changing > > it in different ways at different places at > > different times? > > You're confusing the python specific @decorator > syntax with the OO design pattern by the same name. > This syntax is purely syntactic sugar > for a specific use case of higher order functions. > Yes, that explains my confusion. > > > So why this @deco notation? > > To improve readability. > > @decorator > def my_one_hundred_locs_func(): > ... > > is much more readable than: > def my_one_hundred_locs_func(): > ... > # 100 LOCS later > my_one_hundred_locs_func = decorator (my_one_hundred_locs_func) > That makes sense. > > Note that all this should be clear for anyone having > read the doc... > <blush> Errm, yes, you're so right. Thanks for reading the documentation to me and clearing this up :-) Martin From 63q2o4i02 at sneakemail.com Sun May 28 14:25:59 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 28 May 2006 11:25:59 -0700 Subject: Fancy GUI with Python Message-ID: <1148840759.152708.200750@u72g2000cwu.googlegroups.com> Hi all. I just downloaded and installed the new Office suite from MS with their new 'ribbon' based UI. I think it's pretty cool and AFT* for a new UI paradigm. I hope it sticks. Anyway, I'm wondering how to implement a gui like this with Python. I don't think wx or qt or gtk or tkinter support this sort of fading and glowing type of effects... or do they? I played with wx way back in 2000 or so (C++ version), and it certainly didn't have any of that. I don't know if this stuff is now built into XP, or if it's specialized libraries only accessible to MS for their purposes. Can a python gui framework be redirected to use the new gui? Or is this something that has to be manually emulated from a low-level if python is to make use of it? What about under linux? So I'm not sure if this is a Python question, a xxx-Python question (where xxx is the widget toolkit of choice), or a windows API type of question. How does one make fancy fading guis with python? (cross-platform if possible) thanks ms *AFT = about freakin' time From LittlePython at lost.com Tue May 30 20:22:30 2006 From: LittlePython at lost.com (LittlePython) Date: Wed, 31 May 2006 00:22:30 GMT Subject: Try/Except for ADSI GetObject Message-ID: <al5fg.9877$ho6.1459@trnddc07> I am a little confused on why I can not detect an object that does not exist with a try and except. If I understand ADSI correctly from what I have read you do not create these objects but rather get them. They already exist. I believe if I do the equivalent in VB I would generate an error when I try to get an object that does not exist (can not find). What have I done wrong? I have included the function below that works in ever respect but detecting incorrect NT Domain Names (objects that do not exist) . Any tips, insight or comments would be welcome by this newbie. Thx def CheckNT4(header, all): adsi = win32com.client.Dispatch('ADsNameSpaces') try: nt = adsi.GetObject('', "WinNT://"+ frm.NTName) #----->I need some type of try/except to detect incorrect NT Domain Names except: print "Domain name failed" # this does not detect a problem nt.Filter = ['user'] try: oSID = win32com.client.Dispatch('ADsSid') except: MyUsers = [ eauser for eauser in all if eauser[GetPostion(header, 'STATUS')] is ''] for ea in MyUsers: ea[GetPostion(header, 'STATUS')] = 'FailNT' ea[GetPostion(header, 'COMMENT')] ='Can not find ADsSid' MyUsers = [ eauser for eauser in all if eauser[GetPostion(header, 'STATUS')] is ''] intcnt = 0 for user in nt: for ea in MyUsers: if string.upper(user.Name) == string.upper(ea[GetPostion(header, 'OLDNTLOGON')]): frm.MyProgress.Update ( intcnt, 'Found NT user and SID : ' + user.Name ) intcnt = intcnt+ 1 if user.AccountDisabled: ea[GetPostion(header, 'STATUS')] = 'FailNT' ea[GetPostion(header, 'COMMENT')] ='Disabled' else: if ea[GetPostion(header, 'COMMENT')] is not '': ea[GetPostion(header, 'COMMENT')] = '' oSID.SetAs (5, "WinNT://"+ frm.NTName + '/' + user.Name) ea[GetPostion(header, 'STATUS')] = 'PassNT' ea[GetPostion(header, 'Nt4Sid')] = oSID.GetAs(1) for user in [ eauser for eauser in all if eauser[GetPostion(header, 'STATUS')] is '']: user[GetPostion(header, 'STATUS')] = 'FailNT' user[GetPostion(header, 'COMMENT')] = 'NoNt4Account' From vbgunz at gmail.com Thu May 11 15:13:46 2006 From: vbgunz at gmail.com (vbgunz) Date: 11 May 2006 12:13:46 -0700 Subject: find all index positions References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> Message-ID: <1147374826.341124.129260@g10g2000cwb.googlegroups.com> I thought this to be a great exercise so I went the extra length to turn it into a function for my little but growing library. I hope you enjoy :) def indexer(string, target): '''indexer(string, target) -> [list of target indexes] enter in a string and a target and indexer will either return a list of all targeted indexes if at least one target is found or indexer will return None if the target is not found in sequence. >>> indexer('a long long day is long', 'long') [2, 7, 19] >>> indexer('a long long day is long', 'day') [12] >>> indexer('a long long day is long', 'short') None ''' res = [] if string.count(target) >= 1: res.append(string.find(target)) if string.count(target) >= 2: for item in xrange(string.count(target) - 1): res.append(string.find(target, res[-1] + 1)) return res if __name__ == '__main__': print indexer('a long long day is long', 'long') # -> [2, 7, 19] print indexer('a long long day is long', 'day') # -> [12] print indexer('a long long day is long', 'short') # -> None From ramen at lackingtalent.com Thu May 11 18:09:35 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 11 May 2006 17:09:35 -0500 Subject: Time to bundle PythonWin Message-ID: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> Hey folks, Why is PythonWin (win32all) still a separate download from a third party? Is it legal, technical, or what? I think it's about time it be part of the standard distribution. There are many useful things that you ought to be able to do without downloading third-party libraries. Terminating a process, for example. Communicating with other applications via a standard, common protocol (COM). We demand these things from our UNIX environments--why do we tolerate their omission on the Windows platform? Mac libraries are bundled with Python's *standard library*. I'm not even advocating merging the win32 extensions with the standard library. All I'm saying is that when you install Python on Windows, it should ask you if you want to install PythonWin too, and that this option be selected by default. I write applications that use COM and Tkinter to automate basic office tasks. My users are thankfully benevolent enough to download and install Python on their own. They don't know what PythonWin is, they aren't remembering it, and frankly, I don't think it should be their concern. It's time to bundle PythonWin. -- .:[ dave benjamin -( ramen/sp00 )- http://spoomusic.com/ ]:. "we control the sun" - toys that kill From python.list at tim.thechases.com Thu May 25 07:54:44 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 25 May 2006 06:54:44 -0500 Subject: regex in python In-Reply-To: <1148551097.266423.141230@j55g2000cwa.googlegroups.com> References: <1148551097.266423.141230@j55g2000cwa.googlegroups.com> Message-ID: <44759B04.7090501@tim.thechases.com> > r = > re.compile(r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*') ... > sre_constants.error: nothing to repeat The error gives something away (like any good error message should) You're attempting to repeat something that may not exist. In this case, it's the last question-mark. The item before it (\d*) could be empty, and thus have "nothing to repeat". Simply removing the question-mark in question, making it r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*).*' has the same effect as desired (AFAIU) without the error. -tkc From lialie at 126.com Fri May 19 05:58:24 2006 From: lialie at 126.com (Lialie KingMax) Date: Fri, 19 May 2006 17:58:24 +0800 Subject: how to read a list from python in C? Message-ID: <446D96C0.2010100@126.com> Hi, all I am writing a C extension with .Net. Now I have a list of points, like [(0.0, 0.0), (2.0, 3.0), (random x, random y)....]. Is there a better way to translate it to an array than doing it one by one? Thanks From rkern at enthought.com Thu May 25 03:02:48 2006 From: rkern at enthought.com (Robert Kern) Date: Thu, 25 May 2006 02:02:48 -0500 Subject: determining available space for Float32, for instance In-Reply-To: <519D71619DEB5348BFCBC6AEBC3F9A03014E1180@exchsrv2.cseresearch.cs.washington.edu> References: <e505uf$hkq$1@sea.gmane.org> <519D71619DEB5348BFCBC6AEBC3F9A03014E1180@exchsrv2.cseresearch.cs.washington.edu> Message-ID: <e53kqm$dna$1@sea.gmane.org> David Socha wrote: > Robert Kern wrote: >>However, keeping track of the sizes of your arrays and the >>size of your datatypes may be a bit much to ask. > > Exactly. Building a duplicate mechanism for tracking this informaiton > would be a sad solution. Surely Python has access to the amount of > memory being used by the different data types. How can I get to that > information? I meant that you shouldn't bother doing any of this manually at all. *Using* such a mechanism is going to be a sad solution much less building a duplicate one. Instead, use a persistent data store like PyTables or possibly an SQL database (but I do recommend PyTables for your use-case). For numpy arrays, I showed you how to calculate the memory footprint (modulo the bytes for the actual Python structure itself that contains the metadata, but that's tiny compared to the actual array). I think there's a more general function that tries to guess the number of bytes used, but it's not terribly reliable, and I don't recommend its use. For example, how does one measure the memory footprint of a Python list? Do you count the memory footprint of each of the items? What if the items are repeated or shared between other objects? >>[snip] >>numpy (definitely not Numeric) does have a feature called >>record arrays which will allow you to deal with your agents >>much more conveniently: >> >> http://www.scipy.org/RecordArrays >> >>Also, you will certainly want to look at using PyTables to >>store and access your data. With PyTables you can leave all >>of your data on disk and access arbitrary parts of it in a >>relatively clean fashion without doing the fiddly work of >>swapping chunks of memory from disk and back again: >> >> http://www.pytables.org/moin > > Do RecordArrays and PyTables work well together? Yes. Currently, PyTables uses numarray's implementation of record arrays to represent HDF5 tables (which are essentially equivalent in structure to record arrays). It can interact with numpy record arrays just fine. Eventually, PyTables will be using numpy and numpy only. -- 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 eric_brunel at despammed.com Tue May 9 06:46:38 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Tue, 09 May 2006 12:46:38 +0200 Subject: Tkfont.families does not list all installed fonts References: <1147071305.425322.271490@j73g2000cwa.googlegroups.com> Message-ID: <ops895j0corqur0o@eb.pragmadev> On 7 May 2006 23:55:05 -0700, Atul <atul.nene at gmail.com> wrote: > Hi, > > I have installed a truetype font (.ttf) on a linux machne (SUSE linux > 10, KDE) by copying it to my .fonts folder. I can use the font in all > applications like open-office and firefox browser. > > However, I cannot use the font in a python app that I am writing. The > list returned by Tkfont.families does not contain this particular font. I don't know the Suse distro, but it seems on "modern" Linux distributions, there are 2 levels of font support: the first is the "native" X support, the second is provided by the graphical toolkit you're using (Qt with KDE, but I think OpenOffice & FireFox use Gtk). Unfortunately, tk - and therefore Tkinter - only sees the fonts at the X level, and not those at the Qt/Gtk level. But apparently, dropping your font file in your .fonts directory only makes the font available for Qt/Gtk, not for X. You can check that by running the command xlsfonts in a terminal: I really suspect your font will not appear in the list. To make the font visible at X level, you should make your .fonts directory a component of the X font path: - Go to your .fonts directory. - Check if the directory contains file named fonts.dir; If it does, check that the file contains a line referencing your .ttf file. If it does, skip the next 2 steps. - Create the fonts.scale file describing your TrueType fonts; this is done via a distribution-dependent utility, usually mkfontscale or ttmkfdir. - Create the fonts.dir file describing all the fonts in the directory by running mkfontdir in it. - Add the directory to you X font path by running the command: xset +fp ~/.fonts This last step is for testing purposes only, since its results won't survive your X session. You'll have to find a way to do it each time you log to your session, or each time your X server is restarted. You may also add your font file to a global font directory so that X will automatically see it when it starts (you'll have to rebuild the fonts.scale and fonts.dir files as above). HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From mail at microcorp.co.za Sun May 21 07:05:24 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Sun, 21 May 2006 13:05:24 +0200 Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com><e4fmkb$fn2$1@mlucom4.urz.uni-halle.de><1148002901.419641.326110@y43g2000cwc.googlegroups.com><Xns97C7D8A0ABE54castleamber@130.133.1.4><1148072317.975060.42970@j33g2000cwa.googlegroups.com><Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> Message-ID: <000201c67efc$20c86460$03000080@hendrik> on Friday, May 19, 2006 11:26 PM akameswaran at gmail.com wrote: | All I would ask is what objective evidence does either of actually | have? How can you know? What is a fair way to even count line | numbers? From there how do we begin to objectively measure software | quality? That's why this discussion interests me, and why I don't | understand why you are so adamant it doesn't work. I'll agree that I | have never seen line count/char count type data used for anything other | than marketing swill and kitty litter. Doesn't mean it can't be used. | But first things first... and this one I think is solvable - their has | got to be an equitable way to count how much code was written - maybe | it isn't lines maybe it is. In truth, since you are so opposed to the | idea, I'd be curious if you can think of a way to measure the quantity | of code objectively? ANd that's it - not can we make a qualitative | statement beyond that. But simply can we quanitfy the amount of code | in some fashion that allows a reasonable comparison? This is a difficult question - one way to measure - more or less objectively - is to somehow figure out how many machine instructions (on some "standard" machine - Turing?) would be generated by the code.... Even that won't tell us much - cos it will favour inline code as somehow "heavier" than looping code... Now we know that inline code is faster on most machines, and looping code is more compact, - so how to say what is best? And this only covers what you computer scientists call the "procedures" or "methods" - the actual instructions that are executed by the machine - how is the memory space used to be measured and factored in? - and the running stack space needed? - specially in the case of recursions.... And then how do you handle an interpreted language vs a compliled language - do you count the machine instructions of the interpreter, or only the ones actually executed? - and the memory consumed by the interpreter?..... - And if you count the interpreter, why not the compiler?... Not simple, not easy - in fact it's a minefield.... - Hendrik van Rooyen From nobody at 127.0.0.1 Tue May 2 15:53:58 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 19:53:58 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> Message-ID: <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> bruno at modulix wrote: > It is to be taken literally. Either you talk about how Python > effectively works or the whole discussion is useless. I started talking about the code-level view (programmer's perspective) so shorthand was fine. Now that we've moved on to interpreter/compiler-level stuff, I agree that more precision is warranted. > You skipped the interesting part, so I repost it and ask again: how > could the following code work without the instance being an explicit > parameter of the function to be used as a method ? > > def someFunc(obj): > try: > print obj.name > except AttributeError: > print "obj %s has no name" % obj > > import types > m = MyObj('parrot') > m.someMeth = types.MethodType(someFunc, obj, obj.__class__) > m.someMeth() I posted the only part that needs modification. Here it is again with the entire segment: class MyObj(object): ??def?__init__(name): ????self.name?=?name <== interpreter binds name 'self' to object instance. compiler adds 'self' to method sig as 1st param. def someFunc(obj): try: print obj.name <== 'obj' gets bound to first arg passed. when bound as a method, first arg will be object instance. when called as func, it will be first actual arg. except AttributeError: print "obj %s has no name" % obj import types m = MyObj('parrot') m.someMeth = types.MethodType(someFunc, obj, obj.__class__) <== binds obj to first parameter of someFunc as usual m.someMeth() > You see, wrapping a function into a method is not done at compile-time, > but at runtime. And it can be done manually outside a class statement. > In the above example, someFunc() can be used as a plain function. All the parameter information has been preserved. Method signatures are unchanged from their current form, so the interpreter has no trouble deducing arguments. You just don't actually declare self yourself. When binding a function to an object as above, the interpreter sees and does exactly the same thing as now. > This > wouldn't work with some automagical injection of the instance in the > function's local namespace, because you would then have to write > "method"'s code diffently from function's code. Maybe this will make it clearer: Programmer's view Compiler Interpreter's view def func (a, b) func (a, b) -> func (a, b) func (a, b) def method (a) method (a) -> method (self, a) method (self, a) IOW the compiler adds 'self' to the front of the parameter list when processing a method declaration. Interpreter sees the same signature as now, only programmer doesn't have to write 'self' anymore. >> And the rest should work fine. When the interpreter sees a method >> declaration, > > The interpreter never sees a 'method declaration', since there is no > such thing as a 'method declaration' in Python. The def statement > creates a *function* object: Fine, whatever, compiler sees method declaration, interpreter sees function object. The point is, the interpreter sees the same thing it does now. >> Complete non-sequitor, what does this have to do with self? > > It has to do that the obj.name() syntax doesn't imply a *method* call - > it can as well be a plain function call. Ok I see your point, but it doesn't matter because the interpreter sees the same function object as before. This confusion is partly (mostly? ;) my fault. I haven't been distinguishing precisely between the interpreter and the compiler because usually with Python it doesn't matter (in practice). This is clearly one place it does. In the words of Douglas Adams: We apologize for the inconvenience. > Also, and FWIW: >>>> def moduleFunc(): > ... print self.name > ... >>>> moduleFunc() > Traceback (most recent call last): > NameError: global name 'self' is not defined Exactly, that was my point in the first place. From pmartin at snakecard.com Fri May 12 14:56:55 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 12 May 2006 13:56:55 -0500 Subject: nix logon in Python References: <hx09g.9651$B42.5085@dukeread05> Message-ID: <XT49g.9689$B42.8207@dukeread05> Philippe Martin wrote: > Hi, > > Are there any (even prototypes/proof of concept) gdm/kdm/xdm.../-style > packages written in Python ? > > Regards, > > Philippe I guess to further define my problem: I am looking for clues as to how to launch an X11 session (remote or not) from a Python-TKinter-based application. I got (a few months ago) this hint from this NG but had to work on another project ... I'm now back into it and would like to know how to learn the basics. Thanks. """ There should be no problem with this. After all, even the "greeter" is just an X application. Depending on which login manager you use (xdm/kdm/gdm/whatever) the details of getting your Tkinter app to actually be run will vary, though. In gdm, it looks like adding it to the file /etc/X11/gdm/Init/default may be the ticket. It is probably best to run app.tk.call("rename", "send", "") in your program, for the reasons outlined in the send(n) manpage: SECURITY The send command is potentially a serious security loophole. On Unix, any application that can connect to your X server can send scripts to your applications. These incoming scripts can use Tcl to read and write your files and invoke subprocesses under your name. Jeff """ Regards, Philippe From leo at lspace.org Mon May 8 08:55:46 2006 From: leo at lspace.org (Leo Breebaart) Date: 8 May 2006 12:55:46 GMT Subject: Logging vs printing References: <4c6o1sF14hhjuU1@individual.net> <1147035825.643595.139800@e56g2000cwe.googlegroups.com> <4c8qroF14g6feU1@individual.net> <slrne5udla.30k.sybrenUSE@schuimige.stuvel.eu> Message-ID: <4c8teiF142m3nU1@individual.net> Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> writes: > Leo Breebaart enlightened us with: > > I think the main reason why I am not using [logging] by > > default is because, when all is said and done, it still comes > > easier to me to resort to guarded print statements then to > > set up and use the logging machinery. > > The logging "machinery" isn't that huge nor is it difficult to set up: > > ================================================== > import logging > > logging.basicConfig() > log = logging.getLogger('your.module.name') > ================================================== > > and that's all there is to it. I did say: "it comes easier *to me*" -- I am aware that my own tastes, which may not be shared by others, or be entirely logical, feature into this. Having said that, I do think it's also not *quite* as trivial as you claim. In order to duplicate what I already have ("if config.verbose: print msg"), I probably need to log at the DEBUG level, and I need to change the format so that that output looks like the 'print' output (no timestamping cruft etc.) Okay, you say, that's still easy. It's just: logging.basicConfig(level=logging.DEBUG, format='%(message)s') logging.debug('A debug message') And that's true, but I did have to go and look this up, and I made a couple of false starts first. I can only repeat that the workings of the logging framework are rarely intuitive to me. Also, assume that I have set it up as above. Now I want certain other print statements to go to sys.stderr alone. If I understand the docs correctly (possibly I don't), the way to do this is to start attaching explicit StreamHandlers and whatnot. Whereas with print, I can say "print >>sys.stderr, msg". I know that it won't take much for a script to become so complex that the extra stuff logging buys you vastly overpowers the convenience of the print statements. I have just not needed that often enough for it to become second nature to use in smaller scripts as well. -- Leo Breebaart <leo at lspace.org> From george.sakkis at gmail.com Sun May 14 22:09:24 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 14 May 2006 19:09:24 -0700 Subject: count items in generator References: <mailman.5686.1147646248.27775.python-list@python.org> Message-ID: <1147658964.209463.308680@j73g2000cwa.googlegroups.com> Delaney, Timothy (Tim) wrote: > George Sakkis wrote: > > > Paul Rubin wrote: > > > >> claird at lairds.us (Cameron Laird) writes: > >>> For that matter, would it be an advantage for len() to operate > >>> on iterables? > >> > >> print len(itertools.count()) > >> > >> Ouch!! > > > > How is this worse than list(itertools.count()) ? > > list(itertools.count()) will eventually fail with a MemoryError. > > Actually len(itertools.count()) would as well - when a couple of long > instances used up everything available - but it would take a *lot* > longer. > > Tim Delaney That's more of a theoretical argument on why the latter is worse. How many real-world programs are prepared for MemoryError every time they call list(), catch it and handle it graciously ? I'd say that the only reason an exception would be preferable in such case would be debugging; it's nice to have an informative traceback instead of a program that entered an infinite loop. George From rick446 at NOSPAM.usa.net Wed May 17 13:22:07 2006 From: rick446 at NOSPAM.usa.net (Richard Copeland) Date: Wed, 17 May 2006 13:22:07 -0400 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <1147885843.162424.133030@i40g2000cwc.googlegroups.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> <9bKdnakiGs9Cy_bZRVn-qw@comcast.com> <1147885843.162424.133030@i40g2000cwc.googlegroups.com> Message-ID: <No-dnWwTHKK3wfbZnZ2dnUVZ_s-dnZ2d@comcast.com> I tested the exact code I sent you on python 2.4.1. What version of Python are you using? Thanks, Rick Pierre wrote: > Nop I get the same AttributeError when I try to access to the property > "c"... > From spmok2 at canada.com Tue May 23 14:28:20 2006 From: spmok2 at canada.com (Joseph) Date: 23 May 2006 11:28:20 -0700 Subject: real time info to web browser from apache side ? Message-ID: <1148408900.176202.281530@g10g2000cwb.googlegroups.com> I know about writing CGI application using Perl and Apache to refresh a static webpage that displays on the browser. But now i have an application requirement that I hope someone can help me. The server side sits in another room down the factory plant, its monitoring some hardware environment, namely temperatures and pressures etc inside the plant. This server of course have Apache running. I would like to be able to have a browser in the comfortable office somewhere point to the apache server, and after I enter the password, it would display the temperature and pressures etc in the plant (in real time, ie. as the temperate changes from a degree to another, the browser will immediately display this). So I am looking more for a push technology than a pull from teh browser (user hit Ctrl-R to refresh is a pull). What are the current technology that allows for this. I know its possible because I can use my browser sometimes to chat with people online, and I swear that I don't have to do a Control-R everytime to see that the other person's typing is updating constantly on my browser. Thanks in advance, Push technology wannabe From andrew.arobert at gmail.com Tue May 16 13:30:33 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Tue, 16 May 2006 13:30:33 -0400 Subject: Option parser question - reading options from file as well as command line Message-ID: <126k3273j7kb28f@corp.supernews.com> Hi Everyone. I tried the following to get input into optionparser from either a file or command line. The code below detects the passed file argument and prints the file contents but the individual swithces do not get passed to option parser. Doing a test print of options.qmanager shows it unassigned. Any ideas? # # Parse command line options and automatically build help/usage # display # if len(sys.argv) == 2: infile= open(sys.argv[1],"rb").read() print infile parser=OptionParser( infile ) else: parser = OptionParser() parser.add_option("-m","--qmanager", dest="qmanager", help="\t\tQueue Manager to inquire against"), parser.add_option("-q","--queue", dest="queue", help="\t\tQueue the message will be sent to"), parser.add_option("-t","--to", dest="mto", help="\t\taddress any mail messages will be sent to") (options, args) = parser.parse_args() print options.qmanager From email at christoph-haas.de Wed May 31 17:28:14 2006 From: email at christoph-haas.de (Christoph Haas) Date: Wed, 31 May 2006 23:28:14 +0200 Subject: Save data to a file thru a http connection In-Reply-To: <20060531185853.GA5099@workaround.org> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> <20060531185853.GA5099@workaround.org> Message-ID: <20060531212814.GC5099@workaround.org> On Wed, May 31, 2006 at 08:58:53PM +0200, Christoph Haas wrote: > On Wed, May 31, 2006 at 11:37:47AM -0700, yinglcs at gmail.com wrote: > > I am new to python. I read an example here about how to fetch data thru > > a HTTP connection: > > http://diveintopython.org/http_web_services/review.html, > > > > My question is how can i save the data to a file after reading it from > > a http connection. > > Usually HTTP is read-only. There are extensions like WebDAV though that > may do what you need. Google for "python webdav" and see how far you get. Misunderstanding on my side. Ignore me. :) Christoph From ptmcg at austin.rr._bogus_.com Mon May 22 19:11:35 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 22 May 2006 23:11:35 GMT Subject: global name not defined References: <1148336761.776348.260450@j33g2000cwa.googlegroups.com> Message-ID: <Hyrcg.57779$CH2.30532@tornado.texas.rr.com> "NetKev" <kevin at netkev.com> wrote in message news:1148336761.776348.260450 at j33g2000cwa.googlegroups.com... > I added a function 'warn_Admin' and defined it just before another > function 'process_log'. 'process_log' calls this warn_Admin' function. > However, when it gets called i get the following error every time: > --- > Traceback (most recent call last): > File "/usr/bin/denyhosts.py", line 202, in ? > first_time, noemail, daemon) > File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line > 86, in __init__ > last_offset) > File "/usr/lib/python2.3/site-packages/DenyHosts/daemon.py", line 74, > in createDaemon > apply(func, args) > File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line > 137, in runDaemon > purge_time, purge_sleep_ratio) > File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line > 178, in daemonLoop > last_offset = self.process_log(logfile, last_offset) > File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line > 380, in process_log > [warn_Admin(ip) for ip in new_denied_hosts] > NameError: global name 'warn_Admin' is not defined > -- > If I take the two functions out of their current environment and store > them in test file and run it, it doesn't complain. I'm new to python > so I'm guessing there is some weird scope rule I am missing. I did try > 'self.warn_Admin(ip)' just to be safe but then I got a 'too many > arguments' error? > > I'm lost :) > > the added function plus the header of the existing function(its too > large): > ------------ > def warn_Admin(warn_ip): > SENDMAIL = "/usr/sbin/sendmail" # sendmail location > p = os.popen("%s -t" % SENDMAIL, "w") > p.write("To: kevin at netkev.com\n") > p.write("Subject: test from denyhosts\n") > p.write("\n") # blank line separating headers from body > p.write("Some text\n") > p.write(warn_ip) > sts = p.close() > if sts != 0: > info("Sendmail exit status: %s", sts) > return sts > > > def process_log(self, logfile, offset): > ------------- > > the call to warn_Admin from process_log: > --- > if new_denied_hosts: > info("new denied hosts: %s", str(new_denied_hosts)) > #[info(ip) for ip in new_denied_hosts] > [warn_Admin(ip) for ip in new_denied_hosts] > else: > debug("no new denied hosts") > > -kevin > Sounds like warn_Admin is defined within a class. a. could not resolve name when call was not qualified with "self." b. when called as "self.warn_Admin", name was resolved, but got "too many arguments" - this is because there was no explicit self argument in the definition of warn_Admin. It doesn't look like warn_Admin needs to be in the class. Move warn_Admin to module-level scope, outside of the class containing process_log, and see if things work better. -- Paul -- Paul From johnjsal at NOSPAMgmail.com Tue May 2 12:58:44 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 16:58:44 GMT Subject: simultaneous assignment Message-ID: <8dM5g.2031$No6.43874@news.tufts.edu> Is there a way to assign multiple variables to the same value, but so that an identity test still evaluates to False? e.g.: >>> w = x = y = z = False >>> w False >>> x False >>> w == x True >>> w is x True # not sure if this is harmful The first line above is the only way I know to do it, but it seems to necessarily lead to the true identity test. From usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo Sun May 21 06:38:35 2006 From: usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo (KW) Date: Sun, 21 May 2006 12:38:35 +0200 Subject: PHP's openssl_sign() using M2Crypto? References: <slrne6v5vk.f2c.usenet2@localhost.localdomain> Message-ID: <slrne70gpb.f6r.usenet2@localhost.localdomain> On 2006-05-20, KW wrote: > I'm trying to convert some PHP code using OpenSSL to Python and I'm stuck > on openssl_sign() which uses an RSA private key to compute a signature. I think basicly my question is: how do I extract the key from a private key in M2Crypto? Best regards, -- Konrad From OlafMeding at gmail.com Wed May 3 17:26:53 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 14:26:53 -0700 Subject: Because of multithreading semantics, this is not reliable. In-Reply-To: <mailman.5280.1146690817.27775.python-list@python.org> References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <mailman.5280.1146690817.27775.python-list@python.org> Message-ID: <1146691613.911363.242620@e56g2000cwe.googlegroups.com> Tim and Grant >>> if q.empty(): return >>> Of course you explanation is understood and ideally should be included as a note in the Python documentation. And the "not reliable" should be removed from the documentation! Anyway, many thanks for your explanations (I feel "safer" now). Olaf From rpdooling at gmail.com Tue May 2 19:09:25 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 2 May 2006 16:09:25 -0700 Subject: search file for tabs In-Reply-To: <mailman.5238.1146607658.27775.python-list@python.org> References: <1146606666.249084.12810@j73g2000cwa.googlegroups.com> <mailman.5238.1146607658.27775.python-list@python.org> Message-ID: <1146611365.777244.71280@i39g2000cwa.googlegroups.com> >> Patient: "Doctor! It hurts when I press here." >> Doctor: "Well don't press there" I told the doctor I broke my leg in two places. He told me to quit going to those places. --Henny Youngman rpd From 63q2o4i02 at sneakemail.com Wed May 17 13:44:55 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 17 May 2006 10:44:55 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <Xns97C65986E948Dduncanbooth@127.0.0.1> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> Message-ID: <1147887895.871827.313860@i40g2000cwc.googlegroups.com> I use Edit Plus for all my text-editing needs. With a simple shift-alt-i it faintly displays all spaces as little dots and all tabs as '>>' (but using the single ascii character instead). I use tabs to indent blocks, then if stuff within a block needs to be aligned (such as if statements or dictionaries), I used spaces. So this is mixing tabs and spaces, but the indentation level is always tabs. From luis_lupe2XXX at netvisaoXXX.pt Mon May 8 20:04:58 2006 From: luis_lupe2XXX at netvisaoXXX.pt (Luis P. Mendes) Date: Tue, 09 May 2006 01:04:58 +0100 Subject: ascii to latin1 Message-ID: <445fdc6c$0$15793$14726298@news.sunsite.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I'm developing a django based intranet web server that has a search page. Data contained in the database is mixed. Some of the words are accented, some are not but they should be. This is because the collection of data began a long time ago when ascii was the only way to go. The problem is users have to search more than once for some word, because the searched word can be or not be accented. If we consider that some expressions can have several letters that can be accented, the search effort is too much. I've searched the net for some kind of solution but couldn't find. I've just found for the opposite. example: if the word searched is 'televis?o', I want that a search by either 'televisao', 'televis?o' or even 't?l?visao' (this last one doesn't exist in Portuguese) is successful. So, instead of only one search, there will be several used. Is there anything already coded, or will I have to try to do it all by myself? Luis P. Mendes -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEX9yqHn4UHCY8rB8RAovDAJ90vllWjxfXN5bnNvg0OCKadbrfnwCfb4Hp 2jmRFyNYySukPwYACJ1TdM8= =hTr3 -----END PGP SIGNATURE----- From crankycoder at gmail.com Wed May 24 21:17:45 2006 From: crankycoder at gmail.com (Victor Ng) Date: Wed, 24 May 2006 18:17:45 -0700 Subject: Web frameworks and credit cards In-Reply-To: <37FBB44B-74F0-4EC7-A55E-3335E6CBFCEC@leafe.com> References: <37FBB44B-74F0-4EC7-A55E-3335E6CBFCEC@leafe.com> Message-ID: <a8bfd74c0605241817s22c3c8bbl1acc96d8b588d187@mail.gmail.com> Ed, Its very simple to add credit card processing to your app. I have personally used moneris , worldpay and debitech with no issues. Sometimes you need to do a little ctypes or pyrex but overall - its easy. On 5/24/06, Ed Leafe <ed at leafe.com> wrote: > I may have an opportunity to develop an online ordering system for a > client, and will have the ability to develop using any tool I choose. > Given the fact that there are more web frameworks in Python than > keywords ;-) , what I need to know is any experience anyone out there > has had integrating credit card processing with the various Python > web frameworks. Until now, my only practical experience is with Zope > 2.x, but I'm open to any and all alternatives, so long as it's Python! > > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com > > > > -- > http://mail.python.org/mailman/listinfo/python-list > -- "Never attribute to malice that which can be adequately explained by stupidity." - Hanlon's Razor From bignose+hates-spam at benfinney.id.au Tue May 2 19:34:35 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 03 May 2006 09:34:35 +1000 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> Message-ID: <87u088c86s.fsf@benfinney.id.au> Edward Elliott <nobody at 127.0.0.1> writes: > bruno at modulix wrote: > > class MyObj(object): > > def __init__(self, name): > > self.name = name > > class MyObj(object): > def __init__(name): > self.name = name So the tradeoff you propose is: - Honour "explicit is better than implicit", but users are confused over "why do I need to declare the instance in the method signature?" against - Break "explicit is better than implicit", take away some of the flexibility in Python, and users are confused over "where the heck did this 'self' thing come from?" or "how the heck do I refer to the instance object?" I don't see a net gain by going with the latter. -1. -- \ "Those who will not reason, are bigots, those who cannot, are | `\ fools, and those who dare not, are slaves." -- "Lord" George | _o__) Gordon Noel Byron | Ben Finney From bj_666 at gmx.net Mon May 29 16:48:34 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Mon, 29 May 2006 22:48:34 +0200 Subject: Need C# Coding for MD5 Algorithm... References: <1148884151.511656.81110@j73g2000cwa.googlegroups.com> Message-ID: <pan.2006.05.29.20.48.32.125423@gmx.net> In <1148884151.511656.81110 at j73g2000cwa.googlegroups.com>, Charleees wrote: > I need C# code for Implementing MD5 Algorithm.. Hope all would have > heard of MD5 Algorith... Does any one have the C# coding for that > Algorithm.. please Send... ITs URgent..... There's one in `System.Security.Cryptography`, no need to implement your own. You can get an MD5 `HashAlgorithm` object this way:: HashAlgorithm algorithm = HashAlgorithm.Create("MD5"); Ciao, Marc 'BlackJack' Rintsch From timr at probo.com Wed May 24 01:15:46 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 24 May 2006 05:15:46 GMT Subject: No math module?? References: <pan.2006.05.23.01.20.13.781679@none.none> <mailman.6094.1148352074.27775.python-list@python.org> <pan.2006.05.23.03.28.38.905789@none.none> Message-ID: <itq772dkbncaen04t68nrdk4l6pshsblpj@4ax.com> WIdgeteye <None at none.none> wrote: > >On Tue, 23 May 2006 12:40:49 +1000, Ben Finney wrote: > >Ok this is weird. I checked: >/usr/local/lib/python2.3/lib-dynload/math.so > >Just as you have on your system and it's there. >So why in the heck isn't it loading with: >import math ???? > >This is strange. Is the Python that you are running actually 2.3? Some Linux systems have both Python 1 and a Python 2 installed. Typing "python" at a command line often gets Python 1, because the vendor's configuration scripts assume that. However, that doesn't answer the question, because even Python 1.5 should have a module called "math". -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From j-waldby at pat7.com Mon May 1 21:02:22 2006 From: j-waldby at pat7.com (James Waldby) Date: Mon, 01 May 2006 19:02:22 -0600 Subject: set partitioning References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> <1146522121.798317.206180@i39g2000cwa.googlegroups.com> <1146523373.778624.142510@y43g2000cwc.googlegroups.com> Message-ID: <4456AF9E.ADF79BE@pat7.com> "hymort at hotmail.com" wrote: > Can someone tell me of a good algorithm to partition a set of n > elements into m non-empty, disjoint subsets, where each subset has > size k? and later wrote in a separate post > Also, if I do not care about the number of subsets, what is a good > algorithm to partition a set of n elements into non-empty, disjoint > subsets of size k? and then execrably wrote [ie, top-posted]: > Not quite what I'm looking for. I would like a list of all partitions > with each partition having k or less elements, not just one instance. when Aaron Watters wrote: > Something like this, or am I missing something? > > def partition(List, n, m, k): [snip Watters' program to partition set of n elements into m non-empty disjoint subsets, each of size k] So if n=3 and k=2 and set S={a,b,c}, you would want a list like the following? 1. {a},{b},{c} 2. {a,b},{c} 3. {a,c},{b} 4. {b,c},{a} So it appears you need to do 2 things - (1) Produce a list of additive partitions of n with numbers not exceeding k. In the S={a,b,c} example, the list contains (1,1,1) and (2,1). I think you can make the list with work O(T(n,k)). For values of T(n,k) (ie, "number of partitions of n in which the greatest part is k, 1<=k<=n") see http://www.research.att.com/~njas/sequences/A008284 . (2) For each list from (1), fill in elements from S into each of the subsets, in canonical order. (Eg, after filling in (1,1,1) to make {a},{b},{c}, don't produce {a},{c},{b} etc.) See a combinatorial algorithms book, eg Reingold, for this part. http://www.amazon.com/gp/product/013152447X/104-5966364-8396722?n=283155 -jiw From deets at nospam.web.de Mon May 1 17:30:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 01 May 2006 23:30:47 +0200 Subject: list*list In-Reply-To: <1146511951.257209.100260@e56g2000cwe.googlegroups.com> References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> <4bmotsF126gicU1@uni-berlin.de> <1146511951.257209.100260@e56g2000cwe.googlegroups.com> Message-ID: <4bnd07Fsfq9jU1@uni-berlin.de> Klaas schrieb: > Diez wrote: >> First of all: it's considered bad style to use range if all you want is a >> enumeration of indices, as it will actually create a list of the size you >> specified. Use xrange in such cases. > >> But maybe nicer is zip: >> c = [av * bv for av, bv in zip(a, b)] > > By your logic, shouldn't it also be "bad style" to create an > unnecessary list with zip instead of using izip? Yep. I always forget about the itertools. And then of course we'd go for an generator expression, won't we? Diez From bj_666 at gmx.net Wed May 3 02:01:12 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 03 May 2006 08:01:12 +0200 Subject: request help with Pipe class in iterwrap.py References: <pan.2006.05.02.00.56.56.146384@hastings.org> Message-ID: <pan.2006.05.03.06.01.10.796900@gmx.net> In <pan.2006.05.02.00.56.56.146384 at hastings.org>, Steve R. Hastings wrote: > What is the friendliest and most Pythonic way to write a Pipe class for > iterwrap? Maybe one with less "magic" syntax. What about using a function that takes the iterators and an iterable and returns an iterator of the chained iterators:: new_list = pipe(grep('larch'), grep('parrot', 'v')), list)(my_list) Ciao, Marc 'BlackJack' Rintsch From verec at mac.com Sun May 7 13:59:47 2006 From: verec at mac.com (verec) Date: Sun, 7 May 2006 18:59:47 +0100 Subject: algorithmic mathematical art References: <1146996866.280944.313050@y43g2000cwc.googlegroups.com> <9nelgqhh0dxf.thq8flk8fold$.dlg@40tude.net> Message-ID: <445e3594$0$25455$5a6aecb4@news.aaisp.net.uk> On 2006-05-07 12:31:47 +0100, Frank Buss <fb at frank-buss.de> said: >> anyway, today i ran into this page by Frank Bu? >> http://www.frank-buss.de/lisp/functional.html >> which used the idea in the book to render a traditional Escher's tiling >> piece. > > I should note that I've used the original paper from Peter Henderson, which > is cited in the book, too: > > http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#footnote_Temp_202 A very simple change to the code allows it to run on most platforms: 1. prefix Frank's code with: (defvar *ps-file* "/Users/verec/workspace/pictures/eisher.ps") where you replace the string literal with whatever hard coded path is right for your platform. 2. change plot so that it reads: (defun plot (p) " saves a picture as postscript and shows it" (with-open-file (s *ps-file* :direction :output :if-exists :supersede) (format s "500 500 scale~%") (format s ".1 .1 translate~%") (format s "0 setlinewidth~%") (format s "0 0 moveto 1 0 lineto 1 1 lineto 0 1 lineto 0 0 lineto~%") (dolist (line (funcall p '(0 0) '(1 0) '(0 1))) (destructuring-bind ((x0 y0) (x1 y1)) line (format s "~D ~D moveto ~D ~D lineto~%" (float x0) (float y0) (float x1) (float y1)))) (format s "stroke~%") (format s "showpage~%")) #+nil (sys:call-system "c:/gs/gs7.05/bin/gswin32.exe -g800x800 c:/tmp/test.ps") ) that is, the hard-coded path now refers to *ps-file*, and the OS specific call is commented out. 3. evaluate: (plot *fishes*) The resulting file is a plain PS file. On OS X you can view it with Preview, and even convert it to pdf if you so wish: http://lisp.jfb-city.co.uk/misc/eisher.pdf -- JFB From tim.golden at viacom-outdoor.co.uk Wed May 17 06:46:06 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Wed, 17 May 2006 11:46:06 +0100 Subject: Python script windows servcie Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1CD@vogbs009.gb.vo.local> [Mivabe] | Mivabe formulated the question : | > | > Google helped me discovering that it has something to do | something with | > 'CTRL_LOGOFF_EVENT'. I know what it means but i don't know | how to solve it. | > Is that something i have to configure in the script? | > | > I'n totally new to Python so maybe someone can point me to | the right | > direction? :D | > | > Regards, Mivabe | | No-one who can help me or did i visit the wrong group for this | 'problem'? I did start to formulate a reply of sorts, but got distracted. In short what you seem to be saying is: You have a python script (which happens to attach to a Jabber server, but that's really immaterial) and you've used SRVANY / INSTSRV to run it as a service, but then it stops running when something happens. It's not clear how the Remote Desktop part of things comes in -- are you installing the service when logged on a via RD? Or are you running Wildfire via RD? Whichever way round it is, the fact that it is a Python script doesn't seem terribly relevant. It sounds like its an issue to do with running something as a service via SRVANY and logging off a Remote Desktop session. This is not to be unfriendly -- I hope someone here can help -- but your description was sufficiently vague that I imagine many people -- like me -- couldn't quite work out what was happening, and so couldn't really help. 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 onurb at xiludom.gro Tue May 9 05:14:25 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 11:14:25 +0200 Subject: Memory leak in Python In-Reply-To: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> Message-ID: <44605dd1$0$2056$626a54ce@news.free.fr> diffuser78 at gmail.com wrote: > I have a python code which is running on a huge data set. After > starting the program the computer becomes unstable and gets very > diffucult to even open konsole to kill that process. What I am assuming > is that I am running out of memory. > > What should I do to make sure that my code runs fine without becoming > unstable. How should I address the memory leak problem if any ? I have > a gig of RAM. > > Every help is appreciated. Just a hint : if you're trying to load your whole "huge data set" in memory, you're in for trouble whatever the language - for an example, doing a 'buf = openedFile.read()' on a 100 gig file may not be a good idea... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Ericzhao82 at gmail.com Thu May 11 08:22:06 2006 From: Ericzhao82 at gmail.com (Eric.zhao.82) Date: 11 May 2006 05:22:06 -0700 Subject: Python memory deallocate In-Reply-To: <1147347601.597292.15220@j73g2000cwa.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <1147347601.597292.15220@j73g2000cwa.googlegroups.com> Message-ID: <1147350125.948424.242050@v46g2000cwv.googlegroups.com> O I see From jack at performancedrivers.com Fri May 5 23:35:06 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Fri, 5 May 2006 23:35:06 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Message-ID: <20060506033506.GA3374@performancedrivers.com> On Fri, May 05, 2006 at 05:26:26PM -0700, Xah Lee wrote: > Python, Lambda, and Guido van Rossum [snip] Foxtrot Oscar Alpha Delta Others have said banning this troll would be wrong or undemocratic but let's be sane: he has wasted hundreds of hours of other people's time and hurt newbies especially as they don't know well enough to ignore him. Killfile him at the source. Heck, filter every post with a [his domain omitted] domain in the body and make him spend an extra $10 to buy another domain before crossposting garbage. No one else in the world would links to him, so it is a safe bet. -Jack From leipold at ace-net.com Fri May 26 08:54:47 2006 From: leipold at ace-net.com (Walter S. Leipold) Date: Fri, 26 May 2006 08:54:47 -0400 Subject: Quote ? [was: John Bokma harassment] Message-ID: <E5F271CA3BECD511A5DB0040F60C8C89060543FF@bdcde0.ace-net.com> Chris Uppal (chris.uppal at metagnostic.REMOVE-THIS.org) wrote: > Geoffrey Summerhayes wrote: > > > After you kill Navarth, will it be nothing but gruff and deedle > > with a little wobbly to fill in the chinks? > > Where does that come from ? It sounds like a quote, > and Navarth is a Jack Vance name (and /what/ a character), > but I don't remember the rest of it occurring in Vance. Trullion: Alastor 2262, a planet with a collectivist, sort-of-communist government, a huge population, and a crumbling infrastructure -- 'gruff' and 'deedle' are sweet desserts much loved by the population. I think all three of the Alastor novels have been collected in a single volume... [click click click...] Yep, ISBN 0312869525. Classic Jack Vance, and well worth reading. -- Walt From me+python at modelnine.org Wed May 17 14:24:18 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 17 May 2006 20:24:18 +0200 Subject: Pyparsing: Grammar Suggestion. 2nd thought In-Reply-To: <3d00e6dc0605171105u3ff919ffke9e07b6b6f71dc08@mail.gmail.com> References: <3d00e6dc0605171105u3ff919ffke9e07b6b6f71dc08@mail.gmail.com> Message-ID: <200605172024.18470.me+python@modelnine.org> Am Mittwoch 17 Mai 2006 20:05 schrieb Khoa Nguyen: > ======== > On 2nd thought, I don't think this will check for the correct order of > the fields. For example, the following would be incorrectly accepted: > > f1,f5,f2 END_RECORD > > Thanks, > Khoa If I'm not completely mistaken, parsers written using PyParsing can accept a small superset of all languages that an N/DFA can accept, and as such PyParsing isn't a "general purpose" parsing toolkit (the latter implements matching of a subset of all languages a N/DSA can accept, think SLR, LR(1), LALR(1), GLR or the like), because it doesn't support the notion of left-/right-recursion (at least I didn't find anything like it back in the days when I had a look at PyParsing), but I might be wrong here. If I am, someone enlighten me. ;-) Anyway, the language you're trying to match here (along with more complex productions for the f's) is nothing that an NFA can ever match. So, either you use PyParsing to implement the "tokenization" for you, and postprocess using a handwritten parser (LL-parsers are easy to implement, and I'd guess a small LL-parser is sufficient for your needs), or you have a look at one of the available LR-parsing frameworks for Python, such as pyrr (which isn't the only one, by far). By the way: if you have a variable length argument list, such as: f1,f2,,,f5,f9,f12,... and there is no upper bound on the number of acceptable arguments, no parsing framework that doesn't accept context sensitive grammars (DSA) can ever verify the order for you. You'll have to do the verification of correct order in a later step, after the parsing has been done. --- Heiko. From tgl at sss.pgh.pa.us Mon May 15 17:21:32 2006 From: tgl at sss.pgh.pa.us (Tom Lane) Date: Mon, 15 May 2006 17:21:32 -0400 Subject: [HACKERS] Iterating generator from C (PostgreSQL's pl/python RETUN In-Reply-To: <1147725190.3790.37.camel@localhost.localdomain> References: <1147725190.3790.37.camel@localhost.localdomain> Message-ID: <14388.1147728092@sss.pgh.pa.us> Hannu Krosing <hannu at skype.net> writes: >> Sven Suursoho wrote: >>> As for testing in actual pl/python build environment, we had objections from >>> leading postgresql Tom Lane that even if we do test it at build time, >>> a determined DBA may substitute a buggy python.so later and still crash her DB instance. The above is a straw-man depiction of my point. What I said was that just because python is up-to-date on the system where plpython is *compiled* does not mean it'll be up-to-date on the system where plpython is *used*. With the increasing popularity of prebuilt packages (rpm, deb, etc), I think it's folly to use a build-time check for this. regards, tom lane From tdw at tdw.net Sun May 7 12:43:52 2006 From: tdw at tdw.net (Tim Williams) Date: Sun, 7 May 2006 17:43:52 +0100 Subject: printing list In-Reply-To: <G41117174.958.17.1@mx-extra.net> References: <G41117174.958.17.1@mx-extra.net> Message-ID: <9afea2ac0605070943y7459860dy4ee4cec785c0a1ca@mail.gmail.com> On 7 May 2006 09:15:10 -0700, compboy <compboyxyz at gmail.com> wrote: > How do you print elements of the list in one line? > > alist = [1, 2, 5, 10, 15] > > so it will be like this: > 1, 2, 5, 10, 15 > > because if I use this code > > for i in alist: > print i > > the result would be like this > > 1 > 2 > 5 > 10 > 15 >>> alist = [1, 2, 5, 10, 15] >>> print str(alist)[1:-1] 1, 2, 5, 10, 15 or not quite the same result >>> alist = [1, 2, 5, 10, 15] >>> for i in alist: ... print "%s," % i, 1, 2, 5, 10, 15, HTH :) From paolopantaleo at gmail.com Mon May 22 06:06:25 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Mon, 22 May 2006 12:06:25 +0200 Subject: Includeing Python in text files Message-ID: <83e8215e0605220306g26231a29r956e1d7db6d2e6ff@mail.gmail.com> I am working on this: I have a text file, containig certain section in the form <?py python code here py?> I parse the text file and substitute the python code with its result [redirecting sys.stdin to a StringIO]. It something like php or embedded perl. So my little toy works not bad, but I was wondering if such a feature already existed, if yes, can you point me out some links? Thnx PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From malvert at telenet.be Tue May 9 11:09:58 2006 From: malvert at telenet.be (malv) Date: 9 May 2006 08:09:58 -0700 Subject: Python editor recommendation. References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1147186782.792802.227170@g10g2000cwb.googlegroups.com> Message-ID: <1147187398.410726.111770@y43g2000cwc.googlegroups.com> Look at eric: http://www.die-offenbachs.de/detlev/eric3.html Editor is QScintalla I tried everithing and prefer eric. (it's free) malv From conor.robinson at gmail.com Wed May 10 18:36:25 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 10 May 2006 15:36:25 -0700 Subject: segmentation fault in scipy? In-Reply-To: <mailman.5569.1147300170.27775.python-list@python.org> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <mailman.5569.1147300170.27775.python-list@python.org> Message-ID: <1147300585.185111.322730@g10g2000cwb.googlegroups.com> If I run it from the shell (unix) I get: Segmentation fault and see a core dump in my processes. If I run it in the python shell I get as above: File "D:\Python24\Lib\site-packages\numpy\core\defmatrix.py", line 149, in __mul__ return N.dot(self, other) MemoryError I your experience as one of the dev of scipy, is this too much data? thank you From steven.bethard at gmail.com Tue May 9 16:51:42 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Tue, 09 May 2006 14:51:42 -0600 Subject: elementtidy, \0 chars and parsing from a string Message-ID: <mNednUAIsJJHnfzZnZ2dnUVZ_tednZ2d@comcast.com> So I see that elementtidy doesn't like strings with \0 characters in them: >>> import urllib >>> from elementtidy import TidyHTMLTreeBuilder >>> url = 'http://news.bbc.co.uk/1/hi/world/europe/492215.stm' >>> url_file = urllib.urlopen(url) >>> tree = TidyHTMLTreeBuilder.parse(url_file) Traceback (most recent call last): ... File "...elementtidy\TidyHTMLTreeBuilder.py", line 90, in close stdout, stderr = _elementtidy.fixup(*args) TypeError: fixup() argument 1 must be string without null bytes, not str The obvious solution would be to str.replace('\0', '') on the file's text, but I'm not sure how to ask elementtidy to parse from a string instead of a file-like object. Do I need to wrap it in a StringIO, or is there a better way? STeVe From johnjsal at NOSPAMgmail.com Sun May 14 18:59:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 14 May 2006 18:59:57 -0400 Subject: comparing values in two sets Message-ID: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> I'd like to compare the values in two different sets to test if any of the positions in either set share the same value (e.g., if the third element of each set is an 'a', then the test fails). I have this: def test_sets(original_set, trans_letters): for pair in zip(original_set, trans_letters): if pair[0] == pair[1]: return False return True zip() was the first thing I thought of, but I was wondering if there's some other way to do it, perhaps a builtin that actually does this kind of testing. Thanks. From hslee911 at yahoo.com Wed May 10 14:13:18 2006 From: hslee911 at yahoo.com (James) Date: 10 May 2006 11:13:18 -0700 Subject: syntax for -c cmd Message-ID: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> Wrong syntax is shown below. What should be the delimiter before else? python -c 'if 1==1: print "yes"; else print "no"' James From Michael.J.Fromberger at Clothing.Dartmouth.EDU Tue May 9 01:02:45 2006 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Tue, 09 May 2006 01:02:45 -0400 Subject: Enumerating Regular Expressions References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> <e3p46c$j21$1@zinnia.noc.ucla.edu> <1147148644.762057.238640@v46g2000cwv.googlegroups.com> <e3p74r$3ol$1@daisy.noc.ucla.edu> Message-ID: <Michael.J.Fromberger-9A8523.01024509052006@localhost> In article <e3p74r$3ol$1 at daisy.noc.ucla.edu>, James Stroud <jstroud at ucla.edu> wrote: > blair.bethwaite at gmail.com wrote: > > James Stroud wrote: > > > >>You mean like re.compile(r'.*') ? > > > > > > No. I mean like: > > > >>>>regex = re.compile(r'a|b') > >>>>regex.enumerate() > > > > a > > b > > You see the difficulty don't you? How will the computer know in advance > that the regex matches only a finite set of possible strings? You don't. Hence, you want something that behaves like a generator, and will produce the strings one at a time. Preferably, for the purposes of useful computation, in some canonical order. I'm sorry to say I don't know of an existing Python module to do this, although you could write one for at least the basic regular expression operators if you wanted. The basic problem isn't all that hard to solve, though the full generality of the re module's input syntax is far more expressive than truly "regular" expressions from language theory. Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From pydecker at gmail.com Wed May 17 10:57:25 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 17 May 2006 10:57:25 -0400 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <e4fcjr$ohq$1@sea.gmane.org> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <e4f8nr$8q9$1@sea.gmane.org> <ca55a9900605170639re1ad32co4164913a78d8f228@mail.gmail.com> <e4fas7$hlk$1@sea.gmane.org> <ca55a9900605170731mab99520id4ce4ae664bccb32@mail.gmail.com> <e4fcjr$ohq$1@sea.gmane.org> Message-ID: <ca55a9900605170757v55ab29aeu9dbcda6acaccc587@mail.gmail.com> On 5/17/06, Andy Sy <andy at neotitans.com> wrote: > > Uh, I should know better than to try to educate, but FYI: using the > > same argument construction and having it reach an invalid conclusion > > suffices to show that the original construction is invalid, and thus > > the original conclusion is suspect. > > > I guess this *REALLY* is how a misguided tab user exercises his 'logic': > Syntax replication (e.g. so-called 'argument construction') is enough, > semantics don't matter. > > ROTFLMAO! My instincts were correct: it is foolhardy to attempt to educate closed minds. <twitfilter status="on"> -- # p.d. From kevin at netkev.com Mon May 22 19:32:11 2006 From: kevin at netkev.com (NetKev) Date: 22 May 2006 16:32:11 -0700 Subject: global name not defined In-Reply-To: <Hyrcg.57779$CH2.30532@tornado.texas.rr.com> References: <1148336761.776348.260450@j33g2000cwa.googlegroups.com> <Hyrcg.57779$CH2.30532@tornado.texas.rr.com> Message-ID: <1148340731.742024.270290@j73g2000cwa.googlegroups.com> You are probably right and I think I will do so but just for the sake of my understanding of python...I noticed somthing. process_log takes two arguments when called but it's definition has 3 and one of them is "self". So I'm thinking if I modify my warn_Admin definition to include "self" and then call it from process_log with self.warn_Admin... it will work. This explains why I was getting the "too many arguments" error. From bdesth.quelquechose at free.quelquepart.fr Fri May 26 16:09:25 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 May 2006 22:09:25 +0200 Subject: __getattr__ and functions that don't exist In-Reply-To: <447648ab$1@nntp.zianet.com> References: <44762cf8$1@nntp.zianet.com> <1148596303.833301.15190@g10g2000cwb.googlegroups.com> <447648ab$1@nntp.zianet.com> Message-ID: <44773123$0$19180$626a54ce@news.free.fr> Erik Johnson a ?crit : (snip) > I was thinking it would be clean to maintain an interface where you > could call things like f.set_Spam('ham') and implement that as self.Spam = > 'ham' If all you want to do is to assign 'ham' to self.spam, just do it - no need for a setter. And if you worry about possible future needs for controlling assignement to spam, internally use another name for it or any other computation at this level, then it will be time to refactor obj.spam as a property: class Parrot(object): def _set_spam(self, value): self._another_attrib = any_computation_here(value) def _get_spam(self): return some_more_processing_here(self._another_attrib) spam = property(_get_spam, _set_spam) p = Parrot() p.spam = "ham" print p.spam > without actually having to define all the set_XXX methods for all the > different things I would want to set on my object (as opposed to just making > an attribute assignment), but I am starting to think that is probably an > idea I should just simply abandon. indeed. From aleaxit at yahoo.com Sat May 6 20:53:40 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 17:53:40 -0700 Subject: Splice two lists References: <1146961724.195038.18680@u72g2000cwu.googlegroups.com> Message-ID: <1hexgaa.u7dlyp1t1g80iN%aleaxit@yahoo.com> danmcleran at yahoo.com <danmcleran at yahoo.com> wrote: > Is there a good way to splice two lists together without resorting to a > manual loop? Say I had 2 lists: > > l1 = [a,b,c] > l2 = [1,2,3] > > And I want a list: > > [a,1,b,2,c,3] as the result. > > I've been searching around but I can't seem to find a good example. One way: result = 6*[None] result[0::2] = l1 result[1::2] = l2 Alex From roy at panix.com Mon May 15 13:24:36 2006 From: roy at panix.com (Roy Smith) Date: Mon, 15 May 2006 17:24:36 +0000 (UTC) Subject: Large Dictionaries References: <1147699064.107490@teuthos> <roy-765731.09112115052006@reader1.panix.com> <e4abj6$p6a$1@panix1.panix.com> Message-ID: <e4adgk$196$1@reader1.panix.com> Aahz <aahz at pythoncraft.com> wrote: > Don't forget that adding keys requires resizing the dict, which is a > moderately expensive operation. My guess would be that each resize grows the table by a constant factor, which IIRC, works out to amortized O(n). It's not as good as creating the dict the right size in the first place, but it's really not that bad. Somewhat more troubling is that it can lead to memory fragmentation problems. I don't understand why Python doesn't have a way to give a size hint when creating a dict. It seems so obvious to be able to say "d = dict (size=10*1000*1000)" if you know beforehand that's how many keys you're going to add. Looking at the docs, I'm astounded to discover that you can indeed do exactly that, but you get {size:10000000}. I am befuddled as to why people thought creating a dict by keyword would be a useful thing to do, but left out (and, indeed, eliminated the chance to add the syntax later) the obviously useful ability to hint at the size. I suppose we could still add: d = {} d.reserve (10*1000*1000) From sigzero at gmail.com Thu May 11 15:32:13 2006 From: sigzero at gmail.com (Robert Hicks) Date: 11 May 2006 12:32:13 -0700 Subject: 2 books for me In-Reply-To: <4462f24d$0$311$636a55ce@news.free.fr> References: <87lkt9ytxx.fsf@localhost.localdomain> <4462f24d$0$311$636a55ce@news.free.fr> Message-ID: <1147375933.114803.40870@q12g2000cwa.googlegroups.com> Wouldn't portability go with Tkinter since that is installed with every Python? Robert From kent at kentsjohnson.com Thu May 11 16:04:22 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 11 May 2006 16:04:22 -0400 Subject: glob() that traverses a folder tree In-Reply-To: <1147324439.841992.132710@q12g2000cwa.googlegroups.com> References: <1147308393.712592.233200@j73g2000cwa.googlegroups.com> <1147324439.841992.132710@q12g2000cwa.googlegroups.com> Message-ID: <4463983a$1_1@newspeer2.tds.net> seannakasone at yahoo.com wrote: > # i'm guessing os.walk() is the best way to traverse folder trees. > > import os, glob > > for dir, subdir, files in os.walk('.\InteropSolution'): > for file in files: > if glob.fnmatch.fnmatch(file,"*.dll") or > glob.fnmatch.fnmatch(file,"*.exe"): > print dir+file Or use Jason Orendorff's path module. For a single glob it is very easy: import path for f in path.path('.\InteropSolution').walkfiles('*.dll'): print f For multiple globs you have to work a little harder: for f in path.path('.\InteropSolution').walkfiles(): if f.fnmatch('*.dll') or f.fnmatch('*.exe'): print f or maybe for f in path.path('.\InteropSolution').walkfiles(): if f.ext in ['.dll', '.exe']: print f http://www.jorendorff.com/articles/python/path/index.html Kent From AbrahamLincolnIllinois at yahoo.com Sat May 27 09:43:40 2006 From: AbrahamLincolnIllinois at yahoo.com (AbrahamLincolnIllinois at yahoo.com) Date: 27 May 2006 06:43:40 -0700 Subject: "Learning Python" 2nd ed. p479 error? In-Reply-To: <1148663730.950031.219830@38g2000cwa.googlegroups.com> References: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> <1148663730.950031.219830@38g2000cwa.googlegroups.com> Message-ID: <1148737420.797074.59610@u72g2000cwu.googlegroups.com> Thanks for your help, guys. I'm convinced it is a bug, not a misunderstanding. I submitted it to the errata page at O'Reilly. Regards, Abraham From richie at entrian.com Mon May 15 11:01:35 2006 From: richie at entrian.com (Richie Hindle) Date: Mon, 15 May 2006 16:01:35 +0100 Subject: Making all string literals Unicode In-Reply-To: <4468432C.3030102@python.net> References: <e1gg625ci6792r2g3a337d6h5mrpcusm46@4ax.com> <4468432C.3030102@python.net> Message-ID: <tp5h62pd1ohdan92fcpuai3r94acn2mp09@4ax.com> [Richie] > is there a switch or an environment variable to > make Python treat all string literals as unicode? [Thomas] > python -U Ah! Thanks. (I see it's deliberately omitted from the documentation because pieces of the standard library don't work with it, which is quite reasonable and explains why I couldn't find it.) -- Richie Hindle richie at entrian.com From anthra.norell at tiscalinet.ch Fri May 12 12:21:57 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 12 May 2006 18:21:57 +0200 Subject: Replace References: <R40975357.427.5217.1@mx-extra.net><mailman.5419.1146921316.27775.python-list@python.org><u757g.202$NB6.173@trndny03><jssp529kre6g83fso3clj3ndf1s6t2dua2@4ax.com><ng1q52hgo2bjkp471d1jkbd52u7odfep47@4ax.com> <wpa7g.3081$923.1771@trndny02> Message-ID: <039001c675e0$30b796e0$0201a8c0@mcuf7> se = SE.SE (r' "~=.~=\=#') >>> se ('tyrtrbd =ffgtyuf == =tyryr =u=p ttttff') 'tyrtrbd =#fgtyuf =# =#yryr =#=# ttttff' I am in the final stages of documenting my stream editor SE. There are quite a few problems raised on this list which SE would handle elegantly. Where do I propose it for distribution? Frederic ----- Original Message ----- From: "Eric" <elw000 at verizonz.net> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Sunday, May 07, 2006 1:35 AM Subject: Re: Replace > On 2006-05-06, Dennis Lee Bieber wrote: > > On Sat, 06 May 2006 19:55:35 GMT, Dennis Lee Bieber > ><wlfraed at ix.netcom.com> declaimed the following in comp.lang.python: > > > > > >> splits = encData.split("#", 1) > > > > Whoops.... # => = > > > > Since there are only what, five, escaped characters, the use of a > > translate table seems somewhat overkill... A simple dictionary can be > > used... > > > > # pseudo-yENC decoder > > # ignores all of the protocol except for the > > # data portion decode > > > > d42 = "".join([chr((x - 42) % 256) for x in range(256)]) > > d64 = { "@" : "\0", > > "I" : "\t", > > "J" : "\n", > > "M" : "\r", > > "}" : "=" } > > e42 = "".join([chr((x + 42) % 256) for x in range(256)]) > > e64 = { "\0" : "=@", > > "\t" : "=I", > > "\n" : "=J", > > "\r" : "=M", > > "=" : "=}" } > > > > def decode(encData): > > segments = [] > > while True: > > splits = encData.split("=", 1) > > segments.append(splits[0]) > > if len(splits) == 1: break > > segments.append(d64[splits[1][0]]) > > encData = splits[1][1:] > > > > decData = "".join(segments).translate(d42) > > return decData > > > > def encode(decData): > > segments = [] > > encData = decData.translate(e42) > > while encData: > > pos = len(encData) > > > > nl = encData.find("\0") > > tb = encData.find("\t") > > lf = encData.find("\n") > > cr = encData.find("\r") > > eq = encData.find("=") > > > > if nl != -1: > > pos = min(pos, nl) > > if tb != -1: > > pos = min(pos, tb) > > if lf != -1: > > pos = min(pos, lf) > > if cr != -1: > > pos = min(pos, cr) > > if eq != -1: > > pos = min(pos, eq) > > > > segments.append(encData[:pos]) > > > > if pos < len(encData): > > segments.append(e64[encData[pos]]) > > encData = encData[pos+1:] > > > > return "".join(segments) > > > > > > if __name__ == "__main__": > > junk = """This is not > > the end of the silliness > > being inflicted upon the world of 183743ljf8734jflu807ur32""" > > > > morejunk = encode(junk) > > print morejunk > > > > print decode(morejunk) > > print > > > > tbl = "".join([chr(x) for x in range(256)]) > > > > print repr(tbl) > > print > > yetmore = encode(tbl) > > print repr(yetmore) > > print > > print repr(decode(yetmore)) > > I think you right about the d64 translation thing, it does seem like overkill. > I've been playin with sting.split(), came up with... > > def decode(encData): > segments = [] > splits = encData.split("=") > for i in range(len(splits)): > if i == 0: > segments.append(splits[0].translate(d42)) > else: > segments.append(splits[i][0].translate(d64) + splits[i][1:].translate(d42 > )) > > decoded = ''.join(segments) > return decoded > > string.split might be the way to go, this function almost decodes the test file > from the ydec site correctly. > -- > http://mail.python.org/mailman/listinfo/python-list From snail at objmedia.demon.co.uk Fri May 12 02:57:14 2006 From: snail at objmedia.demon.co.uk (Stephen Kellett) Date: Fri, 12 May 2006 07:57:14 +0100 Subject: Memory leak in Python References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <ccl062h5tc24b4qe3d66b7hvh7ujgrklcp@4ax.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> <1147252803.325579.151510@j33g2000cwa.googlegroups.com> <1147303585.301968.270590@i39g2000cwa.googlegroups.com> <1147357496.710958.164370@g10g2000cwb.googlegroups.com> Message-ID: <xDpEnwAKHDZEFw1S@objmedia.demon.co.uk> In message <1147357496.710958.164370 at g10g2000cwb.googlegroups.com>, Serge Orlov <Serge.Orlov at gmail.com> writes >The next step is to find out what type of objects contributes to the >growth most of all, Shame you aren't on Windows, as Python Memory Validator does all of this. >after that print several object of that type that >didn't exist on iteration N-1 but exist on iteration N And this, but for garbage collection generations. Stephen -- Stephen Kellett Object Media Limited http://www.objmedia.demon.co.uk/software.html Computer Consultancy, Software Development Windows C++, Java, Assembler, Performance Analysis, Troubleshooting From ibr at radix50.net Fri May 26 20:34:09 2006 From: ibr at radix50.net (Baurzhan Ismagulov) Date: Sat, 27 May 2006 02:34:09 +0200 Subject: logging In-Reply-To: <1148577240.250304.116360@j55g2000cwa.googlegroups.com> References: <mailman.6101.1148366215.27775.python-list@python.org> <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <mailman.6143.1148460752.27775.python-list@python.org> <1148577240.250304.116360@j55g2000cwa.googlegroups.com> Message-ID: <20060527003409.GB1975@radix50.net> Hello Vinay, On Thu, May 25, 2006 at 10:14:00AM -0700, Vinay Sajip wrote: > I don't know what your logger hierarchy looks like: you could perhaps > log to child loggers of l01 ("l01.XXX"), or set all other loggers you > use to have a CRITICAL level, or filter them using a filter which > filters out everything. Ok, here is my hierarchy: [formatters] keys=f01 [handlers] keys=console [loggers] keys=root,l01,l02 [formatter_f01] format=%(name)s: %(message)s [handler_console] class=StreamHandler args=[] formatter=f01 [logger_root] level=CRITICAL handlers=console [logger_l01] level=DEBUG qualname=l01 handlers=console [logger_l02] level=CRITICAL qualname=l02 handlers=console The program is: import logging import logging.config logging.config.fileConfig('a.conf') log1 = logging.getLogger('l01') log2 = logging.getLogger('l02') log1.debug('zzz') log2.debug('qqq') With the config above, I expect that zzz gets printed, and qqq doesn't. When I run the script, zzz is printed twice, and qqq isn't. I want that zzz is printed once. How do I do that? I can add a filter if this can't be done otherwise, however, I'm at the moment reluctant to do that since I don't see why CRITICAL for root passes zzz through and drops qqq correctly for l02. Thanks in advance, Baurzhan. From matt.good at gmail.com Fri May 19 11:57:41 2006 From: matt.good at gmail.com (Matt Good) Date: 19 May 2006 08:57:41 -0700 Subject: Python sqlite and regex. In-Reply-To: <mailman.5942.1148042842.27775.python-list@python.org> References: <mailman.5942.1148042842.27775.python-list@python.org> Message-ID: <1148054261.004682.310800@38g2000cwa.googlegroups.com> SQLite3 already has a REGEXP function, so you don't need to create your own. As Dan mentioned you also have a problem in your expression: 'aa.[0-9]) You need a closing quote on the expression, and you need to match the close paren with an open paren, or remove it. Also, in case you weren't aware, there will be a "sqlite3" module in Python 2.5 based on pysqlite 2.2: http://initd.org/tracker/pysqlite Using pysqlite will make it easier to move to the Python 2.5 sqlite3 module if that's important to you. -- Matt Good From fredrik at pythonware.com Fri May 5 11:03:17 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 May 2006 17:03:17 +0200 Subject: Is this a legal / acceptable statement ? References: <2AI6g.10201$9c6.5375@dukeread11><-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> <zvJ6g.10203$9c6.6603@dukeread11> Message-ID: <e3fpfm$eii$1@sea.gmane.org> Philippe Martin wrote: > l_init really is a boolean parameter and l_value a value that _might_ exist > in a shelve. > > So I just want to have a parameter to a method so if the first value tested > is false (l_init) then the second (l_value) does not get tested ... because > it is the second in the statement and only seems to get evaluated if the how do you look things up in the shelve ? </F> From fredrik at pythonware.com Mon May 29 15:53:04 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 May 2006 21:53:04 +0200 Subject: HTMLParser chokes on bad end tag in comment In-Reply-To: <4RHeg.103064$F_3.6208@newssvr29.news.prodigy.net> References: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> <mailman.6303.1148884549.27775.python-list@python.org> <4RHeg.103064$F_3.6208@newssvr29.news.prodigy.net> Message-ID: <e5fjev$dt8$2@sea.gmane.org> Edward Elliott wrote: > Guess you learn something new every day. Too bad there's so much illegal > code in the wild. :( if more people learned something new every day, the wild would look a lot different. </F> From kent at kentsjohnson.com Sat May 6 10:17:46 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Sat, 06 May 2006 10:17:46 -0400 Subject: Replace In-Reply-To: <IsS6g.711$re6.599@trndny04> References: <IsS6g.711$re6.599@trndny04> Message-ID: <445caf99$1_1@newspeer2.tds.net> Eric wrote: > I have a string... > > str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" > > I want to replace the characters after each '=', If you are replacing any char after = with # then re.sub() makes it easy: In [1]: import re In [2]: s = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" In [3]: re.sub('=.', '=#', s) Out[3]: 'tyrtrbd =#fgtyuf =# =#yryr =#=# ttttff' If the replacement char is not fixed then make the second argument to re.sub() be a callable that computes the replacement. PS str is not a good name for a string, it shadows the built-in str. Kent From paolopantaleo at gmail.com Tue May 23 10:58:56 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Tue, 23 May 2006 16:58:56 +0200 Subject: Includeing Python in text files In-Reply-To: <e4u0mn$ni8$1@sea.gmane.org> References: <mailman.6070.1148292392.27775.python-list@python.org> <4ddilkF18fs7bU1@uni-berlin.de> <e4u0mn$ni8$1@sea.gmane.org> Message-ID: <83e8215e0605230758x576f1d8eg188c82bd153d5d3b@mail.gmail.com> 2006/5/23, Chris Smith <mc_anjo at tamu.edu>: > Diez B. Roggisch wrote: > > Paolo Pantaleo wrote: > > > > > >>I am working on this: > >> > >>I have a text file, containig certain section in the form > >><?py > >> python code here > >>py?> > >> > >>I parse the text file and substitute the python code with its result > >>[redirecting sys.stdin to a StringIO]. It something like php or > >>embedded perl. > >> > >>So my little toy works not bad, but I was wondering if such a feature > >>already existed, if yes, can you point me out some links? > > > > > > Its a templating system, and there are a gazillion out there. Some of them > > are listed here: > > > > http://www.cherrypy.org/wiki/ChoosingATemplatingLanguage > > > > > > Diez > > > > > > > I'm just getting into programming so this may be a dumb question...but > why would you want to do this? What is templating good for? > > Chris > > -- > http://mail.python.org/mailman/listinfo/python-list > Well php is base on this principle, most (server side) dynamic sites are based on some template sistem PAolo -- if you have a minute to spend please visit my photogrphy site: http://mypic.co.nr From ark at acm.org Tue May 2 11:39:59 2006 From: ark at acm.org (Andrew Koenig) Date: Tue, 02 May 2006 15:39:59 GMT Subject: bug in modulus? References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> <4450928c$0$21107$626a54ce@news.free.fr> Message-ID: <j3L5g.18187$Fs1.621@bgtnsc05-news.ops.worldnet.att.net> "Christophe" <chris.cavalaria at free.fr> wrote in message news:4450928c$0$21107$626a54ce at news.free.fr... > jantod at gmail.com a ?crit : > Floating point numbers just don't have the required precision to represent > 2.0 - 1e-050. For your specific problem, if you really want the result to > be < 2.0, the the best you can do is admit that floating point operations > have errors and return 0.0 when the modulus operation equals 2.0. I disagree. For any two floating-point numbers a and b, with b != 0, it is always possible to represent the exact value of a mod b as a floating-point number--at least on every floating-point system I have ever encountered. The implementation is not even that difficult. From duncan.booth at invalid.invalid Wed May 17 03:54:33 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 May 2006 07:54:33 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> Message-ID: <Xns97C65986E948Dduncanbooth@127.0.0.1> achates wrote: > Duncan Booth wrote: > >>However the important thing is that a tab does >>not map to a single indentation level in Python: it can map to any >>number of indents, and unless I know the convention you are using to >>display the tabs I cannot know how many indents are equivalent to a >>tabstop. > > Sorry but this is just wrong. Python works out the indentation level > for a source file dynamically: see > http://docs.python.org/ref/indentation.html. The particular algorithm > it uses is designed to accommodate people who mix tabs and spaces > (which is unfortunate, and should probably be changed). Nevertheless, > using tabs only, one tab does indeed map to exactly one indentation > level. One tabstop == one indent, on your editor and on mine. Please be careful how much you trim. I also wrote: > Using spaces everywhere allows this, using tabs everywhere > allows this, mixing spaces and tabs is a bad thing. Yes, if you use tabs only tabs map to exactly one indentation level, but as soon as there is a mix it breaks horrible. The problem arises because in most situations there is no visual distinction between tabs and spaces so it isn't obvious when there is an accidental mix until things break. Fortunately Python is reasonably robust, and in most cases you will get a syntax error instead of a silent change to the meaning of the code. > You do not need to know my display convention to run my code. The Python interpreter does not know your display convention either: it assumes that tabs expand to 8 character boundaries. So long as you have pure tabs this doesn't matter, but if there is any mixing it means that any editor set to expand tabs to a different width will no longer display the indentation as the interpreter sees it. The problem is that although you are a tab purist (as I am a space purist), too many people out there are neither. If you set an editor to only insert spaces then it is unlikely to accidentally insert tabs, but if the editor is set up to do indentation with tabs then a naive user is still likely to use the space bar occasionally and then wonders why Python is complaining about an error when they can see (with their 4 space indents) that everything is indented correctly. From peace.is.our.profession at gmx.de Thu May 11 09:26:11 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Thu, 11 May 2006 15:26:11 +0200 Subject: redirecting print to a a file In-Reply-To: <FbWdnZOzBY-Bqv7ZnZ2dnUVZ_v2dnZ2d@comcast.com> References: <7JudnYwllewrrv7ZRVn-vA@comcast.com> <1147352171.658508.187490@y43g2000cwc.googlegroups.com> <FbWdnZGzBY9hqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> <slrne66ddp.d4s.sybrenUSE@schuimige.stuvel.eu> <FbWdnZOzBY-Bqv7ZnZ2dnUVZ_v2dnZ2d@comcast.com> Message-ID: <e3ve7q$cvu$1@mlucom4.urz.uni-halle.de> AndyL wrote: >> $ python some_program.py | tee output.log > Thx again. Python is cool, do that in C++ or Java :-) Yes, thats obviously true ;-) $> javac someprogram.java; $> java someprogram | tee output.log $> g++ someother.cpp -o someother $> ./someother | tee output.log SCNR, Mirco From scott.daniels at acm.org Mon May 8 19:59:15 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 16:59:15 -0700 Subject: utility functions within a class? In-Reply-To: <q%N7g.2062$No6.45493@news.tufts.edu> References: <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <USH7g.2052$No6.45672@news.tufts.edu> <SdI7g.2055$No6.45780@news.tufts.edu> <98uu52hiic72dtt9ibu0e7anfgndv6o8qb@4ax.com> <uQM7g.2060$No6.45697@news.tufts.edu> <445fa2c1$1@nntp0.pdx.net> <q%N7g.2062$No6.45493@news.tufts.edu> Message-ID: <445fd798$1@nntp0.pdx.net> John Salerno wrote: > Scott David Daniels wrote: >> John Salerno wrote: >>> ... But isn't there something about a single leading underscore >>> that doesn't import when you use from X import *? Or am I thinking of >>> something else? Is that also the double underscore? >> >> That has to do with module contents, and is a completely separate issue. >> If you define a module with a variable name '__all__' which is a list >> (or tuple) of strings, only module elements with those names will be >> imported with a "from module import *". If you fail to define the >> '__all__' element, all names which do not start with an underscore will >> be imported. > > Thanks, that's what I was thinking of. So it doesn't apply to the > contents within a class, just top-level contents? Precisely, a "from ... import *" only creates a bunch of names bound to a module's top-level contents (at the time of execution of the "from ... import *"), and does not affect anything about those bound values (except, of course, the refcount). -- -Scott David Daniels scott.daniels at acm.org From vbgunz at gmail.com Wed May 24 08:37:27 2006 From: vbgunz at gmail.com (vbgunz) Date: 24 May 2006 05:37:27 -0700 Subject: NEWB: how to convert a string to dict (dictionary) References: <1148449947.201179.116470@j55g2000cwa.googlegroups.com> Message-ID: <1148474247.755910.183720@38g2000cwa.googlegroups.com> I am sure something much more elaborate will show it's face but this I made in about 10 minutes. Didn't do much testing on it but it certainly does convert your string modeled after a dictionary into a real dictionary. You might wish to check against more variations and possibilities and tweak and learn till your heart is content... def stringDict(stringdictionary): ''' alpha! convert a string dictionary to a real dictionary.''' x = str(stringdictionary[1:-1].split(':')) res = {} for index, keyval in enumerate(x.split(',')): if index == 0: keyval = keyval[2:] if index % 2 == 0: y = keyval.lstrip(" '").rstrip("'\" ") res[y] = None else: z = keyval.lstrip(" \" '").rstrip("'") res[y] = z res[y] = z[:-2] print res # {'syllable': "u'cv-i b.v^ y^-f", 'ketiv-qere': 'n', 'wordWTS': "u'8'"} sd = "{'syllable': u'cv-i b.v^ y^-f', 'ketiv-qere': 'n', 'wordWTS': u'8'}" stringDict(sd) keep in mind the above code will ultimately return every value as a substring of the main string fed in so may not be very helpful when trying to save int's or identifiers. None the less, I hope it is useful to some degree :) From me+python at modelnine.org Wed May 17 11:19:25 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 17 May 2006 17:19:25 +0200 Subject: List behaviour In-Reply-To: <1147878414.819145.88580@i40g2000cwc.googlegroups.com> References: <1147878414.819145.88580@i40g2000cwc.googlegroups.com> Message-ID: <200605171719.25863.me+python@modelnine.org> Am Mittwoch 17 Mai 2006 17:06 schrieb barberomarcelo at gmail.com: > Maybe I'm missing something but the latter is not the behaviour I'm > > expecting: > >>> a = [[1,2,3,4], [5,6,7,8]] > >>> b = a[:] > >>> b > > [[1, 2, 3, 4], [5, 6, 7, 8]] > > >>> a == b > > True > > >>> a is b > > False > Try an: >>> a[0] is b[0] and >>> a[1] is b[1] here, and you'll see, that [:] only creates a shallow copy. Thus, the lists in the lists aren't copied, they are shared by the distinct lists a and b. Hope this clears it up. --- Heiko. From Serge.Orlov at gmail.com Thu May 11 00:59:21 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 10 May 2006 21:59:21 -0700 Subject: data entry tool References: <445f038f@news.maxnet.co.nz> <1147267750.833367.234180@v46g2000cwv.googlegroups.com> <446236d5@news.maxnet.co.nz> <1147291993.831470.156300@y43g2000cwc.googlegroups.com> Message-ID: <1147323561.625445.114010@i39g2000cwa.googlegroups.com> bearophileHUGS at lycos.com wrote: > If the data to be entered is simple and textual you can even think > about using a text only interface. The resulting program will be really > simple, and probably good enough. FWIW here is size of "Hello, world!" program distribution using different interfaces: text console: 1.2Mb web.py w/o ssl: 1.5Mb tkinter: 2.1Mb wxpython: 3.0Mb Getting more slim distributions requires some manual work From timothy.williams at nvl.army.mil Wed May 10 15:45:49 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 10 May 2006 12:45:49 -0700 Subject: can distutils windows installer invoke another distutils windows installer Message-ID: <1147290349.140963.201030@i39g2000cwa.googlegroups.com> Hi all. I have a package that uses other packages. I created a setup.py to use 'try:' and import to check if some required packages are installed. I have the tarballs and corresponding windows installers in my sdist distribution, so if I untar my source distribution and do 'python setup.py install', the script either untars the subpackages to a tmp directory and does an os.system('python setup.py install') (Linux), or os.system(<bdist_wininst installer>) (win32) for the missing subpackage. This seems to work fine, except that on Windows, I can't uninstall the main package with Windows 'Add or Remove Programs' from the control panel. If I install my main package with a bdist_winst installer, I can. Is there a way to set up a bdist_wininst installer to do what I can do with the source dist? Thanks in advance, ---- Tim Williams From email at christoph-haas.de Tue May 9 16:01:25 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 9 May 2006 22:01:25 +0200 Subject: How to recast integer to a string In-Reply-To: <1147203245.870258.64860@u72g2000cwu.googlegroups.com> References: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> <mailman.5523.1147202670.27775.python-list@python.org> <1147203245.870258.64860@u72g2000cwu.googlegroups.com> Message-ID: <20060509200125.GG21047@workaround.org> On Tue, May 09, 2006 at 12:34:05PM -0700, James wrote: > > Christoph Haas wrote: > > On Tue, May 09, 2006 at 12:17:34PM -0700, James wrote: > > > How to recast an integer to a string? > > > > > > something like > > > n = 5 > > > str = str + char(n) > > > > str(n) > > > > Kindly > > Christoph > > In python2,4, I 've got > TypeError: 'str' object is not callable What I meant was: string_from_number = str(n) Kindly Christoph From johnjsal at NOSPAMgmail.com Thu May 11 10:17:25 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 11 May 2006 14:17:25 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: <1147306546.383277.11820@j33g2000cwa.googlegroups.com> References: <YMm8g.2077$No6.45935@news.tufts.edu> <1147306546.383277.11820@j33g2000cwa.googlegroups.com> Message-ID: <VHH8g.2086$No6.45839@news.tufts.edu> Ben Cartwright wrote: > Yes, and no extra for loops are needed! You can define groups inside > the lookahead assertion: > > >>> import re > >>> re.findall(r'(?=(aba))', 'abababababababab') > ['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba'] Wow, that was like magic! :) From andychambers2002 at yahoo.co.uk Sat May 27 05:24:39 2006 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 27 May 2006 02:24:39 -0700 Subject: Running External Commands + Seeing when they are Finished In-Reply-To: <1148707745.744045.77770@g10g2000cwb.googlegroups.com> References: <1148707745.744045.77770@g10g2000cwb.googlegroups.com> Message-ID: <1148721879.618230.49710@y43g2000cwc.googlegroups.com> from os import * for cmd in ['adaware', 'spybot']: system(cmd) From akameswaran at gmail.com Sat May 27 02:47:46 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 26 May 2006 23:47:46 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <mailman.6269.1148709362.27775.python-list@python.org> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <mailman.6269.1148709362.27775.python-list@python.org> Message-ID: <1148712466.299743.209350@j73g2000cwa.googlegroups.com> Terry Reedy wrote: > > Are the dice identical or distinguishable (marked). In other words, with 2 > dice, is 1,2 the same as 2,1 or different? Note that in most dice games, > such as craps, the dice are not distinguished, but probability calculations > must treast them as if they were to get the elementary events. > they are distinct. This isn't necessarily about simulating a game. So yes the dice are marked and I want to track those different possibilties. From george.sakkis at gmail.com Wed May 17 13:14:41 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 17 May 2006 10:14:41 -0700 Subject: How to customize getattr(obj, prop) function ? References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> Message-ID: <1147886081.457370.52650@i39g2000cwa.googlegroups.com> Pierre wrote: > Hi, > > Sorry in advance, english is not my main language :/ > > I'd like to customize the result obtained by getattr on an object : if > the object has the requested property then return it BUT if the object > doesn't has actually this property return something else. > > In my case, I can't use getattr(object, property, default_value). > > I tried to write a class with a __getattr__ method and even a > __getattribute__ method but this doesn't do what I want.... > > Maybe I didn't correctly understand this : > http://docs.python.org/ref/attribute-access.html > > Here is a piece of my code : > ===================================== > class myclass: > """docstring""" > > a = 'aa' > b = 'bb' > > def __getattr___(self, ppt): > """getattr""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" 1) You have misspelled the method by adding a hard-to-spot third trailing underscore. 2) __getattr__ is called when normal lookup fails, so the condition evaluates always to False. > def __getattribute__(self, ppt): > """getattribute""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" 1) __getattribute__ is called for new-style classes only (those that inherit directly or indirectly from object). 2) Even if your class was new-style, this would enter an infinite loop because 'self.ppt' calls __getattribute__ again. George From softwindow at gmail.com Fri May 19 02:53:30 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 23:53:30 -0700 Subject: who can give me the detailed introduction of re modle? In-Reply-To: <mailman.5928.1148020361.27775.python-list@python.org> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> <mailman.5928.1148020361.27775.python-list@python.org> Message-ID: <1148021610.385296.26220@i39g2000cwa.googlegroups.com> thanks for your advice! :) From kkylheku at gmail.com Fri May 19 13:02:05 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 19 May 2006 10:02:05 -0700 Subject: number of different lines in a file In-Reply-To: <1147991237.732146.29350@j55g2000cwa.googlegroups.com> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <1147991237.732146.29350@j55g2000cwa.googlegroups.com> Message-ID: <1148058125.773912.180080@i39g2000cwa.googlegroups.com> Bill Pursell wrote: > Have you tried > cat file | sort | uniq | wc -l ? The standard input file descriptor of sort can be attached directly to a file. You don't need a file catenating process in order to feed it: sort < file | uniq | wc -l And sort also takes a filename argument: sort file | uniq | wc -l And sort has the uniq functionality built in: sort -u file | wc -l Really, all this piping between little utilities is inefficient bullshit, isn't it! All that IPC through the kernel, copying the data. Why can't sort also count the damn lines? There should be one huge utility which can do it all in a single address space. > sort might choke on the large file, and this isn't python, but it > might work. Solid implementations of sort can use external storage for large files, and perform a poly-phase type sort, rather than doing the entire sort in memory. I seem to recall that GNU sort does something like this, using temporary files. Naively written Python code is a lot more likely to choke on a large data set. > You might try breaking the file into > smaller peices, maybe based on the first character, and then > process them seperately. No, the way this is done is simply to read the file and insert the data into an ordered data structure until memory fills up. After that, you keep reading the file and inseting, but each time you insert, you remove the smallest element and write it out to the segment file. You keep doing it until it's no longer possible to extract a smallest element which is greater than all that have been already written to the file. When that happens, you start a new file. That does not happen until you have filled memory at least twice. So for instance with half a gig of RAM, you can produce merge segments on the order of a gig. From tomerfiliba at gmail.com Sun May 21 13:50:39 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 21 May 2006 10:50:39 -0700 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <mailman.6031.1148224219.27775.python-list@python.org> References: <mailman.6031.1148224219.27775.python-list@python.org> Message-ID: <1148233839.826012.174410@38g2000cwa.googlegroups.com> i wanted to suggest this myself. +1 -tomer From pain.and.cookies at gmail.com Mon May 1 18:45:58 2006 From: pain.and.cookies at gmail.com (pain.and.cookies at gmail.com) Date: 1 May 2006 15:45:58 -0700 Subject: python colorfinding In-Reply-To: <ifma5253nlp8i332p00lligdogekvedc1v@4ax.com> References: <1146442386.155633.297640@j73g2000cwa.googlegroups.com> <ifma5253nlp8i332p00lligdogekvedc1v@4ax.com> Message-ID: <1146523558.255802.293390@i39g2000cwa.googlegroups.com> sorry in a java app running on windows XP From brian at brianandkate.com Fri May 19 09:44:00 2006 From: brian at brianandkate.com (Brian Blazer) Date: Fri, 19 May 2006 08:44:00 -0500 Subject: noob import question In-Reply-To: <4d5vqaF18i4l1U1@uni-berlin.de> References: <mailman.5945.1148045097.27775.python-list@python.org> <4d5vqaF18i4l1U1@uni-berlin.de> Message-ID: <DB3DA882-103B-4AFF-ADFF-458070A8CD3C@brianandkate.com> Thank you for your responses. I had a feeling is had something to do with a namespace issue but I wasn't sure. You are right, I do come from a Java background. If it is poor form to name your class file the same as your class, can I ask what the standard is? Thanks again, Brian On May 19, 2006, at 8:33 AM, Diez B. Roggisch wrote: >> I have tried to look up what is going on, but I have not found >> anything. Would it be possible for someone to take a minute and give >> an explanation? > > The > > from <module> import <*|nameslist> > > syntax imports some or all names found in <module> into the current > modules > namespace. Thus you can access your class. > > But if you do > > import <module> > > you only get <module> in your current namespace. So you need to access > anything inside <module> by prefixing the expression. In your case, > it is > > Student.Student > > If you only write Student, that in fact is the MODULE Student, which > explains the error message. > > Now while this sounds as if the from <module> import * syntax is > the way to > go, you should refrain from that until you really know what you are > doing > (and you currently _don't_ know), as this can introduce subtle and > difficult to debug bugs. If you don't want to write long module- > names, you > can alias them: > > import <moduel-with-long-name> as <shortname> > > > And it seems as if you have some JAVA-background, putting one class > in one > file called the same as the class. Don't do that, it's a stupid > restriction > in JAVA and should be avoided in PYTHON. > > Diez > -- > http://mail.python.org/mailman/listinfo/python-list From paddy3118 at netscape.net Wed May 24 16:50:04 2006 From: paddy3118 at netscape.net (Paddy) Date: 24 May 2006 13:50:04 -0700 Subject: Using python for a CAD program In-Reply-To: <447430f8$0$22978$c83e3ef6@nn1-read.tele2.net> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <e4ham3$1td$1@sea.gmane.org> <446C8950.3070107@anansispaceworks.com> <mailman.6000.1148109587.27775.python-list@python.org> <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> <mailman.6062.1148282177.27775.python-list@python.org> <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> <1148404366.743786.258280@u72g2000cwu.googlegroups.com> <447430f8$0$22978$c83e3ef6@nn1-read.tele2.net> Message-ID: <1148503804.153537.324180@i40g2000cwc.googlegroups.com> I guess the 'advanced O/R mapping tools' make it easier to map the data to an RDBMS, but their is still the performance issue. Since this has degenerated into a an issue of performance then I suggest the original poster create a clear interface between his data and its persistance method. This should make it easier to attach another, if his first choice is not up to it. - Cheers, Pad. From r.pellegrini at gmail.com Mon May 29 06:05:23 2006 From: r.pellegrini at gmail.com (Rocco) Date: 29 May 2006 03:05:23 -0700 Subject: why not in python 2.4.3 In-Reply-To: <1148870627.058561.12800@y43g2000cwc.googlegroups.com> References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> <r94k725bfor7ssate10bd5veld2v6q6mm0@4ax.com> <1148851375.148311.320780@g10g2000cwb.googlegroups.com> <1148870627.058561.12800@y43g2000cwc.googlegroups.com> Message-ID: <1148897123.135779.91870@j33g2000cwa.googlegroups.com> Also with ascii the function does not work. From kay.schluehr at gmx.net Wed May 24 12:25:28 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 24 May 2006 09:25:28 -0700 Subject: John Bokma harassment In-Reply-To: <1148482679.779623.211680@g10g2000cwb.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <1148482679.779623.211680@g10g2000cwb.googlegroups.com> Message-ID: <1148487928.876590.322870@u72g2000cwu.googlegroups.com> bradb wrote: > > C'mon, John Bokma (and everyone else dumb enough to crosspost their > > shushing to every group on the crosspost list -- why do they do that? So > > Xah will hear them six times? No, they want everyone to see how witty > > they are when they tell Xah off. Now /that/ is spam) is the problem. > > > > kenny > > I agree. It is not Xah who is the problem, but the 200 replies to him > telling him to go away. To make a witty comment: Xah starts flamewars and people really *do* like to contribute although they find it awfull. Xah is the star, who undresses his mind. But good and sensitive people don't like liking to contribute in those nasty battles and believe their time is deserved to something less wastefull. I mildly disagree with attitude and tend to think that most serious work is a waste of time. Xah lets people really do what they want: ranting about other programming languages, ranting about programming language communities ( which are mostly boring and awfull but that's kind of a familiy thing: my family is boring and awfull too but when being attacked it's still my family ) and ranting about trolls that let them do what they want. Everything in the name of Xah the lord of misrule. If any language community was actually cool - unfortunetaly there is none - they would invite Xah to write essays for them. A kind of weekly "Xah commentary" on the state of the language ( and of course its documentation and other languages etc. ). Maybe it would evolve quite fine if Xah could be pacified? From nobody at 127.0.0.1 Wed May 3 13:22:56 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 17:22:56 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <4457fc52$0$31159$636a55ce@news.free.fr> <445874fe$0$12865$626a54ce@news.free.fr> Message-ID: <QF56g.72398$H71.7518@newssvr13.news.prodigy.com> bruno at modulix wrote: > And of course propose an implementation - perhaps the compiler.ast could > be useful ? Ugh. Just when I thought I'd seen my last abstract syntax tree, one rears its ugly head. From Serge.Orlov at gmail.com Sun May 7 04:08:23 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 7 May 2006 01:08:23 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> Message-ID: <1146989302.961178.91070@y43g2000cwc.googlegroups.com> Bill Atkins wrote: > "Serge Orlov" <Serge.Orlov at gmail.com> writes: > > > Ken Tilton wrote: > >> It is vastly more disappointing that an alleged tech genius would sniff > >> at the chance to take undeserved credit for PyCells, something probably > >> better than a similar project on which Adobe (your superiors at > >> software, right?) has bet the ranch. This is the Grail, dude, Brooks's > >> long lost Silver Bullet. And you want to pass????? > >> > >> C'mon, Alex, I just want you as co-mentor for your star quality. Of > >> course you won't have to do a thing, just identify for me a True Python > >> Geek and she and I will take it from there. > >> > >> Here's the link in case you lost it: > >> > >> http://www.lispnyc.org/wiki.clp?page=PyCells > >> > >> :) > >> > >> peace, kenny > >> > >> ps. flaming aside, PyCells really would be amazingly good for Python. > >> And so Google. (Now your job is on the line. <g>) k > > > > Perhaps I'm missing something but what's the big deal about PyCells? > > Here is 22-lines barebones implementation of spreadsheet in Python, > > later I create 2 cells "a" and "b", "b" depends on a and evaluate all > > the cells. The output is > > > > a = negate(sin(pi/2)+one) = -2.0 > > b = negate(a)*10 = 20.0 > > > > =================== spreadsheet.py ================== > > class Spreadsheet(dict): > > def __init__(self, **kwd): > > self.namespace = kwd > > def __getitem__(self, cell_name): > > item = self.namespace[cell_name] > > if hasattr(item, "formula"): > > return item() > > return item > > def evaluate(self, formula): > > return eval(formula, self) > > def cell(self, cell_name, formula): > > "Create a cell defined by formula" > > def evaluate_cell(): > > return self.evaluate(formula) > > evaluate_cell.formula = formula > > self.namespace[cell_name] = evaluate_cell > > def cells(self): > > "Yield all cells of the spreadsheet along with current values > > and formulas" > > for cell_name, value in self.namespace.items(): > > if not hasattr(value, "formula"): > > continue > > yield cell_name, self[cell_name], value.formula > > > > import math > > def negate(x): > > return -x > > sheet1 = Spreadsheet(one=1, sin=math.sin, pi=math.pi, negate=negate) > > sheet1.cell("a", "negate(sin(pi/2)+one)") > > sheet1.cell("b", "negate(a)*10") > > for name, value, formula in sheet1.cells(): > > print name, "=", formula, "=", value > > > > I hope Ken doesn't mind me answering for him, but Cells is not a > spreadsheet (where did you get that idea?). It's written on the page linked above, second sentence: "Think of the slots as cells in a spreadsheet, and you've got the right idea". I'm not claiming that my code is full PyCell implementation. > It does apply the basic > idea of a spreadsheet to software - that is, instead of updating value > when some event occurs, you specify in advance how that value can be > computed and then you stop worrying about keeping it updated. The result is the same. Of course, I don't track dependances in such a tiny barebones example. But when you retrieve a cell you will get the same value as with dependances. Adding dependances is left as an exercise. > > Incidentally, is this supposed to be an example of Python's supposed > "aesthetic pleasantness"? Nope. This is an example that you don't need macros and multi-statements. Ken writes: "While the absence of macros and multi-statement lambda in Python will make coding more cumbersome". I'd like to see Python code doing the same if the language had macros and multi-statement lambda. Will it be more simple? More expressive? > I find it a little hideous, even giving you > the benefit of the doubt and pretending there are newlines between > each function. There's nothing like a word wrapped in pairs of > underscores to totally ruin an aesthetic experience. I don't think anyone who is not a master of a language can judge readability. You're just distracted by insignificant details, they don't matter if you code in that language for many years. I'm not going to tell you how Lisp Cell code looks to me ;) > P.S. Is this really a spreadsheet? It looks like it's a flat > hashtable... Does it matter if it's flat or 2D? From conor.robinson at gmail.com Wed May 10 23:34:59 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 10 May 2006 20:34:59 -0700 Subject: segmentation fault in scipy? In-Reply-To: <mailman.5572.1147304930.27775.python-list@python.org> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <mailman.5571.1147301063.27775.python-list@python.org> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <mailman.5572.1147304930.27775.python-list@python.org> Message-ID: <1147318499.764838.243020@u72g2000cwu.googlegroups.com> Im using rprop (not dependent on error function in this case ie. standard rprop vs. irprop or arprop) for an MLP tanh, sigmod nnet as part of a hybrid model. I guess I was using a little Matlab thought when I wrote the SSE funtion. My batches are about 25,000 x 80 so my absolute error (diff between net outputs and desired outputs) when using *one* output unit is shape(~25000,), am I wrong to assume trace(error*transpose(error)) is the sum of the squared errors which should be an shape(1,)? I'm just now starting to dig a little deeper into scipy, and I need to get the full doc. Thanks for all your input. From phddas at yahoo.com Thu May 4 18:15:12 2006 From: phddas at yahoo.com (Gary Wessle) Date: 05 May 2006 08:15:12 +1000 Subject: scope of variables References: <874q06bz4c.fsf@localhost.localdomain> <pan.2006.05.03.21.37.01.804277@hastings.org> <87zmhyagqq.fsf@localhost.localdomain> <mailman.5292.1146698030.27775.python-list@python.org> <87lktinmp2.fsf@localhost.localdomain> <4459d59d$0$27055$626a54ce@news.free.fr> Message-ID: <87odydo2rz.fsf@localhost.localdomain> thank you From durumdara at mailpont.hu Mon May 15 03:45:50 2006 From: durumdara at mailpont.hu (Christian Stooker) Date: Mon, 15 May 2006 09:45:50 +0200 Subject: Unicode to DOS filenames (to call FSUM.exe) Message-ID: <446831AE.8040802@mailpont.hu> Hi ! Yesterday I got a very interesting bug. I don't understand, why I got it, because I thinking about this function: that is safe. But I was not. The code: import sys,os UFN=u'%s\\xA\xff'%os.getcwd() if os.path.exists(UFN): os.remove(UFN) f=open(UFN,'w') f.write('%s\n'%('='*80)) f.close() import win32api dfn=win32api.GetShortPathName(UFN) sys.exit() ################################################### Commandline: C:\Python24\python.exe G:\SPEEDT~1\Module1.py Workingdirectory: G:\speedtest Timeout: 0 ms Traceback (most recent call last): File "G:\SPEEDT~1\Module1.py", line 14, in ? dfn=win32api.GetShortPathName(UFN) UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 15: ordinal not in range(128) Process "Pyhton Interpeter" terminated, ExitCode: 00000001 ################################################### I want to get the sorter file name to pass it the FSUM.exe. But I got this error in every machine. How to I avoid this error ? I need very safe code for my program. Thanx for help: dd From andrew.arobert at gmail.com Sat May 20 17:49:28 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sat, 20 May 2006 17:49:28 -0400 Subject: 'error reading datastream' -- loading file only when transfer is complete? In-Reply-To: <1148159335.678868.22850@j73g2000cwa.googlegroups.com> References: <1148159335.678868.22850@j73g2000cwa.googlegroups.com> Message-ID: <126v3nsag5bcqdb@corp.supernews.com> liuliuliu at gmail.com wrote: > hello -- > > i'm running python/pygame on maemo (nokia 770). my situation is that > i'm continually scouring this one directory for incoming files. if i > see if there's a new file (coming in via wireless scp), i proceed to > load it and process it. > > however, i think i am running into the issue that my program starts to > load the file after it recognises there is new data, but before the > file has completely transferred, so at unpredictable times i get a > pygame.error: Error reading from datastream. > > what is the easiest way to work out this issue? easy being the key > word. :) thank you very much! > > christine > You might want to test for file locking before attempting to use From tjreedy at udel.edu Tue May 9 14:55:45 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 9 May 2006 14:55:45 -0400 Subject: Is there any plan to port python to ACCESS Palm Linux Platform? References: <1147152028.828197.196790@j73g2000cwa.googlegroups.com> <4cbbanF14dkunU1@uni-berlin.de> Message-ID: <e3qojh$pqi$1@sea.gmane.org> > heidan wrote: > >> Another quick question about python and palm? >> As we all have known that ACCESS has planned to build Palm OS on top of >> Linux, is there any plan to port python to THIS future PALM OS? If will happen if and when someone volunteers to do a port if and when Access releases such a Linux version. From michael at elehack.net Fri May 5 14:12:28 2006 From: michael at elehack.net (Michael Ekstrand) Date: Fri, 5 May 2006 13:12:28 -0500 Subject: to thine own SELF be true... In-Reply-To: <cEL6g.73268$H71.7968@newssvr13.news.prodigy.com> References: <cEL6g.73268$H71.7968@newssvr13.news.prodigy.com> Message-ID: <20060505181228.GD27583@localhost.localdomain> On Fri, May 05, 2006 at 05:08:24PM +0000, Mark Harrison wrote: > Is there a way to get rid of those the "self." references, or is this > just something I need to get my brain to accept? It's pretty much just something you'll need to get your brain to accept. You can replace self with something shorter, like s, but that's sure to cause mass confusion for other people who try to read your code. I, however, find that the self. references are a great benefit to readability, as it makes the scope of a variable quite easy to tell. A lot of my C++ code is littered with `this->' or similar explicit-scope-description things... - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From me+python at modelnine.org Tue May 2 17:37:41 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 23:37:41 +0200 Subject: data regex match In-Reply-To: <e38j93$md1$1@sea.gmane.org> References: <87r73cdtmk.fsf@localhost.localdomain> <200605022327.57422.me+python@modelnine.org> <e38j93$md1$1@sea.gmane.org> Message-ID: <200605022337.41450.me+python@modelnine.org> Am Dienstag 02 Mai 2006 23:34 schrieb Fredrik Lundh: > Heiko Wundram wrote: > > As always, use a raw string for regular expressions. \d is being > > interpreted to mean an ascii character, and not to mean the character > > class you're trying to reference here. > > \d isn't an ASCII character, but \1 is. > > >>> print '(\d{2})/\1/\1\1' I tried that just know. Didn't know that \[a-z] weren't all interpreted as escape sequences... Seems like I learn something every day. ;-) --- Heiko. From nvasiliev at whiteriversoft.com Thu May 11 18:24:27 2006 From: nvasiliev at whiteriversoft.com (Nicolay A. Vasiliev) Date: Fri, 12 May 2006 02:24:27 +0400 Subject: MySQLdb trouble In-Reply-To: <499362p7mj6ukup03tipcisr6e6kojs83m@4ax.com> References: <mailman.5547.1147249433.27775.python-list@python.org> <499362p7mj6ukup03tipcisr6e6kojs83m@4ax.com> Message-ID: <4463B99B.5050003@whiteriversoft.com> Hi! > Number two suggestion: try committing the transaction (autocommit > might not be enabled in your environment). > commit() - is what I need :) Thank you very much! From johnjsal at NOSPAMgmail.com Thu May 25 11:03:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 25 May 2006 15:03:46 GMT Subject: how to change sys.path? In-Reply-To: <s1la72p6fm03t4fnqtem0c95eqmo3v04bd@4ax.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <5aGcg.2150$No6.46806@news.tufts.edu> <e4vn3u$brc$1@atlantis.news.tpi.pl> <W8Kcg.2156$No6.46787@news.tufts.edu> <e2n772hhn9rhqi0arkc6qdns0aql6nrvfc@4ax.com> <Dk_cg.2161$No6.46749@news.tufts.edu> <532972pkqut50suspvi4qhmkkeporlcopv@4ax.com> <YE0dg.2171$No6.46883@news.tufts.edu> <s1la72p6fm03t4fnqtem0c95eqmo3v04bd@4ax.com> Message-ID: <mHjdg.2176$No6.47014@news.tufts.edu> Dennis Lee Bieber wrote: > On Wed, 24 May 2006 17:24:08 GMT, John Salerno > <johnjsal at NOSPAMgmail.com> declaimed the following in comp.lang.python: > >> Dennis Lee Bieber wrote: >> >>> I may have gotten slightly confused >> That's my job. :) > > Okay: > > You have gotten me slightly confused <G> Your job is to pay no attention to me and my blathering. :) From http Sat May 6 21:29:35 2006 From: http (Paul Rubin) Date: 06 May 2006 18:29:35 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> <87bquaskap.fsf@rpi.edu> Message-ID: <7xiroioc5c.fsf@ruckus.brouhaha.com> Bill Atkins <NOatkinwSPAM at rpi.edu> writes: > Does Python have any support for closures? If so, ignore this point. > But if not, what about examples like this: > > (defun make-window (window observer) > ;; initialization code here > (add-handler window 'close > (lambda (event) > (notify observer event))) > ;; more code) Python has closures but you can only read the closed variables, not write them. > Being able to keep pass around state with functions is useful. > > There are also cases where a function is so trivial that the simplest > way to describe it is with its source code, where giving it a name and > putting it at the beginning of a function is just distracting and > time-consuming. E.g.: > > (remove-if (lambda (name) > (find #\- name :test #'char=)) > list-of-names) If I read that correctly, in Python you could use filter(list_of_names, lambda name: '-' not in name) or [name for name in list_of_names if '-' not in name] Both of these have become more natural for me than the Lisp version. From durumdara at gmail.com Thu May 11 04:22:43 2006 From: durumdara at gmail.com (DurumDara) Date: Thu, 11 May 2006 10:22:43 +0200 Subject: Use subprocesses in simple way... In-Reply-To: <1147262237.501896.177210@y43g2000cwc.googlegroups.com> References: <mailman.5549.1147258880.27775.python-list@python.org> <1147262237.501896.177210@y43g2000cwc.googlegroups.com> Message-ID: <4462F453.7060904@gmail.com> 10 May 2006 04:57:17 -0700, Serge Orlov <Serge.Orlov at gmail.com>: > I thought md5 algorithm is pretty light, so you'll be I/O-bound, then > why bother with multi-processor algorithm? This is an assessor utility. The program's architecture must be flexible, because I don't know, where it need to run (only I have a possibility to fix this: I write to user's guide). But I want to speedup my alg. with native code, and multiprocess code. I not tested yed, but I think that 4 subprocess quickly as one large process. > > > 2.) > > Do you know command line to just like FSUM that can compute file > > hashes (MD5/SHA1), and don't have any problems with unicode alt. file > > names ? > > I believe you can wrap the broken program with a simple python wrapper. > Use win32api.GetShortPathName to convert non-ascii file names to DOS > filenames. I use FindFilesW with 8. (?) parameter. This is the alternative name of the file, but yet I found a file that not handled by FSUM utility... Thanx for help: dd Ps: I wrote some code to test pipes and subprocesses. The name of the mod. is testpipe.py. The code is: import sys,random,subprocess,time,os,popen2,threading,thread IsMaster=len(sys.argv)==1 class ProcessThread(threading.Thread): def __init__(self,Param): threading.Thread.__init__(self) self.Param=Param self.RetVal=None self.start() def run(self): param=self.Param print "New thread with param",param po=os.popen2('c:\\python24\\python.exe testpipe.py 1') child_stdin,child_stdout=po child_stdin.write(str(param)+'\n') retval=child_stdout.readlines() child_stdin.close() child_stdout.close() self.RetVal=retval if IsMaster: print "M:",time.time() print "M: Start" print "M: Open subprocess" cnt=1 fcnt=0 pths=[] ress=[None]*9 while True: if cnt<10: pt=ProcessThread(cnt) pths.append(pt) cnt+=1 pcnt=0 for pt in pths: if pt: pcnt+=1 if pcnt: for i in range(len(pths)): pt=pths[i] if pt and pt.RetVal: pths[i]=None ress[i]=pt.RetVal print [pt.RetVal] else: break print "\M: The results are:" for s in ress: print s print "M: End" else: print "S:",time.time() print "S: Start" print "S: Data" print "S: End" s=sys.stdin.readline() print "S: %s"%s time.sleep(1) print "Echo: %s"%s print "Finished" From seannakasone at yahoo.com Thu May 11 01:13:59 2006 From: seannakasone at yahoo.com (seannakasone at yahoo.com) Date: 10 May 2006 22:13:59 -0700 Subject: glob() that traverses a folder tree In-Reply-To: <1147308393.712592.233200@j73g2000cwa.googlegroups.com> References: <1147308393.712592.233200@j73g2000cwa.googlegroups.com> Message-ID: <1147324439.841992.132710@q12g2000cwa.googlegroups.com> # i'm guessing os.walk() is the best way to traverse folder trees. import os, glob for dir, subdir, files in os.walk('.\InteropSolution'): for file in files: if glob.fnmatch.fnmatch(file,"*.dll") or glob.fnmatch.fnmatch(file,"*.exe"): print dir+file From johnjsal at NOSPAMgmail.com Mon May 15 15:15:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 19:15:00 GMT Subject: common practice for creating utility functions? In-Reply-To: <ZI3ag.2095$No6.46239@news.tufts.edu> References: <ZI3ag.2095$No6.46239@news.tufts.edu> Message-ID: <Uq4ag.2096$No6.46172@news.tufts.edu> John Salerno wrote: > Just a quickie for today Another quick one I'll combine in this thread: How can I create two separate conditions in a for loop? Such as this, which doesn't seem to work beyond string.punctuation: for char in string.punctuation or string.whitespace: From JShrager at gmail.com Mon May 8 02:51:22 2006 From: JShrager at gmail.com (JShrager at gmail.com) Date: 7 May 2006 23:51:22 -0700 Subject: "Only one obvious way..." In-Reply-To: <1hezn87.h8wwmp3kpz96N%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <pan.2006.05.07.08.35.04.362248@gmail.com> <1heytan.zl0xgh9v134kN%aleaxit@yahoo.com> <slrne5tkhg.b7l.tomasz.zielonka@tomekz.gem.lan> <1hezn87.h8wwmp3kpz96N%aleax@mac.com> Message-ID: <1147071082.880568.237540@g10g2000cwb.googlegroups.com> >If I ever _DO_ find a language that *DOES* mercilessly refactor in pursuit > of the ideal "only one obvious way", I may well jump ship, since my faith in > Python's adherence to this principle which I cherish so intensely has > been so badly broken ... The phrase "only one obvious way..." is nearly the most absurd marketing bullshit I have ever heard; topped only by "it fits your brain". Why are so many clearly intelligent and apparently self-respecting hard-core software engineers repeating this kind of claptrap? It sounds more like a religious cult than a programming language community. If one of my students answered the question: "Why use X for Y?" with "X fits your brain." or "There's only one obvious way to do Y in X." I'd laugh out loud before failing them. From sandro at e-den.it Fri May 5 03:59:09 2006 From: sandro at e-den.it (Sandro Dentella) Date: Fri, 05 May 2006 07:59:09 GMT Subject: __init__.py, __path__ and packaging References: <slrne5i46s.3hc.sandro@bluff.diade.it> <445932cc$1@nntp0.pdx.net> <slrne5l24f.3nl.sandro@bluff.diade.it> <j1sl52p7fpkjph0kcghpmn80o15iu5j9hc@4ax.com> Message-ID: <slrne5m1ed.9l3.sandro@bluff.diade.it> > Now, why you couldn't do "dbg.DBG = ..."? Very simple... "from > module import *" doesn't give you a dbg /module/, it only gives you > references to each piece inside the module. really the reason why I wanted that should probably be solved in other ways. I just wanted to split my dbg module in different files but load the dbg module in one single operation: dbg/ |-- __init__.py |-- lib |-- __init__.py |-- debug.py |-- gtk_dbg.py and inside dbg/__init__.py I used "from dbg.debug import *" so that a single 'import dbg' could present me the module 'debug' (of course in this simple case seems easier to put debug.py directly under dbg, but my main case is a much more complex module, with a tree structure that reflects the relation between modules that I want to hide to the end user). But to summarize, if I use 'from my_module import *' there is no way to reach directly 'my_module' and set a variable there? Thanks again sandro *:-) > I'm trying to fix the packaging of a very simple package, but some problem > show me that I have not well understood > > the structure of my package (some debug functions) is as follows: > > python/ > `-- dbg/ > |-- __init__.py > `-- lib > |-- __init__.py > |-- debug.py > `-- gtk_dbg.py > > > my sys.path includes 'python' and I wanted that the content of debug.py was > simply included by: 'import dbg', so I wrote dbg/__init__.py as follows: > > import os > Dir = os.path.dirname(__file__) > __path__ = [os.path.join(Dir, 'lib')] > from debug import * > > -- Sandro Dentella *:-) e-mail: sandro at e-den.it http://www.tksql.org TkSQL Home page - My GPL work From kentilton at gmail.com Fri May 5 22:44:59 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 05 May 2006 22:44:59 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> Message-ID: <L4U6g.88$Ey5.52@fe12.lga> Alex Martelli wrote: > Ken Tilton <kentilton at gmail.com> wrote: > ... > >>But the key in the whole thread is simply that indentation will not >>scale. Nor will Python. > > > Absolutely. That's why firms who are interested in building *seriously* > large scale systems, like my employer (and supplier of your free mail > account), would never, EVER use Python, nor employ in prominent > positions such people as the language's inventor and BDFL, the author of > the most used checking tool for it, and the author of the best-selling > reference book about that language; and, for that matter, a Director of > Search Quality who, while personally a world-renowned expert of AI and > LISP, is on record as supporting Python very strongly, and publically > stating its importance to said employer. > > Obviously will not scale. Never. > > Well... hardly ever! You are talking about being incredibly popular. I was talking about language expressivity. COBOL in its day was incredibly popular and certainly the language of choice (hell, the only language) for the biggest corporations you can imagine. But it did not scale as a language. I hope there are no doubts on that score (and I actually am a huge fan of COBOL). The problem for Python is its success. meant to be a KISS scripting language, it has caught on so well that people are asking it to be a full-blown, OO, GC, reflexive, yada, yada, yada language. Tough to do when all you wanted to be when you grew up was a scripting language. kenny (who is old enough to have seen many a language come and go) -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From godoy at ieee.org Wed May 17 09:38:33 2006 From: godoy at ieee.org (Jorge Godoy) Date: Wed, 17 May 2006 10:38:33 -0300 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <Xns97C65986E948Dduncanbooth@127.0.0.1> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> <1147862865.142339.117610@j55g2000cwa.googlegroups.com> <Xns97C683D60F53Fduncanbooth@127.0.0.1> <1147868309.125766.112550@u72g2000cwu.googlegroups.com> Message-ID: <1352828.BsCtm2PuaN@jupiter.g2ctech> achates wrote: >>Hitting the spacebar like a madman? If you have a sensible editor then at >>the start of a line you press tab once > > True! but normally if I'm editing someone else's code then I'm only > making small changes and so can't be bothered to temporarily cripple my > editor. If I'm merging my code with someone else's space-indented code > then piping through sed 's/TAB/SPACES' does the trick. Emacs guess what's used in the file and allows me to use tabs all the time, doing the correct thing... Personally, I like using spaces, but I don't have problems with files using tabs... -- Jorge Godoy <godoy at ieee.org> "Quidquid latine dictum sit, altum sonatur." - Qualquer coisa dita em latim soa profundo. - Anything said in Latin sounds smart. From __peter__ at web.de Tue May 23 02:06:54 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 23 May 2006 08:06:54 +0200 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 22) References: <e4sma5$msm$1@lairds.us> <e4t35c$7su$1@news.Stanford.EDU> Message-ID: <e4u8lp$d21$00$1@news.t-online.com> Andy Salnikov wrote: >> QOTW: "It's hard to make a mistake by having too many short and simple >> functions. And much too easy to make them when you have too few ;-)" >> - Thomas Bartkus >> > And of course there is a mathematical proof of that provided > somewhere, isn't it? :) If there were a proof I wouldn't have picked it as the QOTW. All the interesting stuff is what could be wrong but isn't :) Peter From hancock at anansispaceworks.com Wed May 17 20:07:51 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Thu, 18 May 2006 00:07:51 +0000 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147905290_7@news-east.n> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> <1147796116.826750@elch.in-berlin.de> <1147905290_7@news-east.n> Message-ID: <446BBAD7.6040006@anansispaceworks.com> Edmond Dantes wrote: >The real issue is, of course, that ASCII is showing its age and we should >probably supplant it with something better. But I know that will never fly, >given the torrents of code, configuration files, and everything else in >ASCII. Even Unicode couldn't put a dent in it, despite the obvious growing >global development efforts. Not sure how many compilers would be able to >handle Unicode source anyway. I suspect the large majority of them would >would choke big time. > > I think that was the old conventional wisdom, but it's not so obvious anymore. UTF-8 is a pretty cool standard. gVim handles it just fine, Python source allows UTF-8 within string literals, even if it doesn't like it in identifiers, and IIRC, Unicode is the official standard for Java files. It continues not to be used so much, but a lot of the capacity is there. Also, the 'config files in ASCII' thing is simply not a problem -- ASCII *is* a full-subset of UTF-8, so an ASCII config file is already a UTF-8 config file. Personally, I don't think ASCII is nearly as entrenched as you suggest. I wouldn't be surprised if Unicode/UTF-8 has fully supplanted it inside of 10 years. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From bignose+hates-spam at benfinney.id.au Tue May 23 18:45:19 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 24 May 2006 08:45:19 +1000 Subject: how to change sys.path? References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <4473867f$0$7721$626a54ce@news.free.fr> Message-ID: <87zmh81hts.fsf@benfinney.id.au> Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> writes: > Ju Hui a ?crit : > > what the relationship between it and the sys.path? > > Don't you guess ? He's following sound Python philosophy :-) -- \ Hercules Grytpype-Thynne: "Well, Neddie, I'm going to be | `\ frank." Ned Seagoon: "Right, I'll be Tom." Count Moriarty: | _o__) "I'll be Gladys." *slap* -- The Goon Show, _World War I_ | Ben Finney From kentilton at gmail.com Mon May 8 18:46:57 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 08 May 2006 18:46:57 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> References: <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> Message-ID: <NUP7g.17$G22.12@fe11.lga> David C. Ullrich wrote: > On 08 May 2006 12:53:09 -0700, tfb at conquest.OCF.Berkeley.EDU (Thomas > F. Burdick) wrote: > > >>Ken Tilton <kentilton at gmail.com> writes: >> >> >>>No, you do not want on-change handlers propagating data to other >>>slots, though that is a sound albeit primitive way of improving >>>self-consistency of data in big apps. The productivity win with >>>VisiCalc was that one simply writes rules that use other cells, and >>>the system keeps track of what to update as any cell changes for >>>you. You have that exactly backwards: every slot has to know what >>>other slots to update. Ick. >> >>No no, that's fine and the way it should be: when you change a slot, >>it should know who to update. And that's also the way it works in >>Cells. The trick is that Cells takes care of that part for you: > > > I'm glad you said that - this may be what he meant, but it seems > more plausible than what he actually said. There may be some confusion here because there are two places for code being discussed at the same time, and two sense of propagation. the two places for code are (1) the rule attached to A which is responsible for computing a value for A and (2) a callback for A to be invoked whenever A changes. Why the difference? In Cells, A is a slot such as 'background-color'. Whenever that changes, we have to do something more. On Mac OS9 it was "InvalidateRect" of the widget. In Cells-Tk, it is: (Tcl_interp "mywidget configure -background <new color>") In my OpenGL GUI, it is to rebuild the display-list for the widget. That is the same no matter what rule some instance has for the slot background-color, and different instances will have different rules. As for propagating, yes, Cells propagates automatically. More below on that. What I saw in the example offered was a hardcoded on-change callback that was doing /user/ propagation form B to A (and B to A! ... doesn't that loop, btw? Anyway...) > > >>all >>the *programmer* has to care about is what values a slot depends on -- >>Cells takes care of inverting that for you, which is important because >>that's a job that a computer is much better at than a human. > > > Fine. I suppose that is better; if b is going to return a + 1 > the fact that this is what b returns should belong to b, not > to a. So a has an update list including b, so when a's value > is set a tells b it needs to update itself. > > If we're allowed to pass (at some point, to some constructor > or other) something like (b, a + 1, [a]), which sets up a > cell b that shall return a + 1, and where the [a] is used > in the constructor to tell a to add b to a's update list > then this seems like no big deal. > > And doing that doesn't seem so bad - now when the programmer > is writing b he has to decide that it should return a + 1 > and also explicitly state that b shall depend on a; this > is all nice and localized, it's still _b_ telling _a_ to > add b to a's update list, and the programmer only has > to figure out what _b_ depends on when he's writing _b_. > Doesn't seem so bad. > > But of course it would be better to be able to pass just > something morally equivalent to (b, a + 1) to whatever > constructor and have the system figure out automatically > that since b returns a + 1 it has to add a to b's update > list. There must be some simple trick to accomplish that > (using Python, without parsing code). Right, you do not want to parse code. It really would not work as powerfully as Cells, which notice any dynamic access to another cell while a rule is running. So my rule can call a function on "self" (the instance that wons the slot being calculated, and since self can have pointers to other instances, the algorithm can navigate high and low calling other functions before finally reading another ruled slot. You want to track those. > Exactly what the trick is I > don't see immediately. To compute a value for a slot that happens to have a rule associated with it, have a little cell datastructure that implements all this and associate the cell with the slot and store a pointer to the rule in the cell. Then have a global variable called *dependent* and locally: currentdependent = *dependent* oldvalue = cell.value newvalue = call cell.rule, passing it the self instance *dependent* = currentvalue if newvalue not = oldvalue call on-change on the slot name, self, newvalue and oldvalue (the on-chnage needs to dispatch on as many arguments as the language allows. Lisp does it on them all) In the reader on a slot (in your getattr) you need code that notices if the value being read is mediated by a ruled cell, and if the global *dependent* is non empty. If so, both cells get a record of the other (for varying demands of the implementation). > > In Cells do we just pass a rule using other cells to > determine this cell's value, or do we also include > an explicit list of cells that this cell depends on? Again, the former. Just write the rule, the above scheme dynamically figures out the dependencies. Note then that dependencies vary over time because of different branches a rule might take. I want to reassure the community that this (nor the spreadsheet analogy <g>) is not just my crazy idea. In 1992: http://www.cs.utk.edu/~bvz/active-value-spreadsheet.html "It is becoming increasingly evident that imperative languages are unsuitable for supporting the complicated flow-of-control that arises in interactive applications. This paper describes a declarative paradigm for specifying interactive applications that is based on the spreadsheet model of programing. This model includes multi-way constraints and action procedures that can be triggered when constraints change the values of variables." Cells do not do multi-way constraints, btw. Nor partial constraints. To hard to program, because the system gets non-deterministic. That kinda killed (well, left to a small niche) the whole research programme. I have citations on that as well. :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From bearophileHUGS at lycos.com Fri May 19 14:18:08 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 May 2006 11:18:08 -0700 Subject: newb: comapring two strings In-Reply-To: <1148062114.800989.293270@j73g2000cwa.googlegroups.com> References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <4d4chmF185ohoU1@uni-berlin.de> <1148038726.023455.145900@j73g2000cwa.googlegroups.com> <1148062114.800989.293270@j73g2000cwa.googlegroups.com> Message-ID: <1148062688.445501.30260@y43g2000cwc.googlegroups.com> > I have suggested C because if the words are all of the same length then > you have 30000^2 = 90 000 000 000 pairs to test. Sorry, you have (n*(n-1))/2 pairs to test (~ 45 000 000 000). bearophile From tzz at lifelogs.com Wed May 31 12:27:19 2006 From: tzz at lifelogs.com (Ted Zlatanov) Date: Wed, 31 May 2006 12:27:19 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1149083474.097849.262460@i40g2000cwc.googlegroups.com> Message-ID: <g69bqtetb14.fsf@CN1374059D0130.kendall.corp.akamai.com> On 31 May 2006, xah at xahlee.org wrote: > Most languages stay blindly in their own community, oblivious to the > nature or facts of computing languages outside of their world. If > there are more relevant cross-posting, then this problem can be > lessened. (cross-posted to c.l.perl.misc and c.l.python only because they are named in Xah Lee's discourse) That's interesting. So to "correct" the attitude of several communities *you* believe are insular and opinionated (most people would disagree with you, but that's besides the point) you took it upon yourself to cross-post your thoughts to all those communities. Do you really believe this is ethically correct? (I'm sure you believe it's morally correct, but that's also besides the point. I hope you at least understand the difference between morals and ethics, and which of the two apply when you deal with a community.) You mention philosophers, cooperation, and open-mindedness. You also use loaded terms like "hot air," "brainlessness," call Python people "militant" and "poor in knowledge," and name a "Perl cult." I hope you see how this is at best inconsistent (I would call it hypocritical), and makes you and your postings unwelcome with the communities you've peppered with your opinions. Ted From reply.in.the.newsgroup at my.address.is.invalid Mon May 29 03:05:17 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 29 May 2006 09:05:17 +0200 Subject: HTMLParser chokes on bad end tag in comment References: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> <mailman.6303.1148884549.27775.python-list@python.org> Message-ID: <o27l721fntpjk4aifnetb0kdpsauhko7um@4ax.com> Fredrik Lundh: >Rene Pijlman: >[end tag in html comment in script element] >The end tag it chokes on is in comment, isn't it? > >no. STYLE and SCRIPT elements contain character data, not parsed >character data, so comments are treated as characters, and the first >"</" ends the element. Ah, I see. I'll report the problem to the application that's generating this broken code (vBulletin forum)... >if you have broken documents, you can tweak this by setting the >CDATA_CONTENT_ELEMENTS parser attribute before you start parsing. ... and in the mean time that's a good workaround. Thank you very much Fredrik. -- Ren? Pijlman From roy at panix.com Mon May 1 08:24:12 2006 From: roy at panix.com (Roy Smith) Date: Mon, 01 May 2006 08:24:12 -0400 Subject: returning none when it should be returning a list? References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> Message-ID: <roy-4AC032.08241201052006@reader1.panix.com> randomtalk at gmail.com wrote: Several people have already given you good answers as to why you're getting None, and how to improve the algorithm you're using. I want to address some stylistic questions. First, is the > if(next >= lim): > print(seed) > return seed > else: > count = 0; > [...] construct. You don't need the else part, since the if clause ends with a return. You can just un-indent one stop and put everything that is now inside the "else" at the same level as the "if". This makes your program easier to read and understand. Your program isn't too bad because it's only got about a dozen lines of code in the "else", and you only end up about 4 indents deep. In larger programs, you can end up with 100's of lines of code and 5, 6, or more indents. Then it's a nightmare to understand. The other sylistic issue is this: > if(count == len(seed)): > seed.append(next) > findPrime(seed, next+2, lim) > else: > findPrime(seed, next+2, lim) You've repeated the call to findPrime(). You refactor that out like: if(count == len(seed)): seed.append(next) findPrime(seed, next+2, lim) Three lines of code instead of five, and no repeated code. Easier to understand. From bdesth.quelquechose at free.quelquepart.fr Wed May 3 20:28:12 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 May 2006 02:28:12 +0200 Subject: This coding style bad practise? In-Reply-To: <44591463$0$31639$e4fe514c@news.xs4all.nl> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> Message-ID: <44591be3$0$2626$636a55ce@news.free.fr> Martin P. Hellwig a ?crit : > Hi all, > > I created a class which creates a relative unique id string, now my > program just works fine and as expected but somehow I get the feeling > that I misused the __repr__ since I guess people expect to 'execute' a > function in an instance instead of using it's representation string of > the instance itself, could you elaborate whether you find this bad > practice and if yes what would have been a better way to do it? Why not just use the call operator instead ? ie: >>> id = IDGenerator(...) >>> id() 01_20060424_151903_1 >>> id() 01_20060424_151905_2 From larry.bates at websafe.com Fri May 5 16:22:39 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 05 May 2006 15:22:39 -0500 Subject: how to remove 50000 elements from a 100000 list? In-Reply-To: <e3ftkp$qe7$03$1@news.t-online.com> References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> <4c13mdF13esivU1@uni-berlin.de> <4c14snF13tbobU1@uni-berlin.de> <1146844567.717687.228160@j33g2000cwa.googlegroups.com> <e3ftkp$qe7$03$1@news.t-online.com> Message-ID: <zNudne9wssqeKcbZRVn-hg@comcast.com> Peter Otten wrote: > Ju Hui wrote: > >> cool! >> thanks you all! >> I choose >> a=set(range(100000)) >> b=set(range(50000)) >> a.symmetric_difference(b) >> certainly,the real data not range(), I am satisfied the performance of >> set.difference >> >> thank you all again! > > Be warned that this may /add/ items to a: > >>>> set("abc").symmetric_difference("bcd") > set(['a', 'd']) > > If your subject is correct you want difference(), not > symmetric_difference(). > > Peter Whoops. My bad. Peter is correct. -Larry From gmc at serveisw3.net Sun May 21 20:09:41 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Mon, 22 May 2006 02:09:41 +0200 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1146076193.605314.70200@g10g2000cwb.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> Message-ID: <44710145.6040603@serveisw3.net> sturlamolden escribi?: >Julien Fiore wrote: > > >># step A.3 # >>Install Mingw, the gcc compiler for Windows, available at >>http://www.mingw.org/download.shtml. (we downloaded the file >>MinGW-5.0.2.exe and installed only the "base tool" (this includes >>mingw-runtime 3.9, w32api-3.6, binutils 2.15.91 and gcc-core 3.4.2). >>Add Mingw path ("C:\MinGW\bin") to the Windows "Path" environment >>variable. If you already have cygwin installed, add C:\MinGW\bin before >>the Cygwin path. >> >> > > >I don't think this is safe. MinGW links with msvcrt.dll whereas the >main Python distribution links with msvcr71.dll (due to Visual C++ >2003). It is not safe to mix and blend different C runtime libraries. >If you are to build a C extension with MinGW, you also need to build >Python against msvcrt.dll, i.e. you have to use a Python built with >MinGW or Visual C++ 6.0. There other option is to make MinGW link >against msvcr71.dll. I don't know if that is feasible. > > > I use Python 2.4.3 (msvcrt71) and I succesfully installed the last version of binutils, pyrex and MinGW, some weeks ago, using Julien Fiore step-by-step guide, so "my" MinGW is linking with msvcrt71.dll, with the default configuration. I don't understand why do you say MinGW links with msvcrt.dll... perhaps you've got an older version than the ones Julien posted? Hope it helps, Gonzalo. From rpdooling at gmail.com Wed May 3 18:38:24 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 3 May 2006 15:38:24 -0700 Subject: Gettings subdirectories In-Reply-To: <1146683720.748769.36490@g10g2000cwb.googlegroups.com> References: <e3au5u$drm$1@news.in.tum.de> <1146683720.748769.36490@g10g2000cwb.googlegroups.com> Message-ID: <1146695904.623400.128100@y43g2000cwc.googlegroups.com> >> root, dirnames, filenames = os.walk(r"C:\").next() Wow. How does that work? Just point me to where I can read about it. I don't see it under os.walk. That's cool. Thanks, Rick From NOatkinwSPAM at rpi.edu Sun May 7 14:34:14 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 14:34:14 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> <yfshd41yeaj.fsf@oc.ex.ac.uk> <87mzdt4ri5.fsf@rpi.edu> Message-ID: <87d5ep4rbt.fsf@rpi.edu> Bill Atkins <NOatkinwSPAM at rpi.edu> writes: > Alexander Schmolck <a.schmolck at gmail.com> writes: > >> [trimmed groups] >> >> Ken Tilton <kentilton at gmail.com> writes: >> >>> yes, but do not feel bad, everyone gets confused by the /analogy/ to >>> spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief >>> period I swore off the analogy because it was so invariably misunderstood. >>> Even Graham misunderstood it. >> >> Count me in. >> >>> >>> But it is such a great analogy! <sigh> >>> >>> > but what's the big deal about PyCells? >>> > Here is 22-lines barebones implementation of spreadsheet in Python, >>> > later I create 2 cells "a" and "b", "b" depends on a and evaluate all >>> > the cells. The output is >>> > a = negate(sin(pi/2)+one) = -2.0 >>> >>> > b = negate(a)*10 = 20.0 >>> >>> Very roughly speaking, that is supposed to be the code, not the output. So you >>> would start with (just guessing at the Python, it has been years since I did >>> half a port to Python): >>> >>> >>> v1 = one >>> a = determined_by(negate(sin(pi/2)+v1) >>> b = determined_by(negate(a)*10) >>> print(a) -> -2.0 ;; this and the next are easy >>> print(b) -> 20 >>> v1 = two ;; fun part starts here >>> print(b) -> 40 ;; of course a got updated, too >>> >> >> do you mean 30? >> >> I've translated my interpretation of the above to this actual python code: >> >> from math import sin, pi >> v1 = cell(lambda: 1) >> a = cell(lambda:-(sin(pi/2)+v1.val), dependsOn=[v1]) >> b = cell(lambda: -a.val*10, dependsOn=[a], >> onChange=lambda *args: printChangeBlurp(name='b',*args)) >> print 'v1 is', v1 >> print 'a is', a # -2.0 ;; this and the next are easy >> print 'b is', b # 20 >> v1.val = 2 # ;; fun part starts here >> print 'v1 now is', v1 >> print 'b now is', b # 30 ;; of course a got updated, too >> >> >> I get the following printout: >> >> v1 is 1 >> a is -2.0 >> b is [cell 'b' changed from <__main__.unbound object at 0xb4e2472c> to 20.0, >> it was not bound]20.0 >> [cell 'b' changed from 20.0 to 30.0, it was bound ] v1 now is 2 >> b now is 30.0 >> >> Does that seem vaguely right? >> >>> The other thing we want is (really inventing syntax here): >>> >>> on_change(a,new,old,old-bound?) print(list(new, old, old-bound?) >> >> Is the above what you want (you can also dynamically assign onChange later >> on, as required or have a list of procedures instead)? >> >>> >>> Then the print statements Just Happen. ie, It is not as if we are just hiding >>> computed variables behind syntax and computations get kicked off when a value >>> is read. Instead, an underlying engine propagates any assignment throughout >>> the dependency graph before the assignment returns. >> >> Updating on write rather than recalculating on read does in itself not seem >> particularly complicated. >> >>> My Cells hack does the above, not with global variables, but with slots (data >>> members?) of instances in the CL object system. I have thought about doing it >>> with global variables such as a and b above, but never really seen much of >>> need, maybe because I like OO and can always think of a class to create of >>> which the value should be just one attribute. >> >> OK, so in what way does the quick 35 line hack below also completely miss your >> point? >> >> >> # (NB. for lispers: 'is' == EQ; '==' is sort of like EQUAL) >> >> def printChangeBlurp(someCell, oldVal, newVal, bound, name=''): >> print '[cell %r changed from %r to %r, it was %s]' % ( >> name, oldVal, newVal, ['not bound', 'bound '][bound]), >> >> _unbound = type('unbound', (), {})() # just an unique dummy value >> def updateDependents(dependents): >> seen = {} >> for dependent in dependents: >> if dependent not in seen: >> seen[dependent] = True >> dependent.recalculate() >> updateDependents(dependent._dependents) >> class cell(object): >> def __init__(self, formula, dependsOn=(), onChange=None): >> self.formula = formula >> self.dependencies = dependsOn >> self.onChange = onChange >> self._val = _unbound >> for dependency in self.dependencies: >> if self not in dependency._dependents: >> dependency._dependents.append(self) >> self._dependents = [] >> def __str__(self): >> return str(self.val) >> def recalculate(self): >> newVal = self.formula() >> if self.onChange is not None: >> oldVal = self._val >> self.onChange(self, oldVal, newVal, oldVal is not _unbound) >> self._val = newVal >> def getVal(self): >> if self._val is _unbound: >> self.recalculate() >> return self._val >> def setVal(self, value): >> self._val = value >> updateDependents(self._dependents) >> val = property(getVal, setVal) >> >> >> >> 'as > > Here's how one of the cells examples might look in corrupted Python > (this is definitely not executable): > > class FallingRock: > def __init__(self, pos): > define_slot( 'velocity', lambda: self.accel * self.elapsed ) > define_slot( 'pos', lambda: self.accel * (self.elapsed ** 2) / 2, > initial_position = cell_initial_value( 100 ) ) > self.accel = -9.8 > > rock = FallingRock(100) > print rock.accel, rock.velocity, rock.pos > # -9.8, 0, 100 > > rock.elapsed = 1 > print rock.accel, rock.velocity, rock.pos > # -9.8, -9.8, -9.8 > > rock.elapsed = 8 > print rock.accel, rock.velocity, rock.pos > # -9.8, -78.4, -627.2 > > Make sense? The idea is to declare what a slot's value represents > (with code) and then to stop worrying about keeping different things > synchronized. > > Here's another of the examples, also translated into my horrific > rendition of Python (forgive me): > > class Menu: > def __init__(self): > define_slot( 'enabled', > lambda: focused_object( self ).__class__ == TextEntry and > focused_object( self ).selection ) > > Now whenever the enabled slot is accessed, it will be calculated based > on what object has the focus. Again, it frees the programmer from > having to keep these different dependencies updated. > > -- > This is a song that took me ten years to live and two years to write. > - Bob Dylan Oh dear, there were a few typos: class FallingRock: def __init__(self, pos): define_slot( 'velocity', lambda: self.accel * self.elapsed ) define_slot( 'pos', lambda: self.accel * (self.elapsed ** 2) / 2, initial_value = cell_initial_value( 100 ) ) self.accel = -9.8 rock = FallingRock(100) print rock.accel, rock.velocity, rock.pos # -9.8, 0, 100 rock.elapsed = 1 print rock.accel, rock.velocity, rock.pos # -9.8, -9.8, 90.2 rock.elapsed = 8 print rock.accel, rock.velocity, rock.pos # -9.8, -78.4, -527.2 -- This is a song that took me ten years to live and two years to write. - Bob Dylan From bignose+hates-spam at benfinney.id.au Tue May 16 22:38:28 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 12:38:28 +1000 Subject: A Unicode problem -HELP References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> Message-ID: <87lkt1pe8r.fsf@benfinney.id.au> "manstey" <manstey at csu.edu.au> writes: > input_file = open(input_file_loc, 'r') > output_file = open(output_file_loc, 'w') > for line in input_file: > output_file.write(str(word_info + parse + gloss)) # = three functions that return tuples If you mean that 'word_info', 'parse' and 'gloss' are three functions that return tuples, then you get that return value by calling them. >>> def foo(): ... return "foo's return value" ... >>> def bar(baz): ... return "bar's return value (including '%s')" % baz ... >>> print foo() foo's return value >>> print bar <function bar at 0x401fe80c> >>> print bar("orange") bar's return value (including 'orange') -- \ "A man must consider what a rich realm he abdicates when he | `\ becomes a conformist." -- Ralph Waldo Emerson | _o__) | Ben Finney From Joel.Hedlund at gmail.com Mon May 8 17:54:31 2006 From: Joel.Hedlund at gmail.com (Joel.Hedlund at gmail.com) Date: 8 May 2006 14:54:31 -0700 Subject: logging module: add client_addr to all log records Message-ID: <1147125271.065354.66180@j73g2000cwa.googlegroups.com> Hi! I'm writing a server and I want to use the logging module for logging stuff. I want to log all transactions in detail, and if everything goes haywire I want to know which client did it. Therefore I want to affix the client address to every single log item. I would like to do the following: Formatter("[%(client_addr)s]: %(message)s") ... logger.critical("Offal Barrage Detected: Running Away", client_addr = 'french.knights.org') I've written something that accomplishes this (example below), but I have this nagging feeling that this could have been done in a better way. Any ideas? When test.py executes it prints this: [WARNING|2006-05-08 23:44:57,421|internal]: Unable to Pronounce 'ni!' [WARNING|2006-05-08 23:44:57,421|french.knights.nu]: Incoming Bovine Detected I'm grateful for any advice. Cheers! /Joel Hedlund test.py --------------------------------------------------------------------- import logging import cowlogger logger = logging.getLogger('cowlogger') logger.warning("Unable to Pronounce 'ni!'") logger.warning("Incoming Bovine Detected", client_addr = 'french.knights.nu') --------------------------------------------------------------------- cowlogger.py --------------------------------------------------------------------- import logging BaseLogger = logging.getLoggerClass() class LogRecord(logging.LogRecord): def __init__(self, name, level, pathname, lineno, msg, args, exc_info, client_addr): """ Adding client_addr as instantiation parameter and attribute. """ logging.LogRecord.__init__(self, name, level, pathname, lineno, msg, args, exc_info) self.client_addr = client_addr class CowLogger(BaseLogger): def makeRecord(self, name, level, fn, lno, msg, args, exc_info, client_addr): """ Code nicked from logging.Logger. I just added client_addr to header and LogRecord instantiation. """ return LogRecord(name, level, fn, lno, msg, args, exc_info, client_addr) def _log(self, level, msg, args, exc_info=None, client_addr = 'internal'): """ Code nicked from logging.Logger. I just added client_addr to header and makeRecord call. """ if logging._srcfile: fn, lno, func = self.findCaller() else: fn, lno, func = "(unknown file)", 0, "(unknown function)" if exc_info: if type(exc_info) != types.TupleType: exc_info = sys.exc_info() record = self.makeRecord(self.name, level, fn, lno, msg, args, exc_info, client_addr) self.handle(record) logging.setLoggerClass(CowLogger) # Setting up log item formatting: format = "[%(levelname)s|%(asctime)s|%(client_addr)s]: %(message)s" formatter = logging.Formatter(format) handler = logging.StreamHandler() handler.setFormatter(formatter) logger = logging.getLogger('cowlogger') logger.addHandler(handler) --------------------------------------------------------------------- From ptmcg at austin.rr._bogus_.com Tue May 16 22:53:02 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 17 May 2006 02:53:02 GMT Subject: help with a function References: <446a85c6$0$61170$ae4e5890@news.nationwide.net> <mYvag.37952$CH2.9832@tornado.texas.rr.com> Message-ID: <iewag.37960$CH2.15322@tornado.texas.rr.com> "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message news:mYvag.37952$CH2.9832 at tornado.texas.rr.com... > "Lance Hoffmeyer" <lance at augustmail.com> wrote in message > news:446a85c6$0$61170$ae4e5890 at news.nationwide.net... > > Hey all, > > > > I'm new to python. I keep getting an error when running this. > > I'm sure there is an easy fix but I can't figure it out. > > What am I doing wrong? How do I fix it? > > > > def even_odd_round(num): > > if(round(num,2) + .5 == int(round(num,2)) + 1): > > if(int(num,0) % 2): #an odd number > > rounded_num = round(num,2) + .1 > > else: #an even number > > rounded_num = round(num,2) - .1 > > rounded_num = int(rounded_num) > > return rounded_num > > > > even_odd_round(5.5) > > > > Traceback (most recent call last): > > File "<interactive input>", line 1, in ? > > File "<interactive input>", line 3, in even_odd_round > > TypeError: int() can't convert non-string with explicit base > > >>> > > 1 def even_odd_round(num): > 2 if(round(num,2) + .5 == int(round(num,2)) + 1): > 3 if(int(num,0) % 2): #an odd number > 4 rounded_num = round(num,2) + .1 > 5 else: #an even number > 6 rounded_num = round(num,2) - .1 > 7 rounded_num = int(rounded_num) > 8 return rounded_num > 9 > 10 even_odd_round(5.5) > > > Traceback (most recent call last): > > File "<interactive input>", line 1, in ? > > File "<interactive input>", line 3, in even_odd_round > > TypeError: int() can't convert non-string with explicit base > This error message tells us there is a problem on line 3, something to do with the int() method call. You have posted a number of posts this week, and it feels like you write a bunch of code, run into a problem, then post it without trying to figure it out. I don't mean to offend, but really, many of your questions are pretty basic: - how do I use regex's (to extract data from an easily split string of space-delimited numbers)? - how do I round a number? - I get this traceback, what's wrong with my program? Please read up on the Python tutorials, and learn how to use the interactive help. Overall, c.l.py is pretty newbie-friendly, and a "n00b" question every so often is no big deal - but you've got to make more of an effort yourself. There is also a tutorial mailing list that is - I started to say "more geared for beginners", but we have plenty of lurker beginners on c.l.py, I'm sure - I'd say the tutorial mailing list is more willing to handhold new Python programmers. And a posted "thanks" once in a while is not bad etiquette either. -- Paul From andy at neotitans.com Wed May 17 12:15:44 2006 From: andy at neotitans.com (Andy Sy) Date: Thu, 18 May 2006 00:15:44 +0800 Subject: Tabs are *EVIL* AND *STUPID*, NOT 'misunderstood' (Re: Tabs versus Spaces in Source Code) In-Reply-To: <1147878055.475472.118270@j73g2000cwa.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <e4f8nr$8q9$1@sea.gmane.org> <ca55a9900605170639re1ad32co4164913a78d8f228@mail.gmail.com> <e4fas7$hlk$1@sea.gmane.org> <ca55a9900605170731mab99520id4ce4ae664bccb32@mail.gmail.com> <mailman.5811.1147876907.27775.python-list@python.org> <1147878055.475472.118270@j73g2000cwa.googlegroups.com> Message-ID: <e4fi11$fl3$1@sea.gmane.org> achates wrote: > Andy Sy > >> I guess this *REALLY* is how a misguided tab user exercises his 'logic': >> Syntax replication (e.g. so-called 'argument construction') is enough, >> semantics don't matter. > > That's quite amusing.. you've unwittingly stumbled on a pretty concise > statement of Hilbert's first postulate of formal logic, proved by Godel > in 1930.. > >> ROTFLMAO! > > Indeed. Too bad that only applies to /statements phrased in formal logic/, not to everyday statements expressed in a human language. Only someone who has run out of sensible arguments or a disingenuous sophist would try to extend this so-called postulate the way Peter and you did. Really... if you *actually* believed that Peter's argument had merit and he was not merely being facetious, I guess I rest my case regarding tab users and their 'logical prowess'. LMAO again. From rune.strand at gmail.com Wed May 24 11:29:57 2006 From: rune.strand at gmail.com (Rune Strand) Date: 24 May 2006 08:29:57 -0700 Subject: John Bokma harassment In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <1148484597.410529.219960@j33g2000cwa.googlegroups.com> Xah Lee wrote: > I'm sorry to trouble everyone. But as you might know, due to my > controversial writings and style, recently John Bokma lobbied people to > complaint to my web hosting provider. After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. > xah at xahlee.org > ? http://xahlee.org/ I can just declare my support. Reading Mr. Bokmas comments below [*] certainly makes my suport stronger. * http://groups.google.com/group/comp.lang.python/tree/browse_frm/thread/28edb6b248dbae85/b89d934d12adf3a9?rnum=61&utoken=rJk98zMAAAAqRjR_RIs2SQx_9Hh6SccKbmCj1Nw6TBD3Zp3qTOpBLP1axhNO2WH2KLoXjtKtup7b9E_jTXH5EMe8d2Tvis0T&_done=%2Fgroup%2Fcomp.lang.python%2Fbrowse_frm%2Fthread%2F28edb6b248dbae85%2Fbbcab154ad579cd4%3Futoken%3DrJk98zMAAAAqRjR_RIs2SQx_9Hh6SccKbmCj1Nw6TBD3Zp3qTOpBLP1axhNO2WH2KLoXjtKtup7b9E_jTXH5EMe8d2Tvis0T%26#doc_837dc168e2a56fa2 From bdesth.quelquechose at free.quelquepart.fr Sat May 27 09:44:09 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 27 May 2006 15:44:09 +0200 Subject: CMFBoard In-Reply-To: <1148721534.535888.21460@y43g2000cwc.googlegroups.com> References: <1148721534.535888.21460@y43g2000cwc.googlegroups.com> Message-ID: <4478284b$0$13041$626a54ce@news.free.fr> maria a ?crit : > Hi everybody! > > I use CMFBoard 2.2.1 as a discussion board on my website. > I want to open the forum to all users, anonymous and registred users! > But my problem is, that whenever an ano user posts a topic, the > overview doesn't display the message correctly. Instead of a table > containing topic-title, short description, last reply, user...... there > is only some text shown, like this: > > {'last_reply_created': '2006-05-27 09:36', 'msgIcon': ' ', > 'Title': 'test', 'actions': {'reply': > 'http:/..../forumfolder.2006-05-27.1751137831/public/0002/forum_reply_form', > 'delete': (snip) Please repost this on Zope's mailing list - that's where you'll get the best answers. FWIW, your problem is likely a CMF configuration problem and has nothing to do with the Python language. From nobody at 127.0.0.1 Mon May 1 02:10:09 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 01 May 2006 06:10:09 GMT Subject: returning none when it should be returning a list? References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> Message-ID: <5Dh5g.71445$H71.59445@newssvr13.news.prodigy.com> randomtalk at gmail.com wrote: > The function basically takes in a list of all the prime number found, > it takes the next number to be tested for (next) and the limit it will > go up to. It divide next by the list of previous prime numbers if next > is not bigger than lim, count up all the times where it's not evenly > divdided, if the result is equal the length of prime number, then we > have another prime number, lather rinse and repeat :) Your basic algorithm as described above sounds workable, but can be made more efficient (I didn't look closely at your code for bugs). I won't even go near the complicated number theory algorithms. 1. integer mod will be faster than floating point mod (unless you're getting into numbers too large to store efficiently as ints, but you'll probably run into other limitations before you get near that point in this code). 2. you can stop as soon as you find a zero remainder, no need to keep testing the rest of the primes in the list. 3. you can stop testing numbers at the halfway point. there are no primes smaller than 2, so no number x can have a factor larger than x/2. 4. in fact you can do even better. a simple proof by contradiction shows that if primes 1..y don't divide x and y^2 > x then x must be prime. put another way, once you test up to the square root of x, there's no point continuing. if one factor were bigger than sqrt(x), the other would have to be smaller than sqrt(x). but you've already tested the factors smaller than sqrt(x), so there can't be any factors. 5. you can do better than checking every odd number (next+2) to find the next prime, but I'm too tired to look into it right now. it may require more complex machinery. Locating primes is an interesting challenge because of the seemingly endless grades of refinements over simple brute-force search. Like I said though, if speed and size aren't concerns, your algorithm is fine. From tzot at sil-tec.gr Tue May 2 06:07:33 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 02 May 2006 13:07:33 +0300 Subject: resume picking items from a previous list References: <1146352140.248299.136880@g10g2000cwb.googlegroups.com> <1146400419.173078.96860@g10g2000cwb.googlegroups.com> Message-ID: <vmbe52d02kk54senjn09vc8ilsejfg08ds@4ax.com> On 30 Apr 2006 05:33:39 -0700, rumours say that "willmcgugan at gmail.com" <willmcgugan at gmail.com> might have written: > >kpp9c wrote: >> For a time i pick from my songs, but i only play a few of the songs in >> that list... now my wife, Jessica Alba, comes home, and i start playing >> from Jessica's list of songs. After playing a few songs, Jessica, who >> needs her beauty sleep, goes to bed, and i start my play loop which >> starts picking from my songs again... >Not sure I follow. Jessica goes to bed, and you... _listen to music_?? He said his *wife*, Jessica Alba. There's *no* way you marry *anyone* you won't get bored of eventually. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From john at castleamber.com Wed May 17 13:43:24 2006 From: john at castleamber.com (John Bokma) Date: 17 May 2006 17:43:24 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <Xns97C5D08D18788castleamber@130.133.1.4> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> Message-ID: <Xns97C6816C1D618castleamber@130.133.1.4> Edward Elliott <nobody at 127.0.0.1> wrote: > John Bokma wrote: > >> Edward Elliott <nobody at 127.0.0.1> wrote: >> >>> This is just anecdotal, but I still find it interesting. Take it for >>> what it's worth. I'm interested in hearing others' perspectives, just >>> please don't turn this into a pissing contest. >> >> Without seeing the actual code this is quite meaningless. > > Evaluating my experiences yes, relating your own no. What would the point be? Most important to me would be: am I happy with the result? And that rarely has to do with the number of lines of actual code or the programming language. A language is just a tool. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From me+python at modelnine.org Thu May 4 07:57:23 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 4 May 2006 13:57:23 +0200 Subject: about the implement of the PyString_InternFromString In-Reply-To: <000301c66f70$1f0995e0$3500a8c0@kyom> References: <000301c66f70$1f0995e0$3500a8c0@kyom> Message-ID: <200605041357.23735.me+python@modelnine.org> Am Donnerstag 04 Mai 2006 13:44 schrieb Kyo Guan: > Hi guys: > > I have a question about the this API. > > PyObject * > PyString_InternFromString(const char *cp) > { > PyObject *s = PyString_FromString(cp); > if (s == NULL) > return NULL; > PyString_InternInPlace(&s); > return s; > } > > > Why it always try to call PyString_FromString first? if char* cp is > already in the interned dict, this PyString_FromString call is waster. so I > think this API should implement as: Have you looked at the type of cp? It's const char*, that's not a Python type. PyString_FromString does nothing else than create a Python string-object from the C string, which can then in turn be interned. This call is necessary. --- Heiko. From rpdooling at gmail.com Mon May 15 10:46:01 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 May 2006 07:46:01 -0700 Subject: keyword help in Pythonwin interpreter References: <1147702380.665861.106540@g10g2000cwb.googlegroups.com> Message-ID: <1147704361.557550.263720@g10g2000cwb.googlegroups.com> I should add that if I type: >>>help ('sys') It works fine. So it's finding the module documentation, but not the keyword or topic. Thanks rick From malvert at telenet.be Wed May 10 13:00:38 2006 From: malvert at telenet.be (malv) Date: 10 May 2006 10:00:38 -0700 Subject: interactive shell -- reload definitions? In-Reply-To: <4461d67a$0$3551$626a54ce@news.free.fr> References: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> <4461d67a$0$3551$626a54ce@news.free.fr> Message-ID: <1147280438.193621.66340@u72g2000cwu.googlegroups.com> This is a question that comes up almost continuously for at least six years now. For Python users having to deal with major real-life applications, this may make them think twice about the future suitability of Python as a competitive development tool. Ruby is featuring a software modify and go feature. Lisp is, even VB does. In the design of Smalltalk this used to be one of the major considerations. Plenty of posts will turn up doing a search on "reload". The following references summarize some of these problems: http://groups.google.com/group/comp.lang.python/browse_frm/thread/efba62d227ba4794/41f57f366affd057?q=Hung+Jung+Lu+reload&rnum=2#41f57f366affd057 http://groups.google.com/group/comp.lang.python/browse_frm/thread/efba62d227ba4794/41f57f366affd057?q=Hung+Jung+Lu+reload&rnum=2#41f57f366affd057 In fact, doing a reload usually will not accomplish what one is looking for. Class instances should also be upgraded on reload(), preferably automatically. This can be accomplished as shown by Michael Hudson in: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 Variants on this theme exist which seem to be broken. Given the persistent push of Ruby, I would strongly recommend that a workable integrated solution will be found for Reload & Go in Python, taking priority on many way out features of rather low practicality for many programmers. From struggleyb at gmail.com Wed May 31 05:20:43 2006 From: struggleyb at gmail.com (Bo Yang) Date: Wed, 31 May 2006 17:20:43 +0800 Subject: An algorithm problem In-Reply-To: <slrne7qiso.5k5.sybrenUSE@schuimige.stuvel.eu> References: <mailman.6350.1149058719.27775.python-list@python.org> <slrne7qiso.5k5.sybrenUSE@schuimige.stuvel.eu> Message-ID: <447D5FEB.9040504@gmail.com> I am sorry , and thanks for your friendliness . I have change my source code for more meaningful variable name and more comments follow the instructions John has writen . I think that is useful for you to look my code . And this time I put the code in the attachment . Indeed , I write that in the Eclipse Pydev , I don't know why it lose its idention in the mailing list . Also , I forget an example for the question , and I compensate for it : Given the integer 2 for instance : what we exapct from the algorithm is a list of 0 or 1 , for this instance it is 1 1 0 0 . We can take it as a ring , and fetch any continuous 2 numbers from it , finally get four combinations : 11 , 10 , 00 , 01 and they are 3 , 2 , 0 , 1 . I hope this time it is clear for all to understand what problem confront me . And again I am sorry for the trouble , thanks for you again ! Best Regard Bo Yang -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: ring.py URL: <http://mail.python.org/pipermail/python-list/attachments/20060531/85332161/attachment.ksh> From edreamleo at charter.net Thu May 25 07:23:52 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 25 May 2006 06:23:52 -0500 Subject: Two idle questions Message-ID: <gtgdg.668$Qn7.292@fe06.lga> I've asked these questions on idle-dev with no answer. 1. How can code tell whether it is being run from Idle's debugger? 2. How can code being run from Idle's debugger simulate a breakpoint, such as pdb.set_trace() does? Yes, pdb.set_trace() does work, but I want to enable idle's debugging console and get all of Idle's nice debugging features. Thanks. Edward P.S. I've studied Idle's debugger code for several hours and the answers are not exactly jumping out at me :-) Perhaps it would be good to create wrapper functions (no idea where) to make these tasks easier. Or maybe they already exist? EKR -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From rpdooling at gmail.com Sat May 20 12:32:59 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 20 May 2006 09:32:59 -0700 Subject: combining a C# GUI with Python code? In-Reply-To: <446f4058$0$1987$c3e8da3@news.astraweb.com> References: <3Dnbg.2135$No6.46516@news.tufts.edu> <mn.a2757d657d031da4.43626@yahoo.fr.invalid> <446f4058$0$1987$c3e8da3@news.astraweb.com> Message-ID: <1148142778.993864.86920@y43g2000cwc.googlegroups.com> John, I know you started out asking about .NET, but peruse this thread, wherein some old hands recommend staying with what you know, if what you know is VBA guis. http://tinyurl.com/ehujm rick From http Tue May 23 13:00:47 2006 From: http (Paul Rubin) Date: 23 May 2006 10:00:47 -0700 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <mailman.6050.1148253641.27775.python-list@python.org> <44732c19$0$21103$626a54ce@news.free.fr> <1148400804.164224.244680@y43g2000cwc.googlegroups.com> Message-ID: <7x3bf0r800.fsf@ruckus.brouhaha.com> "SamFeltus" <sam at nuevageorgia.com> writes: > > But your brain doesn't care. It's got a shortcut to your wallet, and > > the information on the screen is accessing that. > This was the most useful comment for me. I never fully considered that > Flash was aiming at a different part of the brain. HTML is resonant > with the mindset of Python, Flash is not. Perceptual match vs > perceptual mismatch. I'm reminded of a passage in "Cryptonomicon", about a guy trying to gather info about how to organize a scuba dive to investigate a 150-meter-deep shipwreck. He gets hold of a bunch of diving books and finds that the tables in them only go down to 1/3rd of that depth and are useless: Randy closes up all of the books and looks at them peevishly for a while. They are all nice new books with color photographs on the covers. He picked them off the shelf because (getting introspective here) he is a computer guy, and in the computer world any book printed more than two months ago is a campy nostalgia item. Investigating a little more, he finds that all three of these shiny new books have been personally autographed by the authors, with long personal inscriptions: two addressed to Doug, and one to Amy. The one to Amy has obviously been written by a man who is desperately in love with her. Reading it is like moisturizing with Tabasco. He concludes that these are all consumer-grade diving books written for rum-drenched tourists, and furthermore that the publishers probably had teams of lawyers go over them one word at a time to make sure there would not be liability trouble. That the contents of these books, therefore, probably represent about one percent of everything that the authors actually know about diving, but that the lawyers have made sure that the authors don't even -mention- that. Randy does a sorting procedure on the diving books now: he ignores anything that has color photographs, or that appears to have been published within the last twenty years, or that has any quotes on the back cover containing the words "stunning", "superb", "user-friendly",or, worst of all, "easy-to-understand". He looks for old, thick books with worn-out bindings and block-lettered titles like DIVE MANUAL. Anything with angry marginal notes written by Doug Shaftoe gets extra points. The Python mindset? From LittlePython at lost.com Sat May 27 20:14:49 2006 From: LittlePython at lost.com (LittlePython) Date: Sun, 28 May 2006 00:14:49 GMT Subject: Using a package like PyInstaller References: <FyYdg.2216$As2.860@trnddc02> <e5ab5l$tkm$1@daisy.noc.ucla.edu> <DD4eg.2432$As2.2216@trnddc02> <e5amec$64m$1@daisy.noc.ucla.edu> Message-ID: <ZX5eg.287$xO5.197@trnddc03> That is very close to what I have being doing, however I was unable to enclose a bmp or another file for that matter in the exe. I used both DATA and BINARY key words with no luck. I checked what was in the package and there were there. I guess for some reason it could not locate then when executed. I used snap 274 if I remember correctly. I am not too sure I am explaining my question correctly though. I have not problem creating and distributing my python/wxpython scripts in exe (stand-a-lone) except for what I have described above. I am worrying that when the py script is run I am leaving behind files. That the components of my stand-alone exe is somehow coming out of the exe (PyInstaller) and being installed. My setup exe is not what's is bothering me although I do like the your suggestion and have just been tinkering with it. It is cool stuff and much better then what I have been using. Thx "James Stroud" <jstroud at ucla.edu> wrote in message news:e5amec$64m$1 at daisy.noc.ucla.edu... > LittlePython wrote: > > Thx for the tip. > > > > I am referring more to the use of PyInstaller or py2exe. Packages that > > create exe files that basically have your py script and a small py > > interpreter all rolled up into one. This way py does not need to be > > installed on a system to execute a py script. I am being advised that python > > is installed onto systems (windows) it should not be on. I am new to python > > and these types of packages and am not too sure how dumb a question this > > really is.. but can these packages bleed out files, dll, exe ect. to systems > > they are run on? > > They don't have to "bleed" anything. Everything, including the python > interpreter, and 3rd party libraries can be included in a single > executable. Here is an example script for pyinstaller that rolls > evertyhing into one file (this is what I use to roll up my passerby > program at passerby.souceforge.net): > > > setenv TEMP temp > > set pythonexe='c:/Python23-Enthought/python' > set pbydir='z:/Code/pby/current/' > > rm *.pyc > > rm -rf ./temp/ ./passerby/ > mkdir temp > > $pythonexe Configure.py > $pythonexe Makespec.py --onefile --tk --noconsole \ > --icon $pbydir/../icons/passerby.ico \ > $pbydir/passerby.py passerby/passerby.spec > $pythonexe Build.py passerby/passerby.spec > > > You can control installation with innosetup. > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From defcon8 at gmail.com Sun May 14 03:57:55 2006 From: defcon8 at gmail.com (defcon8) Date: 14 May 2006 00:57:55 -0700 Subject: Cellular automata and image manipulation In-Reply-To: <i4OdnQZa45PQ7_vZUSdV9g@ptd.net> References: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> <i4OdnQZa45PQ7_vZUSdV9g@ptd.net> Message-ID: <1147593475.950458.192440@g10g2000cwb.googlegroups.com> Thank you very much. That is highly simple, useful and it works. From anthra.norell at tiscalinet.ch Fri May 12 13:51:32 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 12 May 2006 19:51:32 +0200 Subject: How to get a part of string which follows a particular pattern usingshell script References: <1147083512.620270.231680@j73g2000cwa.googlegroups.com> Message-ID: <069201c675ec$b4917100$0201a8c0@mcuf7> This is the third problem today which I propose to solve with my stream editor SE. If the group thinks it could be useful I would submit it the moment I'm done with the doc, which is in the final stage. Frederic >>> se = SE.SE ('<EAT> ~addr=[0-9.]+~==(10) | addr\== ') >>> string = """(a)test="192.168.1.17:/home/ankur/nios_fson/mnt/tmptype > nfs(rw,addr=192.168.1.17)" > b)test="/dev/root on / typr nfs > (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93)")""") >>> print se (string) 192.168.1.17 192.168.1.93 ----- Original Message ----- From: "Hari" <p.r.hariram at gmail.com> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Monday, May 08, 2006 12:18 PM Subject: How to get a part of string which follows a particular pattern usingshell script > Hi all, > > I need to get a part of string which follows a pattern 'addr=' > > > For example: > > > a)test="192.168.1.17:/home/ankur/nios_fson/mnt/tmptype > nfs(rw,addr=192.168.1.17)" > b)test="/dev/root on / typr nfs > (rw,v2,rsize=1024,wsize=1024,hard,udp,nolock,addr=192.168.1.93)" > > > I need to get the ipaddress from the above two strings a and b which > follows 'addr='. I tried to use cut, but it accepts only single charter > > as delimiter. If I give delimiter as 'addr=' for cut command it gives > me a error. > > > So please help me. > > > A bunch of thanks in advance. > > > Regards, > P.R.Hariram > > -- > http://mail.python.org/mailman/listinfo/python-list From robert.kern at gmail.com Wed May 10 14:45:29 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 10 May 2006 13:45:29 -0500 Subject: Masked arrays In-Reply-To: <F0B70A3B-CC34-4EED-BDE1-CB4B79D06B3F@mac.com> References: <F0B70A3B-CC34-4EED-BDE1-CB4B79D06B3F@mac.com> Message-ID: <e3tcc9$e1n$1@sea.gmane.org> Tommy Grav wrote: > I am trying to get the flux of a star in an image. I have been using numpy > and pyfits and have the code. You will probably want to ask on numpy-discussion, instead. http://www.scipy.org/Mailing_Lists > def distance(im,xc,yc): > (rows,cols) = im.shape > dist = zeros([rows,cols]).astype(Float64) > for row in range(rows): > for col in range(cols): > dist[row,col] = sqrt(((row + 0.5) - yc)**2 + ((col + 0.5) - > xc)**2) > return dist You will probably want to use numpy.fromfunction() instead. > def apphot(im,x,y,r): > dist = distance(im,x,y) > appmask = where(dist <= r,1,0) You don't have to use where() here. (dist <= r) returns an array of bools, which are already 1 and 0 (for most purposes). > fluxim = where(appmask,im,0) > appflux = sum(sum(fluxim)) > skymask = where(dist > r, 1,0) > skyim = where(skymask,im,0) > sky = mean(skyim) > print skyim > print sky > > return 1 > > Output: >> array (20,20) , type = f, has 400 elements >> [ 45.89742126, 45.92555847, 45.8874054 , 45.88538208, 45.88244934, > 45.9353241 , > 36.75245361, 29.85816345, 27.53547668, 22.93712311, 22.93178101, > 22.93699799, 22.91038208, 27.4988739 , 29.84021606, 36.71789551, > 45.86646729, 45.86741638, 45.85328979, 45.823349 ,] > > where im is a ndarray, x and y are the position of the star and r is > the radius of the aperture. I calculate the flux inside the aperture, > but when I want to calculate the mean of the pixels outside the > aperture I run into problems as the pixels values inside the aperture > is 0 and is still considered in the mean calculation. Is there a way to > do this without using masked arrays? Sure! But ... > How would I use a masked array > to do it? ... masked arrays already do the appropriate tasks for you. In [1]: from numpy import ma In [2]: ma.average? Type: function Base Class: <type 'function'> String Form: <function average at 0x697ef0> Namespace: Interactive File: /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/numpy-0.9.7.2476-py2.4-macosx-10.4-ppc.egg/numpy/core/ma.py Definition: ma.average(a, axis=0, weights=None, returned=0) Docstring: average(a, axis=0, weights=None) Computes average along indicated axis. If axis is None, average over the entire array Inputs can be integer or floating types; result is of type float. If weights are given, result is sum(a*weights)/(sum(weights)*1.0) weights must have a's shape or be the 1-d with length the size of a in the given axis. If returned, return a tuple: the result and the sum of the weights or count of values. Results will have the same shape. masked values in the weights will be set to 0.0 -- 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 jab3 at _del_linuxmail._del_org Sun May 21 21:43:49 2006 From: jab3 at _del_linuxmail._del_org (jab3) Date: Sun, 21 May 2006 21:43:49 -0400 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <1148225181.251089.261160@j55g2000cwa.googlegroups.com> Message-ID: <JeKdnQCt_qvIiuzZRVn-tQ@comcast.com> SamFeltus wrote: > Religious Fanaticism is a very strong in the Computer community. But, > is it really a surprise that when a bunch of hairless apes created a > new mental world, they created it with a complicated Quilt of religions > and nationalities, and many became fanatical? > > I am confidant the responces Xah will recieve will validate his > observation on religious fanaticism. It is funny, Xah always questions > people's Sacred Cow's, I have often noted that the reponces often read > like the writings of religious fanatics. As a Georgian (US), the > responces often remind me of the Dark Side (there is a Light) of the > Southern Baptist Church, translated into Computer Speak. > > Software needs philosophers is an interesting point, perhaps the most > important function of Philosophers is exposing Sacred Cows as just > Cattle. Unless Xah Lee is Steve Yegge, Xah Lee did not write that essay. Nor did he claim to: > Software Needs Philosophers > by Steve Yegge, 2006-04-15. <....> > This post is archived at: > http://steve-yegge.blogspot.com/2006/04/software-needs-philosophers.html > and http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html > This essay is reported with permission. From fredrik at pythonware.com Fri May 12 04:48:25 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 May 2006 10:48:25 +0200 Subject: reusing parts of a string in RE matches? References: <YMm8g.2077$No6.45935@news.tufts.edu><mailman.5557.1147274047.27775.python-list@python.org><M2o8g.2080$No6.45875@news.tufts.edu><1147283334.610613.220770@j33g2000cwa.googlegroups.com><whq8g.2082$No6.45965@news.tufts.edu><1147287162.914661.237370@i39g2000cwa.googlegroups.com><E6r8g.2083$No6.45931@news.tufts.edu><eir8g.2084$No6.45965@news.tufts.edu><1147291197.423570.242440@g10g2000cwb.googlegroups.com><e3v387$9tt$1@mlucom4.urz.uni-halle.de><GGH8g.2085$No6.45839@news.tufts.edu><e3vikl$ecv$1@mlucom4.urz.uni-halle.de><eRI8g.2087$No6.45924@news.tufts.edu> <e408o5$kta$1@mlucom4.urz.uni-halle.de> Message-ID: <e41i4s$nq1$1@sea.gmane.org> Mirco Wahab wrote: > In Python, you have to deconstruct > the 2D-lists (here: long list of > short lists [a,2] ...) by > 'slicing the slice': > > char,num = list[:][:] > > in a loop and using the apropriate element then: > > import re > > t = 'a1a2a3Aa4a35a6b7b8c9c'; > r = r'(\w)(?=(.)\1)' > l = re.findall(r, t) > > for a,b in (l[:][:]) : print b > > In the moment, I find this syntax > awkward and arbitary, but my mind > should change if I'm adopted more > to this in the end ;-) in contemporary Python, this is best done by a list comprehension: l = [m[1] for m in re.findall(r, t)] or, depending on what you want to do with the result, a generator expression: g = (m[1] for m in re.findall(r, t)) or process(m[1] for m in re.findall(r, t)) if you want to avoid creating the tuples, you can use finditer instead: l = [m.group(2) for m in re.finditer(r, t)] g = (m.group(2) for m in re.finditer(r, t)) finditer is also a good tool to use if you need to do more things with each match: for m in re.finditer(r, t): s = m.group(2) ... process s in some way ... the code body will be executed every time the RE engine finds a match, which can be useful if you're working on large target strings, and only want to process the first few matches. for m in re.finditer(r, t): s = m.group(2) if s == something: break ... process s in some way ... </F> From nogradi at gmail.com Thu May 4 08:03:39 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 4 May 2006 14:03:39 +0200 Subject: Mod_python.publisher behavior - sending .py file tobrowser not processing it in pyton In-Reply-To: <F8ED685B-2383-42E0-A661-4FDADB22E8F3@dscpl.com.au> References: <1146716203.13055@dscpl.user.openhosting.com> <5f56302b0605040317o4f327f4fob58a1c824dbf3124@mail.gmail.com> <F8ED685B-2383-42E0-A661-4FDADB22E8F3@dscpl.com.au> Message-ID: <5f56302b0605040503u72fb7bb1j8bdd55dd129f2c1@mail.gmail.com> > > As Graham pointed out SetHandler and AddHandler should not be used at > > the same time. "SetHandler mod_python" causes all files to be served > > by mod_python and when you refer to them in your browser you don't > > need to specify any extension such as .py and "AddHandler mod_python > > .py" causes all files ending in .py to be served by mod_python but in > > this case when referring to a file in your browser you should add the > > .py extension. So if you have > > > > <Directory '/your_document_root/whatever'> > > SetHandler mod_python > > PythonHandler mod_python.publisher > > </Directory> > > > > and you have a file /whatever/foo.py with a function bar( ) then in > > your browser you would type http://yourserver/whatever/foo/bar, > > When using SetHandler you should still be able to use: > > http://yourserver/whatever/foo.py/bar > > Your mileage may vary though depending on how some of the > other bits of Apache configuration are set. See some of previous > rants for possibly useful about this. > > http://www.modpython.org/pipermail/mod_python/2005-August/018828.html > http://www.modpython.org/pipermail/mod_python/2005-August/018829.html > http://www.modpython.org/pipermail/mod_python/2006-March/020501.html > > > whereas with > > > > <Directory '/your_document_root/whatever'> > > AddHandler mod_python .py > > PythonHandler mod_python.publisher > > </Directory> > > > > you would need http://yourserver/whatever/foo.py/bar > > As long as you have content negotiation directives set correctly, you > don't have to use .py extension when AddHandler is used. See my linked > rants above for details. > > > So it's really up to you which behaviour you like, you want *all* > > files to be served by mod_python or only those that have a specific > > extension and then you set either AddHandler or SetHandler. But not > > both :) And in any case, you certainly don't want your .pyc files to > > be served at all, so you should probably remove "AddHandler mod_python > > .pyc". > > If using AddHandler and Apache has write permission to directory, it is > actually a good idea to have: > > <Files *.pyc> > deny from all > </Files> > > This will prevent the pyc files being accessible. > > Using AddHandler for pyc extension will probably actually cause it to > execute the file as publisher, just like if py extension was used. > This is > because mod_python.publisher will quite happily drop the pyc extension > and use basename to match to .py file. > > Besides the fact that AddHandler allows you to mix other file types in > the same directory, the main difference between SetHandler and > AddHandler > as far as mod_python.publisher goes is that when SetHandler is used a > request against the directory is passed through direct to > mod_python.publisher > and it resolves request to index.py. > > When AddHandler is used, a request against the directory results in > mod_dir > trying to match for a file listed in DirectoryIndex directive. In > order for > mod_python.publisher to be triggered, you would need to list index.py > in the DirectoryIndex directive. > > Other than that, with the correct Apache directives defined related > to content > negotiation, both ways should allow for optional use of extension. Thanks for these clarifications, I indeed didn't realize that my rule of thumb 'AddHandler: extension needed' vs. 'SetHandler: no extension' is not quite true. Probably my particular configuration gave me the feeling that it is always the case, but good to know that it isn't :) From webraviteja at gmail.com Wed May 10 01:14:23 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 9 May 2006 22:14:23 -0700 Subject: Can Python installation be as clean as PHP? In-Reply-To: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> Message-ID: <1147238063.235221.13120@j73g2000cwa.googlegroups.com> PHP and Python are different languages. They do things differently. You are just familiar more with one than the other. Give it some time. The many file approach is the modular design of Python. Having the standard library separate from the main Python DLL is an advantage, not a disadvantage. For example, it allows me to pick just the libraries I want to distribute when I make a single file executables. It allows me to distribute just the parts of the standard library I want when I embed Python in another application. Not to mention being able to debug right into the source. Most languages take the Python approach. Have you looked at your C compiler and counted the include and library files? Have you seen Perl or Ruby to check how their library is distributed? I can think of only a few languages that take the PHP approach... early BASIC interpreters, Shells, DSLs and some lesser known interpreters and compilers... none of which are exactly reputed to be flexible. How is manually copying files and editing configuration files easier than clicking through standard distutils installers or typing "setup install" or better ... using eggs through EasyInstall? BTW, you can manually copy Python libraries too in most cases to install and PEAR does offer a package manager for PHP. Installation has never been a problem for me with Python, if not the easiest. In fact, among the languages I regularly use, Python is the only one that includes installer support right in the standard library (distutils) and I find it surprising that you managed to find it wanting all because there are more files :-). From ptmcg at austin.rr._bogus_.com Fri May 19 14:00:53 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 18:00:53 GMT Subject: Python sqlite and regex. References: <mailman.5942.1148042842.27775.python-list@python.org><1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> <hunbg.46845$CH2.29994@tornado.texas.rr.com> <Zwnbg.46846$CH2.28826@tornado.texas.rr.com> <4Anbg.2134$No6.46516@news.tufts.edu> Message-ID: <pJnbg.46849$CH2.26018@tornado.texas.rr.com> "John Salerno" <johnjsal at NOSPAMgmail.com> wrote in message news:4Anbg.2134$No6.46516 at news.tufts.edu... > Paul McGuire wrote: > > "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message > > news:hunbg.46845$CH2.29994 at tornado.texas.rr.com... > > > >> where '*' matches one or more characters, and '?' matches any single > > > > oops, I meant '*' matches zero or more characters. > > '?' also matches 0 characters Maybe it does, and maybe it doesn't... :) Here is my test with the glob module (in my directory, there is a file named PUTTY.RND): >>> glob.glob('PUTTY.RND') ['PUTTY.RND'] >>> glob.glob('PUTTY.RN?') ['PUTTY.RND'] >>> glob.glob('PUTTY.RN?D') [] >>> glob.glob('PUTTY.RN?') ['PUTTY.RND'] >>> glob.glob('PUTTY.RND?') [] >>> glob.glob('PUTT?.RND') ['PUTTY.RND'] >>> glob.glob('PUTTY?.RND') [] >>> glob.glob('PUTT?Y.RND') [] >>> Looks like '?' does *not* match zero characters in glob. On the other hand, in the Windows console window, it appears that '?' *does* match zero characters. Of course, you could write your regexp() routine to interpret '?' any way you wanted. -- Paul From jes at nl.demon.net Sat May 20 19:07:38 2006 From: jes at nl.demon.net (Jim Segrave) Date: Sat, 20 May 2006 23:07:38 -0000 Subject: 'error reading datastream' -- loading file only when transfer is complete? References: <1148159335.678868.22850@j73g2000cwa.googlegroups.com> <126v3nsag5bcqdb@corp.supernews.com> Message-ID: <126v89qbrj1i063@corp.supernews.com> In article <126v3nsag5bcqdb at corp.supernews.com>, Andrew Robert <andrew.arobert at gmail.com> wrote: >liuliuliu at gmail.com wrote: >> hello -- >> >> i'm running python/pygame on maemo (nokia 770). my situation is that >> i'm continually scouring this one directory for incoming files. if i >> see if there's a new file (coming in via wireless scp), i proceed to >> load it and process it. >> >> however, i think i am running into the issue that my program starts to >> load the file after it recognises there is new data, but before the >> file has completely transferred, so at unpredictable times i get a >> pygame.error: Error reading from datastream. >> >> what is the easiest way to work out this issue? easy being the key >> word. :) thank you very much! >> >> christine >> > >You might want to test for file locking before attempting to use Or, really crude - when you see the file, record the time and the file size, but don't attempt to process it yet. Wait for a short interval, then check the size again. If it's changed, wait again. When it gives the same size after a delay period, assume all the data is there. This isn't a good method, but it's simple to implement and will reduce the occurrence of attempts to process a file which is still in transit/ -- Jim Segrave (jes at jes-2.demon.nl) From mike.klaas at gmail.com Wed May 24 19:33:51 2006 From: mike.klaas at gmail.com (Klaas) Date: 24 May 2006 16:33:51 -0700 Subject: Large Dictionaries In-Reply-To: <1147788226.309918@teuthos> References: <1147699064.107490@teuthos> <e49va0$m72$1@newsreader3.netcologne.de> <1147772420.405097@teuthos> <e4cfd3$rq$1@newsreader3.netcologne.de> <1147788226.309918@teuthos> Message-ID: <1148513631.527332.127660@u72g2000cwu.googlegroups.com> Chris: > Berkeley DB is great for accessing data by key for things already > stored on disk (i.e. read access), but write performance for each > key-value pair is slow due to it being careful about flushing > writes to disk by default. This is absolutely false. -Mike From pmartin at snakecard.com Mon May 8 10:21:04 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 08 May 2006 09:21:04 -0500 Subject: How can I do this with python ? References: <mailman.5460.1147060043.27775.python-list@python.org> <1147078986.624152.14770@u72g2000cwu.googlegroups.com> <mailman.5472.1147093519.27775.python-list@python.org> Message-ID: <ktI7g.9360$B42.880@dukeread05> Xiao Jianfeng wrote: > Tim N. van der Leeuw wrote: >> Your question is insufficiently clear for me to answer. >> >> Do you want to know how to read from standard-input in a Python >> program? >> >> Do you want to know how to start an external program from Python, and >> then connect something to that programs standard input? >> >> Do you want to know something else? >> >> Please specify! >> >> Cheers, >> >> --Tim >> >> > Thanks. > > For example, I can call vim and do something like this in a shell script, > > #!/bin/sh > > vim a.file<<-EOF > :some_vim_command > :some_vim_command > :w > :q > EOF > > I want to know how to call vim and to the same thing with python. > > Regrads, hi, os.popen should do that. Philippe From qrczak at knm.org.pl Wed May 10 10:10:58 2006 From: qrczak at knm.org.pl (Marcin 'Qrczak' Kowalczyk) Date: Wed, 10 May 2006 16:10:58 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <87wtcyy5i0.fsf@rpi.edu> <445dc17a$1$25449$bed64819@news.gradwell.net> <87d5eq6rx1.fsf@rpi.edu> Message-ID: <87d5em9dhp.fsf@qrnik.zagroda> Followup-To: comp.lang.lisp Bill Atkins <NOatkinwSPAM at rpi.edu> writes: > The cool thing about ITERATE is that it lets you express looping > concepts in a language designed explicitly for such a purpose, e.g. > > (iter (for x in '(1 3 3)) > (summing x)) => 7 > > (iter (for x in '(1 -3 2)) > (finding x maximizing (abs x))) => -3 > > (iter (for x in '(a b c 1 d 3 e)) > (when (symbolp x) > (collect x))) => (a b c d e) While such macros indeed allow to generate efficient code, I don't find these examples convincing in terms of readability. The same examples in my language where iteration is based on higher order functions are shorter and also clear: Sum [1 3 3] => 7 [1 (-3) 2]->MaximumBy Abs => -3 [#a #b #c 1 #d 3 #e]->Select (_ %Is SYMBOL) => [#a #b #c #d #e] -- __("< Marcin Kowalczyk \__/ qrczak at knm.org.pl ^^ http://qrnik.knm.org.pl/~qrczak/ From aaronwmail-usenet at yahoo.com Mon May 1 18:22:01 2006 From: aaronwmail-usenet at yahoo.com (aaronwmail-usenet at yahoo.com) Date: 1 May 2006 15:22:01 -0700 Subject: set partitioning In-Reply-To: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> Message-ID: <1146522121.798317.206180@i39g2000cwa.googlegroups.com> Something like this, or am I missing something? def partition(List, n, m, k): if n!=m*k: raise "sorry, too many or too few elts" D = {} for x in List: D[x] = 1 if len(D)!=n: raise "sorry (2) you lied about the number" List2 = D.keys() result = [] for i in range(m): result.append( List2[i*k: i*k+k] ) return result ? If this was a take home exam problem, you should be ashamed of yourself! -- Aaron Watters === It's easy. All you have to do is hit the right keys at the right time and the organ plays itself. -- J.S. Bach From gene.tani at gmail.com Fri May 19 18:54:31 2006 From: gene.tani at gmail.com (gene tani) Date: 19 May 2006 15:54:31 -0700 Subject: Daily python url archives In-Reply-To: <1148077127.433261.205800@u72g2000cwu.googlegroups.com> References: <pan.2006.05.19.17.48.58.716100@strasbourg.france> <1148077127.433261.205800@u72g2000cwu.googlegroups.com> Message-ID: <1148079271.103383.26580@u72g2000cwu.googlegroups.com> gene tani wrote: > Bobert wrote: > > Hi, > > > > Do you know by chance if someone has archives from the "daily python url" > > feed (http://www.pythonware.com/daily/rss2.xml) ? An archive of the last 3 > > or 6 months would be most useful to me. > > it gets picked up on Swik.net, with a bunch of other stuff: > > http://swik.net/Python?page=45 Oops, nevermind, you can't access the underlying stories that way From nogradi at gmail.com Mon May 1 05:19:42 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 1 May 2006 11:19:42 +0200 Subject: [ANN] markup.py 1.3 - an HTML and XML writer In-Reply-To: <5f56302b0605010159t702ef8dbl672e149de3d1e4ac@mail.gmail.com> References: <5f56302b0605010159t702ef8dbl672e149de3d1e4ac@mail.gmail.com> Message-ID: <5f56302b0605010219j216f4a59lb3ad54e5e68946ff@mail.gmail.com> > The new 1.3 release of markup.py is available from > > http://markup.sourceforge.net/ > > The markup module attempts to make it easier to output HTML or XML > from a python program without cluttering your code with tags in a > simple and flexible way. > > Changes > > * improved documentation > * function added to optionally escape < and > as &tl; and &gt; > * several functions added for frequently used HTML tag combinations > to speed up things Ooops, I forgot the most important change resulting from a thread on this list. Now if you want to use python keywords as keyword arguments, such as class (happens often in HTML) or print then this should be done as class_ or print_. This convention conforms to PEP-8. From nobody at 127.0.0.1 Tue May 16 21:18:32 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 01:18:32 GMT Subject: python vs perl lines of code Message-ID: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> This is just anecdotal, but I still find it interesting. Take it for what it's worth. I'm interested in hearing others' perspectives, just please don't turn this into a pissing contest. I'm in the process of converting some old perl programs to python. These programs use some network code and do a lot of list/dict data processing. The old ones work fine but are a pain to extend. After two conversions, the python versions are noticeably shorter. The first program does some http retrieval, sort of a poor-man's wget with some extra features. In fact it could be written as a bash script with wget, but the extra processing would make it very messy. Here are the numbers on the two versions: Raw -Blanks -Comments lines chars lines chars lines chars mirror.py 167 4632 132 4597 118 4009 mirror.pl 309 5836 211 5647 184 4790 I've listed line and character counts for three forms. Raw is the source file as-is. -Blanks is the source with blank lines removed, including lines with just a brace. -Comments removes both blanks and comment lines. I think -Blanks is the better measure because comments are a function of code complexity, but either works. By the numbers, the python code appears roughly 60% as long by line and 80% as long by characters. The chars percentage being (higher relative to line count) doesn't surprise me since things like list comprehensions and explicit module calling produce lengthy but readable lines. I should point out this wasn't a straight line-for-line conversion, but the basic code structure is extremely similar. I did make a number of improvements in the Python version with stricter arg checks and better error handling, plus added a couple minor new features. The second program is an smtp outbound filtering proxy. Same categories as before: Raw -Blanks -Comments lines chars lines chars lines chars smtp-proxy.py 261 7788 222 7749 205 6964 smtp-proxy.pl 966 24110 660 23469 452 14869 The numbers here look much more impressive but it's not a fair comparison. I wasn't happy with any of the cpan libraries for smtp sending at the time so I rolled my own. That accounts for 150 raw lines of difference. Another 70 raw lines are logging functions that the python version does with the standard library. The new version performs the same algorithms and data manipulations as the original. I did do some major refactoring along the way, but it wasn't the sort that greatly reduces line count by eliminating redundancy; there is very little redundancy in either version. In any case, these factors alone don't account for the entire difference, even if you take 220 raw lines directly off the latter columns. The two versions were written about 5 years apart, all by me. At the time of each, I had about 3 years experience in the given language and would classify my skill level in it as midway between intermediate and advanced. IOW I'm very comfortable with the language and library reference docs (minus a few odd corners), but generally draw the line at mucking with interpreter internals like symbol tables. I'd like to here from others what their experience converting between perl and python is (either direction). I don't have the sense that either language is particularly better suited for my problem domain than the other, as they both handle network io and list/dict processing very well. What are the differences like in other domains? Do you attribute those differences to the language, the library, the programmer, or other factors? What are the consistent differences across space and time, if any? I'm interested in properties of the code itself, not performance. And just what is the question to the ultimate answer to life, the universe, and everything anyway? ;) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From jens.goepfert at tracetronic.de Wed May 17 08:45:46 2006 From: jens.goepfert at tracetronic.de (Jens) Date: 17 May 2006 05:45:46 -0700 Subject: problem with namespaces using eval and exec In-Reply-To: <e4c80l$ton$00$1@news.t-online.com> References: <1147770312.756392.147920@i39g2000cwa.googlegroups.com> <e4c80l$ton$00$1@news.t-online.com> Message-ID: <1147869946.221732.19530@38g2000cwa.googlegroups.com> Thanks a lot, that works for me. From bdesth.quelquechose at free.quelquepart.fr Tue May 9 22:02:13 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 May 2006 04:02:13 +0200 Subject: problemi con POST In-Reply-To: <mailman.5534.1147211197.27775.python-list@python.org> References: <1147208587.275024.317410@i40g2000cwc.googlegroups.com> <44610a77$0$2082$626a54ce@news.free.fr> <mailman.5534.1147211197.27775.python-list@python.org> Message-ID: <44611ac1$0$23453$636a55ce@news.free.fr> Michael Hobbs a ?crit : > Bruno Desthuilliers wrote: > >> Heavy a ?crit : >> >> >>> Ciao a tutti, >>> sto creando una applicazione in python, che deve fungere anche da >>> server web... >>> non ho assolutamente problemi a prendere i parametri di una 'GET', mi >>> limito a fare il parsing della URL, ma come faccio a prendere i >>> parametri di una 'POST'? io cerco di leggere dal socket di lettura >>> 'rfile' ma poi resto bloccato all'infinito perch? evidemente resta in >>> attesa di qualcosaltro... c'? gi? qualche metodo che mi pu? >>> aiutare?? oppure sapete darmi qualche dritta? grazie... >>> >>> >> >> D?sol?, mais je n'ai rien compris (enfin, si : que tu avais des >> probl?mes pour parser une requ?te HTTP POST et que tu te retrouvais >> avec une lecture bloquante sur un socket, mais ce n'est pas avec ?a >> qu'on va pouvoir t'aider). Tu pourrais nous reposter ?a en english ?-) >> > > Aay Enchfray eplyray otay anay Italianay estionquay? Ellway, Iay ancay > itewray inay aay oreignfay anguagelay ootay! didnee !-) WTB, rof eht elpoep ereh taht t'nod kaeps hcnerf, I saw tsuj gniyrt ot nialpxe eht PO taht gnitsoper ni hsilgnE thgim eb a doog aedi. From johnjsal at NOSPAMgmail.com Mon May 15 15:20:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 19:20:57 GMT Subject: common practice for creating utility functions? In-Reply-To: <m2k68n2k8y.fsf@unique.fqdn> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <m2k68n2k8y.fsf@unique.fqdn> Message-ID: <tw4ag.2097$No6.46172@news.tufts.edu> Dan Sommers wrote: > Perhaps I'm "old school," but I don't bother with classes unless I'm > going to end up with multiple instances (or I'm pushed into a corner by, > e.g., a GUI framework). Thanks to all of you! In fact, I sort of came to this same conclusion. I started with a class, but realized there wasn't much of a point since I'm just doing some 'work' and returning the cryptogram. I might try the other suggestion too about convert_quote = make_code, that might be ok. Or I can simply call make_code. Thanks! From ptmcg at austin.rr._bogus_.com Fri May 19 02:35:47 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 06:35:47 GMT Subject: Getting URL's References: <1148019975.277742.253400@y43g2000cwc.googlegroups.com> Message-ID: <7Hdbg.41202$Qq.40549@tornado.texas.rr.com> "defcon8" <defcon8 at gmail.com> wrote in message news:1148019975.277742.253400 at y43g2000cwc.googlegroups.com... > How do I get all the URL's in a page? > pyparsing comes with a simple example that does this, too. -- Paul Download pyparsing at http://sourceforge.net/projects/pyparsing From gherron at islandtraining.com Sat May 6 03:00:24 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sat, 06 May 2006 00:00:24 -0700 Subject: combined files together In-Reply-To: <87psirslhy.fsf@localhost.localdomain> References: <87psirslhy.fsf@localhost.localdomain> Message-ID: <445C4988.7050902@islandtraining.com> Gary Wessle wrote: >Hi > >is there a module to do things like concatenate all files in a given >directory into a big file, where all the files have the same data >formate? >name address phone_no. > >or do I have to open each, read from old/write-or-append to new ... > >thanks > > > There's hardly enough code here to make a module out of this: combined = open('...', 'wb') for name in os.listdir(path): infile = open(os.path.join(path,name), 'rb') for line in infile: combined.write(line) It could be more efficient by reading larger chunks than single lines, and could be more accurate by closing both input and output files when done, but you get the point I hope. On the other hand, if you've got the right OS, you might try something like: os.system("cat * > combined") Gary Herron From steve at holdenweb.com Sun May 21 02:06:08 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 May 2006 07:06:08 +0100 Subject: Feature request: sorting a list slice In-Reply-To: <e4ougq$dba$1@sea.gmane.org> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> <e4ouaa$cu6$1@sea.gmane.org> <e4ougq$dba$1@sea.gmane.org> Message-ID: <e4p00b$fts$2@sea.gmane.org> Robert Kern wrote: > Steve Holden wrote: > >>The effbot wrote: >> >> >>>George Sakkis wrote: >>> >>> >>>>>It would be useful if list.sort() accepted two more optional >>>>>parameters >>> >>>useful for what? what's the use case ? >> >>John Machin then wrote, without quoting any context at all: >> >> >>>Use case? >> >>He means "under what circumstances do you see someone actually using the >>proposed feature rather than just nodding and saying "that looks >>useful". IOW, who would use the new feature, and why? > > > I believe that John was asking George for a use case rather than asking Fredrik > what a use case was. > In which case, as I pointed out, John would have done better to quote a little more context. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From python.list at tim.thechases.com Fri May 19 12:04:51 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 19 May 2006 11:04:51 -0500 Subject: number of different lines in a file In-Reply-To: <446DD5E4.5090701@anansispaceworks.com> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <mailman.5913.1147991572.27775.python-list@python.org> <iY7bg.3778$x4.261@newsread3.news.pas.earthlink.net> <e4jnbd$vmg$1@sea.gmane.org> <446DD5E4.5090701@anansispaceworks.com> Message-ID: <446DECA3.9090309@tim.thechases.com> > I actually had this problem a couple of weeks ago when I > discovered that my son's .Xsession file was 26 GB and had > filled the disk partition (!). Apparently some games he was > playing were spewing out a lot of errors, and I wanted to find > out which ones were at fault. > > Basically, uniq died on this task (well, it probably was > working, but not completed after over 10 hours). I was using > it something like this: > > cat Xsession.errors | uniq > Xsession.uniq A couple things I noticed that may play into matters: 1) uniq is a dedicated tool for the task of uniquely identifying *neighboring* lines in the file. It doesn't get much faster than that, *if* that's your input. This leads to #4 below. 2) (uneventfully?) you have a superfluous use of cat. I don't know if that's bogging matters down, but you can just use uniq < Xsession.errors > Xsession.uniq which would save you from having each line touched twice...once by cat, and once by uniq. 3) as "uniq" doesn't report on its progress, if it's processing a humongous 26 gig file, it may just sit there churning for a long time before finishing. It looks like it may have taken >10hr :) 4) "uniq" requires sorted input. Unless you've sorted your Xsession.errors before-hand, your output isn't likely to be as helpful. The python set/generator scheme may work well to keep you from having to sort matters first--especially if you only have a fairly scant handful of unique errors. 5) I presume wherever you were writing Xsession.uniq had enough space...you mentioned your son filling your HDD. It may gasp, wheeze and die if there wasn't enough space...or it might just hang. I'd hope it would be smart enough to gracefully report "out of disk-space" errors in the process. 6) unless I'm experiencing trouble, I just tend to keep my .xsession-errors file as a soft-link to /dev/null, especially as (when I use KDE rather than Fluxbox) KDE likes to spit out mountains of KIO file errors. It's easy enough to unlink it and let it generate the file if needed. 7) With a file this large, you most certainly want to use a generator scheme rather than trying to load each of the lines in the file :) (Note to Bruno...yes, *this* would be one of those places you mentioned to me earlier about *not* using readlines() ;) If you're using 2.3.x, and don't have 2.4's nice syntax for len(set(line.strip() for line in file("xsession.errors"))) you should be able to bypass reading the whole file into memory (and make use of sets) with from sets import Set as set s = set() for line in file("xsession.errors"): s.add(line.strip()) return len(s) In your case, you likely don't have to call strip() and can just get away with adding each line to the set. Just a few ideas for the next time you have a multi-gig Xsession.errors situation :) -tkc From girodt at gmail.com Fri May 5 06:27:42 2006 From: girodt at gmail.com (TG) Date: 5 May 2006 03:27:42 -0700 Subject: Subclassing array In-Reply-To: <445a4845$0$21665$626a54ce@news.free.fr> References: <1146747096.623101.122510@j73g2000cwa.googlegroups.com> <1heszg6.1q17bgp1jwua35N%aleaxit@yahoo.com> <o5r*BDOfr@news.chiark.greenend.org.uk> <445a4845$0$21665$626a54ce@news.free.fr> Message-ID: <1146824862.073573.82550@v46g2000cwv.googlegroups.com> That's great, thanks ! To put it short, when I create a Stimulus object, it first seek __new__() method. But if I don't define it, it looks for the one defined in Vector. This raises a problem because the parameters passed to Stimulus(params) aren't fitting with Vector parameters, raising an exception. That's why I have to use this *arg **kw syntax in order to allow my subclasses having any arguments without causing troubles. Am I right ? From scott.daniels at acm.org Tue May 16 18:27:29 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 16 May 2006 15:27:29 -0700 Subject: round numbers in an array without importing Numeric or Math? - SOLVED, sort of In-Reply-To: <cHpag.37880$CH2.22854@tornado.texas.rr.com> References: <446a1748$0$61168$ae4e5890@news.nationwide.net> <446a2032$0$61167$ae4e5890@news.nationwide.net> <cHpag.37880$CH2.22854@tornado.texas.rr.com> Message-ID: <446a4ddd$1@nntp0.pdx.net> Paul McGuire wrote: > ... or if you prefer the functional approach (using map)... > > roundToInt = lambda z : int(z+0.5) > Topamax = map( roundToInt, map( float, map(str, Topamax) ) ) Somehow, the list comprehension looks simpler and clearer to me: Topamax = [int(float(uni) + .5) for uni in Topamax] I really dislike lines like: roundToInt = lambda z : int(z+0.5) You've already chosen a name, but you'd rather write in the lisp style. def roundToInt(z):return int(z+0.5) takes all of _one_ more character. I also don't understand why you convert to string from unicode in: ... map(str, Topamax) ) ) float works on all string types (including unicode), and will accept some non-ASCII digit values. -- -Scott David Daniels scott.daniels at acm.org From johnjsal at NOSPAMgmail.com Fri May 12 10:01:51 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 12 May 2006 14:01:51 GMT Subject: where do you run database scripts/where are DBs 'located'? Message-ID: <jz09g.2091$No6.46071@news.tufts.edu> Ok, I've been browsing through the MySQLdb docs, and I *think* I know the kind of code I need to write (connect, cursor, manipulate data, commmit, etc. -- although I probably need to get more familiar with actual SQL commands too), but here's my problem: I don't know where these scripts are supposed to be executed, or how they are supposed to 'find' the database. Really, I have the same question for two different scenarios: accessing and working with a database that is stored locally on my PC, and the same with a DB that is on my web server space. I figure I already know the host, username, password and database name (in fact, all these things are spelled out as far as my web DB is concerned; I assume my host name for the local DB is my computer's name). But my question is, can these DB scripts be executed anywhere, and they will find the DB based on the connect() parameters? Or do I need to do something special with them? It seems like a similar problem to when you don't have your PYTHONPATH variable set up properly. I've tried some DB stuff, but it doesn't seem to work. If more information is needed, I will try my local DB when I get home later. As for the web DB, I figure there's probably more issues involved that I'm not aware of, since web programming is still new to me. So without actually giving you some code and tracebacks, is there any general advice about how to set up these scripts? Also, is there any better documentation than this: http://sourceforge.net/docman/display_doc.php?docid=32071&group_id=22307 It doesn't seem too thorough, and it also doesn't cover actual SQL queries that you'd have to pass to the query method. Maybe I will just have to find that information in a MySQL tutorial. Thanks. From onurb at xiludom.gro Fri May 19 06:48:48 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 12:48:48 +0200 Subject: who can give me the detailed introduction of re modle? In-Reply-To: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: <446da2f8$0$5388$626a54ce@news.free.fr> softwindow wrote: > the re module is too large and difficult to study Too bad. > i need a detaild introduction. That's fine. Then write it. Or pay someone to do so. Just for the record : that's the only answers you would have get on most usenet groups. Hopefully, c.l.py is a very friendly and tolerant newsgroup. Seriously, do yourself a favour, read this: http://www.catb.org/~esr/faqs/smart-questions.html HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From softwindow at gmail.com Wed May 24 05:16:20 2006 From: softwindow at gmail.com (softwindow) Date: 24 May 2006 02:16:20 -0700 Subject: hi,every body. a problem with PyQt. Message-ID: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> i use QT-designer to design application GUI. now i save the test.ui file into e:\test\test.ui next step,how can i run it? From deets at nospam.web.de Wed May 17 18:07:58 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 May 2006 00:07:58 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <4d1l5nF188kcuU1@uni-berlin.de> glomde schrieb: > i I would like to extend python so that you could create hiercical > tree structures (XML, HTML etc) easier and that resulting code would be > more readable than how you write today with packages like elementtree > and xist. > I dont want to replace the packages but the packages could be used with > the > new operators and the resulting IMHO is much more readable. > > The syntax i would like is something like the below: > > # Example creating html tree > > '*!*' is an operator that creates an new node, > '*=*' is an operator that sets an attribute. > > So if you take an example to build a smalle web page > and compare with how it looks with in element tree now > and how it would look like when the abover operators would exist. > > With element tree package. > > # build a tree structure > root = ET.Element("html") > head = ET.SubElement(root, "head") > title = ET.SubElement(head, "title") > title.text = "Page Title" > body = ET.SubElement(root, "body") > body.set("bgcolor", "#ffffff") > body.text = "Hello, World!" > > > > With syntactical sugar: > > # build a tree structure > root = ET.Element("html") > *!*root: > *!*head("head"): > *!*title("title): > *=*text = "Page Title" > *!*body("body"): > *=*bgcolor = "#ffffff" > *=*text = "Hello, World!" > > > > I think that with the added syntax you get better view of the html > page. > Repeating things dissapears and you get indentation that corresponds to > the tree. > I think it is very pythonic IMHO. > > It could be done quite generic. If the variable, object after '*!*' > must support append > method and if you use '*=*' it must support __setitem__ > > Any comments? It's ugly, and could easily achieved using the built-in tupels, lists and dictionaries together with a simple traversing function. Like this (untested): class Node(object): def __init__(self, value): self.value = vallue self._childs = [] def append(self, child): self._childs.append(child) t = ('root', ('child1, ('grandchild', ()), 'child2', () ) ) def create_node(t): value, childs = t n = Node(value) if childs: for ch in childs: n.append(create_node(ch)) return n IMHO that tuple-based tree is waaay more readable than your proposal - and no need to come up with new syntax. Diez From sam at nuevageorgia.com Mon May 22 11:52:46 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 22 May 2006 08:52:46 -0700 Subject: Python - Web Display Technology In-Reply-To: <slrne73loa.8pe.sybrenUSE@schuimige.stuvel.eu> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <bhv172hbu1i37nqi3kp1rhnuaujj1qo208@4ax.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <slrne73loa.8pe.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1148313166.202814.55680@j73g2000cwa.googlegroups.com> I don't agree with 99.9%, but the majority of Flash sites are done poorly. Mine is certainly sub-optimal, :) 1. Loss of back button Isn't this really a myth? A page with a time dimension, be it Flash, HTML/JS or whatever, breaks the back button. A page without a time dimension doesn't break the back button. Should we now and forever more give up the time dimension to avoid breaking the back button. Perhaps for non-text sites, the back button is an anachronism? Fonts are problematic in Flash, this is a weakness of Flash. Scaling Fonts is even more problematic, but, fonts are an issue in any precise design on the web. I wouldn't argue Flash is better for text sites at the moment, due to Search Engine shortcomings. As for the blind issue,that makes no sense to me. Is the suggestion that we should give up using images in web sites since some people can't see them. Might as well throw out the use of the img tag while we are at it? From rschroev_nospam_ml at fastmail.fm Thu May 18 10:43:14 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Thu, 18 May 2006 14:43:14 GMT Subject: Question about exausted iterators In-Reply-To: <mailman.5882.1147962343.27775.python-list@python.org> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <mailman.5879.1147959939.27775.python-list@python.org> <446c7f44$0$7128$626a54ce@news.free.fr> <mailman.5882.1147962343.27775.python-list@python.org> Message-ID: <6K%ag.432621$_c4.11671650@phobos.telenet-ops.be> Fredrik Lundh schreef: > Christophe wrote: > >>>> Because I'm still waiting for a valid answer to my question. >>>> The answer "Because it has been coded like that" or is not a >>>> valid one. >>> it's been coded like that because that's what the specification >>> says: >>> >>> http://www.python.org/dev/peps/pep-0234/ >> I didn't though I had to mention that "Because the spec has been >> writen like that" wasn't a valid answer either. > > so what is a valid answer? I think he wants to know why the spec has been written that way. The rationale mentions exhausted iterators: "Once a particular iterator object has raised StopIteration, will it also raise StopIteration on all subsequent next() calls? Some say that it would be useful to require this, others say that it is useful to leave this open to individual iterators. Note that this may require an additional state bit for some iterator implementations (e.g. function-wrapping iterators). Resolution: once StopIteration is raised, calling it.next() continues to raise StopIteration." This doesn't, however, completey answer the OP's question, I think. It is about raising or not raising StopIteration on subsequent next() calls but doesn't say anything on possible alternatives, such as raising another exception (I believe that's what the OP would like). Not that I know of use cases for other exceptions after StopIteration; just clarifying what I think the OP means. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From admin at angerona.cult.cu Wed May 3 15:03:33 2006 From: admin at angerona.cult.cu (=?iso-8859-1?Q?Tom=E1s_Rodriguez_Orta?=) Date: Wed, 3 May 2006 13:03:33 -0600 Subject: I have problem with the qt-module333.dll Message-ID: <004a01c66ee4$460e77f0$0000fea9@zeus> Hello friends. I have the pyqt 3.14 educational and when execute some exmple the system sohow the following error. The dinamic link library qt-module333.dll could not be the found the specified path c:\\python24\lib I hope some help. bst regards TOMAS ------------------------------------------------------------------------- Este correo fue escaneado en busca de virus con el MDaemon Antivirus 2.27 en el dominio de correo angerona.cult.cu y no se encontro ninguna coincidencia. From bleamz at gmail.com Mon May 15 04:15:18 2006 From: bleamz at gmail.com (BLeAm) Date: 15 May 2006 01:15:18 -0700 Subject: Web framework to recommend References: <e495q1$1085$1@news.hgc.com.hk> Message-ID: <1147680918.627917.279480@v46g2000cwv.googlegroups.com> Hi Jacky, Even though Turbogears and Django are focused from many people, and I'm not so sure whether this the best or not, but let's check at http://spyce.sourceforge.net, you can embed Python script into the page just like JPS,ASP,PHP. Hope this help. Cheers! From scott.daniels at acm.org Mon May 8 13:03:40 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 10:03:40 -0700 Subject: Problem with iterators and inheritance In-Reply-To: <1146843136.146086@seven.kulnet.kuleuven.ac.be> References: <1146843136.146086@seven.kulnet.kuleuven.ac.be> Message-ID: <445f7634$1@nntp0.pdx.net> Yves wrote: (in surprise because C's __init__ doesn't over-ride next) > class A(object): > def __init__(self, n): self.n = n > def __iter__(self): return self > def next(self): > if self.n > 0: > self.n -= 1 > return "A: %d" % self.n > else: raise StopIteration() > > class C(A): > def __init__(self, n): > super(C,self).__init__(n) > self.next = self.mynext > def __iter__(self): return self > def mynext(self): > if self.n > 0: > self.n -= 1 > return "C: %d" % self.n > else: > raise StopIteration() The answer is to understand the following code: class Xyz(object): def __init__(self): self.x = 23 def x(self): return 42 print Xyz().x New-style classes control object attribute lookups, and messages go to the class first (ignoring the instance dictionary). That is also how "properties" work, which (if you think about it right) could not otherwise survive the first assignment of the property. --Scott David Daniels scott.daniels at acm.org From akameswaran at gmail.com Tue May 30 15:20:23 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 30 May 2006 12:20:23 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <447c8c6e$1@nntp0.pdx.net> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <mailman.6282.1148767807.27775.python-list@python.org> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> <447c8c6e$1@nntp0.pdx.net> Message-ID: <1149016823.214610.258930@r44g2000cwb.googlegroups.com> Scott David Daniels wrote: > This works with "iterables" (and produces), rather than "iterators", > which is vital to the operation. > > --Scott David Daniels > scott.daniels at acm.org Sorry, it doesn't. It works with strings. It doesn't work with file, it doesn't work with iterators I have created. I have been using file objects as my test iterables for now - forgoing any complications in my own iterables. such that my test bed has been: f = open('word.txt') f2 = open('word2.txt') f3 = open('word3.txt') for combo in [testable function here] print combo Each file contains the letter a through g on, with each letter on a line. At least I don't feel as bad anymore. My first attempts generate the same output, and a couple of my earlier attempts work quite nicely with lists, and similar things. But I can't find anthing that works generically with any iterable, nor anything that works with generators. From alastair at gotadsl.co.uk Wed May 24 12:32:03 2006 From: alastair at gotadsl.co.uk (Alastair Alexander) Date: Wed, 24 May 2006 17:32:03 +0100 Subject: COM Server crashing when returning large arrays References: <mailman.6105.1148382878.27775.python-list@python.org> Message-ID: <L_ednagNB9hwFenZRVnyvg@pipex.net> Thanks for the replies Tim & Stefan I'm using Python 2.3.5 on XP and the PythonWin build number seems to be 201 ... I'll see if I can find 207. The following blows up on both an XP and Win2k box ... both have same build of Python and PythonWin: ################################ import sys class Cache: _public_methods_ = ['GoPop'] _reg_progid_ = 'pyTestCOM.Test' _reg_clsid_ = '{F1CC1052-BD44-4980-8EA5-9B29CDDB5955}' def GoPop(self): return [["spam, eggs and spam" for i in range(0,10)] for i in range(1,500)] if __name__ == '__main__': print 'Registering COM Server' import win32com.server.register win32com.server.register.UseCommandLine(Cache) ################################ I'll check out the other mailing list too. This is my first foray into the wider Python community. I've been using the language on and off for the last few years as it is the embedded scripting language in the Front Arena trading system. I'm now working on a data modelling project that (sadly) requires a considerable amount of data processing to take place in Excel/VBA. Excel is fine for presentation, but Python is much better for many of the data processing tasks. pythoncom would offer an almost effortless way of getting VBA and Python to interact ... if I could just pass large chunks of data ... From mensanator at aol.com Tue May 9 16:27:40 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 9 May 2006 13:27:40 -0700 Subject: Shadow Detection? References: <HGEOKIAPAMCIFPPBDALKMEINCAAA.m.yanowitz@kearfott.com> <mailman.5531.1147206185.27775.python-list@python.org> Message-ID: <1147206460.858812.143390@i40g2000cwc.googlegroups.com> Carl J. Van Arsdall wrote: > Michael Yanowitz wrote: > > Hello: > > > > Many times, people are warning things like > > "Don't use 'str' as a variable name as it will shadow the > > built in str function." > > Is there some way to determine if a string is already > > defined in some higher scope? > > Maybe something like > > <code> > > > > if isdefined ('str'): > > print 'str is already defined, please choose another name' > > > > > You might check out globals() which returns a dictionary of everything: > > Python 2.2 (#1, Mar 26 2002, 15:46:04) > [GCC 2.95.3 20010315 (SuSE)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > >>> globals() > {'__builtins__': <module '__builtin__' (built-in)>, '__name__': > '__main__', '__doc__': None} > >>> blah = None > >>> globals() > {'__builtins__': <module '__builtin__' (built-in)>, '__name__': > '__main__', '__doc__': None, 'blah': None} > > #Taking this a step further, this is a dictionary so you can use the > has_key method or try to access the dict and catch an exception should > the key not exist > > >>> if globals().has_key('blah'): > ... print "I have blah" > ... > I have blah > > > -carl > > > -- > > Carl J. Van Arsdall > cvanarsdall at mvista.com > Build and Release > MontaVista Software There's also the dir() function: >>> dir() ['__builtins__', '__doc__', '__name__'] >>> dir(__builtins__) ['ArithmeticError', 'AssertionError', 'AttributeError', 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False', 'FloatingPointError', 'FutureWarning', 'IOError', 'ImportError', 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', 'PendingDeprecationWarning', 'ReferenceError', 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', 'True', 'TypeError', 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError', 'UnicodeError', 'UnicodeTranslateError', 'UserWarning', 'ValueError', 'Warning', 'WindowsError', 'ZeroDivisionError', '_', '__debug__', '__doc__', '__import__', '__name__', 'abs', 'apply', 'basestring', 'bool', 'buffer', 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', 'frozenset', 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', 'range', 'raw_input', 'reduce', 'reload', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice', 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] >>> dir(__name__) ['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith', 'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'replace', 'rfind', 'rindex', 'rjust', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill'] >>> dir(__doc__) ['__class__', '__delattr__', '__doc__', '__getattribute__', '__hash__', '__init__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__str__'] From zombek at gmail.com Mon May 15 12:07:24 2006 From: zombek at gmail.com (zombek at gmail.com) Date: 15 May 2006 09:07:24 -0700 Subject: saving file permission denied on windows In-Reply-To: <1147709018.186441.245100@v46g2000cwv.googlegroups.com> References: <1147708797.746442.19220@j73g2000cwa.googlegroups.com> <1147709018.186441.245100@v46g2000cwv.googlegroups.com> Message-ID: <1147709244.897487.60690@j73g2000cwa.googlegroups.com> The permission is OK I guess... I don't see anything about permission there, but I tried to save to maaaaaany other catalogs even to C:\ and D:\ and it raised the same error From eugene.morozov at gmail.com Tue May 9 04:59:17 2006 From: eugene.morozov at gmail.com (eugene.morozov at gmail.com) Date: 9 May 2006 01:59:17 -0700 Subject: PythonWin's Check (any other Lint tool) ? In-Reply-To: <1147159218.850130.103110@j73g2000cwa.googlegroups.com> References: <1147159218.850130.103110@j73g2000cwa.googlegroups.com> Message-ID: <1147165157.222256.324530@e56g2000cwe.googlegroups.com> Hello, There're a pylint (http://www.logilab.org/projects/pylint) and pychecker (http://pychecker.sourceforge.net/) projects. Eugene From wistanswick at linuxmail.org Sat May 6 01:10:43 2006 From: wistanswick at linuxmail.org (Glyn Millington) Date: Sat, 06 May 2006 06:10:43 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> Message-ID: <87k68zybzg.fsf@nowhere.org> Ken Tilton <kentilton at gmail.com> writes: > kenny (wondering what to call a flock (?!) of lemmings) Couldn't find it here:- http://ojohaven.com/collectives/ So I would propose a "leap" of lemmings :-) WAY OT! Sorry. atb Glyn From johnjsal at NOSPAMgmail.com Wed May 10 09:56:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 13:56:52 GMT Subject: multiline strings and proper indentation/alignment In-Reply-To: <4461c445$0$14031$626a54ce@news.free.fr> References: <Ms48g.2070$No6.45827@news.tufts.edu> <mailman.5527.1147204632.27775.python-list@python.org> <44613e5d$0$9438$c3e8da3@news.astraweb.com> <4461c445$0$14031$626a54ce@news.free.fr> Message-ID: <Eim8g.2075$No6.45677@news.tufts.edu> bruno at modulix wrote: > Why not trying by yourself ?-) Doh! I always forget I can do this! :) > Mmm. Not good. Let's try again: >>>> print textwrap.dedent(s).strip() > this is a multiline > triple-quted string with > indentation for nicer code formatting > > Well, seems like we're done. About 2'30'' to solve the problem. Actually, I'm still wondering if it's possible to remove the newlines at the end of the first and second lines (after 'multiline' and 'with'), so that the string is one line. But it's already been shown that textwrap alone doesn't do this, so I'd rather not mess with all the extra stuff to do it, when I can just put the string in parentheses. Thanks. From bignose+hates-spam at benfinney.id.au Fri May 19 20:46:05 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 May 2006 10:46:05 +1000 Subject: How to append to a dictionary References: <1148039985.232831.56040@i40g2000cwc.googlegroups.com> Message-ID: <87k68hjzg2.fsf@benfinney.id.au> "Harlin Seritt" <harlinseritt at yahoo.com> writes: > groups = {'IRISH' : 'green', 'AMERICAN' : 'blue'} > > I want to add another key: 'ITALIAN' : 'orange' > > How do I append this to 'groups'? Dictionary items have no implicit sequence, so you don't "append" to one. Assigning any value to a key in the dictionary will create that key if it doesn't exist. >>> groups = {'IRISH': 'green', 'AMERICAN': 'blue'} >>> groups['ITALIAN'] = 'orange' >>> print groups {'IRISH': 'green', 'AMERICAN': 'blue', 'ITALIAN': 'orange'} Please enjoy your trip through the Python tutorial, working through the examples and understanding each one. <URL:http://docs.python.org/tut/> -- \ "It is the responsibility of intellectuals to tell the truth | `\ and expose lies." -- Noam Chomsky | _o__) | Ben Finney From mpeters42 at gmail.com Wed May 10 15:59:57 2006 From: mpeters42 at gmail.com (mpeters42 at gmail.com) Date: 10 May 2006 12:59:57 -0700 Subject: reusing parts of a string in RE matches? In-Reply-To: <eir8g.2084$No6.45965@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> <E6r8g.2083$No6.45931@news.tufts.edu> <eir8g.2084$No6.45965@news.tufts.edu> Message-ID: <1147291197.423570.242440@g10g2000cwb.googlegroups.com> Exactly, Now this will work as long as there are no wildcards in the pattern. Thus, only with fixed strings. But if you have a fixed string, there is really no need to use regex, as it will complicate you life for no real reason (as opposed to simple string methods). With a more complex pattern (like 'a.a': match any character between two 'a' characters) this will get the length, but not what character is between the a's. To actually do that you will need to iterate through the string and apply the pattern match (which matches only the beginning of a string) to a indexed subset of the original (see example in the last post) From olsongt at verizon.net Thu May 18 11:52:20 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 18 May 2006 08:52:20 -0700 Subject: Python Install In-Reply-To: <mailman.5887.1147965090.27775.python-list@python.org> References: <1147962608.945821.226220@i40g2000cwc.googlegroups.com> <mailman.5887.1147965090.27775.python-list@python.org> Message-ID: <1147967540.424467.138910@38g2000cwa.googlegroups.com> Paul Osman wrote: > On 18-May-06, at 10:30 AM, D wrote: > > > I'm sure this is an easy question for most here, but it's throwing me > > for a loop at the moment - I need to upgrade RHEL 3 with the latest > > version of Python. I downloaded the source and installed, but we're > > still having problems (i.e. some Python apps don't work, Add/Remove > > Applications console errors out and doesn't open, etc.). My guess is > > that it's using old libraries or otherwise conflicting with the old > > Python version, but I'm not sure how to remove the original version. > > Any help would be greatly appreciated! > > RHEL uses python for distro specific tools pretty extensively iirc. > I'd stay away from source installs and stick to rpms / yum / > up2date / whatever RH uses these days. > > Cheers, > > Paul Osman > http://www.eval.ca You can also use 'make altinstall' This does everything but symlink to python, so you can still run (for example) python2.4 to start your scripts. From Serge.Orlov at gmail.com Wed May 17 07:35:49 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 17 May 2006 04:35:49 -0700 Subject: arrays, even, roundup, odd round down ? References: <446a4891$0$61165$ae4e5890@news.nationwide.net> Message-ID: <1147865749.366316.181260@g10g2000cwb.googlegroups.com> Lance Hoffmeyer wrote: > So, I have using the following to grab numbers from MS Word. I discovered that that there is a "special" > rule being used for rounding. > > If a ??.5 is even the number is to rounded down (20.5 = 20) > if a ??.5 is odd the number is to rounded up (21.5 = 22) > > Brands = ["B1","B2"] > A1 = [] > A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, target_table).group(1) for i in Brands ] > A1 = [int(float(str(x))+0.5) for x in A1 ] > print A1 > > > Any solutions for this line with the above conditions? Seems like a job for Decimal: from decimal import Decimal numbers = "20.50 21.5".split() ZERO_PLACES = Decimal("1") print [int(Decimal(num).quantize(ZERO_PLACES)) for num in numbers] produces [20, 22] From frank at chagford.com Sun May 21 06:11:12 2006 From: frank at chagford.com (Frank Millman) Date: 21 May 2006 03:11:12 -0700 Subject: Problem with odbc and Sql Server Message-ID: <1148206272.017343.75600@y43g2000cwc.googlegroups.com> Hi all I have found a problem using MS Sql Server connecting via the odbc module from python-win32. I am liaising with Mark Hammond, and he is trying to help, but he is very busy, and I cannot be certain whether the problem originates with the odbc module, with the ODBC Driver, or with Sql Server itself. If anyone can help me to pinpoint this, I will be very grateful. Assume a table 't1' with a column 'c1' of type varchar(10). >From Python, set c1 to an empty string - cur.execute("UPDATE t1 SET c1 = ?",['']) The result is that c1 is actually set to a string of 10 spaces. If I execute the command without using parameters - cur.execute("UPDATE t1 SET c1 = ''") it works - c1 is set to an empty string. I am using Windows Server 2003 (SP1), Sql Server 2000 (SP4), and ODBC Driver 2000.86.1830.00. I tried it on Sql Server 2005, also using Windows Server 2003. It gives the same problem. Mark has a test suite which creates an MS Access database on the fly, and allows you to run any odbc command against it. If I try the above command with this setup, it works correctly. If I modify the test suite to connect to my installed Sql Server, it fails. This seems to suggest that the problem is not coming from the odbc module. I have googled the MS Sql Server newsgroup, searching for 'empty string'. I found several posts, but they were all to do with the fact that, in an earlier version of Sql Server, trying to set a varchar column to an empty string resulted in it being set to a single space. I would have thought that, if my problem comes from the MS side, I would find some reference to it, but I could not. One way of proving it would be to execute the command from some other tool that allows you to pass paramaterised commands via the ODBC driver through to Sql Server. I seem to remember reading that you can do this from VB and from MS Access, but I have no idea how to do this. I have MS Access installed on my machine, so if anyone can talk me through the steps required, I can give it a try myself. Alternatively, if anyone has a setup where they can test this, I would be very interested to hear the result. Any suggestions will be much appreciated. Thanks Frank Millman From claudio.grondi at freenet.de Fri May 19 10:42:50 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Fri, 19 May 2006 16:42:50 +0200 Subject: open file with whitespaces In-Reply-To: <446dd79c$0$8021$636a55ce@news.free.fr> References: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> <446dd79c$0$8021$636a55ce@news.free.fr> Message-ID: <e4klh5$c84$1@newsreader3.netcologne.de> Christophe wrote: > mardif a ?crit : > >> Hi guys. >> I've a very big big big problem: >> >> I've in my windows computer a file named cicciobello.html, located in >> c:\documents and settings\username\desktop\cicciobello.html. >> >> Now, I MUST open this file with os.spawn(os.P_WAIT ...., because I must >> wait the user cancel the explorer window, ok? >> And so, I write: >> >> import os >> os.spawnl(os.P_WAIT, "c:\programmi\internet explorer\iexplorer.exe", >> "c:\documents and settings\username\desktop\cicciobello.html") >> >> the python process don't fail, but explorer don't visualize correctly >> the file opened: i receive an "not found" error message. >> >> I've found that the whitespaces in file path are the problem. >> If you see to explorer address bar, you will find the address >> completely wrong... >> >> I've found no solution! >> Can you help me, please?? >> >> thx very very very much!!! >> > > And I thought the problem where the incorrectly used \ :) Try that first : > > os.spawnl(os.P_WAIT, r"c:\programmi\internet explorer\iexplorer.exe", > r"c:\documents and settings\username\desktop\cicciobello.html") Another option to try in case this is not the problem is to put the file name in quotation marks as it is necessary when using command line shell (not tested, just an idea): os.spawnl(os.P_WAIT,'"c:\\programmi\\internet explorer\\iexplorer.exe"', '"c:\\documents and settings\\username\\desktop\\cicciobello.html"') From george.sakkis at gmail.com Wed May 24 15:03:08 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 24 May 2006 12:03:08 -0700 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> <1148485967.164221.304310@y43g2000cwc.googlegroups.com> <Xns97CD70C3D2CEEcastleamber@130.133.1.4> <87y7wre6yr.fsf@rpi.edu> <1l1dg.1627$%Z2.224933@news20.bellglobal.com> Message-ID: <1148497388.593504.265190@j33g2000cwa.googlegroups.com> Geoffrey Summerhayes wrote: > "Bill Atkins" <NOatkinwSPAM at rpi.edu> wrote in message > news:87y7wre6yr.fsf at rpi.edu... > > John Bokma <john at castleamber.com> writes: > > > > [snip] > > > >> -- > >> John MexIT: http://johnbokma.com/mexit/ > >> personal page: http://johnbokma.com/ > >> Experienced programmer available: http://castleamber.com/ > >> Happy Customers: http://castleamber.com/testimonials.html > > > > Interesting. Doesn't your signature contain advertisements for your > > website? Aren't you posting to five different groups? > > Shh! Pointing out ironic hypocrisy never works. You can say that again: http://tinyurl.com/hvvqd George From pedronis at strakt.com Thu May 18 18:27:37 2006 From: pedronis at strakt.com (Samuele Pedroni) Date: Fri, 19 May 2006 00:27:37 +0200 Subject: Reminder: call for proposals "Python Language and Libraries Track" for Europython 2006 Message-ID: <446CF4D9.1070404@strakt.com> Registration for Europython (3-5 July) at CERN in Geneva is now open, if you feel submitting a talk proposal there's still time until the 31th of May. If you want to talk about a library you developed, or you know well and want to share your knowledge, or about how you are making the best out of Python through inventive/elegant idioms and patterns (or if you are a language guru willing to disseminate your wisdom), you can submit a proposal for the Python Language and Libraries track """ A track about Python the Language, all batteries included. Talks about the language, language evolution, patterns and idioms, implementations (CPython, IronPython, Jython, PyPy ...) and implementation issues belong to the track. So do talks about the standard library or interesting 3rd-party libraries (and frameworks), unless the gravitational pull of other tracks is stronger. """ The full call and submission links are at: http://www.europython.org/sections/tracks_and_talks/call-for-proposals Samuele Pedroni, Python Language and Libraries Track Chair From bitsandbytes88 at hotmail.com Thu May 25 13:46:15 2006 From: bitsandbytes88 at hotmail.com (Dan) Date: Thu, 25 May 2006 13:46:15 -0400 Subject: sybase open client 15_0 References: <NPOdnbx8s-CdcejZRVn-iw@speakeasy.net> Message-ID: <BcmdnQxbloXocOjZRVn-rQ@speakeasy.net> I'm running SLES 9.3 on Tyan with 2 single core 64-bit Opteron & 8 GB of memory and SWAP. OCS-15_0 sybperl-2.18 python 2.3.5 "Dan" <bitsandbytes88 at hotmail.com> wrote in message news:NPOdnbx8s-CdcejZRVn-iw at speakeasy.net... >I have compiled and installed sybase-.037 , the module to add sybase to >python. However, when I try to use it I get Import error: >/usr/local/lib/python2.3/site-packages/sybasect.so > > undefined symbol: cs_dt_info > > I've seen some posts on the internet with other people having this issue. > But nothing they've suggested has resolved this issue. Maybe python just > needs to be installed again or upgraded to support sybase Open Client. > > Thanks, > ~DjK > From george.sakkis at gmail.com Sun May 14 01:33:25 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 13 May 2006 22:33:25 -0700 Subject: count items in generator In-Reply-To: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> Message-ID: <1147584805.462908.201300@g10g2000cwb.googlegroups.com> BartlebyScrivener wrote: > Still new. I am trying to make a simple word count script. > > I found this in the great Python Cookbook, which allows me to process > every word in a file. But how do I use it to count the items generated? > > def words_of_file(thefilepath, line_to_words=str.split): > the_file = open(thefilepath) > for line in the_file: > for word in line_to_words(line): > yield word > the_file.close() > for word in words_of_file(thefilepath): > dosomethingwith(word) > > The best I could come up with: > > def words_of_file(thefilepath, line_to_words=str.split): > the_file = open(thefilepath) > for line in the_file: > for word in line_to_words(line): > yield word > the_file.close() > len(list(words_of_file(thefilepath))) > > But that seems clunky. As clunky as it seems, I don't think you can beat it in terms of brevity; if you care about memory efficiency though, here's what I use: def length(iterable): try: return len(iterable) except: i = 0 for x in iterable: i += 1 return i You can even shadow the builtin len() if you prefer: import __builtin__ def len(iterable): try: return __builtin__.len(iterable) except: i = 0 for x in iterable: i += 1 return i HTH, George From michele.simionato at gmail.com Tue May 9 08:22:10 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 May 2006 05:22:10 -0700 Subject: What to use for adding syntax for hierarcical trees, metaclasses, tokenize.py or PLY? In-Reply-To: <1147175821.309279.271730@j33g2000cwa.googlegroups.com> References: <1147175821.309279.271730@j33g2000cwa.googlegroups.com> Message-ID: <1147177330.638282.271650@y43g2000cwc.googlegroups.com> glomde wrote: <questions on how to extend Python syntax> You should look at the compiler package and at the new AST in Python 2.5. For easy things tokenize could be enough, though. Notice that in Python 2.5 tokenize grew a new 'untokenize' function which is pretty useful. See http://docs.python.org/dev/lib/module-tokenize.html for examples. Michele Simionato From aahz at pythoncraft.com Sat May 20 13:21:35 2006 From: aahz at pythoncraft.com (Aahz) Date: 20 May 2006 10:21:35 -0700 Subject: DO NOT USE file() References: <1Mobg.2139$No6.46432@news.tufts.edu> <446e8a54$0$5326$c3e8da3@news.astraweb.com> <1f7befae0605192133m1760cb91wfb8dee9e4936c2ad@mail.gmail.com> <mailman.5997.1148104426.27775.python-list@python.org> Message-ID: <e4nj6v$k2j$1@panix3.panix.com> In article <mailman.5997.1148104426.27775.python-list at python.org>, Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: >"Tim Peters" <tim.peters at gmail.com> writes: >> [John Salerno, on the difference between `open` and `file`] >>> >>> Interesting. What is the difference between them now? >> >> In 2.5 `file` is unchanged but `open` becomes a function: >> >>>>> file >> <type 'file'> >>>>> open >> <built-in function open> > >In that case I'll happily use 'file()', since it meshes nicely with >creating a new instance of any built-in type. Nobody will prevent you from going against the standard decreed by Guido. But you also probably won't be able to contribute any code to the standard library, and other people mucking with your code who do care about Guido's decrees will probably change it. Unlike all the other built-in types, files are special because they are proxies for non-Python external objects. For that reason, there has long been interest in extending open() to work with file-like objects (such as URLs). Splitting open() and file() is a necessary precondition to making that happen, and it's also possible that Python 3.0 may have separate textfile and binary file objects. Finally, file() doesn't exist in Python 2.1 and earlier, and using file() instead of open() is gratuitous breakage. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From kentilton at gmail.com Sat May 6 23:56:55 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 23:56:55 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> Message-ID: <cee7g.543$RO4.202@fe12.lga> Alex Martelli wrote: > Ken Tilton <kentilton at gmail.com> wrote: > ... > >>Why? (symbol-name '|(|) -> "(" (No, the "s are not part of the name!) >> >>If you want to argue about that, I will have to bring up the Lisp >>readtable. Or did you forget that, too? > > > Mea culpa -- it wasn't in the Lisp(s) I used 25+ years ago, nor in > Scheme; I've never used Common Lisp in anger, and obviously "just > dabbling" gives one no good feel for how *INSANELY COMPLICATED* (or, if > you prefer, "insanely extensible") it truly is. > > I personally think these gyrations... Please. You are the only one gyrating. I was joking with both |(| and the fact that its length is one, no matter what our eyes tell us. And I hope to god you were joking with the objection that a Lisper could not name a variable "(". You would not say something that daft just to win a Usenet debate, would you? Omigod...I think you did! I mean, look at the way you were jumping up and down and shouting and accusing Bill and me of not understanding English and... well, you are an uber tech geek, what did i expect? All is forgiven. But... It is vastly more disappointing that an alleged tech genius would sniff at the chance to take undeserved credit for PyCells, something probably better than a similar project on which Adobe (your superiors at software, right?) has bet the ranch. This is the Grail, dude, Brooks's long lost Silver Bullet. And you want to pass????? C'mon, Alex, I just want you as co-mentor for your star quality. Of course you won't have to do a thing, just identify for me a True Python Geek and she and I will take it from there. Here's the link in case you lost it: http://www.lispnyc.org/wiki.clp?page=PyCells :) peace, kenny ps. flaming aside, PyCells really would be amazingly good for Python. And so Google. (Now your job is on the line. <g>) k -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From steve at holdenweb.com Mon May 1 22:10:17 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 May 2006 03:10:17 +0100 Subject: Can Python kill a child process that keeps on running? In-Reply-To: <MTy5g.104796$7a.25459@pd7tw1no> References: <g0x5g.104639$7a.102977@pd7tw1no> <1146532884.872505.154370@i40g2000cwc.googlegroups.com> <MTy5g.104796$7a.25459@pd7tw1no> Message-ID: <4456BF89.60802@holdenweb.com> I. Myself wrote: > Serge Orlov wrote: > >>I. Myself wrote: >> >> >>>Suppose we spawn a child process with Popen. I'm thinking of an >>>executable file, like a compiled C program. >>>Suppose it is supposed to run for one minute, but it just keeps going >>>and going. Does Python have any way to kill it? >>> >>>This is not hypothetical; I'm doing it now, and it's working pretty >>>well, but I would like to be able to handle this run-on condition. I'm >>>using Windows 2000, but I want my program to be portable to linux. >>> >> >>On linux it's pretty easy to do, just setup alarm signal. On windows >>it's not so trivial to the point you cannot do it using python.org >>distribution, you will need to poke in low level C API using win32 >>extensions or ctypes. AFAIK twisted package <http://twistedmatrix.com> >>has some code to help you. Also take a look at buildbot sources >><http://buildbot.sf.net> that uses twisted. Buildbot has the same >>problem as you have, it needs to kill run away or non-responding >>processes. >> > > That is bad news. Thanks anyway; bad news is better than no news. > Note, however, taht ctypes is planned to be a part of the 2.5 distribution, so while there may not be a platform-independent way to achieve your goals you will at leats be able to do so without external extensions. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From soundinmotiondj at yahoo.com Tue May 23 13:27:54 2006 From: soundinmotiondj at yahoo.com (soundinmotiondj at yahoo.com) Date: 23 May 2006 10:27:54 -0700 Subject: What's with the @ sign In-Reply-To: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> References: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> Message-ID: <1148405274.238590.216100@j55g2000cwa.googlegroups.com> jordan.taylor2 at gmail.com wrote: > What's with code that has the @ symbol in front of classes or > functions? This has probably already been asked but I can't find any > info on it. http://www.python.org/doc/2.4.2/whatsnew/node6.html From khoa.coffee at gmail.com Wed May 17 15:48:58 2006 From: khoa.coffee at gmail.com (Khoa Nguyen) Date: Wed, 17 May 2006 15:48:58 -0400 Subject: Python-list Digest, Vol 32, Issue 300 In-Reply-To: <mailman.22401.1147894204.27774.python-list@python.org> References: <mailman.22401.1147894204.27774.python-list@python.org> Message-ID: <3d00e6dc0605171248s685af11dj5c29b8a11acb83e2@mail.gmail.com> > Optional(f1SpecificFormat) + "," + Optional(f2SpecificFormat) + "," + ... > and so on. Thanks for your input again. This is exactly what I am trying. The only thing is it can get ugly if the number of fields are many -- I have about 61 fields right now. Just wondering if there is a "cleaner" approach. Thanks, Khoa ================== from pyparsing import * DELIM = Suppress('&') RECORD_END = Suppress(';') f1 = Literal('a') f2 = Literal('b') f3 = Word(alphanums+'_-.') common = f1 extended = Optional(DELIM + Optional(f2)) \ + Optional(DELIM + Optional(f3)) g = common + Optional(extended) + RECORD_END def parse(record): result = g.parseString(record) print result if __name__=='__main__': good = ['a;', 'a&&c-123;', 'a&b;', 'a&b&c;', 'a&b&c-123-af;'] bad = [ ';', # required field missing 'a', # RECORD_END missing 'b&c;', # required field missing 'a&c&b;', # Incorrect order 'x123&a&b;' # Incorrect order ] for r in good + bad: try: parse(r) except ParseException, err: print err.line print " "*(err.column-1) + "^" print err continue ======================= From buzzard at urubu.freeserve.co.uk Fri May 26 13:03:38 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Fri, 26 May 2006 18:03:38 +0100 Subject: OLAP and pivot tables In-Reply-To: <1148611731.916187.198330@i40g2000cwc.googlegroups.com> References: <1148611731.916187.198330@i40g2000cwc.googlegroups.com> Message-ID: <447736fd.0@entanet> George Sakkis wrote: > After a brief search, I didn't find any python package related to OLAP > and pivot tables. Did I miss anything ? To be more precise, I'm not so > interested in a full-blown OLAP server with an RDBMS backend, but > rather a pythonic API for constructing datacubes in memory, slicing and > dicing them, drilling down or up dimensions and exposing them in some > suitable form to a presentation layer. I've hacked a first cut of a > pivot table implementation and an XHTML generator that produces > hierarchical html tables but it's not particularly general or easily > extensible so far. Is there any interest at all on a pythonic version > of something like JOLAP or XMLA ? > > George > I have a few applications that require the generation of large numbers of contingency tables from a higher-dimensional base table. The approaches I've tried (Numeric arrays / dictionary-based sparse arrays / various caching schemes / searches on subset lattices for previously generated 'super'-tables that can be marginalised from etc.) still represent major bottlenecks. So, I guess I would be interested. Duncan From spudtheimpaler at hotORgooMAIL.invalid Wed May 24 12:48:57 2006 From: spudtheimpaler at hotORgooMAIL.invalid (Mitch) Date: Wed, 24 May 2006 17:48:57 +0100 Subject: John Bokma harassment In-Reply-To: <Xns97CD733A1B9ABcastleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> <447479A1.8050809@hotORgooMAIL.invalid> <Xns97CD6AB19B4F3castleamber@130.133.1.4> <447485B6.4070507@hotORgooMAIL.invalid> <Xns97CD733A1B9ABcastleamber@130.133.1.4> Message-ID: <44748E79.9010208@hotORgooMAIL.invalid> John Bokma wrote: > fup to poster > > Mitch <spudtheimpaler at hotORgooMAIL.invalid> wrote: > >> John Bokma wrote: > > [...] > >>> Funny how people who always think they can "change Usenet" have no >>> clue about what Usenet is and how it works in the first place. >> Who said anything about changing it? I like it just the way it is. > > You don't. > All that I snipped is your opinion, which is yours to do with as you please. "I like it just the way it is." is *MY* opinion, so please don't try to change it. I think I know my opinion best. And as for setting it to reply to only you, I changed that back. I don't think you censoring (redirecting) other peoples replies/opinions serves the purpose of this thread well. From scott.daniels at acm.org Wed May 24 16:37:43 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 24 May 2006 13:37:43 -0700 Subject: Use of lambda functions in OOP, any alternative? In-Reply-To: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> References: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> Message-ID: <4474bfe9$1@nntp0.pdx.net> Pablo wrote: > Second solution: This is what i want, but... > > class Base(object): > def __init__(self, attr): > self._attr = attr > def getattr(self): > return self._attr > attr = property(fget=lambda self: self.getattr()) > > class Derived(Base): > def getattr(self): > return 2*self._attr > > Question: Isn't there an *alternative* way to do it without the lambda > function? > > Thanks in advance! Simplest: class Base(object): def __init__(self, attr): self._attr = attr def getattr(self): return self._attr @property # single-arg property is a read-only thing. def attr(self): return self.getattr() ### Little longer; maybe more explicit (tastes vary): class Base(object): def __init__(self, attr): self._attr = attr def getattr(self): return self._attr def attr(self): return self.getattr() attr = property(fget=attr) --Scott David Daniels scott.daniels at acm.org From duncan.booth at invalid.invalid Tue May 16 09:14:35 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 13:14:35 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> <mailman.5711.1147697881.27775.python-list@python.org> <1147781797.407160.54740@u72g2000cwu.googlegroups.com> <Xns97C58EED2F83Dduncanbooth@127.0.0.1> Message-ID: <Xns97C590E1792DEduncanbooth@127.0.0.1> Duncan Booth wrote: >> BTW why are python dicts implemented as hash tables and not judy >> arrays? >> > Probably because: > > Python predates judy arrays. > Nobody has proposed replacing the current dict implementation. > Nobody has demonstrated that it would actually be an advantage to > replace the current implementation. > Or maybe Python dicts are just more flexible? Also, see http://www.dalkescientific.com/Python/PyJudy.html with the conclusions drawn on performance: > The first conclusion is that Python dictionaries are wicked fast. > There are few cases where PyJudy is faster, though perhaps there might > be a few more if I knew more about the Python extension API. Bear in > mind though that the Judy arrays are in sorted order and the JudyL* > classes have ways to access elements by order. So for a specialised use Judy arrays could be a good idea, but not as a general replacement for Python dicts. From bill.pursell at gmail.com Wed May 17 10:14:33 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 17 May 2006 07:14:33 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <mailman.5804.1147874795.27775.python-list@python.org> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147873879.818361.10040@i40g2000cwc.googlegroups.com> <mailman.5804.1147874795.27775.python-list@python.org> Message-ID: <1147875273.491587.195800@j73g2000cwa.googlegroups.com> Peter Decker wrote: > On 17 May 2006 06:51:19 -0700, Bill Pursell <bill.pursell at gmail.com> wrote: > > > In my experience, the people who complain about the use > > of tabs for indentation are the people who don't know > > how to use their editor, and those people tend to use > > emacs. > > In my experience, whenever there is a 'religious' issue like this, one > side tends to be quick to pronounce the other as 'evil', and insist > that everyone do things their way, while the other tends to feel > comfortable with people having their own preferences. If I ever find > myself on the side of the former, I always wonder if I'm missing > something obvious. I think you unfairly snipped context on me. I was directly responding to the assertion that vi is unable to handle tabs well. As far as tabs vs. spaces, I don't think the spacers are evil, and in fact I am one for pragmatic reasons. I would much prefer to use tabs for indentation, especially since in the last few weeks I've decided to upgrade from 4 to 8, and now all of my spaced code requires much more effort than ":ts=8" to fix. But in today's world, it's easier to go with the flow and use spaces. From dave at waveform.plus.com Mon May 1 16:05:29 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 01 May 2006 20:05:29 GMT Subject: regd efficient methods to manipulate *large* files References: <Pine.SOL.4.56.0605011012270.13646@pollux.cse.buffalo.edu> Message-ID: <44566a09$0$23171$ed2e19e4@ptn-nntp-reader04.plus.net> Madhusudhanan Chandrasekaran wrote: > Hi: > > This question is not directed "entirely" at python only. But since > I want to know how to do it in python, I am posting here. > > > I am constructing a huge matrix (m x n), whose columns n are stored in > smaller files. Once I read m such files, my matrix is complete. I > want to pass this matrix as an input to another script of mine (I > just have the binary.) Currently, the script reads a file (which is > nothing but the matrix) and processes it. Is there any way of doing > this in memory, without writing the matrix onto the disk? > > Since I have to repeat my experimentation for multiple iterations, it > becomes expensive to write the matrix onto the disk. > > Thanks in advance. Help appreciated. > > -Madhu Basically, you're asking about Inter Process Communication (IPC), for which Python provides several interfaces to mechanisms provided by the operating system (whatever that may be). Here's a couple of commonly used methods: Redirected I/O Have a look at the popen functions in the os module, or better still the subprocess module (which is a higher level interface to the same functionality). Specifically, the "Replacing the shell pipe line" example in the subprocess module's documentation should be interesting: output=`dmesg | grep hda` ==> p1 = Popen(["dmesg"], stdout=PIPE) p2 = Popen(["grep", "hda"], stdin=p1.stdout, stdout=PIPE) output = p2.communicate()[0] Here, the stdout of the "dmesg" process has been redirected to the stdin of the "grep" process. You could do something similar with your two scripts: e.g., the first script simply writes the content of the matrix in some format to stdout (e.g. print, sys.stdout.write), while the second script reads the content of the matrix from stdin (e.g. raw_input, sys.stdin.read). Here's some brutally simplistic scripts that demonstrate the method: in.py ===== #!/bin/env python # # I read integers from stdin until I encounter 0 import sys while True: i = int(sys.stdin.readline()) print "Read %d from stdin" % i if i == 0: break out.py ====== #!/bin/env python # # I write some numbers to stdout for i in [1, 2, 3, 4, 5, 0]: print i run.py ====== #!/bin/env python # # I run out.py and in.py with a pipe between them, capture the # output of in.py and print it from subprocess import Popen, PIPE process1 = Popen(["./out.py"], stdout=PIPE) process2 = Popen(["./in.py"], stdin=process1.stdout, stdout=PIPE) output = process2.communicate()[0] print output Sockets Another form of IPC uses sockets to communicate between two processes (see the socket module or one of the higher level modules like SocketServer). Hence, the second process would listen on a port (presumably on the localhost interface, although there's no reason it couldn't listen on a LAN interface for example), and the first process connects to that port and sends the matrix data across it to the second process. Summary Given that your second script currently reads a file containing the complete matrix (if I understand your post correctly), it's probably easiest for you to use the Redirected I/O method (as it's very similar to reading a file, although there are some differences, and sometimes one must be careful about closing pipe ends to avoid deadlocks). However, the sockets method has the advantage that you can easily move one of the processes onto a different machine. There are other methods of IPC (for example, shared memory: see the mmap module) however the two mentioned above are available on most platforms whereas others may be specific to a given platform, or have platform specific subtleties (for example, mmap is only available on Windows and UNIX, and has a slightly different constructor on each). HTH, Dave. -- From webraviteja at gmail.com Mon May 29 02:46:27 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 28 May 2006 23:46:27 -0700 Subject: Need C# Coding for MD5 Algorithm... In-Reply-To: <1148884151.511656.81110@j73g2000cwa.googlegroups.com> References: <1148884151.511656.81110@j73g2000cwa.googlegroups.com> Message-ID: <1148885187.145786.158240@j73g2000cwa.googlegroups.com> > I need C# code for Implementing MD5 Algorithm. So ask in a C# group. Python's is here http://docs.python.org/lib/module-md5.html > please Send... ITs URgent http://www.catb.org/~esr/faqs/smart-questions.html#urgent From liuliuliu at gmail.com Sun May 21 11:06:14 2006 From: liuliuliu at gmail.com (liuliuliu) Date: 21 May 2006 08:06:14 -0700 Subject: 'error reading datastream' -- loading file only when transfer is complete? In-Reply-To: <126v89qbrj1i063@corp.supernews.com> References: <1148159335.678868.22850@j73g2000cwa.googlegroups.com> <126v3nsag5bcqdb@corp.supernews.com> <126v89qbrj1i063@corp.supernews.com> Message-ID: <1148223974.046490.322190@u72g2000cwu.googlegroups.com> thanks all. this seemed to work: import os stat = os.stat(str(newFiles[index])) size1 = stat.st_size pygame.time.wait(100) stat = os.stat(str(newFiles[index])) size2 = stat.st_size while size2 > size1: size1 = size2 pygame.time.wait(500) stat = os.stat(str(newFiles[index])) size2 = stat.st_size # procede to load complete file my delay is so long because somehow pygame (or file-writing) runs relatively slow on maemo/nokia770. even a delay of 400 milliseconds was too quick to accommodate the slothly rate of an incoming file. From sjmachin at lexicon.net Mon May 29 20:48:19 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 May 2006 10:48:19 +1000 Subject: Is anybody knows about a linkable, quick MD5/SHA1 calculator library ? In-Reply-To: <mailman.6314.1148921878.27775.python-list@python.org> References: <mailman.6314.1148921878.27775.python-list@python.org> Message-ID: <447B9653.80005@lexicon.net> On 30/05/2006 2:57 AM, DurumDara wrote: > Hi ! > > I need to speedup my MD5/SHA1 calculator app that working on > filesystem's files. > I use the Python standard modules, but I think that it can be faster if > I use C, or other module for it. > > I use FSUM before, but I got problems, because I "move" into "DOS area", > and the parameterizing of outer process maked me very angry (not working). > You will see this in this place: > http://mail.python.org/pipermail/python-win32/2006-May/004697.html > > So: I must handle unicode filenames. I think that if I find a library > that can working with py's unicode chars, and I can load and use it to > hash files, the code be better, and faster. > > Anybody knows about same code ? > > Py2.4, Windows, Py2Exe, wxPy... That was the specification. > Hello (again), dd ... As the effbot has said, the Python md5 and sha modules are written in C. Hints: (1) the helpfile index says "builtin module" (2) you don't find a sha.py or md5.py in c:\Python24\Lib\ An md5/sha library will concern itself with strings (which you obtain from a file's *contents*), just like Python's modules do. Any struggle with Unicode characters in the *names* of files is a separate concern. Let's all stop worrying about low-level things like getting the 8.3 filename so that you can pass it to an MS-DOS program, and let's try to explore why you think there is a problem with your initial approach. At the end of this posting is a very simple Python function that calculates the hash of a file (and its length), given the name of the file (str or unicode, doesn't matter), which hashing module to use, and a blocksize to use when reading. There is a really flash :-) user interface that allows you to try it with either a glob pattern "*.txt", or (as glob doesn't grok Windows mbcs/unicode filenames) a single utf8-encoded filename. Please try it out. My expectation is that, with a suitable choice of blocksize, you will not be able to find anything that is significantly faster and won't be difficult to interface to (like the FSUM program!). If you have any problems or more questions, please don't hesitate to ask. HTH, John === function and driver === C:\junk>type hashtestbed.py def hash_of_file(hash_module, fname, block_size): f = open(fname, 'rb') hashobj = hash_module.new() filesize = 0 while True: block = f.read(block_size) if not block: break filesize += len(block) hashobj.update(block) f.close() return (filesize, hashobj.digest()) def to_hex(s): return ''.join('%02x' % ord(c) for c in s) if __name__ == "__main__": import sha, md5, time, sys, glob # print sys.argv mdlname = sys.argv[1] mdl = {'sha': sha, 'md5': md5}[mdlname] szs = sys.argv[2].lower() factor = {'m': 1024*1024, 'k': 1024}.get(szs[-1], 1) if factor == 1: bsz = int(szs) else: bsz = int(szs[:-1]) * factor filearg = sys.argv[3] if filearg.startswith("'"): # repr(single filename, encoded in utf8) filenames = [eval(filearg).decode('utf8')] # print filenames else: filenames = glob.glob(sys.argv[3]) # I'm entering the above for the "Best UI of the Year" award :-) for fn in filenames: t0 = time.time() fsz, digest = hash_of_file(mdl, fn, bsz) seconds = time.time() - t0 print "%s, %r, bksz %d: %d bytes," \ " %.2f secs (%.4f secs/MB)\n\thash = %s" \ % (mdlname, fn, bsz, fsz, seconds, seconds/fsz*1024*1024, to_hex(digest)) C:\junk> === sample usage === C:\junk>hashtestbed.py md5 32k '\xe5\xbc\xa0\xe6\x95\x8f.txt' md5, u'\u5f20\u654f.txt', bksz 32768: 17 bytes, 0.00 secs (0.0000 secs/MB) hash = 746d0931605368989a20691a906a67f8 C:\junk>hashtestbed.py md5 32k \downloads\python*.msi md5, '\\downloads\\python-2.4.2.msi', bksz 32768: 9671168 bytes, 0.08 secs (0.00 86 secs/MB) hash = bfb6fc0704d225c7a86d4ba8c922c7f5 md5, '\\downloads\\python-2.4.3.msi', bksz 32768: 9688576 bytes, 0.06 secs (0.00 67 secs/MB) hash = ab946459d7cfba4a8500f9ff8d35cc97 md5, '\\downloads\\python-2.5a2.msi', bksz 32768: 10274816 bytes, 0.05 secs (0.0 048 secs/MB) hash = cedc1e1fed9c4cd137921a80485bf007 === end === From jstroud at ucla.edu Tue May 23 20:18:56 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 23 May 2006 17:18:56 -0700 Subject: Looking for help with Regular Expression In-Reply-To: <1148428798.529016.319100@y43g2000cwc.googlegroups.com> References: <1148428798.529016.319100@y43g2000cwc.googlegroups.com> Message-ID: <e508pg$c1l$1@daisy.noc.ucla.edu> ProvoWallis wrote: > Hi, > > I'm looking for a little advice about regular expressions. I want to > capture a string of text that falls between an opening squre bracket > and a closing square bracket (e.g., "[" and "]") but I've run into a > small problem. > > I've been using this: '''\[(.*?)\]''' as my pattern. I was expecting > this to be greedy but the funny thing is that it's not greedy enough in > some situations. > > Here's my problem: The end of my string sometimes contains a cross > reference to a section in a book and the subsections are cited using > square brackets exactly like the one I'm using as the ending point in > my original regular expression. > > E.g., the text string in my data looks like this: <core:emph > typestyle="it">see</core:emph> discussion in > § 512.16[3][b]] > > But my regular expression is stopping after the first "]" so after I > add the new markup the output looks like this: > > <core:emph typestyle="it">see</core:emph> discussion in > § 512.16[3]</fn:note>[b]] > > So the last subsection is outside of the note tag. I want something > like this: > > <core:emph typestyle="it">see</core:emph> discussion in > § 512.16[3][b]]</fn:note> > > I'm not sure how to make my capture more greedy so I've resorted to > cleaning up the data after I make the first round of replacements: > > data = re.sub(r'''\[(\d*?)\]</fn:note>\[(\w)\]\]''', > '''[\1][\2]]</fn:note>''', data) > > There's got to be a better way but I'm not sure what it is. I do: Pyparsing. from pyparsing import * crossref = Suppress("[") + Word(alphanums, exact=1) + Suppress("]") footnote = ( Suppress("[") + SkipTo(crossref) + ZeroOrMore(crossref) + Suppress("]") ) footnote.parseString("[§ 512.16[3][b]]").asList() py> footnote.parseString("[§ 512.16[3][b]]").asList() ['§ 512.16', '3', 'b'] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From wahab at chemie.uni-halle.de Thu May 11 16:58:17 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Thu, 11 May 2006 22:58:17 +0200 Subject: reusing parts of a string in RE matches? In-Reply-To: <eRI8g.2087$No6.45924@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> <E6r8g.2083$No6.45931@news.tufts.edu> <eir8g.2084$No6.45965@news.tufts.edu> <1147291197.423570.242440@g10g2000cwb.googlegroups.com> <e3v387$9tt$1@mlucom4.urz.uni-halle.de> <GGH8g.2085$No6.45839@news.tufts.edu> <e3vikl$ecv$1@mlucom4.urz.uni-halle.de> <eRI8g.2087$No6.45924@news.tufts.edu> Message-ID: <e408o5$kta$1@mlucom4.urz.uni-halle.de> Hi John > Ah, I see the difference. In Python you get a list of tuples, so there > seems to be a little extra work to do to get the number out. Dohh, after two cups of coffee ans several bars of chocolate I eventually mad(e) it ;-) In Python, you have to deconstruct the 2D-lists (here: long list of short lists [a,2] ...) by 'slicing the slice': char,num = list[:][:] in a loop and using the apropriate element then: import re t = 'a1a2a3Aa4a35a6b7b8c9c'; r = r'(\w)(?=(.)\1)' l = re.findall(r, t) for a,b in (l[:][:]) : print b In the moment, I find this syntax awkward and arbitary, but my mind should change if I'm adopted more to this in the end ;-) Regards, M. From nobody at 127.0.0.1 Wed May 3 19:28:41 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 23:28:41 GMT Subject: Gettings subdirectories References: <e3au5u$drm$1@news.in.tum.de> <1146683720.748769.36490@g10g2000cwb.googlegroups.com> <1146695904.623400.128100@y43g2000cwc.googlegroups.com> <mailman.5291.1146697515.27775.python-list@python.org> Message-ID: <J0b6g.21498$4L1.8686@newssvr11.news.prodigy.com> Ben Finney wrote: > We must be reading different Python websites. > > walk(top[, topdown=True [, onerror=None]]) > > walk() generates the file names in a directory tree, by walking > the tree either top down or bottom up. For each directory in the > tree rooted at directory top (including top itself), it yields a > 3-tuple (dirpath, dirnames, filenames). Maybe he meant os.path.walk, although that's still not quite what he had. From telesphore4 at gmail.com Fri May 19 17:10:09 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 19 May 2006 14:10:09 -0700 Subject: Using metaclasses to inherit class variables Message-ID: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> I want to inherit fresh copies of some class variables. So I set up a metaclass and meddle with the class variables there. Now it would be convenient to run thru a dictionary rather than explicitly set each variable. However getattr() and setattr() are out because they chase the variable thru the class hierarchy. So, I read the dictionary directly with cls.__dict__.has_key(var). Reading works but when I go to set the object's dictionary directly with: cls.__dict__[var] = val I get the following error: File Table.py, line 10, in __init__ if not cls.__dict__.has_key(var): cls.__dict__[var] = val TypeError: Error when calling the metaclass bases object does not support item assignment Is there an easy way around this? Or am I stuck listing out the variables one per line? class SetClassVars(type): cvars = dict(name=None, desc=None, required=True, minlen=1, maxlen=25, idDown=999999999, idNext=0) def __init__(cls, name, bases, dict): if not cls.__dict__.has_key('name'): cls.name = None if not cls.__dict__.has_key('desc'): cls.desc = None if not cls.__dict__.has_key('required'): cls.required = True if not cls.__dict__.has_key('minlen'): cls.minlen = 1 if not cls.__dict__.has_key('maxlen'): cls.maxlen = 25 if not cls.__dict__.has_key('idDown'): cls.idDown = 999999999 if not cls.__dict__.has_key('idNext'): cls.idNext = 0 # It would be more convenient to loop thru a dictionary #for var, val in SetClassVars.cvars.iteritems(): # getattr() and setattr() run thru the MRO # which is not what I want #if not getattr(cls, var): setattr(cls, var, val) #if not cls.__dict__.has_key(var): setattr(cls, var, val) # Setting the dictionary directly generates an error #if not cls.__dict__.has_key(var): cls.__dict__[var] = val thanks t4 From bucodi at yahoo.fr.invalid Thu May 4 11:52:50 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 04 May 2006 17:52:50 +0200 Subject: Swaying A Coder Away From Python References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <mailman.5315.1146743831.27775.python-list@python.org> <R40843717.445.3845.1@mx-extra.net> <mailman.5329.1146749986.27775.python-list@python.org> <C-l*WBOfr@news.chiark.greenend.org.uk> Message-ID: <mn.24307d65c4d4c37d.43626@yahoo.fr.invalid> <QUOTE> "One problem is that python tools suck," he wrote. Wallace compared the various IDEs and other developer tools available to Microsoft's freely available Visual Studio Express and called them "toys." <QUOTE> What s wrong with VI ??? :) R_ >> On 4 May 2006 05:24:40 -0700, BartlebyScrivener <rpdooling at gmail.com> wrote: >>> I'm picking this up via clp on Google Groups. I can't tell what Mr. >>> Lundh is referring to. The first line of his post is: "Tim Williams >>> wrote" but there's nothing that comes before. > > Similarly, I'm reading this via comp.lang.python and the original > article hasn't shown up at this site. > > Tim Williams <tdw at tdw.net> wrote: >> I found the web version at. >> >> http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html > > Wherein we find: > > He also listed a few reasons why C# appeals to him over Python or Java: > * anonymous functions (delegates) > * a python-like yield statement > * a nice type system with generics > * interfaces > * properties (Yay!!) > > So that's two of the five Python has, one explicitly acknowledged, > plus the combination of lambda and functions-as-first-class-objects > is as good as (or better than) "anonymous functions (delegates)". > And then we get onto personal preferences as to how to do type > systems. That's not a great deal with which to sway someone. -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From Serge.Orlov at gmail.com Thu May 11 18:07:06 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 May 2006 15:07:06 -0700 Subject: can distutils windows installer invoke another distutils windows installer References: <1147290349.140963.201030@i39g2000cwa.googlegroups.com> Message-ID: <1147385225.986456.23360@g10g2000cwb.googlegroups.com> timw.google wrote: > Hi all. > > I have a package that uses other packages. I created a setup.py to use > 'try:' and import to check if some required packages are installed. I > have the tarballs and corresponding windows installers in my sdist > distribution, so if I untar my source distribution and do 'python > setup.py install', the script either untars the subpackages to a tmp > directory and does an os.system('python setup.py install') (Linux), or > os.system(<bdist_wininst installer>) (win32) for the missing > subpackage. I believe there are two ways to handle dependances: either you bundle your dependances with your package (they just live in a directory inside your package, you don't install them) or you leave resolution of dependances to the application that uses your package. Handling dependances like you do it (package installs other packages) doesn't seem like a good idea to me. From python.list at tim.thechases.com Mon May 22 21:27:54 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 22 May 2006 20:27:54 -0500 Subject: Too big of a list? and other problems In-Reply-To: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> References: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> Message-ID: <4472651A.3030700@tim.thechases.com> > pics = re.compile(r"images/.*\.jpeg") While I'm not sure if this is the issue, you might be having some trouble with the greediness of the "*" repeater here. HTML like <img src="images/1.jpeg"><img src="hello.jpeg"> will yield a result of "images/1.jpeg"><img src="hello.jpeg" rather than the expected "images/1.jpeg" You can make it "stingy" (rather than greedy) by appending a question-mark: r"images/.*?\.jpeg" I also don't know if they all are coming back as "jpeg", or if some come back as "jpg", in which case you might want to use r"images/.*?\.jpe?g" This still might bork up on things like <img src="images/a.gif"><img src="2.jpeg"> My first thought would be to install the BeautifulSoup parser, and then use it to snag all the <img> tags in your document. Then you know you're just getting the tag, and in turn, just getting their associated "src" attribute. I do something like that in my comic-snatcher (scrapes comics from various sites so I can read them all in one place in one sitting). You're welcome to remash this code excerpt (there's no guarantee it's great code): req = urllib2.Request(url) req.add_header("Referer", referer) page = urllib2.urlopen(req) bs = BeautifulSoup.BeautifulSoup() map(bs.feed, page.readlines()) bs.done() r = re.compile(targetRegex) imageURLs = [img["src"] for img in bs.fetch("img")] targetImageURL = [url for url in imageURLs if r.match(url)] It does blithely assume every image has a "src" attribute as it should, but if not, you can put in an "if" clause in the assignment of imageURLs to only take those that have src attributes. As others have mentioned as well, once you successfully get back the list of images, you'll likely want to *extend()* your master list of image URLs with your list of currently-found-URLs, rather than *append()*, or otherwise you'll end up with a list of lists which may not be what you want. Just a few ideas you might want to try. -tkc From n.estner at gmx.de Thu May 11 12:13:07 2006 From: n.estner at gmx.de (nikie) Date: 11 May 2006 09:13:07 -0700 Subject: which windows python to use? References: <mailman.5589.1147359382.27775.python-list@python.org> Message-ID: <1147363986.909795.270640@q12g2000cwa.googlegroups.com> Brian Blais wrote: > Hello, > > Are there any recommendations for which Windows python version to use? I'd like to > see a pros-and-cons description of each, given that different uses might dictate > different versions. The versions I know (and there are surely more) are: > > 1) download from www.python.org > 2) enthought > 3) activepython > > Are there advantages/disadvantages? I have used enthought before, but it seems as if > they are not at 2.4, and may lag behind in versions (which may not be a bad thing). It depends on what you want to do. If you're going to use SciPy (a library for scientific computing), I'd suggest using enthought, as installing SciPy on windows can be a real nightmare for a newbie... Anyway, the enthought edition comes with lots of interesting libraries installed (listed on their homepage), you might want to look at them even if you don't use their distribution. Note that you can have more than one Python installation on the same PC, so you can also work with Python 2.4 (from www.python.org) and switch to enthought for certain projectes if you need it. I haven't looked into ActivePython too much, from what I read it seemed more or less standard python + mark hammonds Win32 utils, but you can install those manually on a plain www.python.org-distribution. From martin at v.loewis.de Wed May 17 18:16:52 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Thu, 18 May 2006 00:16:52 +0200 Subject: A Unicode problem -HELP In-Reply-To: <1147861173.156979.303100@y43g2000cwc.googlegroups.com> References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <446AAFE6.4080008@v.loewis.de> <1147843788.969853.159420@g10g2000cwb.googlegroups.com> <446abddb$0$31040$9b622d9e@news.freenet.de> <1147861173.156979.303100@y43g2000cwc.googlegroups.com> Message-ID: <446BA0D4.7010308@v.loewis.de> manstey wrote: > Thanks very much. Your def comma_separated_utf8(items): approach raises > an exception in codecs.py, so I tried = u", ".join(word_info + parse + > gloss), which works perfectly. So I want to understand exactly why this > works. word_info and parse and gloss are all tuples. does str convert > the three into an ascii string? Correct: a tuple is converted into a string with (contents), where contents is achieved through comma-separating repr() of each tuple element. repr(a_unicode_string) creates a \x or \u representation. > but the join method retains their unicode status. Correct. The result is a Unicode string if the joiner is a Unicode string, and all tuple elements are Unicode strings. If one is not, a conversion to Unicode is attempted. > In the text file, the unicode characters appear perfectly, so I'm very > happy. Glad it works. Regards, Martin From dadapapa at googlemail.com Sat May 6 12:40:31 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 6 May 2006 09:40:31 -0700 Subject: __getattr__ for global namespace? In-Reply-To: <445a49ea$0$30163$636a55ce@news.free.fr> References: <1146743418.248566.241890@e56g2000cwe.googlegroups.com> <445a49ea$0$30163$636a55ce@news.free.fr> Message-ID: <1146933631.606918.78910@y43g2000cwc.googlegroups.com> Great! sys.excepthook() is exactly what I was looking for. Thank you. From nobody at 127.0.0.1 Wed May 3 19:26:08 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 23:26:08 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <pan.2006.05.03.20.57.05.32060@gmx.net> <Sda6g.67189$F_3.50022@newssvr29.news.prodigy.net> <mailman.5289.1146697051.27775.python-list@python.org> Message-ID: <k_a6g.21491$4L1.14831@newssvr11.news.prodigy.com> Ben Finney wrote: > As I understand it, the point was not what the code does, but to give > a sample input (a Python program) for the "simple text processor" you > described to wade through. Ah, well then, there's no need for a full-blown parser. It should suffice to recognize a class definition and modify the parameter list of every def indented one level further than that. Then pick out the static methods and 'undo' those. Can be done in one pass by keeping the class definition in memory until you've scanned the whole thing, then adding self where needed as you spit it back out. Implementation is left as an exercise for the reader. :) From sybrenUSE at YOURthirdtower.com.imagination Thu May 18 03:16:58 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 18 May 2006 09:16:58 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5867.1147935817.27775.python-list@python.org> Message-ID: <slrne6o7r9.k84.sybrenUSE@schuimige.stuvel.eu> Heiko Wundram enlightened us with: > And: the web is a platform to offer _information_. Not to offer > shiny graphics/sound [...] Many would disagree... Not me, but I know a lot of people that would. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From conor.robinson at gmail.com Wed May 10 18:21:23 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 10 May 2006 15:21:23 -0700 Subject: segmentation fault in scipy? Message-ID: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> I'm running operations large arrays of floats, approx 25,000 x 80. Python (scipy) does not seem to come close to using 4GB of wired mem, but segments at around a gig. Everything works fine on smaller batches of data around 10,000 x 80 and uses a max of ~600mb of mem. Any Ideas? Is this just too much data for scipy? Thanks Conor Traceback (most recent call last): File "C:\Temp\CR_2\run.py", line 68, in ? net.rProp(1.2, .5, .000001, 50.0, input, output, 1) File "/Users/conorrob/Desktop/CR_2/Network.py", line 230, in rProp print scipy.trace(error*scipy.transpose(error)) File "D:\Python24\Lib\site-packages\numpy\core\defmatrix.py", line 149, in __mul__ return N.dot(self, other) MemoryError >>> From chris.cavalaria at free.fr Thu May 18 04:33:58 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 10:33:58 +0200 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <pan.2006.05.18.07.37.44.126396@internode.on.net> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <mailman.5801.1147872851.27775.python-list@python.org> <pan.2006.05.18.07.37.44.126396@internode.on.net> Message-ID: <446c319d$0$5298$626a54ce@news.free.fr> PoD a ?crit : > On Wed, 17 May 2006 21:37:14 +0800, Andy Sy wrote: > > >>If tabs are easily misunderstood, then they are a MISfeature >>and they need to be removed. >> >>>From the Zen of Python: >> >>"Explicit is better than implicit..." >>"In the face of ambiguity, refuse the temptation to guess..." >>"Special cases aren't special enough to break the rules..." > > > Exactly. > How many levels of indentation does 12 spaces indicate? > It could be 1,2,3,4,6 or 12. If you say it's 3 then you are _implying_ > that each level is represented by 4 spaces. Actually, who said you had to always use the same number of spaces to indent ? 12 = 6 + 6 = 4 + 4 + 4 but also 12 = 2 + 10 = 1 + 1 + 3 + 3 + 4 :D > How many levels of indentation is 3 tabs? 3 levels in any code that you > will find in the wild. No, it could be 3 levels or 3 tabs per level or 2 tabs for the first level and 1 tab for the second ... From ajones1 at gmail.com Thu May 4 12:03:12 2006 From: ajones1 at gmail.com (Adam Jones) Date: 4 May 2006 09:03:12 -0700 Subject: Swaying A Coder Away From Python In-Reply-To: <mn.24307d65c4d4c37d.43626@yahoo.fr.invalid> References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <mailman.5315.1146743831.27775.python-list@python.org> <R40843717.445.3845.1@mx-extra.net> <mailman.5329.1146749986.27775.python-list@python.org> <C-l*WBOfr@news.chiark.greenend.org.uk> <mn.24307d65c4d4c37d.43626@yahoo.fr.invalid> Message-ID: <1146758592.602133.51630@g10g2000cwb.googlegroups.com> Rony Steelandt wrote: > <QUOTE> > "One problem is that python tools suck," he wrote. Wallace compared the > various IDEs and other developer tools available to Microsoft's freely > available Visual Studio Express and called them "toys." > > <QUOTE> > > What s wrong with VI ??? :) User error, evidently. Sometimes the interface is more intelligent than its user, and every time this happens the interface is the one that gets the bad rap. Sorry for the snarky comment, but python dev tools do not suck, they are just generally different from visual studio. There are any number of good editing platforms for python, visual studio is just not really one of them. > > R_ > > >> On 4 May 2006 05:24:40 -0700, BartlebyScrivener <rpdooling at gmail.com> wrote: > >>> I'm picking this up via clp on Google Groups. I can't tell what Mr. > >>> Lundh is referring to. The first line of his post is: "Tim Williams > >>> wrote" but there's nothing that comes before. > > > > Similarly, I'm reading this via comp.lang.python and the original > > article hasn't shown up at this site. > > > > Tim Williams <tdw at tdw.net> wrote: > >> I found the web version at. > >> > > > >> http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html > > > > Wherein we find: > > > > He also listed a few reasons why C# appeals to him over Python or Java: > > * anonymous functions (delegates) > > * a python-like yield statement > > * a nice type system with generics > > * interfaces > > * properties (Yay!!) > > > > So that's two of the five Python has, one explicitly acknowledged, > > plus the combination of lambda and functions-as-first-class-objects > > is as good as (or better than) "anonymous functions (delegates)". > > And then we get onto personal preferences as to how to do type > > systems. That's not a great deal with which to sway someone. > > > -- > --- > Rony Steelandt > BuCodi > rony dot steelandt (at) bucodi dot com > > Visit the python blog at http://360.yahoo.com/bucodi From grante at visi.com Sat May 27 13:48:01 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 17:48:01 -0000 Subject: How to control color of contour lines? References: <127h41neuk81408@corp.supernews.com> Message-ID: <127h46hotumkl6c@corp.supernews.com> On 2006-05-27, Grant Edwards <grante at visi.com> wrote: > How do I get contour lines drawn in just one color (e.g. black)? > > Multicolored contour lines on top of a pm3d surface can be very > hard to look at... Of course I found it right after I posted the question: "unset clabel" -- Grant Edwards grante Yow! It was a JOKE!! Get at it?? I was receiving visi.com messages from DAVID LETTERMAN!! YOW!! From dadapapa at googlemail.com Tue May 16 11:04:17 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 16 May 2006 08:04:17 -0700 Subject: what is the difference between tuple and list? In-Reply-To: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> References: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> Message-ID: <1147791857.440245.141240@j55g2000cwa.googlegroups.com> The main difference is that lists are mutables while tuples are not. Tuples are fine if you only want to group some objects (e.g. as a return value) and access their members as in >>> t = (1,2,3,4) >>> t[2] 3 Lists give you a lot more flexibility, because they are mutable: you can change the order of elements (e.g. sort), or delete or append items (all that this is not possible for tuples). These features make lists the primary data structures for stacks, queues, a.s.o. So, whenever you want to change what objects are in your collection or their ordering, use lists, otherwise, use tuples. Note, that this does not mean, that the items themselves cannot be changed. You can perfectly well change an object (e.g. dictionary) that resides in a tuple: >>> t = ({},) # tuple with empty dict as its only item >>> t[0]["foo"] = "bar" But if you e.g. want to exchange, that dictionary by another, you need to go for a list instead of a tuple. Hope that made sense... - harold - From bignose+hates-spam at benfinney.id.au Wed May 31 07:23:53 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 31 May 2006 21:23:53 +1000 Subject: Best Python Editor References: <mailman.24508.1149069603.27774.python-list@python.org> <BHEEKBFODALGBHHKCOFFOECKCGAA.manojk@sasken.com> Message-ID: <87slmqzbcm.fsf@benfinney.id.au> [Please refrain from obnoxious advertising or legal disclaimers on your messages to any discussion forum.] "Manoj Kumar P" <manojk at sasken.com> writes: > Can anyone tell me a good python editor/IDE? The leading programmer's editors are Emacs and Vim. Both have good support for working with Python. > It would be great if you can provide the download link also. The download link depends on where exactly you'll be running it. A good GNU/Linux distribution will have them both available as standard packages to be installed. <URL:http://www.vim.org/> <URL:http://www.gnu.org/software/emacs/> -- \ "A child of five could understand this. Fetch me a child of | `\ five." -- Groucho Marx | _o__) | Ben Finney From antroy at gmail.com Wed May 24 07:06:07 2006 From: antroy at gmail.com (Ant) Date: 24 May 2006 04:06:07 -0700 Subject: John Bokma harassment In-Reply-To: <44-dnSw6EOzlqOnZRVny3g@bt.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> Message-ID: <1148468767.551285.14290@u72g2000cwu.googlegroups.com> > Surely Voltaire didn't support speaking in inappropriate fora? Who knows? But the fora Xah posts to are few (5 or so?) and appropriate. "Software needs Philosophers" wasn't even his rant, but was certainly appropriate to all groups he posted to. If you don't like Xah's posts, then don't read them. Killfile him or whatever. But they *are* generally on-topic, they are not frequent, they are not spam and they do seem to be intended to provoke discussion rather than being simply trolls. I have no particular affinity for Xah's views, but what does get up my nose is usenet Nazism. From ptmcg at austin.rr._bogus_.com Wed May 3 09:02:49 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 03 May 2006 13:02:49 GMT Subject: Recommended data structure for newbie References: <1146626916.066395.206540@y43g2000cwc.googlegroups.com> Message-ID: <ZR16g.1508$CH2.1494@tornado.texas.rr.com> "manstey" <manstey at csu.edu.au> wrote in message news:1146626916.066395.206540 at y43g2000cwc.googlegroups.com... > Hi, > > I have a text file with about 450,000 lines. Each line has 4-5 fields, > separated by various delimiters (spaces, @, etc). > > I want to load in the text file and then run routines on it to produce > 2-3 additional fields. > <snip> Matthew - If you find re's to be too cryptic, here is an example using p From itayyy at gmail.com Tue May 2 17:22:24 2006 From: itayyy at gmail.com (itay_k) Date: 2 May 2006 14:22:24 -0700 Subject: urllib2 not support proxy on SSL connection? Message-ID: <1146604944.658622.119860@u72g2000cwu.googlegroups.com> Hi, I am running the following simple code (just open connection to some https page with proxy): proxy= '666.179.227.666:80' proxy=urllib2.ProxyHandler({"https":'https://'+proxy}) opener = urllib2.build_opener(proxy) request = urllib2.Request('https://somehttpspage....') response = opener.open(request) And I get this error: Traceback (most recent call last): File "<stdin>", line 1, in ? 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 1029, in https_open return self.do_open(httplib.HTTPSConnection, req) File "C:\Python24\lib\urllib2.py", line 996, in do_open raise URLError(err) urllib2.URLError: <urlopen error (1, 'error:140770FC:SSL routines:SSL23_GET_SERV ER_HELLO:unknown protocol')> Is it possible that urllib2 doesnt support for proxy over https connections? Thanks alot, Itay. From dale at riverhall.nospam.co.uk Tue May 9 03:54:56 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Tue, 09 May 2006 08:54:56 +0100 Subject: Why 3.0/5.0 = 0.59999... References: <1147159404.498386.58860@g10g2000cwb.googlegroups.com> Message-ID: <lVX7g.21644$lJ6.3741@fe69.usenetserver.com> Have you looked at the decimal module? python Python 2.4 (#1, Mar 22 2005, 21:42:42) [GCC 3.3.5 20050117 (prerelease) (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> from decimal import * >>> Decimal("3")/Decimal("5") Decimal("0.6") >>> I don't suppose it is quick but it might do what you want. Davy wrote: > Hi all, > > I used to be a Matlab user. And want to use Python to replace some > Matlab work. > > When I type 3.0/5.0, the result is 0.59999... > > Is there some precision loss? And how to overcome it? > > Any suggestions will be appreciated! > Best regards, > Davy -- Dale Strickland-Clark Riverhall Systems - www.riverhall.co.uk From akameswaran at gmail.com Tue May 30 17:34:07 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 30 May 2006 14:34:07 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <447cadf6$1@nntp0.pdx.net> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <mailman.6282.1148767807.27775.python-list@python.org> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> <447c8c6e$1@nntp0.pdx.net> <1149016823.214610.258930@r44g2000cwb.googlegroups.com> <447cadf6$1@nntp0.pdx.net> Message-ID: <1149024847.655949.227290@38g2000cwa.googlegroups.com> Scott David Daniels wrote: > Sorry, "re-iterables". A file re-iterable is: > > class FileReIterable(object): > def __init__(self, file): > if isinstance(file, basestring): > self.file = open(file, 'rU') > else: > self.file = file > def __iter__(self): > self.file.seek(0) > return iter(self.file) > > This works if-and-only-if it is only in use once at a time. > If you have multiple simultaneous accesses, you need to do > something like: > > class FileReIterable2(object): > def __init__(self, file): > if isinstance(file, basestring): > self.file = open(file, 'rU') > else: > self.file = file > def __iter__(self): > self.file.seek(0) > for line in self.file: > nextpos = self.file.tell() > yield line > self.file.seek(nextpos) > > --Scott David Daniels > scott.daniels at acm.org Since I was doing this as a self education excercise. When you say is in use once and only once, you mean I can only use a single instance of the class? I haven't even tested these yet, but I am very curious about that statement. Why is it necessary to return a generator object in the second example? If it's a real long explanation, feel free to point me to some relvant texts. My practical problem was solved about 10 posts ago... but I am still trying to understand the behavior. Thank you for you time. AK From hwiechers at gmail.com Wed May 31 09:50:47 2006 From: hwiechers at gmail.com (hwiechers at gmail.com) Date: 31 May 2006 06:50:47 -0700 Subject: Variable name has a typo, but code still works. Why? In-Reply-To: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> References: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> Message-ID: <1149083447.370584.197070@f6g2000cwb.googlegroups.com> mateus wrote: > print "hello world" > > I have a nested loop where the outer loop iterates over key value pairs > of a dictionary and the inner loop iterates over a list each list of > which is a mapped value from the dictionary > > def showReport(self): > for dev, sessions in self.logger.items(): > for tree in session: > self.addTestItem(self, tree) > > What I don't understand is why this executes w/o any problems when > "sessions" was spelled as plural (sessionS) while later being spelled > in the singular (session). > > Is there some type of name resolution of local variables where Python > makes assumptions? I've never heard of a rule disregarding ending 's'es and I really doubt one exists. Are you sure session isn't a global variable? You can check using globals(). From mhellwig at xs4all.nl Sat May 6 14:18:17 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 06 May 2006 20:18:17 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <7x3bfnvyoj.fsf@ruckus.brouhaha.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> <445c8812$0$31639$e4fe514c@news.xs4all.nl> <7xhd43qkxq.fsf@ruckus.brouhaha.com> <445cb8e6$0$31641$e4fe514c@news.xs4all.nl> <7x3bfnvyoj.fsf@ruckus.brouhaha.com> Message-ID: <445ce874$0$31645$e4fe514c@news.xs4all.nl> Paul Rubin wrote: > "Martin P. Hellwig" <mhellwig at xs4all.nl> writes: >>> This is a weird approach. Why not let the "ticket" by the (maybe >>> encrypted) PRNG seed that generates the permutation? >> Because the server that handles the generate request doesn't need to >> be the same as the one that handles the request to give the client >> that deck. > > Wait a sec, are you giving the entire shuffled deck to the client? > Can you describe the application? I was imagining an online card game > where clients are playing against each other. Letting any client see > the full shuffle is disastrous. Nope I have a front end service that does the client bit, its about this (in this context, there are more services of course): crypto - ZFS - table servers - mirror dispatching - client xmlrpc access - client ( last one has not been written yet ) <cut> > > Depending on just what the server is for, access security may be a far > more important issue. If I'm playing cards online with someone, I'd > be WAY more concerned about the idea of my opponent being able to see > my cards by breaking into the server, than his being able to > cryptanalyze a well-designed PRNG based solely on its previous > outputs. Only client xmlrpc access is (should be) accessible from the outside and since this server is user session based they only see their own card. However this project is still in it's early development, I'm doing now initial alpha-tests (and stress testing) and after this I'm going to let some audit bureau's check for security (probably Madison-Ghurka, but I haven't asked them yet). -- mph From fuzzyman at gmail.com Sat May 13 16:29:47 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 13 May 2006 13:29:47 -0700 Subject: compiling module from string and put into namespace In-Reply-To: <1147546732.243157.174810@i40g2000cwc.googlegroups.com> References: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> <4464754a$0$306$626a54ce@news.free.fr> <1147474282.618115.60590@u72g2000cwu.googlegroups.com> <446599de$0$5314$626a54ce@news.free.fr> <1147546732.243157.174810@i40g2000cwc.googlegroups.com> Message-ID: <1147552187.560843.46290@j73g2000cwa.googlegroups.com> glomde wrote: > Ok, now I think I know what I need to do. > I need to create a variable in the calling functions locals. > So how do I get access to the calles locals dictionary? > Is it possible? If your import is used in the current namespace, just use the global keyword. Best is if your function just returns the module though, and then you have bound your name to it exactly as if you had used import. If you *really* want to poke it into the globals of whereever your function is called from, you can use : sys._getframe(1).globals['name'] = name (or something like that, you will need to look up the semantics.) This is a hack really though, just return the module object and bind the right name to it where you call it from. Fuzzyman http://www.voidspace.org.uk/python/index.shtml From george.sakkis at gmail.com Fri May 26 22:55:22 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 26 May 2006 19:55:22 -0700 Subject: PUDGE - Project Status, Alternative Solutions References: <447786E9.9010208@lazaridis.com> Message-ID: <1148698521.979633.84930@38g2000cwa.googlegroups.com> Ilias Lazaridis wrote: > Is there a similar tool available, with which I can generate python > documentation / websites or both based on templates and reST? rest2web (http://www.voidspace.org.uk/python/rest2web/) seems relevant, though the latest version is 0.4alpha so I'm not sure if it's stable enough for your needs. George From antroy at gmail.com Wed May 24 11:52:47 2006 From: antroy at gmail.com (Ant) Date: 24 May 2006 08:52:47 -0700 Subject: John Bokma harassment In-Reply-To: <Xns97CD6A2A4F305castleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> Message-ID: <1148485967.164221.304310@y43g2000cwc.googlegroups.com> John Bokma wrote: > That's because you're clueless. Well argued. No really. Not quite sure what you base the allegations on of course. John, you're well out of order getting this guy into problems with his ISP. Ken Tilton has it spot on - if everyone who wasn't interested in what he had to say ignored it, then it would make it far easier for those actually interested in the topic to reply, without a tirade of off topic abuse to filter through. I'm not a particular Xah fan, but I do find some of the threads provoked by his posts interesting. What is more of a concern to me is that he should have freedom to post on relevant newsgroups. Take a look at his site. You'll find that he is actually interested in the 5 or so newsgroups he cross-posts to, and his posts are general enough to apply to each of them. In short, get off of your soap box - if you don't like what the guy has to say then *ignore it*. FYI - I have written in support of Xah Lee to the ISP simply because I don't see why your personal problem with the guy should cost him money. From john at castleamber.com Sat May 20 00:56:33 2006 From: john at castleamber.com (John Bokma) Date: 20 May 2006 04:56:33 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> Message-ID: <Xns97C8F38DDC88Ecastleamber@130.133.1.4> Edward Elliott <nobody at 127.0.0.1> wrote: > John Bokma wrote: > >> Edward Elliott <nobody at 127.0.0.1> wrote: >> >>>>> like "from X import *" which are generally frowned on in python >>>>> while 'use MOD qw(id)' is encouraged in perl. >>>> >>>> Not by me, and I doubt it is in general. >>> >>> Well it's all over the Perl Cookbook. >> >> Yeah, sure, all over. > > 125 occurences in 78 recipes. Sure looks like all over to me. >> Maybe check the book again. It is used in some >> examples, sure. And it even explains how it works. > > Yep, 125 times. In 78 recipes. Out of 105 total recipes with 'use'. > I'd say a 3:1 ratio is pretty strong encouragement. > >> Don't forget that most >> of the book was written around 1998. Yes, 8 years ago. > > Doesn't matter. Yes it matters. 8 years is a lot of time in IT. In 1998 Perl5.005 was announced (22 July). [1] Which should tell you a lot if you indeed have 3 years of Perl skills. > It's still the standard example reference. People > use it heavily. They don't magically know what parts are now > deprecated. If they are serious with their study they know that a 8 year old book is hardly up to date. I tend to take most IT related books I use that are older then 3-4 years with quite a grain of salt. I am not going to take an 8 year old Java CookBook very seriously for example. >> You can even find examples on my site that use imported functions >> (which I will fix, because I frown upon it :-) ). But I doubt you can >> find a majority in the perl community that *encourages* the use of >> imported functionality. > > I can readily believe that the "community" frequenting the newsgroups, > mailing lists, and blogs don't encourage it anymore. But that's a > tiny fraction of all perl programmers, and most of them have no > exposure to this little clique. Pfft, you are just guessing around now. > For many people, whatever the > cookbook says goes. If it's wrong, update it. Well, contact the authors or O'Reilly. Seriously, are you using 8 year old Python recipes without thinking? [1] http://history.perl.org/PerlTimeline.html -- 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 tdw at tdw.net Thu May 4 09:39:44 2006 From: tdw at tdw.net (Tim Williams) Date: Thu, 4 May 2006 14:39:44 +0100 Subject: Swaying A Coder Away From Python In-Reply-To: <R40843717.445.3845.1@mx-extra.net> References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <W40839200.311.1532.1@mx-extra.net> <mailman.5315.1146743831.27775.python-list@python.org> <R40843717.445.3845.1@mx-extra.net> Message-ID: <9afea2ac0605040639ub949addj618b539eebb6a465@mail.gmail.com> On 4 May 2006 05:24:40 -0700, BartlebyScrivener <rpdooling at gmail.com> wrote: > I'm picking this up via clp on Google Groups. I can't tell what Mr. > Lundh is referring to. The first line of his post is: "Tim Williams > wrote" but there's nothing that comes before. I had seen the article on > Django on Digg I think, but what is article Tim Williams is referring > to? > > Thanks, > > rick Rick, I found the web version at. http://www.devwebpro.co.uk/devwebprouk-46-20060503SwayingACoderAwayFromPython.html :) From chris at foote.com.au Mon May 15 23:19:50 2006 From: chris at foote.com.au (Chris Foote) Date: Tue, 16 May 2006 12:49:50 +0930 Subject: Large Dictionaries In-Reply-To: <e4abj6$p6a$1@panix1.panix.com> References: <1147699064.107490@teuthos> <roy-765731.09112115052006@reader1.panix.com> <e4abj6$p6a$1@panix1.panix.com> Message-ID: <1147751674.531058@teuthos> Aahz wrote: > In article <roy-765731.09112115052006 at reader1.panix.com>, > Roy Smith <roy at panix.com> wrote: >> In article <1147699064.107490 at teuthos>, Chris Foote <chris at foote.com.au> >> wrote: >>> I have the need to store a large (10M) number of keys in a hash table, >>> based on a tuple of (long_integer, integer). The standard python >>> dictionary works well for small numbers of keys, but starts to >>> perform badly for me inserting roughly 5M keys: >>> >>> # keys dictionary metakit (both using psyco) >>> ------ ---------- ------- >>> 1M 8.8s 22.2s >>> 2M 24.0s 43.7s >>> 5M 115.3s 105.4s >> Are those clock times or CPU times? > > And what are these times measuring? The loading of a file into a dictionary. i.e. no lookup operations. > Don't forget that adding keys > requires resizing the dict, which is a moderately expensive operation. Yep, that's why I probably need a dictionary where I can pre-specify an approximate size at the time of its creation. > Once the dict is constructed, lookup times should be quite good. Very good indeed with Psyco! Cheers, Chris From __peter__ at web.de Sat May 13 12:21:20 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 13 May 2006 18:21:20 +0200 Subject: Package that imports with name of dependent package References: <mailman.5657.1147530941.27775.python-list@python.org> <e44vvm$nvh$01$1@news.t-online.com> Message-ID: <e450ua$q1a$01$1@news.t-online.com> Peter Otten wrote: >> I'd appreciate hearing of what I can do in an __init__ file or what >> other strategy could make this work. Many thanks. > > I think fixing the imports is the better long-term approach. But putting > > from pkgutil import extend_path > import mypackage > __path__ = extend_path(mypackage.__path__, __name__) > > into dependentpackage/__init__.py might work. One big caveat: If you are mixing both import mypackage.somemodule and import dependentpackage.somemodule in the same application, mypackage.somemodule and dependentpackage.somemodule are *not* the same module instance. This may have surprising effects when global variables in somemodule.py are updated... Peter From rdilipk at lycos.com Tue May 9 19:23:54 2006 From: rdilipk at lycos.com (Dilip) Date: 9 May 2006 16:23:54 -0700 Subject: Performance of Blocks in Python Message-ID: <1147217034.010189.224150@j73g2000cwa.googlegroups.com> I read a couple of interesting blog posts about the performance of blocks in languages like Ruby, Python here[1] and here[2]. The posts start out questioning Ruby but towards the middle and the end it does draw analogies between python's design decision to introduce 'with' statement as a language extension rather than a closure. [1] http://pluralsight.com/blogs/dbox/archive/2006/05/09/23068.aspx [2] http://pluralsight.com/blogs/dbox/archive/2006/05/08/23001.aspx From ptmcg at austin.rr._bogus_.com Sun May 21 14:52:13 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 21 May 2006 18:52:13 GMT Subject: escapes in regular expressions References: <1148233776.133200.59280@u72g2000cwu.googlegroups.com> Message-ID: <xF2cg.50254$CH2.25156@tornado.texas.rr.com> "James Thiele" <jamesthiele.usenet at gmail.com> wrote in message news:1148233776.133200.59280 at u72g2000cwu.googlegroups.com... > I was helping a guy at work with regular expressions and found > something I didn't expect: > > >>> re.match('\d', '7').group() > '7' > >>> re.match('\\d', '7').group() > '7' > >>> > > It's not clear to me why these are the same. Could someone please > explain? > This is not a feature of regexp's at all, but of Python strings. If the backslash precedes a character that is not normally interpreted, then it is treated like just a backslash. Look at this sample from the Python command line: >>> s = "\d" >>> s '\\d' >>> s = "\t" >>> s '\t' >>> This is one reason why Python programmers who use regexp's use the "raw" notation to create strings (this is often misnomered as a "raw string", but the resulting string is an ordinary string in every respect - what is "raw" about it is the disabling of escape behavior of any backslashes that are not the last character in the string). It is painful enough to litter your regexp with backslashes, just because you have the misfortune of having to match a '.', '+', '?', '*', or brackets or parentheses in your expression, without having to double up the backslashes for escaping purposes. Consider these sample statements: >>> "\d" == "\\d" True >>> "\t" == "\\t" False >>> r"\t" == "\\t" True >>> So your question is really a string question - you just happened to trip over it while defining a regexp. -- Paul From tomasz.zielonka at gmail.com Mon May 8 01:11:06 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Mon, 8 May 2006 05:11:06 +0000 (UTC) Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <pan.2006.05.07.08.35.04.362248@gmail.com> <1heytan.zl0xgh9v134kN%aleaxit@yahoo.com> Message-ID: <slrne5tkhg.b7l.tomasz.zielonka@tomekz.gem.lan> Alex Martelli wrote: > Worst case, you name all your functions Beverly so you don't have to > think about the naming I didn't think about this, probably because I am accustomed to Haskell, where you rather give functions different names (at the module top-level you have no other choice). I just checked that it would work for nested Beverly-lambdas (but could be quite confusing), but how about using more then one lambda in an expression? You would have to name them differently. > but you also have a chance to use meaningful names (such as, > presumably, zipperize_widget is supposed to be here) to help the > reader. [OK, I am aware that you are talking solely about lambdas in Python, but I want to talk about lambdas in general.] Sometimes body of the function is its best description and naming what it does would be only a burden. Consider that the same things that you place in a loop body in python, you pass as a function to a HOF in Haskell. Would you propose that all loops in Python have the form: def do_something_with_x(x): ... do something with x for x in generator: do_something_with_x(x) Also, having anonymous functions doesn't take your common sense away, so you still "have a chance". Best regards Tomasz From Dorit.Gross at fao.org Wed May 17 06:21:24 2006 From: Dorit.Gross at fao.org (Gross, Dorit (SDRN)) Date: Wed, 17 May 2006 12:21:24 +0200 Subject: How to pass variables between scripts? Message-ID: <5290E77B1FE2FE40B82AA54158825F0601F2C954@hqosex01.fao.org> Marcelo, thank you very much for your help!!! The script is running nicely now and I can pass the variables easily between the scripts. If someone else followed this topic ... a short note at the end. It seems that with the 'globvars' also the modules used by 'second.py' have to be passed. Somehow the modules defined in 'second.py' itself are not available when 'second.py' is called from an external script. So adding following line to the external script solves the problem: globvars = { 'os' : __import__('os') } Many thanks again, Dorit > -----Original Message----- > From: python-list-bounces+dorit.gross=fao.org at python.org > [mailto:python-list-bounces+dorit.gross=fao.org at python.org] > On Behalf Of Marcelo Ramos > Sent: 16 May 2006 19:51 > To: python-list at python.org > Subject: Re: How to pass variables between scripts? > > > Gross, Dorit (SDRN) escribi?: > >>> #! /usr/local/bin/python > >>> # test_exec.py > >>> > >>> import os, sys, glob > >>> > >>> fileList = glob.glob('/data/*.ZIP') > >>> > >>> for f in fileList: > >>> try: > >>> globvars = {'infile' : f} > >>> locvars = {} > >>> execfile('/scripts/second.py', globvars(), locvars) > >>> except IOError: > >>> exit(0) > >>> print locvars > >>> > >>> > >>> > >> You are calling the dictionary globvars as a function then > the error. > >> The fixed line is: > >> > >> execfile('/scripts/second.py', globvars, locvars) > >> > >> > >> > >> What you want is the function globals(). > >> Try putting this line in second.py: > >> > >> print globals()['infile'] > >> > >> Using the dictionary returned by globals() you can make > second.py to > >> read the contents of testexec.py's globvars dictionary. > >> locvars is populated with the local variables of second.py > >> and that is > >> what you want. > >> > >> > > > > Marcelo, thank you! Passing the variables with dictonaries and > > function > > globals() works fine if no other functions are defined in > 'second.py'. Now > > 'second.py' contains further functions and a "if __name__ = > __main__" > > statement and in this case it seems that 'second.py' is not > fully executed > > from 'test_exec.py'. For the sole purpose of testing, > 'second.py' looks like > > this at the moment: > > > > #! /usr/local/bin/python > > # second.py > > > > import os, sys > > > > global zipfile > > print 'Read from globals: ' + globals()['infile'] > > zipfile = globals()['infile'] > > print 'Read from zipfile: ' + zipfile > > > > if __name__ == '__main__': > > > > print 'Hello' > > print globals()['infile'] > > print zipfile > > > > > > Calling test_exec.py results into this output: > > > > ./test_exec.py > > Read from globals: /data/S0012230_0010.ZIP > > Read from zipfile: /data/S0012230_0010.ZIP > > > > > > It seems that the commands within the main are not executed when > > calling test_exec.py!?! Is there a way to make it running? > > > > Regards and thank you again, > > Dorit > > > > > > > If you print __name__ in second.py its value is > '__builtin__', because > of that your "main" doesn't execute. > Try adding this to test_exec.py before the execfile() call: > > globvars[ '__name__' ] = '__main__' > > It looks like a ad hoc fix but i couldn't find any doc about > the change > of __name__ to 'builtin' of a python script being run > from another with execfile(). > > Regards. > > -- > Marcelo Ramos > Fedora Core 5 | 2.6.16 > Socio UYLUG Nro 125 > > -- > http://mail.python.org/mailman/listinfo/python-list > From paddy3118 at netscape.net Fri May 12 01:47:28 2006 From: paddy3118 at netscape.net (Paddy) Date: 11 May 2006 22:47:28 -0700 Subject: Reg Ex help In-Reply-To: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> Message-ID: <1147412848.145617.308680@q12g2000cwa.googlegroups.com> If you have strings of all the CHECKEDOUT (is this from the lsco command?), then the following might work for you: >>> s ="/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4" >>> s.split()[0].split('/')[-2] 'dbg_for_python' >>> - Paddy. From invalidemail at aerojockey.com Sat May 20 04:48:24 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 20 May 2006 01:48:24 -0700 Subject: Exception style (was: calling python functions using variables) References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <9121k3-hjm.ln1@lairds.us> <mailman.5960.1148053232.27775.python-list@python.org> Message-ID: <1148114904.818645.37740@i39g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Cameron Laird wrote: > > > Guys, I try--I try *hard*--to accept the BetterToAskForgiveness > > gospel, but this situation illustrates the discomfort I consistently > > feel: how do I know that the NameError means VARIABLE didn't resolve, > > rather than that it did, but that evaluation of commands.VARIABLE() > > itself didn't throw a NameError? My usual answer: umm, unless I go > > to efforts to prevent it, I *don't* know that didn't happen. > > two notes: > > 1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError. > > 2) as you point out, doing too much inside a single try/except often results in hard- > to-find errors and confusing error messages. the try-except-else pattern comes in > handy in cases like this: > > try: > f = getattr(commands, name) > except AttributeError: > print "command", name, "not known" > else: > f() What if commands were an instance of this class: class CommandClass: .... def __getattr__(self,attr): try: return self.dircontenst[attr] except KeyError: raise AttributeError The call to getattr manages to raise AttributeError even though the command is known. Yes, self.dircontents[attr] does exist and is valid in this example, but it still raises AttributeError because dircontents is spelled wrong. I make this silly example to point out that Python's dynamicism is a possible pitfall with ETAFTP even if you're careful. It's something worth keeping in mind. Another example, much more realistic: GvR says don't use callable(), just try calling it and catch CallableError (or whatever it is). Of course, that error can be raised inside the function; and in this case, there's no way to isolate only the part you you're checking for an exception. Carl Banks From http Tue May 16 20:16:05 2006 From: http (Paul Rubin) Date: 16 May 2006 17:16:05 -0700 Subject: calling upper() on a string, not working? References: <Ayqag.2108$No6.45797@news.tufts.edu> <mailman.5767.1147811690.27775.python-list@python.org> <yNqag.2109$No6.46071@news.tufts.edu> Message-ID: <7xodxxbj5m.fsf@ruckus.brouhaha.com> John Salerno <johnjsal at NOSPAMgmail.com> writes: > Now, I know the actual upper() function works, but I can't understand > if there's a problem with *when* it's being called, or what's being > done with it to get the second result above. You are translating "original" which still has lower case letters: return original.translate(trans_table) You want: return original.upper().translate(trans_table) From rcs at bgoark.no Wed May 24 06:08:05 2006 From: rcs at bgoark.no (baalbek) Date: Wed, 24 May 2006 12:08:05 +0200 Subject: Using python for a CAD program In-Reply-To: <1148404366.743786.258280@u72g2000cwu.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <e4ham3$1td$1@sea.gmane.org> <446C8950.3070107@anansispaceworks.com> <mailman.6000.1148109587.27775.python-list@python.org> <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> <mailman.6062.1148282177.27775.python-list@python.org> <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> <1148404366.743786.258280@u72g2000cwu.googlegroups.com> Message-ID: <447430f8$0$22978$c83e3ef6@nn1-read.tele2.net> Paddy wrote: > Hi Baalbek, > Athouh they are database editors, they are not relational database > editors. Relational database engines fit some type of problems but > others have found that RDBMS don't fit CAD data. They are just too slow > and add complexity in mapping the 'natural CAD data formats' to the > RDBMS table format. Well, considering that most CAD programs (at least those I'm familiar with) structures its data in a very similar fashion as a RDBMS, AND given the advanced object/relational mapping tools we have today, how hard could it be? The CAD system does not even have to be a straight client-server, but a three-tiered system where the application server do batch update/fetching of the data for efficiency. Regards, Baalbek From levub137 at wi.rr.com Tue May 9 08:30:58 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Tue, 09 May 2006 12:30:58 GMT Subject: installing numpy In-Reply-To: <877j4v5ukc.fsf@localhost.localdomain> References: <877j4v5ukc.fsf@localhost.localdomain> Message-ID: <6Y%7g.11622$EC.10694@tornado.rdc-kc.rr.com> Gary Wessle wrote: > Hi > > I am trying to install NumPy in my debian/testing linux > 2.6.15-1-686. > <snip> When installing from source on a Debian system, you want the installed package to wind up in /usr/local/lib/python2.x/site-packages (where x represents the version of Python you are running the installer from). This allows you to keep it separate from the apt managed directories and allows for easy removal/upgrade. So the command you want to execute from root is python setup.py install --prefix=/usr/local By the way, to get NymPy to use the high-performance libraries, you must install these libraries and the associated -dev packages before running the Python install. From arnemeissner at gmx.de Wed May 3 12:09:14 2006 From: arnemeissner at gmx.de (Arne) Date: Wed, 3 May 2006 18:09:14 +0200 Subject: Update Tix ExFileSelectBox Message-ID: <e3akjb$1gi$03$1@news.t-online.com> Hello! I am looking for an option on Tix ExFileSelectBox. I am using this widget to delete files. After I have delete a file it is still on the filelist view. After I have changed the directory and come back I will get the new view. What I am looking for is a function to update the view of the hlist. Somebody knows how to do it? Thank you a lot! Arne From rosssd at gmail.com Wed May 10 05:18:15 2006 From: rosssd at gmail.com (sross) Date: 10 May 2006 02:18:15 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> Message-ID: <1147252695.346762.20020@y43g2000cwc.googlegroups.com> > I do wonder what would happen to Cells if I ever want to support > multiple threads. Or in a parallel processing environment. AFAIK It should be fine. In LW, SBCL and ACL all bindings of dynamic variables are thread-local. Cheers, Sean. From rschroev_nospam_ml at fastmail.fm Mon May 22 16:35:04 2006 From: rschroev_nospam_ml at fastmail.fm (Roel Schroeven) Date: Mon, 22 May 2006 20:35:04 GMT Subject: Python - Web Display Technology In-Reply-To: <slrne7440c.9h4.sybrenUSE@schuimige.stuvel.eu> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <bhv172hbu1i37nqi3kp1rhnuaujj1qo208@4ax.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <slrne73loa.8pe.sybrenUSE@schuimige.stuvel.eu> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> <slrne7440c.9h4.sybrenUSE@schuimige.stuvel.eu> Message-ID: <Yfpcg.441043$CB4.11766852@phobos.telenet-ops.be> Sybren Stuvel schreef: > SamFeltus enlightened us with: >> 1. Loss of back button >> Isn't this really a myth? > > No, it isn't a myth. Pressing the back button is the action second > most performed in a browser, clicking a link being the first. People > want to go back from where they came. I don't even use the back button very much: if there's any chance that I'm going to want to return to the current page, I open new links in new tabs. That way I can be sure that I can return to the page exactly as it is now. With Flash, that approach fails too. One more minus for Flash on the web. -- If I have been able to see further, it was only because I stood on the shoulders of giants. -- Isaac Newton Roel Schroeven From rpdooling at gmail.com Tue May 2 02:27:23 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 1 May 2006 23:27:23 -0700 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <1146518284.210504.319960@i40g2000cwc.googlegroups.com> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5180.1146491500.27775.python-list@python.org> <1146518284.210504.319960@i40g2000cwc.googlegroups.com> Message-ID: <1146551243.698615.30100@v46g2000cwv.googlegroups.com> No way. You didn't deserve it. Unless you came from another OO language, the Guido tutorial on Classes is unintelligible. It assumes way too much knowledge. But I found something else that looks promising that you may want to peek at: http://pytut.infogami.com/node11-baseline.html rd Reply From olsongt at verizon.net Wed May 24 13:18:07 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 24 May 2006 10:18:07 -0700 Subject: John Bokma harassment In-Reply-To: <ws%cg.7001$8G3.3811@twister.nyroc.rr.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> <1148484776.213699.34610@i39g2000cwa.googlegroups.com> <ws%cg.7001$8G3.3811@twister.nyroc.rr.com> Message-ID: <1148491087.816172.154880@j55g2000cwa.googlegroups.com> > > > > > > Time for a game! > > > > Both johnbokma.com and castleamber.com are hosted by seagull.net. Here > > is a link to their TOS: > > > > http://www.seagull.net/tos.html > > > > Who can come up with the most violations that John is committing on > > this thread? I count 4. > > > Let's not drop to his level. > -- I agree. I never actually said that anyone should report him. I simply wanted to illustrate his hipocrisy. [Although John insinuated I did say that, which I find defamitory, and is clearly a violation of his TOS ;-) ] From invalidemail at aerojockey.com Sat May 20 04:00:22 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 20 May 2006 01:00:22 -0700 Subject: PEP 3102 for review and comment In-Reply-To: <1148102845.438543.16380@38g2000cwa.googlegroups.com> References: <1148102845.438543.16380@38g2000cwa.googlegroups.com> Message-ID: <1148112022.745958.168120@j55g2000cwa.googlegroups.com> Talin wrote: > Specification > > Syntactically, the proposed changes are fairly simple. The first > change is to allow regular arguments to appear after a varargs > argument: > > def sortwords(*wordlist, case_sensitive=False): > ... > > This function accepts any number of positional arguments, and it > also accepts a keyword option called 'case_sensitive'. This > option will never be filled in by a positional argument, but > must be explicitly specified by name. Ick. Pretty big change hinging on subtle juxtaposition in the argument list. I don't like it, it doesn't stand out enough... but it makes logical sense and any other solution would have to be way more contrived. I think argument lists are already confusing enough with just mixing *, **, and default arguments. Two thoughts: Would these arguments go before of after **kwargs? This is apparently for Python 3.0. (I'd make the implementation schedule explicit, even if the PEP number implies it's Python 3.0.) It looks like Python 3.0 might declare function arguments like Ada. If so, what about a little modifier (like Ada's "in and out") instead? Problem with that is then positional arguments line up wrong. Ick. def func(a : int = 1): pass def func(a : kwonly int = 1): pass Carl Banks From kent at kentsjohnson.com Tue May 23 10:46:15 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 23 May 2006 10:46:15 -0400 Subject: GUI viewer for profiler output? Message-ID: <44731f6c$1_1@newspeer2.tds.net> Can anyone point me to a GUI program that allows viewing and browsing the output of the profiler? I know I have used one in the past but I can't seem to find it... Thanks, Kent From invalidemail at aerojockey.com Thu May 18 23:16:03 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 18 May 2006 20:16:03 -0700 Subject: Script to make Windows XP-readable ZIP file References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> Message-ID: <1148008563.178335.307330@j55g2000cwa.googlegroups.com> pac wrote: > Suppose you have a set of files in a directory c:\a\b and some > additional > files in c:\a\b\subdir. Using a Python script, you would > like to make a Windows-readable archive (.zip) that preserves this > directory structure, and where the root directory of the archive is > c:\a\b. In other words, all the files from c:\a\b appear in the > archive > without a path prefix, and all the files in c:\a\b\subdir have a path > prefix of \subdir. > > This looks like it should be easy with module zipfile and the handy > function os.walk. Create a zip file, call os.walk, and add the files > to > the archive like so: > > import os > import zipfile > > z = > zipfile.ZipFile(r"c:\a\b\myzip.zip",mode="w",compression=zipfile.ZIP_DEFLATED) > > for dirpath,dirs,files in os.walk(r"c:\a\b"): > for a_file in files: > a_path = os.path.join(dirpath,a_file) > z.write(a_path) # Change, see below > z.close() (Aside: be careful not to use tabs when posting. I suspect the f-bot will be here to tell you that the above code doesn't work.) > Some experimentation suggests that Windows does not like any filename > in the > archive that begins with either a drive designator like c:, or has a > path containing > a leading slash like "\a\b\afile.txt". Relative paths like > "subdir\afile.txt" are > okay, and cause the desired behavior when the archive is extracted, > e.g., a new directory subdir is created and afile.txt is placed in it. > > Since the method ZipFile.write needs a valid pathname for each file, > the correct > solution to the original problem entails messing around with the OS's > current > working directory. ZipFile.write takes an optional second argument for the archive filename. You could have done something like this (untested): for dirpath,dirs,files in os.walk(r"c:\a\b"): for a_file in files: a_path = os.path.join(dirpath,a_file) z_path = a_path[7:] # or whatever z.write(a_path,z_path) z.close() And maybe use a little helper function instead of the string slice to make it more robust (it violates DRY, and I'm not happy to assume the dirpath returned by os.walk has exactly the same prefix as the argument). > Position the CWD in the desired base directory of > the archive, > add the files to the archive using their relative pathnames, and put > the CWD back > where it was when you started: This may be the best way anyways, unless you have some reason to not change the current directory. Carl Banks From claudio.grondi at freenet.de Thu May 18 05:55:11 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 18 May 2006 11:55:11 +0200 Subject: Large Dictionaries In-Reply-To: <1147934447.138732@teuthos> References: <1147699064.107490@teuthos> <e49va0$m72$1@newsreader3.netcologne.de> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <e4ftjn$bp7$1@newsreader3.netcologne.de> <1147934447.138732@teuthos> Message-ID: <e4hg9r$k87$1@newsreader3.netcologne.de> Chris Foote wrote: > Claudio Grondi wrote: >> Chris Foote wrote: >>> Klaas wrote: >>> >>>>> 22.2s 20m25s[3] >>>> >>>> 20m to insert 1m keys? You are doing something wrong. >>> >>> I've put together some simplified test code, but the bsddb >>> module gives 11m for 1M keys: >>> >> I have run your code for the bsddb on my P4 2.8 GHz and have got: >> Number generator test for 1000000 number ranges >> with a maximum of 3 wildcard digits. >> Wed May 17 16:34:06 2006 dictionary population started >> Wed May 17 16:34:14 2006 dictionary population stopped, duration 8.4s >> Wed May 17 16:34:14 2006 StorageBerkeleyDB population started >> Wed May 17 16:35:59 2006 StorageBerkeleyDB population stopped, >> duration 104.3s > > >> Surprising here, that the dictionary population gives the same time, >> but the BerkeleyDB inserts the records 6 times faster on my computer >> than on yours. I am running Python 2.4.2 on Windows XP SP2, and you? > > Fedora core 5 with ext3 filesystem. The difference will be due to > the way that Windows buffers writes for the filesystem you're using > (it sounds like you're using a FAT-based file system). Ok, according to the Windows task manager the Python process reads/writes to the file system during the run of BerkeleyDB test around 7 GByte(!) of data and the hard drive is continuously busy, where the size of file I found in the Temp directory is always below 20 MByte. The hard drive access is probably the main reason for loosing time - here a question to BerkeleyDB experts: Can the BerkeleyDB via Python bsddb3 interface be tuned to use only RAM or as BerkeleyDB can scale to larger data amount it makes not much sense to tweak it into RAM? Chris, is maybe a RAM-disk the right way to go here to save time lost for accessing the file stored in the file system on the hard drive? The RAM requirements, according to Windows XP task manager, are below 100 MByte. I am using the NTFS file system (yes, I know, that FAT is in some configurations faster than NTFS) and XP Professional SP2 without any tuning of file system caching. The CPU is 100% busy. What CPU and RAM (SIMM, DDR, DDR2) do you have? I have 2GByte fast DDR PC400/3200 dual line RAM. It seems, that you are still not getting results within the range others experience running your code, so I suppose, it has something to do with the hardware you are using. > >>> Number generator test for 1000000 number ranges >>> with a maximum of 3 wildcard digits. >>> Wed May 17 22:18:17 2006 dictionary population started >>> Wed May 17 22:18:26 2006 dictionary population stopped, duration 8.6s >>> Wed May 17 22:18:27 2006 StorageBerkeleyDB population started >>> Wed May 17 22:29:32 2006 StorageBerkeleyDB population stopped, >>> duration 665.6s >>> Wed May 17 22:29:33 2006 StorageSQLite population started >>> Wed May 17 22:30:38 2006 StorageSQLite population stopped, duration >>> 65.5s >> As I don't have SQLite installed, it is interesting to see if the >> factor 10 in the speed difference between BerkeleyDB and SQLite can be >> confirmed by someone else. >> Why is SQLite faster here? I suppose, that SQLite first adds all the >> records and builds the index afterwards with all the records there >> (with db.commit()). > > SQLite is way faster because BerkeleyDB always uses a disk file, > and SQLite is in RAM only. One of the reasons I put an eye on BerkeleyDB is that it pretends to scale to a huge amount (Terrabyte) of data and don't need as much RAM as Python dictionary and it is not necessary to save/load pickled version of the data (i.e. here the dictionary) from/to RAM in order to work with it. I guess, that in your case BerkeleyDB is for the named reasons probably the right way to go, except your data will stay small and the Python dictionary with them will always fit into RAM. Now I am curious to know which path you have decided to go and why? Claudio > > Cheers, > Chris From n.estner at gmx.de Tue May 30 18:24:37 2006 From: n.estner at gmx.de (nikie) Date: 30 May 2006 15:24:37 -0700 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> Message-ID: <1149025209.816003.309470@j55g2000cwa.googlegroups.com> xkenneth wrote: > Hi, > > I'm writing a couple python applications that use the serial port > (RS-232) quite extensively. Is there any way I can monitor all activity > on the serial port and have it printed as the transactions occur? I'm > trying to reverse engineer a microcontroller serial routine and I'd > like to see any response the chip sends back. I've done similar things in the past, and the best tools I found at that time were: - Serial Port sniffer from www.hhdsoftware.com Similar to portmon, but (in my experience) more stable. Windows only, though. - VMWare You can run your serial port app in a VMWare and connect the virtual serial port to a file or named pipe on the host system. But this won't help you if the app uses serial commands not available for files/pipes. - Hardware cable If you know how to use a soldering iron, this might be the best way: a serial cable has an RX and a TX wire, connect each of them to the RX wires of two separate serial cables, that way you can "wiretap" the whole communication to two different serial ports (e.g. on your laptop) in a running system. Dead useful for debugging! From steve at hastings.org Mon May 1 20:56:57 2006 From: steve at hastings.org (Steve R. Hastings) Date: Mon, 01 May 2006 17:56:57 -0700 Subject: request help with Pipe class in iterwrap.py Message-ID: <pan.2006.05.02.00.56.56.146384@hastings.org> While studying iterators and generator expressions, I started wishing I had some tools for processing the values. I wanted to be able to chain together a set of functions, sort of like the "pipelines" you can make with command-line programs. So, I wrote a module called iterwrap.py. You can download it from here: http://home.blarg.net/~steveha/iterwrap.tar.gz iterwrap has functions that "wrap" an iterator; when you call the .next() method on a wrapped iterator, it will get the .next() value from the original iterator, apply a function to it, and return the new value. Of course, a wrapped iterator is itself an iterator, so you can wrap it again: you can build up a "chain" of wrappers that will do the processing you want. As an example, here's a command-line pipeline: cat mylist | sort | uniq > newlist Here's the analogous example from iterwrap: newlist = list(iterwrap.uniq(iterwrap.sort(mylist))) You need to call list() because all the wrapper functions in iterwrap always return an iterator. That final list() forces the iterator returned by uniq() to be expanded out to a list. iterwrap.py defines functions based on many common command-line tools: sort, uniq, tr, grep, cat, head, tail, and tee. Plus it defines some other functions that seemed like they would be useful. Well, it doesn't take very many nested function calls before the call gets visually confusing, with lots of parentheses at the end. To avoid this, you can arrange the calls in a vertical chain, like this: temp = iterwrap.sort(mylist) temp = iterwrap.uniq(temp) newlist = list(temp) But I wanted to provide a convenience class to allow "dot-chaining". I wanted something like this to work: from iterwrap import * newlist = Pipe(mylist).sort.uniq.list() I have actually coded up two classes. One, Pipe, works as shown above. The other, which I unimaginatively called "IW" (for "iterwrap"), works in a right-to-left order: from iterwrap import * iw = IW() newlist = iw.list.uniq.sort(mylist) Hear now my cry for help: Both IW() and Pipe() have annoying problems. I'd like to have one class that just works. The problem with Pipe() is that it will act very differently depending on whether the user remembers to put the "()" on the end. For all the dot-chained functions in the middle of the chain, you don't need to put parentheses; it will just work. However, for the function at the end of the dot-chain, you really ought to put the parentheses. In the given example, if the user remembers to put the parentheses, mylist will be set to a list; otherwise, mylist will be set to an instance of class Pipe. An instance of class Pipe works as an iterator, so in this example: itr = Pipe(mylist).sort.uniq ...then the user really need not care whether there are parentheses after uniq() or not. Which of course will make it all the more confusing when the list() case breaks. In comparison with Pipe, IW is clean and elegant. The user cannot forget the parenthetical expression on the end, since that's where the initial sequence (list or iterator) is provided! The annoying thing about IW is that the dot-chained functions cannot have extra arguments passed in. This example works correctly: newlist = Pipe(mylist).grep("larch").grep("parrot", "v").list() newlist will be set to a list of all strings from mylist that contain the string "larch" but do not contain the string "parrot". There is no way to do this example with IW, because IW expects just one call to its __call__() function. The best you could do with IW is: temp = iw.grep(mylist, "larch") newlist = iw.list.grep(temp, "parrot", "v") Since it *is* legal to pass extra arguments to the one permitted __call__(), this works, but it's really not very much of an advantage over the vertical chain: temp = grep(mylist, "larch") temp = grep(temp, "parrot", "v") newlist = list(temp) The key point here is that, when processing a dot-chain, my code doesn't actually know whether it's looking at the end of the dot-chain. If you had newlist = Pipe(mylist).foo.bar.baz and if my code could somehow know that baz is the last thing in the chain, it could treat baz specially (and do the right thing whether there are parentheses on it, or not). I wish there were a special method __set__ called when an expression is being assigned somewhere; that would make this trivial. What is the friendliest and most Pythonic way to write a Pipe class for iterwrap? P.S. I have experimented with overloading the | operator to allow this syntax: newlist = Pipe(mylist) | sort | uniq | list() Personally, I much prefer the dot-chaining syntax. The above is just too tricky. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From david.murmann at rwth-aachen.de Tue May 2 22:05:45 2006 From: david.murmann at rwth-aachen.de (David Murmann) Date: Wed, 03 May 2006 04:05:45 +0200 Subject: Wake on LAN and Shutdown for Windows and Linux In-Reply-To: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> References: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> Message-ID: <4bqhdvF130514U1@news.dfncis.de> diffuser78 at gmail.com schrieb: > How can I shutdown Windows box from my Main (Linux) ? Have you seen this? http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 it probably won't work on linux (maybe with wine or similar?), but you can try to invoke this script on a windows machine somehow... have fun, David. From miki.tebeka at gmail.com Wed May 24 04:07:43 2006 From: miki.tebeka at gmail.com (Miki) Date: 24 May 2006 01:07:43 -0700 Subject: ftputil.py In-Reply-To: <1148454897.089654.46130@j33g2000cwa.googlegroups.com> References: <1148454897.089654.46130@j33g2000cwa.googlegroups.com> Message-ID: <1148458063.643620.222120@i39g2000cwa.googlegroups.com> Hello Sheldon, > Here is the part of the program that I need explained: > > host.download(name, name, 'b') # remote, local, binary mode Download file called "name" from host to a local file in the same name, use binary mode. > source = host.file('index.html', 'r') # file-like object Open a file (like built-in "open") on remote site in read mode > target = host.file('newdir/index.html', 'w') # file-like object Open a file (like built-in "open") on remote site in write mode > host.copyfileobj(source, target) # similar to shutil.copyfileobj Copy 1'st file to the second. HTH, Miki http://pythonwise.blogspot.com/ From john at baumanfamily.com Sat May 13 19:56:59 2006 From: john at baumanfamily.com (John Bauman) Date: Sat, 13 May 2006 19:56:59 -0400 Subject: Cellular automata and image manipulation References: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> Message-ID: <i4OdnQZa45PQ7_vZUSdV9g@ptd.net> <defcon8 at gmail.com> wrote in message news:1147561778.799956.154770 at d71g2000cwd.googlegroups.com... > Hello. I have recently been experimenting with cellular automata and I > would like to know how I could convert a 2d list of 0's and 1's into > white and black squares on an image. I have tried to install matplotlib > and also NumTut but both to no avail. There seem to be bugs in their > installation and I have not been able to figure out how to resolve > them. I would be happy for someone to suggest a library and maybe give > a simple example of how to do what I want to do. > In my 1d cellular automaton, I used the python image library and import Image nim = Image.new("1", (height * 2, height)) nim.putdata(bimg) nim.resize((400,200)).save("output.png") where bimg is a 2d list of 0's and 1's. You could probably remove the resize. From go at away.com Wed May 31 22:21:57 2006 From: go at away.com (3rdshiftcoder) Date: Thu, 01 Jun 2006 02:21:57 GMT Subject: beginner: using parameter in functions References: <lApfg.128$Cw3.54@trndny01> <447e32f3@news.eftel.com> Message-ID: <9bsfg.240$Cw3.174@trndny01> "John Machin" <sjmachin at lexicon.net> wrote in message news:447e32f3 at news.eftel.com... thanks for the help. it is really appreciated. i am going to do some more reading in the next couple of days. jim From nicogrubert at gmail.com Thu May 4 06:58:44 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Thu, 04 May 2006 12:58:44 +0200 Subject: Zope Guru... In-Reply-To: <mailman.19761.1146677220.27774.python-list@python.org> References: <mailman.19761.1146677220.27774.python-list@python.org> Message-ID: <4459DE64.5020607@gmail.com> > In doing some research into Workflow apps regarding document > management, I came across Zope. Given that it's Python Based, I > figured I'd shout to the group here... If you want to develop an application with Zope+Python from scratch, there are a few Zope products out there that handle workflow ("DCWorkflow", "Openflow"). If you look for an existing Zope based DMS, you might want to look at the "Document Library application" which has been released yesterday by infrae. http://www.infrae.com/download/documentlibrary Another existing Zope based application for document management including workflow is "Plone". http://www.plone.org If you plan to start using Zope 3, you might want to take a look at http://www.zope.org/Wikis/DevSite/Projects/ComponentArchitecture/Zope3Workflow Regards, Nico From wrongbad at gmail.com Sun May 7 20:17:20 2006 From: wrongbad at gmail.com (I V) Date: Sun, 07 May 2006 17:17:20 -0700 Subject: why _import__ only works from interactive interpreter? References: <1147041996.232232.165820@i39g2000cwa.googlegroups.com> <1147043686.558715.124540@j73g2000cwa.googlegroups.com> <1147044060.998898.140740@i40g2000cwc.googlegroups.com> Message-ID: <pan.2006.05.08.00.17.20.44832@gmail.com> On Sun, 07 May 2006 16:21:01 -0700, linuxnow at gmail.com wrote: > So, if this is right, I need to put the .py file to be imported inside > sys.path!! And the relative path will be usedto find the module. > > Can I __import__ providing the absolute path? >>> import sys >>> print sys.path ['', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/HTMLgen', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/cairo', '/usr/lib/python2.4/site-packages/gst-0.10', '/usr/lib/python2.4/site-packages/gtk-2.0', '/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode', '/usr/lib/site-python'] Compare with: tim at october:~/src/tests$ cat > test.py import sys print sys.path tim at october:~/src/tests$ python test.py ['/home/tim/src/tests', '/usr/lib/python24.zip', '/usr/lib/python2.4', '/usr/lib/python2.4/plat-linux2', '/usr/lib/python2.4/lib-tk', '/usr/lib/python2.4/lib-dynload', '/usr/local/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages', '/usr/lib/python2.4/site-packages/HTMLgen', '/usr/lib/python2.4/site-packages/Numeric', '/usr/lib/python2.4/site-packages/PIL', '/usr/lib/python2.4/site-packages/cairo', '/usr/lib/python2.4/site-packages/gst-0.10', '/usr/lib/python2.4/site-packages/gtk-2.0', '/usr/lib/python2.4/site-packages/wx-2.6-gtk2-unicode', '/usr/lib/site-python'] Note that the first entry in sys.path when run from the interactive intepreter is a blank string, which doesn't appear in the output from the script - I assume that's what is allowing the interactive version to import via an absolute path. I'm not sure if this is the intended behavior or a bug. You could make your script work the same way as the interactive interpreter by doing: import sys sys.path.append('') mod = __import__('/your/absolute/path/module') But it might be better to just add the particular path: sys.path.append('/your/absolute/path') mod = __import__('module') From timothy.williams at nvl.army.mil Mon May 1 08:43:25 2006 From: timothy.williams at nvl.army.mil (timw.google) Date: 1 May 2006 05:43:25 -0700 Subject: installing pyodbc In-Reply-To: <44551938.8030800@redlinepy.com> References: <1144781232.762308.177500@z34g2000cwc.googlegroups.com> <44551938.8030800@redlinepy.com> Message-ID: <1146487405.332518.289710@u72g2000cwu.googlegroups.com> No I didn't. Thanks for the reply. I've moved on to mx.ODBC. From jstroud at ucla.edu Fri May 19 16:36:35 2006 From: jstroud at ucla.edu (James Stroud) Date: Fri, 19 May 2006 13:36:35 -0700 Subject: altering an object as you iterate over it? In-Reply-To: <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> Message-ID: <e4la8j$od9$1@daisy.noc.ucla.edu> Paul McGuire wrote: > Your coding style is a little dated - are you using an old version of > Python? This style is the old-fashioned way: [clip] > 1. open("xxx") still works - not sure if it's even deprecated or not - but > the new style is to use the file class Python 2.3.4 (#4, Oct 25 2004, 21:40:10) [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 Type "help", "copyright", "credits" or "license" for more information. py> open is file True James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From brian at sweetapp.com Sun May 7 06:04:00 2006 From: brian at sweetapp.com (brian at sweetapp.com) Date: 7 May 2006 03:04:00 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <871wv6b3y0.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1146990071.634244.83380@i39g2000cwa.googlegroups.com> <871wv6b3y0.fsf@rpi.edu> Message-ID: <1146996240.867564.139490@u72g2000cwu.googlegroups.com> Bill Atkins wrote: > brian at sweetapp.com writes: > >> Bill Atkins wrote: >>> Buh? The project doesn't have to be late for Brooks's law to hold; >>> adding programmers, so goes Brooks reasoning, will always increase the >>> time required to complete the project because of various communication >>> issues. >> 1. This is not what Brooks says. Brooks was talking about late >> projects. Please provide a supporting quote if you wish to continue >> to claim that "adding programmers will always increase the time >> required to complete the project". > > The "always" in my claim should not be there, I admit. Brooks didn't > claim that. > > I refer you to pages 17 - 18 of The Mythical Man-Month: > > Since software construction is inherently a systems effort - an > exercise in complex interrelationships - communication effort is > great...Adding more men then lengthens, not shortens, the schedule. > > It is totally absurd to assume that, simply because a project has not > yet passed its deadline, it will somehow become immune to the kinds of > things Brooks is talking about. Right. But only when a project is late does Brooks say that adding programmers will always make it later (the claim that you made). In other cases he says "Add manpower, ..., this may or may not help". That seems intuitively obvious to me. If the programmers being added require extensive training [1] by the team to become productive, and their contribution to the project will be smaller than that amount (e.g. it is a small or nearly completed project) then their net impact on the project will be negative. If, OTOH, the new programmers are able to quickly understand the project/organization/technologies and almost immediately make useful contributions, then they are likely to have a net positive impact. >> 2. There has to be a mechanism where an organization can add >> developers - even if it is only for new projects. Python advocates > > Obviously. It's good that you agree. I think that the ability to add new productive developers to a project/team/organization is at least part of what Alex means by "scaleability". I'm sure that he will correct me if I am wrong. >> [list of proposed Python advantages snipped] > These are not things I look for in a programming language. Fair enough. That doesn't mean that these advantages aren't important to others or, in some situations, objectively important in the survival of a project/organization. For example, imagine that Google had used language X instead of Python to develop their tools (assume they started with 10 expert X programmers). Expert X programmers are Y percent more productive than expert Python programmers. Now Google wants to grow aggressively and needs 100 times more developer productivity (and expects to need even more productivity in the future). If it is harder to find/hire/create experts in language X than Python, then Y will have to be large to make language X a better choice than Python. Also, if non-expert Python programmers can be more productive than non-expert X programmers, then Python also has an advantage. Eric Raymond claims that Python has very high initial productivity and that becoming an expert is fairly easy. BTW, I'm not saying that Common Lisp fits X in this example. Cheers, Brian [1] I'm considering introducing bugs or misdesigns that have to be fixed as part of training for the purposes of this discussion. Also the time needed to learn to coordinate with the rest of the team. From 3dbernard at gmail.com Fri May 26 13:16:05 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 26 May 2006 13:16:05 -0400 Subject: Running Python scripts under a different user In-Reply-To: <4dolv4F1b8m87U1@uni-berlin.de> References: <mailman.6246.1148657024.27775.python-list@python.org> <4dolv4F1b8m87U1@uni-berlin.de> Message-ID: <61d0e2b40605261016m371b6fe0u12869791e9275a87@mail.gmail.com> On 5/26/06, Diez B. Roggisch <deets at nospam.web.de> wrote: > And as you refrain form telling us which OS you are running under [Bernard] The network file server is Red Hat Enterprise 4. The user workstation run through MS Windows XP Pro 32bit SP2, accessing the file server through Samba. one > can only be very vague on what to suggest - UNIXish OSes have for > example the setguid-bit, sudo springs to mind and under certain desktops > there are ways to acquire root-settings (but you need a password then I > guess) > > Windows I don't know so much - but there exist the possibility to make a > program run under a different user-account. [Bernard] Thanks anway. Bernard From levub137 at wi.rr.com Sat May 20 06:57:25 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 20 May 2006 10:57:25 GMT Subject: Decimal and Exponentiation In-Reply-To: <1148060287.088387.41150@j55g2000cwa.googlegroups.com> References: <1148060287.088387.41150@j55g2000cwa.googlegroups.com> Message-ID: <pCCbg.3229$8T4.2912@tornado.rdc-kc.rr.com> elventear wrote: > Hi, > > I am the in the need to do some numerical calculations that involve > real numbers that are larger than what the native float can handle. > > I've tried to use Decimal, but I've found one main obstacle that I > don't know how to sort. I need to do exponentiation with real > exponents, but it seems that Decimal does not support non integer > exponents. > > I would appreciate if anyone could recommend a solution for this > problem. > > Thank you. > The clnum module has arbitrary precision floating point and complex numbers with all of the standard math functions. For example, the cube root of 2 can be computed to 40 decimal places with the following. >>> from clnum import mpf,mpq >>> mpf(2,40)**mpq(1,3) mpf('1.259921049894873164767210607278228350570251464701',46) For more information see http://calcrpnpy.sourceforge.net/clnumManual.html From hannu at tm.ee Sat May 20 12:53:56 2006 From: hannu at tm.ee (Hannu Krosing) Date: Sat, 20 May 2006 19:53:56 +0300 Subject: Iterating generator from C (PostgreSQL's pl/python RETUN SETOF/RECORD iterator support broken on RedHat buggy libs) Message-ID: <1148144037.3833.89.camel@localhost.localdomain> I try to move this to -dev as I hope there more people reading it who are competent in internal working :). So please replay to -dev only. ------------- The question is about use of generators in embedde v2.4 with asserts enabled. Can somebody explain, why the code in try2.c works with wrappers 2 and 3 but crashes on buggy exception for all others, that is pure generator and wrappers 1,4,5 ? In other words, what does [i in i for gen] do differently than other ways of iterating over gen, which helps it to avoid the assert, and also, how could I write something that is still a generator, but does not trigger the assert. While the right solution is to just fix python (which is done for v2.5) we need a workaround for the following reason We have added support for returning rows (as tuples and or dictionaries or classes) and sets of boths scalars and rows to PostgreSQL's pl/plpython embedded language, but have some objections to getting this into distribution, because there is a bug in python 2.4 doing a wrong assert and additional bug in how RedHat rpm build process which leaves the buggy asserts in python.so. So I hoped to write a simple wrapper class, but it only seems to work, when the generator is turned into list, which is not a good solution as it works directly against what generators are good for. -- ---------------- Hannu Krosing Database Architect Skype Technologies O? Akadeemia tee 21 F, Tallinn, 12618, Estonia Skype me: callto:hkrosing Get Skype for free: http://www.skype.com -------------- next part -------------- A non-text attachment was scrubbed... Name: try2.c Type: text/x-csrc Size: 1998 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060520/7ab05f48/attachment.c> From doobiz at gmail.com Tue May 2 02:14:06 2006 From: doobiz at gmail.com (doobiz at gmail.com) Date: 1 May 2006 23:14:06 -0700 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5180.1146491500.27775.python-list@python.org> <1146518284.210504.319960@i40g2000cwc.googlegroups.com> Message-ID: <1146550446.514821.62790@i40g2000cwc.googlegroups.com> Just my opinion, but I think the Guido tutorial on Classes is unintelligible unless you're coming from another OO language. But I found something else that looks promising that you may want to peek at: http://pytut.infogami.com/node11-baseline.html rd From claird at lairds.us Tue May 9 15:17:35 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 9 May 2006 19:17:35 +0000 Subject: Econometrics in Panel data? References: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <07l062li47gjhuskkkqsai7kji82fpfjnq@4ax.com> <44606dd5$0$3285$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <mub6j3-sne.ln1@lairds.us> Message-ID: <ff67j3-fih.ln1@lairds.us> In article <mub6j3-sne.ln1 at lairds.us>, I counseled: >In article <44606dd5$0$3285$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>, >DeepBlue <123 at 321.com> wrote: >>so are you saying that Python is not an appropriate language for doing >>econometrics stuff? >> >> >>Dennis Lee Bieber wrote: >>> On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <123 at 321.com> declaimed the >>> following in comp.lang.python: >>> >>>> Hi all, >>>> >>>> I am new to Python. Just wondering can Python able to do econometric >>>> regression in either Time-series or pooled (panel) data? As well as test >>>> for hetero, autocorrelation, or endogeneity? . . . >There is not, however, a readily-accessible library targeted >for this sort of work. If I had the opportunity to work in >econometrics now, I'd think seriously about R, Lisp, and >Mathematica, and see what's available among the functional >languages, along with Python. Smalltalk, too; I'd throw it in the mix. Much serious econometrics has been done with Fortran, but I have no enthusiasm for pursuing that direction, mostly because I think too much of the computing world is going in a different one. But I'm not you, DeepBlue, or, more specifically, it's unlikely that our circumstances are at all similar. Is your project at a hobbyist level? How does hardware constrain you? How big is your team ...? From pecoraREMOVE at THISanvil.nrl.navy.mil Thu May 25 09:39:28 2006 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Thu, 25 May 2006 09:39:28 -0400 Subject: Bind an instance of a base to a subclass - can this be done? References: <pecoraREMOVE-120DFE.15351024052006@ra.nrl.navy.mil> <4djshnF1asdovU1@uni-berlin.de> <mailman.6167.1148508382.27775.python-list@python.org> Message-ID: <pecoraREMOVE-9D0FFD.09392825052006@ra.nrl.navy.mil> In article <mailman.6167.1148508382.27775.python-list at python.org>, Maric Michaud <maric at aristote.info> wrote: > Le Mercredi 24 Mai 2006 22:04, Diez B. Roggisch a ?crit?: > > Nope, not in that way. But you might consider writing a proxy/wrapper > > for an object. That looks like this (rouch sketch from head): > > > > class FileWrapper(object): > > ? ? def init (self, f): > > ? ? ? ?self. f = f > > > > ? ? def getattr (self, name): > > ? ? ? ?return getattr(self. f, name) > > > > ? ? def myreadline(self): > > ? ? ? ?.... > Why use a proxy when you can just inherit from the builtin file object ? > > class myFile(file) : > def myreadline(self) : print 'yo' > > > In [20]: myFile('frwiki-20060511-abstract.xml') > Out[20]: <open file 'frwiki-20060511-abstract.xml', mode 'r' at 0xa78cc1e4> > > In [21]: myFile('frwiki-20060511-abstract.xml').myreadline() > yo > > In [22]: BINGO! This is exactly what I want. I didn't realize that I could open using file itself instead of open. I did find this in another section of Python in a Nutshell thanks to your suggestion. Thank you. And thanks to all who answered. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From spam4bsimons at yahoo.ca Sat May 27 13:37:07 2006 From: spam4bsimons at yahoo.ca (Brendan) Date: 27 May 2006 10:37:07 -0700 Subject: Serializing / Unserializing datetime Message-ID: <1148751427.204676.238100@g10g2000cwb.googlegroups.com> Hi All I can't find the "Python Way" of writing a datetime instance to a string so that it can be easily parsed back again. time.strptime is apparantly not supported on some platforms, and time.time <==> datetime.utcfromtimestamp will cause problems come 2038. Unfortunately there don't seem to be "fromstring" equivalents for datetime.ctime or datetime.isoformat. Ideally the serialized datetime should be human readable, and potentially parseable from other languages. Any suggestions? Brendan -- Brendan Simons From kent at kentsjohnson.com Mon May 15 15:00:50 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 15 May 2006 15:00:50 -0400 Subject: OOP and Tkinter In-Reply-To: <7gih62p25k5krj9c5l9ot6tpt01c45e723@4ax.com> References: <7gih62p25k5krj9c5l9ot6tpt01c45e723@4ax.com> Message-ID: <4468cf40$1_1@newspeer2.tds.net> Ronny Mandal wrote: > file front_ui.py: > > class Front(object): > _images = [] # Holds image refs to prevent GC > def __init__(self, root): > # Widget Initialization > self._listbox_1 = Tkinter.Listbox(root, > height = 0, > width = 0, > ... > ) > > other file: > > from Front_ui import Front > > class CustomFront(Front): > Front._listbox_1.insert( 0, 'foo' ) > > ... > ... > File "H:\My Documents\Komodo\Front.py", line 63, in CustomFront > Front._listbox_1.insert( 0, foo' ) > AttributeError: type object 'Front' has no attribute '_listbox_1' > > > i.e., it cannot find the listbox! Strange, both files is in the same > folder. What is wrong here? _listbox_1 is an instance attribute, not a class attribute. You need to refer to self._listbox_1 from a CustomFront method, or change _listbox_1 to a class attribute if that is what you really want. Kent From deets at nospam.web.de Sun May 28 16:56:29 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Sun, 28 May 2006 22:56:29 +0200 Subject: Array? Please help. In-Reply-To: <1148762266.844574.210900@y43g2000cwc.googlegroups.com> References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> <4drlreF1ba60oU1@uni-berlin.de> <1148762266.844574.210900@y43g2000cwc.googlegroups.com> Message-ID: <4duh3tF1cbk1bU1@uni-berlin.de> George Sakkis schrieb: > Diez B. Roggisch wrote: >> Dr. Pastor schrieb: >>> I need a row of 127 bytes that I will use as a >>> circular buffer. Into the bytes (at unspecified times) >>> a mark (0<mark<128) will be written, one after the other. >>> After some time the "buffer" will contain the last 127 marks. >>> (A pointer will point to the next byte to write to.) >>> What would be the Pythonic way to do the above? >>> Thanks for any guidance. >> Use a list, use append and slicing on it: >> >> >> max_size = 10 >> buffer = [] >> >> for i in xrange(100): >> buffer.append(i) >> buffer[:] = buffer[-max_size:] >> print buffer >> >> >> Diez > > You're not serious about this, are you ? Tell me why I shouldn't. I presumed he's after a ringbuffer. Ok, the above lacks a way to determine the amount of bytes added since the last read. Add a counter if you want. And proper synchronization in case of a multithreaded environment. But as the OP was sketchy about what he actually needs, I thought that would at least give him a start. Maybe I grossly misunderstood his request. But I didn't see your better implementation so far. So - enlighten me. Diez From johnjsal at NOSPAMgmail.com Sat May 13 22:56:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 13 May 2006 22:56:48 -0400 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <tm1d62tavt9asak8bb55prm18i619av7t4@4ax.com> References: <jz09g.2091$No6.46071@news.tufts.edu> <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> <pqna621sn8s3qk56dt58qsnud6olbammfv@4ax.com> <44662a97$0$1949$c3e8da3@news.astraweb.com> <tm1d62tavt9asak8bb55prm18i619av7t4@4ax.com> Message-ID: <44669d4d$0$9374$c3e8da3@news.astraweb.com> Dennis Lee Bieber wrote: > On Sat, 13 May 2006 14:49:06 -0400, John Salerno > <johnjsal at NOSPAMgmail.com> declaimed the following in comp.lang.python: > >> Yeah, that's actually what I'm trying to do now. I'm not sure how to >> define it, but I assume it has something to do with 3306, since that's >> the default. >> > What firewall application? > > Zone Alarm, that I use, pops up a warning that "xyz" is trying to > act as a server -- I just had to configure it to allow server for local > and block internet. Norton Internet Security. Usually it will pop up a warning and I can accept or decline it, but it doesn't do it in this case. It just won't connect to the database unless it's disabled. From jdsalt_AT_gotadsl.co.uk Wed May 31 13:35:25 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Wed, 31 May 2006 12:35:25 -0500 Subject: Help requested -- importing stuff from a .COM DLL into python Message-ID: <Xns97D4B6A14A5F4BaldHeadedJohn@216.196.109.145> I wonder if some kind soul can help me in my struggle with DLLs? I am trying -- not because I want to, but because I have been told to -- to import things from an API that exists as a bunch of .COM DLLs. I had originally hoped to get them into a Python 2.4 program by a simple import statement. This does not appear to work, so I secured a copy of win32com, and have proven that it works to the extent of opening a M$ Word application. The same approach with the DLLS I actually need to use consistently fails with the message "Invalid class string" (full traceback included below, I doubt that it helps). After a couple of afternoons of vigorous easter- egging, I have not hit upon a valid class string, and my childish assumption that it would be one of the names listed in the API ocumentation is obviously wrong. Staring at the DLL contents with PEBrowse tells me nothing useful. Does anyone with experience of getting .COM stuff from DLLs know where I am going wrong? (Alternatively, can anyone who has got Python to use the MooD API tell me how?) I have no experience of .COM up to this point, and am hoping to keep it that way once this nonsense is done with. Thanks for any assistance, and all the best, John. - - - - - - - - cut here - - - - - - - - Traceback (most recent call last): File "D:\Program Files\MooD\2006\MooDAPI\APIstrangler0_1.py", line 470, in ? thing = win32com.client.Dispatch("MooDAPI.Object.Info") # Fails, "Invalid class string File "D:\Python24\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName (dispatch,userName,clsctx) File "D:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 98, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "D:\Python24\Lib\site-packages\win32com\client\dynamic.py", line 78, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221005, 'Invalid class string', None, None) From joesb.coe9 at gmail.com Mon May 29 09:26:58 2006 From: joesb.coe9 at gmail.com (Pisin Bootvong) Date: 29 May 2006 06:26:58 -0700 Subject: John Bokma harassment In-Reply-To: <447ae549$1_5@news.bluewin.ch> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> Message-ID: <1148909218.417148.222690@i39g2000cwa.googlegroups.com> Boris Borcic wrote: > ilitzroth at gmail.com wrote: > > We seem to have strayed a long way from Voltaire's > > "I do not agree with what you say, but I will defend to the death your > > right to say it.", > > but that was of course the age of enlightenment. > > Obviously this wisdom is getting stale and should be updated to something > like "There is so much noise we can't hear each other, but I will defend > to the death a chance to get heard for whatever you might have to say that's > intelligent (while not necessarily from your own mouth)". > But we might not have enough intelligence to decide what is intelligent and what is not. :-) > Besides, it is not clear that Voltaire really said that. > > Cheers, BB > -- > python >>> filter(lambda W : W not in 'ILLITERATE','BULLSHIT') From dan at catfolks.net Wed May 17 17:10:32 2006 From: dan at catfolks.net (Dan M) Date: Wed, 17 May 2006 14:10:32 -0700 Subject: I'm just not cut out for web programming, I guess :) References: <%0Mag.2117$No6.46299@news.tufts.edu> Message-ID: <pan.2006.05.17.21.10.28.461155@catfolks.net> On Wed, 17 May 2006 20:51:07 +0000, John Salerno wrote: > Ok, I've tinkered with this thing for a while, and I keep fixing little > problems, but I always get a 500 Internal Server error when I go to this > site: > > I don't necessarily even want help just yet, I'd like to figure it out > myself, but can someone at least tell me why I'm not getting helpful > feedback from the cgitb module? Am I using it wrong? The webpage just > displays the internal server error. > > Thanks. Having to debug web scripts on hosts where you don't have shell access can be a major pain. If you are referring to the wrong path in the "bang-path" line, you'd get that error non-message. Likewise if the file permissions were wrong. From ivoras at __-fer.hr-__ Wed May 10 21:57:05 2006 From: ivoras at __-fer.hr-__ (Ivan Voras) Date: Thu, 11 May 2006 03:57:05 +0200 Subject: Slow network reading? Message-ID: <e3u5lf$m1$1@news2.carnet.hr> I have a simple network protocol client (it's a part of this: http://sqlcached.sourceforge.net) implemented in Python, PHP and C. Everything's fine, except that the Python implementation is the slowest - up to 30% slower than the PHP version (which implements exactly the same logic, in a class). In typical usage (also in the benchmark), an object is created and .query is called repeatedly. Typical numbers for the benchmark are: For Python version: Timing 100000 INSERTs... 5964.4 qps Timing 100000 SELECTs... 7491.0 qps For PHP version: Timing 100000 inserts... 7820.2 qps Timing 100000 selects... 9926.2 qps The main part of the client class is: ---- import os, socket, re class SQLCacheD_Exception(Exception): pass class SQLCacheD: DEFAULT_UNIX_SOCKET = '/tmp/sqlcached.sock' SC_VER_SIG = 'sqlcached-1' SOCK_UNIX = 'unix' SOCK_TCP = 'tcp' re_rec = re.compile(r"\+REC (\d+), (\d+)") re_ok = re.compile(r"\+OK (.+)") re_ver = re.compile(r"\+VER (.+)") def __init__(self, host = '/tmp/sqlcached.sock', type = 'unix'): if type != SQLCacheD.SOCK_UNIX: raise self.sock = socket.socket(socket.AF_UNIX, socket.SOCK_STREAM) self.sock.connect(host) self.sf = self.sock.makefile('U', 4000) self.sf.write("VER %s\r\n" % SQLCacheD.SC_VER_SIG) self.sf.flush() if self.sf.readline().rstrip() != '+VER %s' % SQLCacheD.SC_VER_SIG: raise SQLCacheD_Exception("Handshake failure (invalid version signature?)") def query(self, sql): self.sf.write("SQL %s\r\n" % sql) self.sf.flush() resp = self.sf.readline().rstrip() m = SQLCacheD.re_rec.match(resp) if m != None: # only if some rows are returned (SELECT) n_rows = int(m.group(1)) n_cols = int(m.group(2)) cols = [] for c in xrange(n_cols): cols.append(self.sf.readline().rstrip()) rs = [] for r in xrange(n_rows): row = {} for c in cols: row[c] = self.sf.readline().rstrip() rs.append(row) return rs m = SQLCacheD.re_ok.match(resp) if m != None: # no rows returned (e.g. INSERT/UPDATE/DELETE) return True raise SQLCacheD_Exception(resp) ---- My question is: Am I missing something obvious? The C implementation is (as expected) the fastest with result of 10000:15000, but somehow I expected the Python one to be closer to, or even faster than PHP. I tried using 'r' mode for .makefile() but it had no significant effect. From kentilton at gmail.com Wed May 24 10:18:24 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 24 May 2006 10:18:24 -0400 Subject: John Bokma harassment In-Reply-To: <1148470149.596188.18500@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> Message-ID: <0XZcg.247$LO3.235@fe11.lga> Tim N. van der Leeuw wrote: > ilitzroth at gmail.com wrote: > >>I agree there are limits to you right to free speech, but I believe Xah >>Lee is not crossing >>any boundaries. If he starts taking over newspapers and TV stations be >>sure to notify me, >>I might revise my position. >>Immanuel > > > Perhaps he's not crossing boundaries of free speech, but he's > repeatedly crossing boundaries on usenet nettiquette, even though > repeatedly he's being asked not to do so. This would be a more compelling argument if people on newsgroups everywhere did not regularly carry on the most inane threads, often off-topic to begin with, but mostly threads that stray from something relevant to the NG to <insert just about anything>, ending only when Hitler is reached. And I am talking about NG regulars who really do usually talk about stuff specific to the NG. Those are the worst spammers of c.l.l, anyway. Xah's stuff, as wild as it is, is at least technical, and it is only an article here and an article there. John Bokma on the other hand.... well, I have to go write to the dorks at dreamhost now. kenny From cvanarsdall at mvista.com Tue May 23 15:47:05 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 23 May 2006 12:47:05 -0700 Subject: Best way to handle exceptions with try/finally Message-ID: <447366B9.3010207@mvista.com> Hey python people, I'm interested in using the try/finally clause to ensure graceful cleanup regardless of how a block of code exits. However, I still am interested in capturing the exception. The scenario is that I have an object that accesses a global memory space accessible via multiple threads. When shared resources are accessed a lock is acquired and then released. In the case that someone tries to access a variable that doesn't exist, I still need to release the lock so that other threads can continue their work, but an exception should be raised to the caller. Anyhow, I was playing with ideas in my code, and in this attempt I attempted to nest "try"s to at least make sure that accessing variables was raising an exception. That's the case, and then I attempt to raise the exception "ValueError" so that the calling function will get the exception. This doesn't work though. It seems that any exceptions get caught up in that "try/finally" and i can't get the exception to raise higher than that without raising it outside of this try. Is the best thing to do to have the exception mechanism set some type of flag that I can check during the "finally" statement? ##CODE## class Shared: def __init__(self): self.__userData= {} self.__mutex = threading.Lock() #lock object def getVar(self, variableName): temp = None error = 0 self.__mutex.acquire() #accessing shared dictionary try: try: temp = self.__userData[variableName] except: print "Variable doesn't exist in shared space" raise ValueError finally: self.__mutex.release() return temp def putVar(self, variableName, value): self.__mutex.acquire() #accessing shared dictionary try: self.__userData[variableName] = value finally: self.__mutex.release() return -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From sam at nuevageorgia.com Sun May 21 10:55:07 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 21 May 2006 07:55:07 -0700 Subject: Python - Web Display Technology In-Reply-To: <mailman.6024.1148200750.27775.python-list@python.org> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> Message-ID: <1148223307.073050.33710@y43g2000cwc.googlegroups.com> I am in agreement that open standards are better. I also wish the open standards bodies would work more creatively, to bring us the most advanced standards, and not some echo of yesterdays technology. But, too me, saying No Flash is saying No Source if not Open Source. But, for me, it is better Closed Source over No Source. Here is a visual argument, I would love to see a list of AJAX and SVG sites that display excellent graphics. http://bacardimojito.com/main.swf http://tokyoplastic.com/LF.swf http://coolbreathpower.com/ http://www.peterjoel.com/flash8previews/candleFlame.html http://shiroganeya.co.jp/main_en.html http://samfeltus.com/swf/contact_globes.swf http://justforthefofit.com/ http://mochiland.com/ http://obleek.com/iraq/index.html http://www.flashbum.com/v4/ http://spaceinvaders.de/ (example of antiquated graphics simply handled by Flash) It is my opinion, certainly not fact, that Python is an extraordinary language, that tends to be very ordinary when it comes to web display technology, and that it shouldn't be this way. http://samfeltus.com/swf/stamplicker.swf From Serge.Orlov at gmail.com Mon May 29 22:13:12 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 29 May 2006 19:13:12 -0700 Subject: why not in python 2.4.3 References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> <r94k725bfor7ssate10bd5veld2v6q6mm0@4ax.com> <1148851375.148311.320780@g10g2000cwb.googlegroups.com> <1148870627.058561.12800@y43g2000cwc.googlegroups.com> <1148897123.135779.91870@j33g2000cwa.googlegroups.com> <1148906849.894298.323790@g10g2000cwb.googlegroups.com> <447B9C00.9090504@lexicon.net> Message-ID: <1148955192.722244.16630@y43g2000cwc.googlegroups.com> John Machin wrote: > On 29/05/2006 10:47 PM, Serge Orlov wrote: > > Maybe urllib2 in > > python 2.4 reports to the server that it supports compressed data but > > doesn't decompress it when receives the reply? > > > > Something funny is happening here. Others reported it working with 2.4.3 > and Rocco's original code as posted in this thread -- which works for me > on 2.4.2, Windows XP. It "works" for me too, returning raw uncompressed data. > There was one suss thing about Rocco's problem description: > First message ended with d=takefeed(url) > But next message said print rss > Is rss == d? Nope. If you look at html tags, 2.3 code returns <feed> <generator> ... whereas 2.4 code returns <rss> <channel> <generator> ... That may explain why 2.3 result is not compressed and 2.4 result is compressed, but that doesn't explain why 2.4 *is* compressed. I looked at python 2.4 httplib, I'm sure it's not a problem, quote from httplib: # we only want a Content-Encoding of "identity" since we don't # support encodings such as x-gzip or x-deflate. I think there is a web accellerator sitting somewhere between Rocco and Google server that is confused that Rocco is "misinforming" web server saying he's using Firefox, but at the same time claiming that he cannot handle compressed data. That's why they teach little kids: don't lie :) From nobody at 127.0.0.1 Tue May 2 16:58:42 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 20:58:42 GMT Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <NrP5g.11087$Lm5.1177@newssvr12.news.prodigy.com> <mailman.5222.1146603142.27775.python-list@python.org> Message-ID: <6KP5g.11090$Lm5.10089@newssvr12.news.prodigy.com> Heiko Wundram wrote: > Integer and string objects > are immutable in Python, so why'd you want to have different IDs for an > object of the same value? It's the value you're working with in a program, > not the objects ID. At least it should be, if you're truly intent on > working with the (pseudo-random) object-ID, something with your design is > really, really broken. Hence I said, this is an academic exercise. From sjmachin at lexicon.net Fri May 12 17:59:15 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 May 2006 07:59:15 +1000 Subject: find all index positions In-Reply-To: <1147448743.445465.124200@u72g2000cwu.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <1147374826.341124.129260@g10g2000cwb.googlegroups.com> <4463C188.3030202@lexicon.net> <1147448743.445465.124200@u72g2000cwu.googlegroups.com> Message-ID: <44650533.20703@lexicon.net> On 13/05/2006 1:45 AM, vbgunz wrote: > Hello John, > > Thank you very much for your pointers! I decided to redo it and try to > implement your suggestion. I think I did a fair job and because of your > suggestion have a better iterator. Thank you! > > def indexer(string, substring, overlap=1): > '''indexer(string, substring, [overlap=1]) -> int > > indexer takes a string and searches it to return all substring > indexes. by default indexer is set to overlap all occurrences. > to get the index to whole words only, set the overlap argument > to the length of the substring. (1) Computing the length should be done inside the function, if necessary, which (2) avoids the possibility of passing in the wrong length. (3) "whole words only" does *NOT* mean the same as "substrings don't overlap". > The only pitfall to indexer is > it will return the substring whether it stansalone or not. > > >>> list(indexer('ababababa', 'aba')) > [0, 2, 4, 6] > > >>> list(indexer('ababababa', 'aba', len('aba'))) > [0, 4] > > >>> list(indexer('ababababa', 'xxx')) > [] > > >>> list(indexer('show chow', 'how')) > [1, 6] > ''' > > index = string.find(substring) > if index != -1: > yield index > > while index != -1: > index = string.find(substring, index + overlap) > if index == -1: continue > yield index Quite apart from the fact that you are now using both 'string' *AND* 'index' outside their usual meaning, this is hard to follow. (1) You *CAN* avoid doing the 'find' twice without losing readibility and elegance. (2) continue?? Somebody hits you if you use the 'return' statement or the 'break' statement? Sigh. I'll try once more. Here is the function I wrote, with the minimal changes required to make it an iterator, plus changing from 0/1 to False/True: def findallstr(text, target, overlapping=False): startpos = 0 if overlapping: jump = 1 else: jump = max(1, len(target)) while True: newpos = text.find(target, startpos) if newpos == -1: return yield newpos startpos = newpos + jump > > if __name__ == '__main__': > print list(indexer('ababababa', 'aba')) # -> [0, 2, 4, 6] > print list(indexer('ababababa', 'aba', len('aba'))) # -> [0, 4] > print list(indexer('ababababa', 'xxx')) # -> [] > print list(indexer('show chow', 'how')) # -> [1, 6] > Get yourself a self-checking testing mechanism, and a more rigorous set of tests. Ultimately you will want to look at unittest or pytest, but for a small library of functions, you can whip up your own very quickly. Here is what I whipped up yesterday: def indexer2(string, target): res = [] if string.count(target) >= 1: res.append(string.find(target)) if string.count(target) >= 2: for item in xrange(string.count(target) - 1): res.append(string.find(target, res[-1] + 1)) return res # dedent fixed if __name__ == '__main__': tests = [ ('a long long day is long', 'long', [2, 7, 19], [2, 7, 19]), ('a long long day is long', 'day', [12], [12]), ('a long long day is long', 'short', [], []), ('abababababababa', 'aba', [0, 4, 8, 12], [0, 2, 4, 6, 8, 10, 12]), ('qwerty', '', range(7), range(7)), ('', 'qwerty', [], []), ] for test in tests: text, target = test[:2] results = test[2:] for olap in range(2): result = findallstr(text, target, olap) print ( 'FAS', text, target, olap, result, results[olap], result == results[olap], ) for test in tests: text, target = test[:2] results = test[2:] result = indexer2(text, target) print ( 'INDXR2', text, target, result, result == results[0], result == results[1], ) Make sure your keyboard interrupt is not disabled before you run the 2nd-last test :-) HTH, John From roger.miller at nova-sol.com Wed May 31 15:59:36 2006 From: roger.miller at nova-sol.com (Roger Miller) Date: 31 May 2006 12:59:36 -0700 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <mailman.6345.1149049261.27775.python-list@python.org> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <otpq72t7c1n3puh4omc42k3f98db968lhs@4ax.com> <slrne7qr97.8hm.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1149105576.321676.131600@j55g2000cwa.googlegroups.com> Sybren Stuvel wrote: > David C Ullrich enlightened us with: > > I thought that the fact that you could use the same trick for > > _shuffling_ a list was my idea, gonna make me rich and famous. I > > guess I'm not the only one who thought of it. Anyway, you can use > > DSU to _shuffle_ a list by decorating the list with random numbers. > > This is often done in database queries that need to randomize the data > ;-) > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa DSU seems like a lot of trouble to go through in order to use an O(n log n) sorting algorithm to do what can be done in O(N) with a few lines of code. The core code of random.shuffle() shows how easy it is to do it right: for i in reversed(xrange(1, len(x))): # pick an element in x[:i+1] with which to exchange x[i] j = int(random() * (i+1)) x[i], x[j] = x[j], x[i] From email at christoph-haas.de Tue May 9 07:34:25 2006 From: email at christoph-haas.de (Christoph Haas) Date: Tue, 9 May 2006 13:34:25 +0200 Subject: installing numpy In-Reply-To: <877j4v5ukc.fsf@localhost.localdomain> References: <877j4v5ukc.fsf@localhost.localdomain> Message-ID: <20060509113425.GA20063@torf.workaround.org> On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote: > I am trying to install NumPy in my debian/testing linux > 2.6.15-1-686. > > with no numpy for debian/testing, I am left alone, since the > experimental version available by debian will result in a dependency > nightmares, What about "python-numeric"? Found through "apt-cache search numpy". Kindly Christoph -- Please reply to the list - not to me personally. Personal replies are ignored. From onurb at xiludom.gro Mon May 22 07:54:49 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 22 May 2006 13:54:49 +0200 Subject: string.count issue (i'm stupid?) In-Reply-To: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> References: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> Message-ID: <4471a6f4$0$2568$636a55ce@news.free.fr> Matteo Rattotti wrote: > Hi all, > > i've noticed a strange beaviour of string.count: > > in my mind this code must work in this way: > > str = "a_a_a_a_" dont use 'str' as an identifier, it shadows the builtin str type. > howmuch = str.count("_a_") > print howmuch -> 3 > > but the count return only 2 > > Ok this can be fine, but why? The doc string tell that count will > return the number of substring in the master string, if we spoke about > substring i count 3 substring... depends on how you define "number of substring", I mean, overlapping or not. FWIW, I agree that this may be somewhat unintuitive, and would at least require a little bit more precision in the docstring. > Can someone explain me this? It seems obvious that str.count counts non-overlapping substrings. > And in which way i can count all the > occurrence of a substring in a master string? (yes all occurrence > reusing already counter character if needed) Look at the re module. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From fredrik at pythonware.com Wed May 10 11:25:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 May 2006 17:25:44 +0200 Subject: PIL thumbnails unreasonably large References: <1147272829.719796.150680@y43g2000cwc.googlegroups.com> Message-ID: <e3t0lq$s1i$1@sea.gmane.org> Almad wrote: > I wonder how do I create reasonable thumbnails from JPEG with PIL. > My code: > > logging.debug('Downloading image %s' % id) > uri = ''.join([config['photo']['masterpath'], '?p=', > str(id)]) > uf = urlopen(uri).read() > f = tmpfile() > f.write(uf) > f.seek(0) > logging.debug('Resizing image %s' % id) > img = Image.open(f) > prev = img.copy() > img.thumbnail((180,180)) > if prev.size[0] > 640 or prev.size[1] > 640: > prev.thumbnail((640,640)) > # save resized to temporary files > f.seek(0) > img.save(f, "JPEG", quality=50) > fp = tmpfile() > prev.save(fp, "JPEG", quality=200) > > Well, works fine, but img size is about 0,5 MB (!), but strangely, prev > one is around 200 kb. seek(0) doesn't truncate the file. if you want a small thumbnail file, you shouldn't write it to the beginning of a large file. try calling the truncate method after you've saved the file: img.save(f, "JPEG", quality=50) f.truncate() (a better solution would be to wrap the data in a StringIO object, and write the thumbnail into a fresh temp file -- or another StringIO object: uf = urlopen(uri).read() img = Image.open(StringIO.StringIO(uf)) ... f = tmpfile() img.save(f, "JPEG") ... ) </F> From rick446 at NOSPAM.usa.net Wed May 17 12:59:51 2006 From: rick446 at NOSPAM.usa.net (Richard Copeland) Date: Wed, 17 May 2006 12:59:51 -0400 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> Message-ID: <9JCdnfg4wu1Cy_bZRVn-uw@comcast.com> Try this: class Class: a='aa' b='bb' def __getattr__(self, ppt): return 'custom computed result' __getattr__ is only called when "normal" attribute lookup fails, so there's no need for the "hasattr" test. Also, I believe that __getattribute__ only applies to new-style classes (classes derived from "object"), and it will override *all* attribute accesses, anyway (meaning you'd have infinite recursion if you used it since you look up "self.ppt") Pierre wrote: > Hi, > > Sorry in advance, english is not my main language :/ > > I'd like to customize the result obtained by getattr on an object : if > the object has the requested property then return it BUT if the object > doesn't has actually this property return something else. > > In my case, I can't use getattr(object, property, default_value). > > I tried to write a class with a __getattr__ method and even a > __getattribute__ method but this doesn't do what I want.... > > Maybe I didn't correctly understand this : > http://docs.python.org/ref/attribute-access.html > > Here is a piece of my code : > ===================================== > class myclass: > """docstring""" > > a = 'aa' > b = 'bb' > > def __getattr___(self, ppt): > """getattr""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" > > def __getattribute__(self, ppt): > """getattribute""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" > > if __name__ == "__main__": > > d = myclass() > p1 = getattr(d, "a") > print p1 > p2 = getattr(d, "b") > print p2 > p3 = getattr(d, "c") > print p3 > ================================ > > I get an AttributeError when accessing to the property named "c". > > Any explanation/solution to my problem ? > From manstey at csu.edu.au Wed May 24 00:24:13 2006 From: manstey at csu.edu.au (manstey) Date: 23 May 2006 21:24:13 -0700 Subject: pickling multiple dictionaries Message-ID: <1148444653.078683.194750@u72g2000cwu.googlegroups.com> Hi, I am running a script that produces about 450,000 dictionaries. I tried putting them into a tuple and then pickling the tuple, but the tuple gets too big. Can I pickle dictionaries one after another into the same file and then read them out again? Cheers, Matthew From pmartin at snakecard.com Tue May 16 14:39:20 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Tue, 16 May 2006 13:39:20 -0500 Subject: Unable to extract Python source code using Windows References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> <446a0229$1@nntp0.pdx.net> <1147803456.431686.258380@i39g2000cwa.googlegroups.com> Message-ID: <s%oag.10539$B42.3092@dukeread05> Elric02 at rogers.com wrote: >>You can get Python sources from python.org > > I'm unable to locate a source file brings that will work with WinZip. > Can anybody please point me to the exact URL that will get me to the > source code? but it it is tar ball format or a gzip format, than that > will work for me as WinZip is not open. http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tar.bz2 From nobody at 127.0.0.1 Wed May 3 13:28:38 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 17:28:38 GMT Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> <mailman.5253.1146643043.27775.python-list@python.org> <1146644904.906523.255970@j73g2000cwa.googlegroups.com> <1146651877.687428.294320@v46g2000cwv.googlegroups.com> Message-ID: <aL56g.72399$H71.17629@newssvr13.news.prodigy.com> Michele Simionato wrote: > Python solution is to rely on the intelligence of programmers. If they > see an all caps name and then they try to change it without knowing what > they are doing, then they are stupid. If you have stupid programmers there > is no way the language can stop them for making disasters. Which doesn't apply here, one of the OP's examples further up this thread doesn't modify any ALL CAPS vars directly: >>> A = []??#?let's?declare?a?"constant"?here >>> b = A???#?and?let's?assign?the?constant?here >>> b.append('1') # OOPS! From fredrik at pythonware.com Wed May 10 08:33:52 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 May 2006 14:33:52 +0200 Subject: Error : 10053, 'Software caused connection abort' References: <20060510083203.38341.qmail@web38913.mail.mud.yahoo.com> Message-ID: <e3smjg$kpj$1@sea.gmane.org> C Saha wrote: > I have a mail function in my pythin code and seems like due to that > I am getting this error when ever I am running the pythin code. Any > idea, how to resolve this? > > Error is = (10053, 'Software caused connection abort') if you remove the "catch all and don't tell me what really happened" error handling you're using, you'll notice that Python provides a lot more information than you got -- including the exact line in your program that caused this error. you'll find that it's a lot easier to debug stuff if you know *where* things go wrong, and it's a lot easier to help you debug stuff if you don't leave out crucial information. try replacing except Exception, ex: print ex with except Exception: import traceback traceback.print_exc() # print full traceback once you've done that, look at the traceback to see if you can figure out what's happening, and make sure that the SMTP server you've specified does exist, and accepts connections from your machine. </F> From bedouglas at earthlink.net Fri May 5 12:22:10 2006 From: bedouglas at earthlink.net (bruce) Date: Fri, 5 May 2006 09:22:10 -0700 Subject: Drop Down Menus... In-Reply-To: <1146845017.689207.115860@v46g2000cwv.googlegroups.com> Message-ID: <289401c67060$1058bc60$0301a8c0@Mesa.com> I suspect that if an app were to be created that really allowed for "Drop Down" menus that can be initiated via the "right" mouse key, the web app would have to be a java app.... I've seen some web based java apps with this functionality, but never any php/perl.. I didn't think python would be able to given that it is server side, whereas a java web app, because of the shipped/downloadable components could provide this kind of functionality.. -bruce -----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 alisonken1 Sent: Friday, May 05, 2006 9:04 AM To: python-list at python.org Subject: Re: Drop Down Menus... Hello Bruce - bruce wrote: > Hi... > > Never used python, but I have a question regarding Drop Down Menus. Does > Python allow me to create a website, that will permit the user to create > Drop Down menus that can be initiated with the right mouse click? If it can, > is it fairly easy to implement? If you are talking about client-side menu's, you should be looking at Java or Java-Script. Python is good at server-side scripting, but there is no >widely installed< python interpreter on peoples browsers that would work, whereas java and javascript are pretty much the standard in client-side scripting in web browsers. -- http://mail.python.org/mailman/listinfo/python-list From bborcic at gmail.com Mon May 22 05:27:11 2006 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 22 May 2006 11:27:11 +0200 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <mailman.6031.1148224219.27775.python-list@python.org> References: <mailman.6031.1148224219.27775.python-list@python.org> Message-ID: <447183f8$1_5@news.bluewin.ch> Heiko Wundram wrote: ... > As I've noticed that I find myself typing the latter quite often > in code I write, it would only be sensible to add the corresponding > syntax for the for statement: > > for node in tree if node.haschildren(): > <do something with node> > > as syntactic sugar for: > > for node in tree: > if not node.haschildren(): > continue > <do something with node> Mhhh, your unsugared form remind me of darks hours with primitive BASICS in my youth - the kind Dijsktra commented on. Why don't you write for node in tree: if node.haschildren(): <do something with node> ? From blair.bethwaite at gmail.com Thu May 18 21:09:36 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 18 May 2006 18:09:36 -0700 Subject: Subprocess or Process or OMG!! In-Reply-To: <1147992479.110490.41960@i40g2000cwc.googlegroups.com> References: <1147992479.110490.41960@i40g2000cwc.googlegroups.com> Message-ID: <1148000976.455456.11800@i40g2000cwc.googlegroups.com> rh0dium wrote: > This has several problems - least of which args aren't working.... Has > anyone really tried this approach? No, they just wrote the code for the hell of it. :) Seriously though, you may want to consider using the popen2 module. Then you'll be able to wait on the subprocess to return and check the return code, plus you could do your DB update first then go into a wait() to check for success. -B From rpdooling at gmail.com Thu May 25 09:45:46 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 25 May 2006 06:45:46 -0700 Subject: IronPython 1.0 Beta 7 Released References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> <1148518396.856710.173810@g10g2000cwb.googlegroups.com> <1148532003.624344.88030@38g2000cwa.googlegroups.com> Message-ID: <1148564746.724535.259140@38g2000cwa.googlegroups.com> Can you recommend a book or a link for a person learning Python on Windows who does not yet know C# or .NET? Thanks, rick From federico.pelloni at gmail.com Wed May 3 13:55:15 2006 From: federico.pelloni at gmail.com (Fredp) Date: 3 May 2006 10:55:15 -0700 Subject: __getattr__ on non-instantiated class In-Reply-To: <4458e0b7$0$20293$626a54ce@news.free.fr> References: <1146671588.529743.249570@v46g2000cwv.googlegroups.com> <4458D4F9.8010900@websafe.com> <1146673922.994217.241620@j33g2000cwa.googlegroups.com> <4458e0b7$0$20293$626a54ce@news.free.fr> Message-ID: <1146678914.185580.228340@u72g2000cwu.googlegroups.com> Well, actually I need only a tiny subset of a ORM. Or perhaps what I need isn't exactly an ORM, because I have only one kind of Object with a various number of Fields on a separate Table, so I was looking to create something that could fit this scheme and nothing more, but I see in any case it needs much work. SQLObject is a bit unflexible for me (well, I didn't go too deep in it), so I'll give a look to SqlAlchemy, that seems very interesting - though I don't like its "look'n'feel" very much. Thank you very much -Federico Pelloni From vbgunz at gmail.com Thu May 25 23:03:02 2006 From: vbgunz at gmail.com (vbgunz) Date: 25 May 2006 20:03:02 -0700 Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> Message-ID: <1148612582.510390.48040@i39g2000cwa.googlegroups.com> > I guess Fredrik's message was more along the lines of ``don't try to > "help" others after a week or two toying with the language because you > might be offering disservice, despite your good intentions; leave this > to more experienced users``. The words might have been a bit harsher > but that's just his style; you'll get used to it if you hang around > here often. I much rather stand corrected than to silently remain ignorant. I take revision of my solution for all it's worth but to be belittled without correction is arrogant and unnecessary. I've been working with Python for several months now and I feel I know plenty *but* I am still learning. I personally never had to clear a list. I never thought of Roberts answer and my reasoning is in Roberts message. In the end I stood correct because Robert was nice enough to answer two birds with one stone. Fredrik on the other hand had nothing positive to add and his message seemed gestapo. Where I come from and how I grew up is quite simple. A wrong answer is better than no answer and a worthless remark is worth garbage. Why? Because no right answer is gospel and no answer no matter how dumb is cause for discourtesy. I tried and thats the bottom line. From george.sakkis at gmail.com Fri May 26 09:31:09 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 26 May 2006 06:31:09 -0700 Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> Message-ID: <1148650269.190130.209840@i39g2000cwa.googlegroups.com> bruno de chez modulix en face wrote: > > and there's no compelling reason for dict(**kwds). > > Yes there is : this *is* the ordinary Python syntax - calling a type to > get an instance of it. The dict-litteral syntax is mostly syntactic > sugar. The thing is there are four (at least?) ways to get a dict instance: In [1]: d1={'name':'mike', 'age':23} In [2]: d2=dict(d1) In [3]: d3=dict(**d1) In [4]: d4=dict(d1.items()) In [5]: d1==d2==d3==d4 Out[5]: True Talk about "there should be one and preferably one obvious way to do it". > > Perhaps it's something that should be reconsidered for Py3K > > Hopefully not. The fact that you fail to understand why a given feature > exists and how it can be useful is not a reason to ask for arbitrary > restrictions on the language. Perhaps you fail to understand that the given feature is 1) redundant (see above). 2) restricting in a more serious sense: the future addition of optional keyword arguments that affect the dict's behaviour. Google for "default dict" or "dictionary accumulator". George From rpdooling at gmail.com Tue May 23 08:56:20 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 23 May 2006 05:56:20 -0700 Subject: New beginner to python for advice References: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> Message-ID: <1148388980.335933.235110@i39g2000cwa.googlegroups.com> If you are new to programming: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers If you already know at least one programming language: http://wiki.python.org/moin/BeginnersGuide/Programmers Your goal is to read, work the examples, and understand the Python Tutorial by Guido von Rossum: http://docs.python.org/tut/ If you can't understand it, then read other, easier tutorials and books until you do. From vbgunz at gmail.com Fri May 26 05:42:01 2006 From: vbgunz at gmail.com (vbgunz) Date: 26 May 2006 02:42:01 -0700 Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <mailman.6221.1148634413.27775.python-list@python.org> Message-ID: <1148636521.026385.171410@y43g2000cwc.googlegroups.com> Fredrik_Lundh = 'wah' I bet you enjoy stealing candy from babies and dunging on the little guy every chance you get. You're suppose to be a role model in this community? Your temper tantrum and unrelenting 'look at me look at me i'm bigger and better' machismo attitude is nothing more than a decoyed ploy set out by a deluded megalomaniac. You're promoting Python or the fact that you're the son of Zeus and Hera? You're the worse sore losing cry baby I've ever witnessed on the net in my ten years here... pathetic for sure... From robin at NOSPAMreportlab.com Fri May 26 17:27:18 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Fri, 26 May 2006 21:27:18 +0000 Subject: hide python window, con'td In-Reply-To: <nuidnfgKW6EU9urZRVn-gw@comcast.com> References: <mailman.6245.1148656971.27775.python-list@python.org> <nuidnfgKW6EU9urZRVn-gw@comcast.com> Message-ID: <447772B6.3080501@jessikat.plus.net> Larry Bates wrote: > Something that runs all day in the background is a perfect candidate > for being turned into a Service. That and servicemanager has a good > way of managing the task so that it doesn't take up lots of excess > CPU cycles that a "normal" application would take while sleeping > or unnecessarily looping. Pick up a copy of Mark Hammond's Python > Programming on Win32 book for example services in Python. You could > then start/stop the service with service manager or with net start/ > net stop commands. > > -Larry Bates > > Bell, Kevin wrote: >> Great! And now that it's hiding w/ .pyw, how would I kill it if I want? >> Just log off, or is there a better way? >> >> Kevin >> >> It is possible to get a background process in windows especially with Python-2.4, but it's fairly hard. try using python runner.py dingo.py where ###### runner.py def bgScript(script,scriptArgs): from _subprocess import CreateProcess class STARTUPINFO: dwFlags = 0 hStdInput = None hStdOutput = None hStdError = None class pywintypes: error = IOError import sys exe = sys.executable.replace('n.exe','nw.exe') startupinfo = STARTUPINFO() args = ''.join([' "%s"' % a for a in scriptArgs]) cmd = '"%s" "%s" %s' % (exe,script,args) try: hp, ht, pid, tid = CreateProcess(None, cmd, # no special security None, None, 0, #don't inherit standard handles 0x208, None, None, startupinfo) except pywintypes.error, e: print str(e) if __name__=='__main__': import sys bgScript(sys.argv[1],sys.argv[2:]) ###### dingo.py if __name__=='__main__': import time for i in xrange(15): time.sleep(1) ###### dingo.py shoul be running in the background detached from the console. Of course as others point out, the official way to do this stuff is to use all the M$ paraphernalia and have stuff start up at boot time etc etc. -- Robin Becker From akameswaran at gmail.com Thu May 18 21:27:53 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 18:27:53 -0700 Subject: python vs perl lines of code In-Reply-To: <Xns97C7C31D1A937castleamber@130.133.1.4> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <Xns97C7BC8549BA0castleamber@130.133.1.4> <1147996169.818933.252420@u72g2000cwu.googlegroups.com> <Xns97C7C31D1A937castleamber@130.133.1.4> Message-ID: <1148002073.419819.295180@38g2000cwa.googlegroups.com> Hmm, and I thought it was respectful to actually address someone you are talking to. Must every statement be a reaction to a quotable comment? In any case, I realize I was completley wrong. Please allow me to retract my statement. From aylwyn at cantab.net Wed May 17 06:56:17 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 03:56:17 -0700 Subject: Tabs are *EVIL*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> Message-ID: <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Andy Sy wrote: >Don't be evil - always configure your editor to >convert tabs to true spaces. Yet another space-indenter demonstrates that problem actually lies with people who think that tab == some spaces. >And I, for the life of me, have never remembered >getting any source code to display properly by >fiddling with my text editor's (the very popular >SciTE) tab settings. Sorry to hear that. You should try using an editor that's easier for you. By the way, complaining about a thread's existence is pretty dumb. If you don't like it, don't post to it. Or are you unable to operate your news reader either? From bob at passcal.nmt.edu Tue May 23 10:57:53 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Tue, 23 May 2006 08:57:53 -0600 Subject: Canvas items into widgets? Message-ID: <S5WdnVgJgoJ8v-7Z4p2dnA@nmt.edu> I have a "tooltip" class that is used like Lab = Label(Sub, text = "Temp:") Lab.pack() Tooltip(Lab, "The temperature of the reactor core") When the mouse pointer is placed over the "Temp:" label the associated message pops up in a small window near the pointer. I want to use the same thing with a canvas item, but the "create_x" calls return an ID number not a widget 'handle' like Label() does. Is there a way to turn these IDs into widgets? I mean the ovals and rectangles are, technically, widgets already, aren't they? I don't think the tag_bind stuff will quite work (but I don't fully grasp the concept, except in cases where you want to do something like drag the items around on the canvas) since each item will have a different message, like, for example, each point on a graph will have a tooltip that reports what the temperature of that point was. The concept: Rec = can.create_rectangle(<small red rectangle>) Wig = (Then a miracle occurs) Tooltip(Wig, "1500C - She's gonna blow!!") Thanks! Bob :) From python.list at tim.thechases.com Mon May 22 11:26:07 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 22 May 2006 10:26:07 -0500 Subject: string.count issue (i'm stupid?) In-Reply-To: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> References: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> Message-ID: <4471D80F.9090400@tim.thechases.com> I agree the docstring is a bit confusing and could be clarified as to what's happening > Can someone explain me this? And in which way i can count all > the occurrence of a substring in a master string? (yes all > occurrence reusing already counter character if needed) You should be able to use something like s = "a_a_a_a_" count = len([i for i in range(len(s)) if s.startswith("_a_", i)]) which will count the way you wanted, rather than the currently existing count() behavior. -tkc From nobody at 127.0.0.1 Sat May 20 22:32:32 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 02:32:32 GMT Subject: How to tell if function was passed a list or a string? References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> <mailman.5848.1147906051.27775.python-list@python.org> <roy-7FE2C0.18573117052006@reader1.panix.com> Message-ID: <4jQbg.79595$H71.65376@newssvr13.news.prodigy.com> Roy Smith wrote: > Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: >> Currently there's no good duck-typing way to differentiate >> strings from other sequences. > > I suppose you could do something like: > > try: > foo.isalpha > except AttributeError: > print "foo is not a string" Another way: if getattr (foo, 'isalpha', False): print 'foo is a string' Of course now string duck types must have an 'isalpha' and list ones can't, but that shouldn't matter much. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From chris.cavalaria at free.fr Wed May 17 12:00:56 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 17 May 2006 18:00:56 +0200 Subject: Question about exausted iterators Message-ID: <446b48e2$0$5293$626a54ce@news.free.fr> Is there a good reason why when you try to take an element from an already exausted iterator, it throws StopIteration instead of some other exception ? I've lost quite some times already because I was using a lot of iterators and I forgot that that specific function parameter was one. Exemple : >>> def f(i): ... print list(i) ... print list(i) ... >>> f(iter(range(2))) [0, 1] [] >>> This is using Python 2.4.2 From sybrenUSE at YOURthirdtower.com.imagination Fri May 19 12:07:51 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 19 May 2006 18:07:51 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> Message-ID: <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> Florian Diesch enlightened us with: >> - Flash is a proprietary technology requiring a proprietary plugin. > > There seem to be at least two free implementations: But the website of OP together with the websites of many other people are incompatible with those, since they require the latest and greatest Macromedia Flash plugin; that's version 8, while the latest version for Linux is version 7. I doubt that the Free implementations are up to par with a version that hasn't even been released by Macromedia. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From vbgunz at gmail.com Thu May 25 18:26:43 2006 From: vbgunz at gmail.com (vbgunz) Date: 25 May 2006 15:26:43 -0700 Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> Message-ID: <1148596003.879693.63250@i39g2000cwa.googlegroups.com> > if you don't know how to do things, you don't need to post. > if you know why this is about the dumbest way to do what you're doing, > and you're posted this on purpose, you really need to grow up. If this was the case who then would post any questions? I not only made my post with the best of intentions but felt attaching a strongly worded and lengthy warranty over the script performance and pythonic value would be overkill. I admit I am not the best at Python and I have no problem in being offered a more optimized solution but to insult me is childish. no? It's ok and I have no grudge with you Fredrik. I would appreciate though you simply point out my error with a suggested solution and if energy permit, tell me why my solution is not so good and why yours is better. I would value that very much. Also, not to be the dummy or anything but my solution did exactly what the first poster requested. Robert happened to point out a much better and most likely preffered alternative solution. It was great! I live and I learn. Have a good day! From pmartin at snakecard.com Mon May 8 17:53:15 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Mon, 08 May 2006 16:53:15 -0500 Subject: List Ctrl References: <mailman.5484.1147103304.27775.python-list@python.org> Message-ID: <g5P7g.9374$B42.8451@dukeread05> carlosperezs at alumnos.uvigo.es wrote: > > Hello together !!!!!! > > I have programmed a List Control and I introduced information in several > rows. What I want to do is, modify this information when i select a row > and press a button. > There two options: > - when i do this, a window appears and asks me to introduce the > information. - or in the selected row , the last information is removed > and lets me to overwrite. > > Thank you > > > --oOo-----------------------------------------------------------------oOo-- > > Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo > Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo > > Servicios Inform?ticos [ http://si.uvigo.es ] > Universidade de Vigo [ http://www.uvigo.es ] > > URL: https://correoweb.uvigo.es TkInter, wx Widgets , ....., ? What exactly is it that you do not know how to do ? Philippe From chris at foote.com.au Thu May 18 01:42:53 2006 From: chris at foote.com.au (Chris Foote) Date: Thu, 18 May 2006 15:12:53 +0930 Subject: Large Dictionaries In-Reply-To: <mailman.5711.1147697881.27775.python-list@python.org> References: <1147699064.107490@teuthos> <mailman.5711.1147697881.27775.python-list@python.org> Message-ID: <1147933058.405605@teuthos> Richie Hindle wrote: > [Chris] >> Has anyone written a fast hash module which is more optimal for >> large datasets ? > > PyJudy might be what you're looking for, though I've never used it: > > http://www.dalkescientific.com/Python/PyJudy.html > > "Judy's key benefits are scalability, high performance, and memory > efficiency. A Judy array is extensible and can scale up to a very large > number of elements, bounded only by machine memory." ... "PyJudy arrays > are similar to Python dictionaries and sets." Thanks for the suggestion Richie. PyJudy works brilliantly :-) Cheers, Chris From tjreedy at udel.edu Sun May 28 19:34:22 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sun, 28 May 2006 19:34:22 -0400 Subject: pygame and wxpython References: <1148854384.549915.135950@j73g2000cwa.googlegroups.com> Message-ID: <e5dc1v$bc4$1@sea.gmane.org> "DK" <provato at gmail.com> wrote in message news:1148854384.549915.135950 at j73g2000cwa.googlegroups.com... > I'm somewhat new to Python but not to programming. > > I just want to know if it's possible to have a SINGLE wxPython frame > containing two sections where one will contain widgets and the other > will host an animation done using PyGame. > > More specifically, I want to have a list of names of animations on the > left and depending on what is selected, run the PyGame animation in the > main area. I am sure that some PyGamers have used pygame with wxpython. If you don't get an answer here, I suggest asking on the pygame list, gatewayed to gmane.comp.python.pygame. (news.gmane.org) From osv at javad.com Wed May 31 01:14:03 2006 From: osv at javad.com (Sergei Organov) Date: Wed, 31 May 2006 09:14:03 +0400 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <1148998176.105881.156310@g10g2000cwb.googlegroups.com> <127olia8pnldl90@corp.supernews.com> Message-ID: <e5j8ms$8id$1@sea.gmane.org> Grant Edwards <grante at visi.com> writes: > On 2006-05-30, TheSeeker <duane.kaufman at gmail.com> wrote: > >> Have you looked into slsnif >> (http://www.dakotacom.net/~ymg/software.html) > > FYI, slsnif won't work for any serial program that needs to use > parity, 7 data bits, or any of the modem control/status lines. > > Since all of the serial applications I use need to use actual > serial ports, I've never found slsnif to be useful. It's > really a shame that pty devices don't support the same set of > ioctl calls that tty devices do. It seems that sniff on a real tty device could be implemented using the same technique strace uses to intercept and show syscalls, though I'm not aware of any sniffer application that does it. -- Sergei. From fredrik at pythonware.com Fri May 26 05:06:31 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 May 2006 11:06:31 +0200 Subject: how to clear up a List in python? In-Reply-To: <1148602972.946639.40220@38g2000cwa.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> Message-ID: <e56gei$l6a$1@sea.gmane.org> George Sakkis wrote: > I guess Fredrik's message was more along the lines of ``don't try to > "help" others after a week or two toying with the language because you > might be offering disservice, despite your good intentions; leave this > to more experienced users``. no matter what Doug Holton and "vbgunz" thinks, if you ask a question on comp.lang.python and use the answer you're getting, you shouldn't end up on thedailywtf.com. </F> From johnjsal at NOSPAMgmail.com Tue May 2 15:11:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 19:11:36 GMT Subject: simultaneous assignment In-Reply-To: <125fbbj4rfeah20@corp.supernews.com> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> Message-ID: <I9O5g.2039$No6.43918@news.tufts.edu> Grant Edwards wrote: > Python knows how to count. :) > > def countFalse(seq): > return len([v for v in seq if not v]) > > def countTrue(seq): > return len([v for v in seq if v]) > > def truth_test(seq): > return countTrue(seq) == 1 Gosh, so much to learn! Of course, I already know all about list comprehensions, but now I just need to learn to *use* them! :) From fredrik at pythonware.com Mon May 1 07:44:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 1 May 2006 13:44:12 +0200 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> Message-ID: <e34sad$tvs$1@sea.gmane.org> Holger wrote: > Tried searching for a solution to this, but the error message is so > generic, that I could not get any meaningfull results. > > Anyways - errormessage: > ---------------------------------------------------- > TypeError: addFile() takes exactly 1 argument (2 given) > ---------------------------------------------------- > > The script is run with two args "arg1" and "arg2": > ---------------------------------------------------- > import sys > > class KeyBase: > def addFile(file): > print "initialize the base with lines from this file" when defining your own classes, you must spell out the "self" argument in your method definitions: def addFile(self, file): print "initialize the base with lines from this file" see: http://pyfaq.infogami.com/what-is-self </F> From jkgunjal at gmail.com Thu May 25 01:28:58 2006 From: jkgunjal at gmail.com (jkgunjal at gmail.com) Date: 24 May 2006 22:28:58 -0700 Subject: how to change sys.path? In-Reply-To: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> Message-ID: <1148534938.342816.246920@i40g2000cwc.googlegroups.com> sys.path.append("<path containing module to be imported>") eg. sys.path.append("/home/webdoc") From oscartheduck at gmail.com Sun May 21 15:30:57 2006 From: oscartheduck at gmail.com (oscartheduck) Date: 21 May 2006 12:30:57 -0700 Subject: newbie: windows xp scripting In-Reply-To: <mailman.6032.1148231638.27775.python-list@python.org> References: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> <mailman.6032.1148231638.27775.python-list@python.org> Message-ID: <1148239856.998371.160700@u72g2000cwu.googlegroups.com> It wasn't, but after seeing your success I discovered what was wrong. My destination directory didn't exist, and for some reason windows wasn't automatically creating it to dump the files in. I could fix this with a nested if statement, but it "feels" like windows should be creating this folder automatically if it doesn't exist. Oh well, thanks Steve! I wouldn't have performed the next step of manunally creating the directory if you hadn't posted that the script worked! From junkytownMAKNI at gmail.com Tue May 30 14:11:28 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Tue, 30 May 2006 20:11:28 +0200 Subject: saving settings In-Reply-To: <4e2ou0F1cbvi3U1@uni-berlin.de> References: <e5e6g2$nbv$1@ss408.t-com.hr> <pan.2006.05.29.07.30.20.70376@spam.me.please> <e5els6$5sa$1@ss408.t-com.hr> <4e07c8F1c7r6jU1@uni-berlin.de> <127m9nbemdmsha2@corp.supernews.com> <4e2ou0F1cbvi3U1@uni-berlin.de> Message-ID: <e5i1sg$a0n$1@ss408.t-com.hr> Diez B. Roggisch wrote: > Grant Edwards wrote: > > >> Documents and settings aren't quite the same thing, but it's a >> valid point. >> >>> Especially not the ones you wrote on that other machine. >>> >>> Seriously: Who is going to copy a executable around? >> I do. I copy putty.exe around all of the time. > > I download it every time, and if I didn't, I'd be pretty annoyed if I'd copy > it to a friends machine containing ALL MY KEYS embedded into it. > >>> Do you know of any other program that behaves like that? >> Back in the day, that used to be fairly common under >> DOS/Windows. Not that it's still not a really bad idea. > > Back in the day self-modifying code was the craze too. And _some_ people > even do it in python :) those crazy bastards! ;) > > Diez From deets at nospam.web.de Wed May 10 03:49:12 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 10 May 2006 09:49:12 +0200 Subject: Reading Soap struct type In-Reply-To: <mailman.5544.1147233358.27775.python-list@python.org> References: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz><1146620207.56.7672@mint-julep.mondoinfo.com><002901c66e57$05a69090$346ea8c0@tintz.co.nz><1146624295.41.7841@mint-julep.mondoinfo.com><003501c66e64$316deb30$346ea8c0@tintz.co.nz> <1146677203.2.7870@mint-julep.mondoinfo.com> <mailman.5544.1147233358.27775.python-list@python.org> Message-ID: <4cdk7kF15h7qkU1@uni-berlin.de> Thomas Thomas schrieb: > Hi All, > > I am receiving a hash below from my Soap Interface > > <SOAPpy.Types.structType item at 34661160>: {'Field12value': ':C > F3Value', 'Field8': 'Price Text:price_text', 'Field9': 'Text with > File:file_text > ', 'Field11value': ':CF2Value', 'Field7': 'Product Code:product_code', > 'Field7va > lue': ':product_values', 'Field2': 'Job Reference:job_reference', 'Field3': > 'Job > Description:job_description', 'Field6': 'Campaign Name:campaign_name', > 'Field10 > value': ':CF1Value', 'Field6value': ':campaign_values', 'Field5': > 'Keywords:keyw > ords', 'Field10': 'CF1Title:custom_field1', 'Field11': > 'CF2Title:custom_field2', > 'Field12': 'CF3Title:custom_field3', 'Field13': 'CF4Title:custom_field4', > 'Fiel > d14': 'Name:meta_filename', 'Field4': 'Display Name:display_name', > 'Field13value > ': ':CF4Value'} > > How can i iterarte through it bcz when do try do something like > myHash.values() > I am getting the error > AttributeError: structType instance has no attribute 'values' That is because it is no hash - AFAIK SOAP doesn't support hashes (or dicts, in python-lingo) out of the box. What you see above essentially a named tuple. Conceptionally like this: class MyStruct: def __init__(self, foo, bar): self.foo = foo self.bar = bar Either you access the individual values by name - or maybe there is a way to enumerate the names for you, but that depends on what the SOAPpy.Types.structType is capable of. I suggest you look at it's source. Diez From rocky at panix.com Tue May 23 23:35:15 2006 From: rocky at panix.com (R. Bernstein) Date: 23 May 2006 23:35:15 -0400 Subject: continue out of a loop in pdb References: <87mzdkwke3.fsf@localhost.localdomain> <PIK9g.28632$CH2.27494@tornado.texas.rr.com> <87ac9kwdl8.fsf@localhost.localdomain> <4cpqtcF16e1gaU1@uni-berlin.de> <wih7j4cw23a.fsf@panix3.panix.com> Message-ID: <wih3bf0w0wc.fsf@panix3.panix.com> Here's the revision I just made for pydb's documentation (in CVS). I welcome suggestions for improvement. set_trace([cmdfile=None]) Enter the debugger before the statement which follows (in execution) the set_trace() statement. This hard-codes a call to the debugger at a given point in a program, even if the code is not otherwise being debugged. For example you might want to do this when an assertion fails. It is useful in a couple of other situations. First, there may be some problem in getting the debugger to stop at this particular place for whatever reason (like flakiness in the debugger). Alternatively, using the debugger and setting a breakpoint can slow down a program a bit. But if you use this instead, the code will run as though the debugger is not present until you reach this point in the program. When the debugger is quitting, this causes the program to be terminated. If you want the program to continue instead, use the debugger function. > "Diez B. Roggisch" <deets at nospam.web.de> writes: > > > > the code works with no problem, I am playing around with the pdb, i.e > > > **************** > > > from pdb import * > > > set_trace() for i in range(1,500000): > > > print i > > > print "tired of this" > > > print "I am out" > > > **************** > > > fred at debian:~/python/practic$ python practic.py > > >> /home/fred/python/practic/practic.py(4)?() > > > -> for i in range(1,500000): > > > (Pdb) n > > >> /home/fred/python/practic/practic.py(5)?() > > > -> print i > > > (Pdb) n > > > 1 > > >> /home/fred/python/practic/practic.py(4)?() > > > -> for i in range(1,500000): > > > (Pdb) b 6 > > > Breakpoint 1 at /home/fred/python/practic/practic.py:6 > > > (Pdb) c > > >> /home/fred/python/practic/practic.py(5)?() > > > -> print i <<<< I expected (print "tired of this") > > > (Pdb) > > > > > > In TFM it says that set_trace() puts a breakpoint to the current > > frame. I admit that I also wouldn't read that as "each and every > > instruction in this very frame", but that is what essentially > > happens. I think the docs could need some enhancement here. Try > > debugging a called function, there things will work as expected. > > Let me try to explain my understanding here. set_trace() merely tells > the Python interpreter to call the debugger dispatcher after the call > to set_trace() finishes. In effect this is at the next statement of > your program because the caller frame here is always the "set_trace()" > call you put in your program. Okay, so now we've called this "debugger > dispatcher" thing and what does that do? Well, it accepts commands > from you, like "next" or "step" or "continue". . > > In the case above, Python was told to make that set-trace call 500000 > times. > > But yes, I agree the wording in in the pdb (and pydb) manuals are > written too much from view of someone writing a debugger rather than > someone using it. If you or someone else wantsto make a suggestion as > to how to make the description of set_trace() more user friendly (and I > don't think the above explanation succeeds), I'll put it in the next > release of pydb (http://bashdb.sourceforge.net/pydb) which probably > will be in the not-too distant future. From aahz at pythoncraft.com Mon May 15 12:51:50 2006 From: aahz at pythoncraft.com (Aahz) Date: 15 May 2006 09:51:50 -0700 Subject: Large Dictionaries References: <1147699064.107490@teuthos> <roy-765731.09112115052006@reader1.panix.com> Message-ID: <e4abj6$p6a$1@panix1.panix.com> In article <roy-765731.09112115052006 at reader1.panix.com>, Roy Smith <roy at panix.com> wrote: >In article <1147699064.107490 at teuthos>, Chris Foote <chris at foote.com.au> >wrote: >> >> I have the need to store a large (10M) number of keys in a hash table, >> based on a tuple of (long_integer, integer). The standard python >> dictionary works well for small numbers of keys, but starts to >> perform badly for me inserting roughly 5M keys: >> >> # keys dictionary metakit (both using psyco) >> ------ ---------- ------- >> 1M 8.8s 22.2s >> 2M 24.0s 43.7s >> 5M 115.3s 105.4s > >Are those clock times or CPU times? And what are these times measuring? Don't forget that adding keys requires resizing the dict, which is a moderately expensive operation. Once the dict is constructed, lookup times should be quite good. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From sven at spam.pri.ee Sat May 13 17:10:25 2006 From: sven at spam.pri.ee (Sven Suursoho) Date: Sun, 14 May 2006 00:10:25 +0300 Subject: Iterating generator from C Message-ID: <op.s9ic3nhpplgmb3@localhost> Hi, I am working on project that has embedded python interpreter to run user-specified python procedures. Those procedures might return any iterable object with set of result data -- basically everything for which iter() returns valid object (list, tuple, dict, iterator etc) It works ok, except generator under Python 2.4 with debugging enabled (see http://sourceforge.net/tracker/index.php?func=detail&aid=1483133&group_id=5470&atid=105470). Is there any way to rewrite following program to handle returned generator without hitting this bug? Error handling is omitted for clarity. #include <Python.h> const char *py_source = "def fn():\n" " yield 1\n"; int main () { Py_Initialize(); PyObject *globals = PyDict_New(); // insert function code into interpreter PyObject *code = PyRun_String(py_source, Py_file_input, globals, NULL); Py_DECREF(code); // do call code = Py_CompileString("fn()", "<string>", Py_eval_input); PyObject *gen = PyEval_EvalCode((PyCodeObject *)code, globals, NULL); // iterate result PyObject *item; while ((item = PyIter_Next(gen))) { printf("> %ld\n", PyInt_AsLong(item)); Py_DECREF(item); } Py_DECREF(gen); Py_DECREF(code); Py_DECREF(globals); Py_Finalize(); return 0; } Br, -- Sven Suursoho From ToddLMorgan at gmail.com Sat May 13 04:45:53 2006 From: ToddLMorgan at gmail.com (ToddLMorgan) Date: 13 May 2006 01:45:53 -0700 Subject: Is it possible to set the date/time of a directory in windows with Python? If so how? Message-ID: <1147509953.594320.172890@d71g2000cwd.googlegroups.com> I'm trying to set any of the dates (create, modification, access) of a directory under windows with python. I'm trying to do this as I'm trying to write a unittest for a directory cleaning script I'm writing (ie I need the test to set the create/mod time for some of the directories so that I can be sure that the script works properly - as it picks dirs based upon their age). I've tried using the utime( path, times). That doesn't work as the doco states "Whether a directory can be given for path depends on whether the operating system implements directories as files (for example, Windows does not)." So that doesn't work. So I tried mark hammonds win32 extensions with something like this import win32file, win32con, pywintypes filehandle = win32file.CreateFile(file, win32file.GENERIC_WRITE,win32file.FILE_SHARE_WRITE, None,win32con.OPEN_ALWAYS, 0, None) nowWin32=pywintypes.Time(theTime) win32file.SetFileTime(filehandle, nowWin32, nowWin32, nowWin32) which works fine for files but fails with "Access Denied" when I invoke the CreateFile with a directory. This seems to occur no matter the combination of READ or WRITE I choose for the parameters. So does anyone have any useful suggestions (other than not using windows)? I've thought of a couple of reallly nasty solutions: 1. Temporarily alter the underlying system clock back to the required time and create the directory then resetting it back again afterwards. 2. Create the required directory in some form of virtual filesystem - eg Zip file, rar archive, tar etc. Then extract it to the real filesystem and hope windows honors the timestamps (untested at this point). None of those is particularly appealing. Thanks for listening. From johnjsal at NOSPAMgmail.com Thu May 18 17:29:37 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 18 May 2006 21:29:37 GMT Subject: WTF? Printing unicode strings In-Reply-To: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> Message-ID: <5H5bg.2123$No6.46365@news.tufts.edu> Ron Garret wrote: >>>> u'\xbd' > u'\xbd' >>>> print _ > Traceback (most recent call last): > File "<stdin>", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > position 0: ordinal not in range(128) Not sure if this really helps you, but: >>> u'\xbd' u'\xbd' >>> print _ ? >>> From struggleyb at gmail.com Wed May 31 05:19:15 2006 From: struggleyb at gmail.com (Bo Yang) Date: Wed, 31 May 2006 17:19:15 +0800 Subject: An algorithm problem In-Reply-To: <slrne7qiso.5k5.sybrenUSE@schuimige.stuvel.eu> References: <mailman.6350.1149058719.27775.python-list@python.org> <slrne7qiso.5k5.sybrenUSE@schuimige.stuvel.eu> Message-ID: <447D5F93.9000903@gmail.com> I am sorry , and thanks for your friendliness . I have change my source code for more meaningful variable name and more comments follow the instructions John has writen . I think that is useful for you to look my code . And this time I put the code in the attachment . Indeed , I write that in the Eclipse Pydev , I don't know why it lose its idention in the mailing list . Also , I forget an example for the question , and I compensate for it : Given the integer 2 for instance : what we exapct from the algorithm is a list of 0 or 1 , for this instance it is 1 1 0 0 . We can take it as a ring , and fetch any continuous 2 numbers from it , finally get four combinations : 11 , 10 , 00 , 01 and they are 3 , 2 , 0 , 1 . I hope this time it is clear for all to understand what problem confront me . And again I am sorry for the trouble , thanks for you again ! Best Regard Bo Yang From apardon at forel.vub.ac.be Tue May 9 03:23:07 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 May 2006 07:23:07 GMT Subject: how to construct a binary-tree using python? References: <1146879397.871842.183790@u72g2000cwu.googlegroups.com> Message-ID: <slrne60gqr.dac.apardon@rcpc42.vub.ac.be> Op 2006-05-06, hankssong schreef <songyi012133 at gmail.com>: > Hi everyone, I'm wondering whether it's possible to construct a > binary-tree using python. > Since python don't have pointer, it can't dynamically allocate memory > like C language. > But some important data structures like linked list, binary-tree and > hash table are closely linked with dynamic memory technology. > > Any help that can be provided would be greatly appreciated. You may have a look here: http://www.pardon-sleeuwaegen.be/antoon/avltree.html -- Antoon Pardon From runlevelten at gmail.com Sun May 14 09:38:08 2006 From: runlevelten at gmail.com (Ten) Date: Sun, 14 May 2006 14:38:08 +0100 Subject: send an email with picture/rich text format in the body In-Reply-To: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> Message-ID: <200605141438.08438.runlevelten@gmail.com> On Sunday 14 May 2006 12:24, anya wrote: > Hey, > I have a certain problem and till now I didnt find an answer on the > web. > > I want to send an email message with picture in it. I dont want to put > it as > attachment but make it in the body of the mail, so every one who open > the email will see the picture.. (it is possible that the solution will > be in any other format that will be opened i.e pdf, doc and I will put > this in the body ) > > Neither in MimeWriter nor using the definition of MymeTypes I was able > to do it .. > > Does anyone have a solution? > > Thanks The problem with doing this, programmatically or otherwise, is that however you implement it, it's not going to work everywhere. You can easily send it, but if you do include binary data in the message body, then however you do it most people will be seeing a garbled (and offensive to the the eye) message body. I think it's not the right thing to do, either, if you ever managed to do this it would be by working around how email is supposed to work. Eventually, unless you have a userbase that is happy to open things in a particular way for you, you'll have to bite the bullet and use more orthodox techniques, methinks. (he says with an image in his headers) Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. From chris.cavalaria at free.fr Thu May 18 10:36:43 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 16:36:43 +0200 Subject: Question about exausted iterators In-Reply-To: <mailman.5882.1147962343.27775.python-list@python.org> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <mailman.5879.1147959939.27775.python-list@python.org> <446c7f44$0$7128$626a54ce@news.free.fr> <mailman.5882.1147962343.27775.python-list@python.org> Message-ID: <446c86a2$0$32251$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > Christophe wrote: > >>>> Because I'm still waiting for a valid answer to my question. The >>>> answer "Because it has been coded like that" or is not a valid one. >>> >>> >>> it's been coded like that because that's what the specification says: >>> >>> http://www.python.org/dev/peps/pep-0234/ >> >> >> I didn't though I had to mention that "Because the spec has been >> writen like that" wasn't a valid answer either. > > > so what is a valid answer? Some valid use case for that behaviour, some example of why what I ask could cause problems, some implementation difficulties etc ... Saying it's like that because someone said so isn't exactly what I was expecting as an answer :) People sometimes can be wrong you know. From Michael.Coll-Barth at VerizonWireless.com Wed May 24 12:20:53 2006 From: Michael.Coll-Barth at VerizonWireless.com (Michael.Coll-Barth at VerizonWireless.com) Date: Wed, 24 May 2006 12:20:53 -0400 Subject: John Bokma harassment Message-ID: <20060524163104.6CBD11E400C@bag.python.org> ! ! -----Original Message----- From: John Bokma And ain't it cool that reporting Xah's abuse might stop both? -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ CRAP! I am not sure which of these idiots is worse; John or Xah. Although, judging from other folks' responses to Xah Lee's posts, there is some value. John's stuff is just pure crap. I wasn't going to support Xah, but, now, I think I will. BTW, I hate bottom posting, but I didn't want to start another flame war... The information contained in this message and any attachment may be proprietary, confidential, and privileged or subject to the work product doctrine and thus protected from disclosure. If the reader of this message is not the intended recipient, or an employee or agent responsible for delivering this message to the intended recipient, you are hereby notified that any dissemination, distribution or copying of this communication is strictly prohibited. If you have received this communication in error, please notify me immediately by replying to this message and deleting it and all copies and backups thereof. Thank you. From johnjsal at NOSPAMgmail.com Mon May 8 00:06:54 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 00:06:54 -0400 Subject: utility functions within a class? In-Reply-To: <1147060713.875377.104640@y43g2000cwc.googlegroups.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> Message-ID: <445ec3d4$0$1965$c3e8da3@news.astraweb.com> blair.bethwaite at gmail.com wrote: > I'm having trouble deciphering what this bit means - "but these > functions will be called from another method in the class, not from the > instance itself", I don't think it makes sense. Yeah, I'm starting to see that as I tried to implement it. Here's what I came up with, which works: def generate(self, filename): self.head = self.generate_head() self.body = self.generate_body() So the two generate_* methods are called from within another class method, and it seemed necessary to still call them from an instance. What I originally meant was that they would not be called from an instance *outside* the class itself, i.e. they won't be used when writing another script, they are only used by the class itself. From onurb at xiludom.gro Wed May 31 07:48:50 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 31 May 2006 13:48:50 +0200 Subject: Best Python Editor In-Reply-To: <mailman.6359.1149069835.27775.python-list@python.org> References: <mailman.6359.1149069835.27775.python-list@python.org> Message-ID: <447d8314$0$10284$626a54ce@news.free.fr> Manoj Kumar P wrote: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. I hate to be the one answering this, but this is *really* a FAQ - as you would have known if you had google'd this group for this. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From duane.kaufman at gmail.com Tue May 30 10:09:36 2006 From: duane.kaufman at gmail.com (TheSeeker) Date: 30 May 2006 07:09:36 -0700 Subject: Watching serial port activity. In-Reply-To: <127oj612scnl8a0@corp.supernews.com> References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> Message-ID: <1148998176.105881.156310@g10g2000cwb.googlegroups.com> Hi, Have you looked into slsnif (http://www.dakotacom.net/~ymg/software.html) Duane From nicogrubert at gmail.com Wed May 3 08:46:23 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Wed, 03 May 2006 14:46:23 +0200 Subject: Sorting a list of dictionaries by dictionary key Message-ID: <4458A61F.3010004@gmail.com> Hi there, I am looking for a way to sort a list containing dictionaries. This is my example list: [{'Title': 'ABC', 'from_datetime': DateTime('2006/04/25 12:45:00 GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 12:45:00 GMT+2')}, {'Title': 'GHI', 'from_datetime': DateTime('2006/03/10 12:45:00 GMT+2')}] I want to sort the list by dictionary's key 'from_datetime' so the sorted list should be: [{'Title': 'GHI', 'from_datetime': DateTime('2006/03/10 12:45:00 GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 12:45:00 GMT+2')}, {'Title': 'ABC', 'from_datetime': DateTime('2006/04/25 12:45:00 GMT+2')}] Any idea how I can sort this list? Thank you very much in advance, Nico From tjreedy at udel.edu Fri May 26 14:09:23 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 May 2006 14:09:23 -0400 Subject: list comprehensions put non-names into namespaces! References: <1148577813.000229.225330@y43g2000cwc.googlegroups.com><mailman.6206.1148586159.27775.python-list@python.org> <7hBdg.2071$ho5.166428@news20.bellglobal.com> Message-ID: <e57g8h$93b$1@sea.gmane.org> "Mel Wilson" <mwilson-to at sympatico.ca> wrote in message news:7hBdg.2071$ho5.166428 at news20.bellglobal.com... > Point of information, would this be the interpreter putting > the result of its last calculation in _ ? Yes, in interactive mode (but not in batch mode) it binds the valid name '_' to the result of statement expressions. > >>> [2*x for x in range(5)] > [0, 2, 4, 6, 8] > >>> _[4] > 8 which here is the list. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Mon May 15 19:05:09 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 16 May 2006 09:05:09 +1000 Subject: taking qoutes in arguments References: <98063b170605150748h3d0fffddibd6f8de28fff3d4f@mail.gmail.com> Message-ID: <87k68mrisa.fsf@benfinney.id.au> "Lee Caine" <kano.priv at gmail.com> writes: > Im new to python and am in need of a little help.... Possibly also new to command-line shells? > Im attempting to write a program that finds and replaces text in all > files in a given directory. > example of running the program with arguments > >python far.py /home/lee/Documents/ find replace > I have managed to get it all working apart from one thing, if the > find or replace arguments > contain quotes e.g( content="somat" ),? it doesnt work, When asking questions about behaviour, please describe the behaviour and how it differs from your expectations. "It doesn't work" is utterly useless as a description. <URL:http://www.catb.org/~esr/faqs/smart-questions.html> > so I print the string and it shows as content=somat, without the > quotes. This is because your command-line shell (which one are you using?) needs to do its own work on the command you type before Python is even asked. For most command shells, the arguments for a command are separated by spaces, and double-quotes can be used to tell the shell that spaces are part of an argument. $ ls foo bar # lists two files, "foo" and "bar" $ ls "foo bar" # lists one file, "foo bar" The shell parses the command line and determines what the arguments are, stripping the quotes after figuring out where the arguments begin and end. The command receives each argument in an array element, without the quotes. Because of this, to get actual quote characters, you need to tell the shell which quote characters are *not* to be interpreted this way, usually with an escape character like the backslash. > So i tryed this... > >python far.py /home/lee/Documents content=\"somat\" content=\"somat else\" Yep, just like that. > and this works, but I would like a way of not having to do this when > i run the program Your shell may also understand single-quoted arguments, which remove a lot of the special meanings for characters (like double quote characters). $ ls '"foo bar"' # lists one file, '"foo bar"' Read the manual for your command shell, to understand better what characters are special and how to get those characters literally in an argument. Hope that helps. -- \ "My doctor told me to stop having intimate dinners for four. | `\ Unless there are three other people." -- Orson Welles | _o__) | Ben Finney From skryskalla at gmail.com Sat May 20 10:03:04 2006 From: skryskalla at gmail.com (skryskalla at gmail.com) Date: 20 May 2006 07:03:04 -0700 Subject: Generating Cutter numbers References: <1148114166.590393.176250@u72g2000cwu.googlegroups.com> Message-ID: <1148133784.844430.23130@38g2000cwa.googlegroups.com> Gerard Flanagan wrote: > All > > would anyone happen to have code to generate Cutter Numbers: > > eg. http://www1.kfupm.edu.sa/library/cod-web/Cutter-numbers.htm > > or is anyone looking for something to do?-) (I'm under pressure!) > > def cutter(lname, fname, book_title): > What do you use lname and fname (author first name and last name?) for? The page you linked to does not have any information (that I could see) about first names or last names. I wrote a script to see if I could capture what the table is doing on the page you linked to. It gets the Cutter number right about 50% of the time, otherwise its off by a few digits. I am stumped about what to do when the first letter is Q not followed by U. It says to use numbers 2-29 for the second letters a-t, but that is obviously not right (for one thing t would be 21, not 29). Since you seem a little bit more experienced in library science could you explain what is going on? :) you can find the script here: http://lost-theory.org/python/cutter.txt Title mine real match? --------------------------------------- IBM I26 I26 True Idaho I33 I33 True Ilardo I43 I4 False Import I47 I48 False Inman I56 I56 True Ipswich I67 I67 True Ito I86 I87 False Ivy I99 I94 False Sadron S23 S23 True Scanlon S33 S29 False Schreiber S37 S37 True Shillingburg S55 S53 False Singer S56 S57 False Stinson S75 S75 True Suryani S87 S87 True Symposium S96 S96 True Qadduri Q23 Q23 True Qiao Q103 Q27 False Quade Q33 Q33 True Queiroz Q45 Q45 True Quinn Q56 Q56 True Quorum Q67 Q67 True Qutub Q88 Q88 True Qvortrup Q236 Q97 False Campbell C46 C36 False Ceccaldi C53 C43 False Chertok C64 C48 False Clark C73 C58 False Cobblestone C43 C63 False Cryer C79 C79 True Cuellar C74 C84 False Cymbal C36 C96 False Steve From connellybarnes at yahoo.com Thu May 18 23:22:13 2006 From: connellybarnes at yahoo.com (Connelly Barnes) Date: Thu, 18 May 2006 20:22:13 -0700 (PDT) Subject: Programming language productivity Message-ID: <20060519032213.43406.qmail@web54312.mail.yahoo.com> Hi Python folks, I created a summary PDF of two studies on programming language productivity: http://barnesc.blogspot.com/2006/05/programming-language-productivity.html One notes that Python and Perl are the two best languages by the "number of hours to solve problem" metric. I ran into these studies when I was learning Common Lisp, and Googled "lisp productivity." The 2nd hit described the frustrations of Brandon Corfman in trying to reproduce Norvig's Lisp solution to a problem. This led me to Norvig's article, which cited the two given studies. There may be entire areas of academia devoted to studying the "productivity problem;" if so, then I am not familiar with the research in that area, so please let me know where I should look for better/more recent research! - Connelly Barnes __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From john at castleamber.com Mon May 29 15:41:20 2006 From: john at castleamber.com (John Bokma) Date: 29 May 2006 19:41:20 GMT Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> Message-ID: <Xns97D2956C291F0castleamber@130.133.1.4> "Kriv" <kriv.john at gmail.com> wrote: > Hi friends, > > I found this eBook on the web. This book is very very good. > I refer to them. I doubt Apress will be happy with this. Don't post garbage like this, since instead of helping, you're doing the opposite. People interested in copyright infringement don't need your posts, they know where and how to get it. http://diveintopython.org/ Dive into Python http://greenteapress.com/thinkpython/ How to Think Like a Computer Scientist: Learning with Python http://honors.montana.edu/~jjc/easytut/easytut/ Non-Programmers Tutorial For Python http://www.freenetpages.co.uk/hp/alan.gauld/tutintro.htm Learning to program (might be outdated) -- 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 aleaxit at yahoo.com Sat May 6 22:23:10 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 19:23:10 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> <87bquaskap.fsf@rpi.edu> Message-ID: <1hexho5.t9wd5h8dlk09N%aleaxit@yahoo.com> Bill Atkins <NOatkinwSPAM at rpi.edu> wrote: ... > Does Python have any support for closures? If so, ignore this point. Ignored, since closures are there. > Being able to keep pass around state with functions is useful. Sure, but naming the functions doesn't hamper that. > There are also cases where a function is so trivial that the simplest > way to describe it is with its source code, where giving it a name and > putting it at the beginning of a function is just distracting and > time-consuming. E.g.: > > (remove-if (lambda (name) > (find #\- name :test #'char=)) > list-of-names) > > What's the sense of giving that function its own name? It's much > clearer to simply write it in place. Yes, it's _possible_ to use > named functions, but in this case its functionality is so simple that > it's clearer to simply type it in place. Why is this expressiveness a > bad thing, aside from its power to wreck an indentation-significant > language? Offering several "equivalently obvious" approaches to performing just one same task is bad for many reasons: you end up with a bigger language (with all the attending ills) with no extra power, and you diminish the style uniformity of programs written in the language, hampering the ability of many people to work in the same codebase with no "ownership". Like most all design principles, "there should be one, and preferably only one, obvious way to perform a task" is an _ideal_, unattainable in its perfect form in this sublunar world; but I find it an extremely helpful guideline to design, and it does pervade Python (many of the planned improvements for the future Python 3.0, which will be allowed to be backwards-incompatible with 2.*, involve *removing* old features made, in this sense, redundant by enhancements in recent versions; my only beef here is that _not enough_ is scheduled for removal, alas). > people are used to ALGOL-like languages does not mean that ALGOL-like > languages are more aesthetically pleasing on their own merits. "on their own merits" can't be the case -- as Wittgenstein pointed out, we ARE talking about the natural history of human beings. A frequently observed aestethic preference for X over Y says nothing about X and Y ``on their own merits'' (if such noumena could even be envisaged), but it's empirically important about X and Y _when many human beings must interact with them_. Being "used to" some kinds of languages has nothing to do with it: when I met Python I was most "used to" perl (and cognizant of Forth, scheme, pre-common Lisp, sh, APL, ...), nevertheless Python immediately struck me as allowing particularly beautiful coding. And I specifically named many Lisp experts as acknowledging exacty the same thing, further demolishing your "used to" strawman... Alex From manlio_perilloNO at SPAMlibero.it Mon May 15 05:15:47 2006 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Mon, 15 May 2006 09:15:47 GMT Subject: [ANN] pykill32 0.2 Message-ID: <7FX9g.10556$b5.166373@twister2.libero.it> pykill32 is a small library that enable developers and users on Windows 2000/XP to send signals to a Python process. It emulates the POSIX kill. There is also a script, kill.py, with a minimal emulation of POSIX kill(1). And a simple dumpbin.py script that list all modules (DLL) loaded by a process. pykill32 works by creating a thread on the *remote* process (CreateRemoteThread) that calls the raise procedure from the MSVCR71 module. It just works fine for Twisted processes. The library can be found on: http://developer.berlios.de/projects/pykill32/ and via SVN: http://svn.berlios.de/svnroot/repos/pykill32/trunk Regards Manlio Perillo From robert.kern at gmail.com Sun May 28 15:42:52 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 28 May 2006 14:42:52 -0500 Subject: using FFTW3 with Numeric on Windows In-Reply-To: <6.2.3.4.2.20060528153411.02afc960@post.strato.de> References: <6.2.3.4.2.20060528153411.02afc960@post.strato.de> Message-ID: <e5cufs$45v$1@sea.gmane.org> sven koenig wrote: > hi list, > as the subject says, I'm trying to find a way to use > FFTW3 with Numeric arrays. > I'm not very familiar with C(++) - I think ctypes is the > way to go, but I don't really have a clue how to do it. > Has somebody already tried this? scipy can use FFTW3 as its FFT routines. http://www.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 ang.usenet at gmail.com Tue May 16 20:14:07 2006 From: ang.usenet at gmail.com (Aaron Gray) Date: Wed, 17 May 2006 01:14:07 +0100 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <4cv86jF17mq54U1@individual.net> I was once a religous tabber until working on multiple source code sources, now I am a religious spacer :) My 2bits worth, Aaron From kay.schluehr at gmx.net Wed May 24 16:14:33 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 24 May 2006 13:14:33 -0700 Subject: PEP 3102 for review and comment In-Reply-To: <mailman.6145.1148470457.27775.python-list@python.org> References: <mailman.6145.1148470457.27775.python-list@python.org> Message-ID: <1148501673.777367.122660@u72g2000cwu.googlegroups.com> molasses wrote: > I don't mind the naked star and will be happy if thats what we end up with. > > Though how about using *None? > I think that makes the intention of the function clearer. > > eg. > def compare(a, b, *None, key=None): > > Which to me reads as "no further positional arguments". > > Or alternatively: > def compare(a, b, *0, key=None): > > -- Mark Argh! Sorry, but this syntax seems to me a perlish hackaround. Although the star is clearly beautifull and veeeery pythonic ;) >From the PEP: One can easily envision a function which takes a variable number of arguments, but also takes one or more 'options' in the form of keyword arguments. Currently, the only way to do this is to define both a varargs argument, and a 'keywords' argument (**kwargs), and then manually extract the desired keywords from the dictionary. The current solution is fine and not very troublesome. But if you want to drop a named dict just replace it by an unnamed one ( unless you think this will seduce people to use devilish, horrible lambda ... ). Suggestions: def compare(a, b, *args, **kwd): # the classics def compare(a, b, *args, {"key":None}): # pass keywords in unnamed dict def compare(a, b, *args, {key=None}): # alternative syntax def compare(a, b, *args, **kwd={...,"key":None}): # having the cake and eating it Regards, Kay From jeffshannon at gmail.com Sun May 7 16:36:55 2006 From: jeffshannon at gmail.com (jeffshannon at gmail.com) Date: 7 May 2006 13:36:55 -0700 Subject: Passing options around your program In-Reply-To: <4c6o1sF14hhjuU1@individual.net> References: <4c6o1sF14hhjuU1@individual.net> Message-ID: <1147034215.798964.72700@g10g2000cwb.googlegroups.com> When I have done this, I've used the last option -- creating a "config" module which can be imported wherever the configuration info is needed. (This module also handles any config files and/or Windows registry keys needed.) Using a Borg is a nice idea... but that ConfigBorg is probably going to be in its own module, which will need to be imported anyhow... so why not let sys.__import__() do your singleton-enforcement for you? Of course, I hesitate to claim anything that I do as being necessarily related to "best practices", but what would Usenet be without swarms of half-informed opinions? ;) Jeff Shannon From mtobis at gmail.com Thu May 25 17:19:31 2006 From: mtobis at gmail.com (Michael Tobis) Date: 25 May 2006 14:19:31 -0700 Subject: Python Programming Books? In-Reply-To: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> Message-ID: <1148591971.405787.237790@38g2000cwa.googlegroups.com> I am not happy with any of the Python-as-a-First-Language books out there. My vague inclination to write one has not yet formed into a firm intention, but it's close. Of the books that are out there, Learning Python and Dive Into Python are best for the hobbyist as opposed to classroom setting, but my sense is that both of them go a bit too fast for the typical beginner with no formal training. In the classroom setting, Zelle's book or Hetland's are good, but they are a bit dry for the hobbyist. In my opinion, if you are just looking for a pleasant exploration of whether you enjoy programming, one option to consider is Python Programming for the Absolute Beginner by Michael Dawson, which focuses on developing games. mt From bdesth.quelquechose at free.quelquepart.fr Fri May 26 10:26:54 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 26 May 2006 16:26:54 +0200 Subject: Can any body help me In-Reply-To: <1148621554.184942.155430@38g2000cwa.googlegroups.com> References: <1148621554.184942.155430@38g2000cwa.googlegroups.com> Message-ID: <4476e0d7$0$20724$636a55ce@news.free.fr> satish a ?crit : > how to write script for these > (snip homework specifications) - read this: http://www.catb.org/~esr/faqs/smart-questions.html - browse the Python documentation - do the tutorial if needed - open you favorite code editor - do your homework If you're stuck, then post your code here. > thanx HTH From bob_jenkins at burtleburtle.net Tue May 16 18:28:43 2006 From: bob_jenkins at burtleburtle.net (bob_jenkins at burtleburtle.net) Date: 16 May 2006 15:28:43 -0700 Subject: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? References: <1147657728.064817.214850@j73g2000cwa.googlegroups.com> <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> <1147804326.793291.53410@j55g2000cwa.googlegroups.com> <mailman.5762.1147805604.27775.python-list@python.org> Message-ID: <1147818523.764211.234710@u72g2000cwu.googlegroups.com> If you have the same number of entries as buckets, and you have a good hash function, then if you have n buckets your longest chain should have length around ln(n). The average length of a nonempty bucket would be somewhere around 1 1/2. From levub137 at wi.rr.com Wed May 10 07:10:07 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Wed, 10 May 2006 11:10:07 GMT Subject: installing numpy In-Reply-To: <87vesegvtj.fsf@localhost.localdomain> References: <877j4v5ukc.fsf@localhost.localdomain> <6Y%7g.11622$EC.10694@tornado.rdc-kc.rr.com> <8764kfkkhb.fsf@localhost.localdomain> <mailman.5533.1147209024.27775.python-list@python.org> <lPa8g.3970$WP5.1983@tornado.rdc-kc.rr.com> <mailman.5540.1147222998.27775.python-list@python.org> <87vesegvtj.fsf@localhost.localdomain> Message-ID: <jSj8g.13266$EC.2772@tornado.rdc-kc.rr.com> Gary Wessle wrote: > Robert Kern <robert.kern at gmail.com> writes: > > >>Raymond L. Buvel wrote: >> >> >>>Since you are a new Linux user, you should definitely follow Robert's >>>advice about building as an ordinary user separately from the install. >>>I sometimes take a shortcut and just do the install as user root. >>>However, I then wind up cleaning out the build directory as user root >>>(not a very safe thing to do). >> >>For small, pure Python packages, that may be fine. numpy's build is complicated >>enough that you really, *really* want to build as a regular user. >> >>-- >>Robert Kern > > > I have read as much as I can form the python installation manual. > as a regular user, I created a personal configuration file here > > **************** > :~$ cat .pydistutils.cfg > [install] > prefix=/usr/local > **************** > > now to build as a regular user, I am getting some errors > > **************************************************************** > $ cd numpy-0.9.6 > $ python setup.py build > Running from numpy source directory. > Warning: not existing path in numpy/distutils: site.cfg > F2PY Version 2_2236 > Traceback (most recent call last): > File "setup.py", line 76, in ? > setup_package() > File "setup.py", line 63, in setup_package > config.add_subpackage('numpy') > File "/home/fred/numpy-0.9.6/numpy/distutils/misc_util.py", line 592, in add_s ubpackage > config_list = self.get_subpackage(subpackage_name,subpackage_path) > File "/home/fred/numpy-0.9.6/numpy/distutils/misc_util.py", line 582, in get_s ubpackage > subpackage_path) > File "/home/fred/numpy-0.9.6/numpy/distutils/misc_util.py", line 539, in _get_ configuration_from_setup_py > config = setup_module.configuration(*args) > File "/home/fred/numpy-0.9.6/numpy/setup.py", line 10, in configuration > config.add_subpackage('core') > File "/home/fred/numpy-0.9.6/numpy/distutils/misc_util.py", line 592, in add_s ubpackage > config_list = self.get_subpackage(subpackage_name,subpackage_path) > File "/home/fred/numpy-0.9.6/numpy/distutils/misc_util.py", line 582, in get_s ubpackage > subpackage_path) > File "/home/fred/numpy-0.9.6/numpy/distutils/misc_util.py", line 539, in _get_ configuration_from_setup_py > config = setup_module.configuration(*args) > File "numpy/core/setup.py", line 11, in configuration > from numpy.distutils.system_info import get_info, default_lib_dirs > File "/home/fred/numpy-0.9.6/numpy/distutils/system_info.py", line 151, in ? > so_ext = get_config_vars('SO')[0] or '' > File "/usr/lib/python2.4/distutils/sysconfig.py", line 488, in get_config_vars > func() > File "/usr/lib/python2.4/distutils/sysconfig.py", line 358, in _init_posix > raise DistutilsPlatformError(my_msg) > distutils.errors.DistutilsPlatformError: invalid Python installation: unable to open /usr/lib/python2.4/config/Makefile (No such file or directory) I think this is another example where you don't have the -dev package you need installed on your system. In order to build just about anything that requires header files on a Debian system, you need to install the -dev packages. Debian usually packages things into a package for regular users and another package of the same name with a -dev suffix for developers. In this case, it looks like distutils is complaining about a missing Makefile. But this is just the start of the problems. Checking on my system, it looks like you need to install the python2.4-dev package. Note that installing python-dev won't work in your case since that is for the default Python which is still Python2.3 in Debian testing. Using NumPy as your first introduction to building Python extension modules is a real challenge. Good luck! Ray Buvel From siona at chiark.greenend.org.uk Fri May 19 11:11:22 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 19 May 2006 16:11:22 +0100 (BST) Subject: memory error with zipfile module References: <mailman.5938.1148039030.27775.python-list@python.org> <446dbe4d$0$8013$626a54ce@news.free.fr> Message-ID: <sxB*gG3gr@news.chiark.greenend.org.uk> bruno at modulix <onurb at xiludom.gro> wrote: >http://mail.zope.org/pipermail/zope/2004-October/153882.html >""" >MemoryError is raised by Python when an underlying (OS-level) allocation >fails. >(...) >Normally this would mean that you were out of even virtual memory >(swap), but it could also be a symptom of a libc bug, a bad RAM chip, etc. >""" There's another possibility, which I ran into recently. Which is a problem with physical+virtual memory exceding the space addressable by a process. So I've got 2G physical + 4G swap and I'm getting just such a memory error -- I'm sure the compressed + uncompressed data isn't going to eat all of that. But on a 32bit OS, it doesn't need to of course. 2G is quite enough to cause problems.... -- \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 johnmiloo at gmail.com Thu May 11 15:36:33 2006 From: johnmiloo at gmail.com (johnmiloo at gmail.com) Date: 11 May 2006 12:36:33 -0700 Subject: SSL support in SOAPpy to build a SOAP server Message-ID: <1147376193.223499.59960@i40g2000cwc.googlegroups.com> Can some one get me started with a working SOAP server that works over https. (SSL)? I have M2Crypto installed and found the following sample, but something is wrong in ssl_context = SSL.Context() Any help or tutorial appreciated? from SOAPpy import SOAPServer from M2Crypto import SSL def echo(s): return s+s # repeats a string twice ssl_context = SSL.Context() ssl_context.load_cert('server.pem') server = SOAPServer(("localhost",8443), ssl_context = ssl_context) server.registerFunction(echo) server.serve_forever() From roy at panix.com Wed May 17 18:57:32 2006 From: roy at panix.com (Roy Smith) Date: Wed, 17 May 2006 18:57:32 -0400 Subject: How to tell if function was passed a list or a string? References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> <mailman.5848.1147906051.27775.python-list@python.org> Message-ID: <roy-7FE2C0.18573117052006@reader1.panix.com> Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > Currently there's no good duck-typing way to differentiate > strings from other sequences. I suppose you could do something like: try: foo.isalpha except AttributeError: print "foo is not a string" but other than proving that you don't *have* to use isinstance(), I don't think that approach has much going for it. From bdesth.quelquechose at free.quelquepart.fr Mon May 15 21:10:37 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 May 2006 03:10:37 +0200 Subject: count items in generator In-Reply-To: <1147584805.462908.201300@g10g2000cwb.googlegroups.com> References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1147584805.462908.201300@g10g2000cwb.googlegroups.com> Message-ID: <4468f77e$0$5147$626a54ce@news.free.fr> George Sakkis a ?crit : (snip) > def length(iterable): > try: return len(iterable) > except: except TypeError: > i = 0 > for x in iterable: i += 1 > return i > (snip) From Serge.Orlov at gmail.com Tue May 2 10:45:13 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 2 May 2006 07:45:13 -0700 Subject: Strange result with math.atan2() References: <chuji3xd2m.ln2@pollux.home> <44575f1d$0$16971$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <ks6ki3xefk.ln2@pollux.home> Message-ID: <1146581113.211223.244580@v46g2000cwv.googlegroups.com> Vedran Furac wrote: > Ben Caradoc-Davies wrote: > > Vedran Furac wrote: > >> I think that this results must be the same: > >> In [3]: math.atan2(-0.0,-1) > >> Out[3]: -3.1415926535897931 > >> In [4]: math.atan2(-0,-1) > >> Out[4]: 3.1415926535897931 > > > > -0 is converted to 0, then to 0.0 for calculation, losing the sign. You > > might as well write 0.0 instead of -0 > > > > The behaviour of atan2 conforms to the ISO C99 standard (Python is > > implemented in C). Changing the sign of the first argument changes the > > sign of the output, with no special treatment for zero. > > > > http://www.ugcs.caltech.edu/manuals/libs/mpfr-2.2.0/mpfr_22.html > > Well, here I can read: > > Special values are currently handled as described in the ISO C99 standard > for the atan2 function (note this may change in future versions): > > * atan2(+0, -0) returns +Pi. > * atan2(-0, -0) returns -Pi. /* wrong too */ > * atan2(+0, +0) returns +0. > * atan2(-0, +0) returns -0. /* wrong too */ > * atan2(+0, x) returns +Pi for x < 0. > * atan2(-0, x) returns -Pi for x < 0 > ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ > > And the formula (also from that site): > if x < 0, atan2(y, x) = sign(y)*(PI - atan (abs(y/x))) > ^^^^^^^ > > So, you can convert -0 to 0, but you must multiply the result with sign of > y, which is '-' (minus). But you miss the fact that 0 is an *integer*, not a float, and -0 doesn't exist. Use this code until you stop passing integers to atan2: from math import atan2 as math_atan2 def atan2(y, x): if (isinstance(y, int) and y == 0) or ( isinstance(x, int) and x == 0): raise ValueError("Argument that is an integer zero can \ produce wrong results") return math_atan2(y, x) print atan2(-0.0, -0.0) print atan2(-0, -0) From egbert.bouwman at hccnet.nl Wed May 17 02:17:45 2006 From: egbert.bouwman at hccnet.nl (egbert) Date: Wed, 17 May 2006 08:17:45 +0200 Subject: Questions about the event loop Message-ID: <20060517061745.GA13858@hccnet.nl> What does a gui_event_loop know ? My gui is based on pygtk, but i suppose the mechanism is the same everywhere. The gui is created within a class-instance within a function. Normally, ie without a gui, everything that happens within a function is forgotten as soon the function ends. But in a gui_event_loop the callback-method within the function can be called, and this callbacks calls another function also within the same first function. And that function already stopped. Maybe somebody can explain what is going on, or where I can find further explanations. The structure of my gui script is as follows: import gtk def func(): def callback_helper(): ... class Klas(object): def __init__(self): ... # create gui with self.callback() ... def callback(self, widget): callback_helper() ... klas = Klas() func() gtk.main() egbert -- Egbert Bouwman - Keizersgracht 197 II - 1016 DS Amsterdam - 020 6257991 ======================================================================== From ptmcg at austin.rr._bogus_.com Wed May 17 14:57:11 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 17 May 2006 18:57:11 GMT Subject: Pyparsing: Grammar Suggestion References: <mailman.5825.1147888678.27775.python-list@python.org> Message-ID: <bmKag.41840$CH2.32978@tornado.texas.rr.com> "Khoa Nguyen" <khoa.coffee at gmail.com> wrote in message news:mailman.5825.1147888678.27775.python-list at python.org... <snip> > Thanks for your reply. This looks promising, but I have a few more questions: > 1. If f(i) is non-terminal (e.g f(i) is another grammar expression), > how would I adapt your idea to a more generic way? > 2. The field delimiter is not always ',' in my case. So I guess I'll > have to use delimtedList instead? > > Thanks again, > Khoa Khoa, Yes, it sounds like delimitedList is the way to go. Note that the delimiter for delimitedList can also be an expression, it does not have to be a literal string, or terminal. Also, do not bother using delimitedList if your delimiter is just whitespace - pyparsing breaks up tokens on whitespace by default, that is: OneOrMore(Word(alphas)) will correctly parse "This is a sentence made up of alphabetic words", giving: ['This', 'is', 'a', 'sentence', 'made', 'up', 'of', 'alphabetic', 'words'] without having to represent the delimiting whitespace in the grammar. -- Paul From durumdara at gmail.com Thu May 11 03:51:15 2006 From: durumdara at gmail.com (DurumDara) Date: Thu, 11 May 2006 09:51:15 +0200 Subject: How to encode html and xml tag datas with standard python modules ? In-Reply-To: <e39oh1$ppp$1@sea.gmane.org> References: <44586183.2030903@gmail.com> <e39oh1$ppp$1@sea.gmane.org> Message-ID: <4462ECF3.3030306@gmail.com> Hi ! I probed this function, but that is not encode the hungarian specific characters, like ???????????: so the chars above chr(127). Have the python a function that can encode these chars too, like in Zope ? Thanx for help: dd Fredrik Lundh ?rta: > DurumDara wrote: > > >> Have the python standard mod. lib. a html/xml encoder functions/procedures ? >> > > you can use > > cgi.escape(s) # escapes < > & > > for CDATA sections, and > > cgi.escape(s, True) # escapes < > & " > > for attributes. > > to output ASCII, use > > cgi.escape(s).encode("ascii", "xmlcharrefreplace") > cgi.escape(s, True).encode("ascii", "xmlcharrefreplace") > > >> if b<32 or b>127 or c in ['<','>','"',';','&','@','%','#']: >> c="&#%03d;"%b >> > > that's a rather odd set of reserved characters... > > </F> > > > > From incall at msn.com Tue May 23 10:03:06 2006 From: incall at msn.com (Pablo) Date: 23 May 2006 07:03:06 -0700 Subject: Use of lambda functions in OOP, any alternative? References: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> Message-ID: <1148392986.378382.54390@j33g2000cwa.googlegroups.com> Pablo ha escrito: > Hello all, sorry if this is a faq... > > Problem: The intended effect is to override the method 'getattr' in a > way that i dont need to override the property explicitly too. > > class Base(object): > def __init__(self, attr): > self._attr = attr > def getattr(self): > return self._attr > attr = property(fget=getattr) > > class Derived(Base): > def getattr(self): > return 2*self._attr > > if __name__ == "__main__": > b = Base(4) > d = Derived(4) > print b.attr, d.attr > > output>> 4 8 ... so this does not work as i would like it to. sorry, i meant the following sentence: output>> 4 4 ... so this does not work as i would like it to. > > First solution: This is not what i want. > > class Derived(Base): > def getattr(self): > return 2*self._attr > attr = property(fget=getattr) > > Second solution: This is what i want, but... > > class Base(object): > def __init__(self, attr): > self._attr = attr > def getattr(self): > return self._attr > attr = property(fget=lambda self: self.getattr()) > > class Derived(Base): > def getattr(self): > return 2*self._attr > > Question: Isn't there an *alternative* way to do it without the lambda > function? > > Thanks in advance! From gmnation at gmail.com Wed May 10 01:29:52 2006 From: gmnation at gmail.com (=?iso-8859-1?B?Ry4gTW9uevNu?=) Date: 9 May 2006 22:29:52 -0700 Subject: Can Python installation be as clean as PHP? In-Reply-To: <1147234711.208138.160320@y43g2000cwc.googlegroups.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> <1147211815.312069.135140@u72g2000cwu.googlegroups.com> <1147231092.546800.100860@j73g2000cwa.googlegroups.com> <1147234711.208138.160320@y43g2000cwc.googlegroups.com> Message-ID: <1147238991.889910.309190@j33g2000cwa.googlegroups.com> Carl Banks wrote: > G. Monz?n wrote: > > Please don't compare PHP with Python... They are very different worlds. > > I'm not. I was simply agreeing that the single executable way the OP > claimed PHP does it can *sometimes* be preferrable in Python, and > giving him recommendations thereto. > > Carl Banks Sorry Carl, my reply was for the OP. I pressed the wrong reply button... doesn't meant you did any comparation! I said that about comparing, as the OP thought Python coded in Python approach for a lot of core libraries isn't as efficient as in PHP 'cause they are all coded in C. And that's not true. Yes, it could be obvious for some people that it "should" run faster than Python, having all core functions coded in C, yes, but in overall performance matters, that's not true in any case. Python has all the primitives C coded as said in this thread. PHP "primitives" are no more than hash-tables and lots zvals... far away from the hi-tuned advanced data-types Python exposes. That makes a big performance improvement over PHP, regards C or Python coded core functions -let language implementation details apart-. Major loss of performance in Python and PHP is on translating data values to C side and all the functions calling done for as little as a value assignment to a variable. So, sometimes, to code a function in C or let it be Python, makes no more than a 1us per call difference... I'd like to see this value compared to PHP. That's why PHP need a C implementation for all core functions, as if they would be PHP coded, performance would be even a lot worse. And I would't say PHP is slow. But It depends on what you need to do. 'Cause PHP can be really slow and ultra-high memory consuming. While you had this troubles with PHP, is nice to see how Python performs: consumes a lot less of memory and goes 50 % more fast. About a single executable file, I thought PHP is being distributed in windows and linux as an executable plus an dinamic link library, that's the minimum thing you need to run scripts. So OP is wrong, there is not a single executable file. You need two files at least + php.ini + extensions to run almost any PHP script. And a PHP or Python without extensions or batteries, wouldn't be very handy... oh well, that depends on the task to do. Anyway, PHP isn't a bad tool for a *lot* of web-side scripting, but I'd prefer if I could use Python in many of my work projects. :-) I'd feel happier ! Regards, Gonzalo. From peace.is.our.profession at gmx.de Thu May 11 06:18:38 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Thu, 11 May 2006 12:18:38 +0200 Subject: reusing parts of a string in RE matches? In-Reply-To: <1147291197.423570.242440@g10g2000cwb.googlegroups.com> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> <E6r8g.2083$No6.45931@news.tufts.edu> <eir8g.2084$No6.45965@news.tufts.edu> <1147291197.423570.242440@g10g2000cwb.googlegroups.com> Message-ID: <e3v387$9tt$1@mlucom4.urz.uni-halle.de> Hi mpeters42 & John > With a more complex pattern (like 'a.a': match any character between > two 'a' characters) this will get the length, but not what character is > between the a's. Lets take this as a starting point for another example that comes to mind. You have a string of characters interspersed with numbers: tx = 'a1a2a3A4a35a6b7b8c9c' Now you try to find all _numbers_, which have symmetrical characters (like a<-2->a) which are not in 3/3/3... synced groups. This can easy be done in P(ytho|nerl) etc. by positive lookahead (even the same pattern does:) Py: import re tx = 'a1a2a3A4a35a6b7b8c9c' rg = r'(\w)(?=(.\1))' print re.findall(rg, tx) Pe: $_ = 'a1a2a3A4a35a6b7b8c9c'; print /(\w)(?=(.)\1)/g; (should find 1,2,7,9 only, python regex written to var in order to prevent clunky lines ;-) BTW, Py Regex Engine seems to be very close to the perl one: Naive (!) matching of a pattern with 14 o's (intersperded by anything) against a string of 16 o's takes about exaclty the same time here in Py(2.4.3) and Pe (5.8.7): tl = 'oooooooooooooooo' rg = r'o*o*o*o*o*o*o*o*o*o*o*o*o*o*[\W]' print re.search(rg, tl) Py: 101 sec Pe: 109 sec (which would find no match because there's no \W-like character at the end of the string here) Regards Mirco From larswarholm at gmail.com Thu May 4 13:33:18 2006 From: larswarholm at gmail.com (Lars) Date: 4 May 2006 10:33:18 -0700 Subject: Problem building extension under Cygwin (ImportError: Bad address) In-Reply-To: <mailman.5336.1146758236.27775.python-list@python.org> References: <1146739813.157265.238320@i39g2000cwa.googlegroups.com> <mailman.5322.1146745099.27775.python-list@python.org> <1146749003.095894.281280@j73g2000cwa.googlegroups.com> <mailman.5336.1146758236.27775.python-list@python.org> Message-ID: <1146763998.024541.46020@u72g2000cwu.googlegroups.com> Great! Thanks for the advice. Lars From bignose+hates-spam at benfinney.id.au Sun May 21 04:38:54 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 21 May 2006 18:38:54 +1000 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> Message-ID: <87odxrixgh.fsf@benfinney.id.au> foxtree at gmail.com writes: > Flash is like a 2 MB download that works in almost *every* browser > out there. Except all the browsers on platforms Macromedia have not chosen to support. And no-one else can implement it on those platforms, except by guessing about the closed implementation specification that Macromedia have an interest in keeping a secret. Whereas HTML, CSS and any other technologies standardised by standards bodies have open specifications and multiple independent compatible implementations, and anyone who finds their platform under-supported can follow the open specifications and get a full working implementation. -- \ "From the moment I picked your book up until I laid it down I | `\ was convulsed with laughter. Someday I intend reading it." -- | _o__) Groucho Marx | Ben Finney From email at christoph-haas.de Fri May 5 14:55:59 2006 From: email at christoph-haas.de (Christoph Haas) Date: Fri, 5 May 2006 20:55:59 +0200 Subject: Best IDE for Python? In-Reply-To: <288425520605050850i6f94518nafd34adb6ae6581e@mail.gmail.com> References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> <288425520605050850i6f94518nafd34adb6ae6581e@mail.gmail.com> Message-ID: <20060505185559.GB4911@workaround.org> On Fri, May 05, 2006 at 04:50:11PM +0100, Doug Bromley wrote: > I have a Python IDE review I did a few months back you may want to view: > http://www.straw-dogs.co.uk/blog/python-ide-review Sounds interesting. Could you fix the screenshots? I just get a 404 here. Kindly Christoph P.S.: [Rant about TOFU posting suppressed.] From john at castleamber.com Tue May 30 22:40:59 2006 From: john at castleamber.com (John Bokma) Date: 31 May 2006 02:40:59 GMT Subject: TIming References: <pan.2006.05.30.01.24.04.677340@none.none> <ecin725eh7mk1teolpfi2ulj349ogptdir@4ax.com> <pan.2006.05.30.05.23.09.936650@none.none> <mailman.6326.1148969845.27775.python-list@python.org> <pan.2006.05.30.19.50.38.152274@none.none> Message-ID: <Xns97D3DC9134639castleamber@130.133.1.4> WIdgeteye <None at none.none> wrote: > BTW in the time it took me NOT to get an answer for my question in > this so called Python NG, I figured it out for myself. Maybe you want to post the solution in order to help others with similar problems in the future? -- 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 prikryl at skil.cz Wed May 10 02:30:38 2006 From: prikryl at skil.cz (Petr Prikryl) Date: Wed, 10 May 2006 08:30:38 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <44606502$2$645$bed64819@news.gradwell.net> Message-ID: <e3s1af$715$1@news.contactel.cz> "Chris Uppal" wrote... > Alex Martelli wrote: > > > I think it's reasonable to make a name a part of functions, classes and > > modules because they may often be involved in tracebacks (in case of > > uncaught errors): to me, it makes sense to let an error-diagnosing > > tracebacks display packages, modules, classes and functions/methods > > involved in the chain of calls leading to the point of error _by name_. [...] > E.g. consider the Smalltalk code (assumed to be the body of a method): > > aCollection > do: [:each | > each > 0 ifTrue: [^ true]]. > ^ false. > > which iterates over a collection checking to see if any element is > 0. If so > then the method answers true ("^" -- spelled "return" in Java), otherwise it > answers false. In that code, > [^ true] > is syntactically and semantically an anonymous function, which is only invoked > if the antecedent is true (in point of fact the compiler inlines that function > away but I don't think that's relevant here). The passage beginning > [:each | ... > and reaching to the matching ] is also an anonymous function with one parameter > (each) which is applied to each element of the collection in turn. (In this > case it really is an anonymous function, even at the implementation level.) > What "name" would you give to either of them ? I don't believe that /any/ name > is possible, and certainly that no name is desirable. for element in aCollection: if element > 0: return True return False And adding "def test(aCollection):" does not make it more complex, in my opinion. And possibly, the chunk of code may be written in some other way, more Pythonically. Maybe the attempt to rewrite programs from other languages into Python and the effort to use the same "tricks" like in the original program, causes the cry for preserving lambda in future Python. pepr From tjreedy at udel.edu Tue May 16 16:44:04 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Tue, 16 May 2006 16:44:04 -0400 Subject: IDLE confusion References: <1147767977.928350.261650@i39g2000cwa.googlegroups.com><e4c34c$5l6$1@newsreader3.netcologne.de> <446991de$0$7690$626a54ce@news.free.fr> Message-ID: <e4ddik$i88$1@sea.gmane.org> "Christophe" <chris.cavalaria at free.fr> wrote in message news:446991de$0$7690$626a54ce at news.free.fr... > Try in the IDLE menu [Shell] "Restart Shell" (Ctrl+F6) each time you > have changed something in your files - this "resets" anything previously > imported, which stays the same way otherwise. And I though that "bug" was fixed already :) On my system, the current 2.4.3 version of Python+IDLE *does* auto restart with each run (F5). So either the OP is using a much older version (did not specify) or the respondant mis-diagnosed the problem. tjr From Serge.Orlov at gmail.com Sun May 7 18:11:58 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 7 May 2006 15:11:58 -0700 Subject: the tostring and XML methods in ElementTree In-Reply-To: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> References: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> Message-ID: <1147039918.220845.115020@e56g2000cwe.googlegroups.com> mirandacascade at yahoo.com wrote: > Question 1: assuming the following: > a) beforeCtag.text gets assigned a value of 'I\x92m confused' > b) afterRoot is built using the XML() method where the input to the > XML() method is the results of a tostring() method from beforeRoot > Are there any settings/arguments that could have been modified that > would have resulted in afterCtag.text being of type <type 'str'> and > afterCtag.text when printed displays: > I'm confused > > ? str type (also known as byte string) is only suitable for ascii text. chr(0x92) is outside of ascii so you should use unicode strings or you\x92ll be confused :) >>> print u"I\u2019m not confused" I'm not confused > Question 2: Does the fact that resultToStr is equal to resultToStr2 > mean that an encoding of utf-8 is the defacto default when no encoding > is passed as an argument to the tostring method, or does it only mean > that in this particular example, they happened to be the same? No. Dejure default encoding is ascii, defacto people try to change it, but it's not a good idea. I'm not sure how you got the strings to be the same, but it's definately host-specific result, when I repeat your interactive session I get different resultToStr at this point: >>> afterRoot = ElementTree.XML(resultToStr) >>> resultToStr '<beforeRoot><C>I’m confused</C></beforeRoot>' > 3) would it be possible to construct a statement of the form > > newResult = afterCtag.text.encode(?? some argument ??) > > where newResult was the same as beforeCtag.text? If so, what should > the argument be to the encode method? Dealing with unicode doesn't require you to pollute your code with encode methods, just open the file using codecs module and then write unicode strings directly: import codecs fileHandle = codecs.open('c:/output1.text', 'w',"utf-8") fileHandle.write(u"I\u2019m not confused, because I'm using unicode") > 4) what is the second character in encodedCtagtext (the character with > an ordinal value of 194)? That is byte with value 194, it's not a character. It is part of unicode code point U+0092 when it is encoded in utf-8 >>> '\xc2\x92'.decode("utf-8") u'\x92' This code point actually has no name, so you shouldn't produce it: >>> import unicodedata >>> unicodedata.name('\xc2\x92'.decode("utf-8")) Traceback (most recent call last): File "<pyshell#40>", line 1, in -toplevel- unicodedata.name('\xc2\x92'.decode("utf-8")) ValueError: no such name From pydecker at gmail.com Wed May 17 10:33:28 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 17 May 2006 10:33:28 -0400 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147875273.491587.195800@j73g2000cwa.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147873879.818361.10040@i40g2000cwc.googlegroups.com> <mailman.5804.1147874795.27775.python-list@python.org> <1147875273.491587.195800@j73g2000cwa.googlegroups.com> Message-ID: <ca55a9900605170733v240f2307q594ab4da0519e3c0@mail.gmail.com> On 17 May 2006 07:14:33 -0700, Bill Pursell <bill.pursell at gmail.com> wrote: > I think you unfairly snipped context on me. I was directly responding > to the assertion that vi is unable to handle tabs well. I was *agreeing* with you. Sorry if that wasn't clear. -- # p.d. From avharut at gmail.com Fri May 12 06:39:35 2006 From: avharut at gmail.com (avharut at gmail.com) Date: 12 May 2006 03:39:35 -0700 Subject: index of an element in a numarray array Message-ID: <1147430375.161743.29820@q12g2000cwa.googlegroups.com> hello everyone! sorry to disturb you with this, but i really cant find anything suitable about the topic in the numarray documentation. how can i find in an efficient way the index of the last occurrence of a given element in a numarray array? many thanks in advance! From dreedmac at columbus.rr.com Sun May 7 09:07:51 2006 From: dreedmac at columbus.rr.com (David Reed) Date: Sun, 7 May 2006 09:07:51 -0400 Subject: GladeGen and initializing widgets at startup In-Reply-To: <1146990271.569129.160990@y43g2000cwc.googlegroups.com> References: <1146947945.953256.164400@j33g2000cwa.googlegroups.com> <mailman.5430.1146949725.27775.python-list@python.org> <1146990271.569129.160990@y43g2000cwc.googlegroups.com> Message-ID: <54784C6B-057E-4B0B-861B-8290A2493A55@columbus.rr.com> On May 7, 2006, at 4:24 AM, Aengys wrote: > Thank you for your reply! > > I finally managed to do what I wanted. Maybe a little side-remark > here. > In the article you have said that all changes to the init-method are > lost once you regenerate the file. I have tried it, and indeed all my > changes were lost (which I had backed up before). So I've created a > method which do the initialization and I call this method from the > init-method. Maybe it would be a nice extention to include such a > method by default; a method you can fill with all the code that needs > to be done when initializing the window.... I'm not yet so familiar > with the whole process, but I might have a look at it in the future. > I'll keep you updated on that if it happens. > It's been a while since I've looked at it or used it (haven't been doing an GUI programming recently). I should have said to put your code in the __init__ method after the call to init since the init method is regenerated each time. > Regarding the extension of the show method: how do I do that? And what > benefit does it have to the solution mentioned above? You mentioned you were new to Python - you really need to learn more (specifically about inheritance) before you can fully understand this. The GladeWindow provides a show method but you can write your own show method that would get called instead of it. If you want the code to just be called once, using the __init__ method is appropriate but if your window is repeatedly shown/hidden and you want the code executed each time the window is shown. Dave From desale at india.com Fri May 26 03:46:22 2006 From: desale at india.com (sandip desale) Date: Fri, 26 May 2006 15:46:22 +0800 Subject: Parsing python dictionary in Java using JPython Message-ID: <20060526074622.75C007B5EF@ws5-10.us4.outblaze.com> Dear All, I have a python dictionary file. I want to create a map of that dictionary and want to use the same in my Java Program. Can anybody please tell me how to use the same python dictionary in Java as well as in Python. Thanks in advance... Regards, Sandip -- India.com free e-mail - www.india.com. Check out our value-added Premium features, such as an extra 20MB for mail storage, POP3, e-mail forwarding, and ads-free mailboxes! From drs Sat May 20 16:13:08 2006 From: drs (drs) Date: Sat, 20 May 2006 15:13:08 -0500 Subject: mod_python, COM, on win2k3 server References: <7u2dnWkphP166fLZnZ2dnUVZ_vSdnZ2d@comcast.com> Message-ID: <K7OdnYZJf-XF5fLZRVn-tQ@comcast.com> Some details, and this is weirder than I thought. It is working fine with internet explorer or mozilla as the client, but only crashes with Firefox. Moreover, even while firefox is getting errors, IE stilll works fine. The error I get is: Mod_python error: "PythonHandler mod_python.publisher" Traceback (most recent call last): File "C:\Python23\Lib\site-packages\mod_python\apache.py", line 299, in HandlerDispatch result = object(req) File "C:\Python23\Lib\site-packages\mod_python\publisher.py", line 213, in handler published = publish_object(req, object) File "C:\Python23\Lib\site-packages\mod_python\publisher.py", line 410, in publish_object return publish_object(req,util.apply_fs_data(object, req.form, req=req)) File "C:\Python23\Lib\site-packages\mod_python\util.py", line 439, in apply_fs_data return object(**args) File "E:\http_server\timeslips\index.py", line 84, in index rtn.append(ts_widget.make_employee_picker()) File "C:\Python23\lib\site-packages\ecptimeslips\ts_widget.py", line 128, in make_employee_picker rs = win32com.client.Dispatch("ADODB.Recordset") File "C:\Python23\Lib\site-packages\win32com\client\__init__.py", line 95, in Dispatch dispatch, userName = dynamic._GetGoodDispatchAndUserName(dispatch,userName,clsctx) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 91, in _GetGoodDispatchAndUserName return (_GetGoodDispatch(IDispatch, clsctx), userName) File "C:\Python23\Lib\site-packages\win32com\client\dynamic.py", line 79, in _GetGoodDispatch IDispatch = pythoncom.CoCreateInstance(IDispatch, None, clsctx, pythoncom.IID_IDispatch) com_error: (-2147221008, 'CoInitialize has not been called.', None, None) ? From exarkun at divmod.com Tue May 30 16:04:59 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 30 May 2006 16:04:59 -0400 Subject: TIming In-Reply-To: <pan.2006.05.30.19.50.38.152274@none.none> Message-ID: <20060530200459.28682.782533288.divmod.quotient.7797@ohm> On Tue, 30 May 2006 14:50:38 -0500, WIdgeteye <none at none.none> wrote: > > [snip] > >This PYTHON NG blows to high heaven. Whats worse, the answers I got were >most likely from people who know SQUAT about Python scripting. That's why >they gave me such lame fucking answers. > >Idiots. While that may all be true, there's no call for this kind of post. You came here looking for help, and help was offered. If it is not to your liking, you can move on and look for help elsewhere. The people who answer questions here are doing so for no compensation and don't deserve outbursts like this one, regardless of what you think of their responses. Jean-Paul From carlosperezs at alumnos.uvigo.es Wed May 10 07:30:57 2006 From: carlosperezs at alumnos.uvigo.es (carlosperezs at alumnos.uvigo.es) Date: Wed, 10 May 2006 13:30:57 +0200 Subject: wx.ListCtrl.EditLabel Message-ID: <1147260657.4461cef1191e4@correoweb.uvigo.es> I have problems with this method. I have programmed this wx.Listctrl: self.ListCtrlMarks = wx.ListCtrl(self.panel, -1, style = wx.LC_REPORT) self.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnSelectedItemList,self.ListCtrlMarks) vs.Add(self.ListCtrlMarks, 1, wx.EXPAND | wx.ALL, 4) self.ListCtrlMarks.InsertColumn(0, "Name") self.ListCtrlMarks.InsertColumn(1, "Note") self.ListCtrlMarks.InsertColumn(2, "Film") self.ListCtrlMarks.InsertColumn(3, "Init") self.ListCtrlMarks.InsertColumn(4, "End") self.ListCtrlMarks.SetColumnWidth(1, 80) self.ListCtrlMarks.SetColumnWidth(2, 80) self.ListCtrlMarks.SetColumnWidth(3, 40) self.ListCtrlMarks.SetColumnWidth(4, 40) later i introduced values in each column. What i want to programm is : - when i select the row and i press a button called "Change Name" i wanto to can edit the Name and introduce the new value. I tried it with:(the next code lines are in the function that is called when the buttton "Change Name" is pressed.) # I get the row selected index self.currentIdx=self.ListCtrlMarks.GetNextItem(-1, wx.LIST_NEXT_ALL,wx.LIST_STATE_SELECTED) self.ListCtrlMarks.EditLabel(self.currentIdx) I thought that so it would work. But does not work. Don't let me to edit new Name Value Thank you --oOo-----------------------------------------------------------------oOo-- Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo Servicios Inform?ticos [ http://si.uvigo.es ] Universidade de Vigo [ http://www.uvigo.es ] URL: https://correoweb.uvigo.es From larry.bates at websafe.com Tue May 2 13:01:50 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 02 May 2006 12:01:50 -0500 Subject: RFC 822 continuations In-Reply-To: <e3827a$dtd$1@news.in.tum.de> References: <e3827a$dtd$1@news.in.tum.de> Message-ID: <4457907E.5010502@websafe.com> Florian Lindner wrote: > Hello, > http://docs.python.org/lib/module-ConfigParser.html writes: > > "with continuations in the style of RFC 822; " > > what is meant with these continuations? > > Thanks, > > Florian >From ConfigParser source code: Continuations are represented by an embedded newline then leading whitespace. -Larry Bates From sjmachin at lexicon.net Wed May 31 22:14:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 01 Jun 2006 12:14:45 +1000 Subject: Save data to a file thru a http connection In-Reply-To: <1149126761.726836.73360@y43g2000cwc.googlegroups.com> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> <447e0221$1@nntp0.pdx.net> <1149126761.726836.73360@y43g2000cwc.googlegroups.com> Message-ID: <447E4D95.4040805@lexicon.net> On 1/06/2006 11:52 AM, yinglcs at gmail.com wrote: > Scott, > > Can you please tell me which chapter of the tutorial that you are > referring to http://docs.python.org/tut/tut.html? > > The only chapter that I find about http is chapter 10.7, but it does > not have the example that you are referring to Break the problem up into two parts: (1) Get some data. You've achieved that, using HTTP. (2) Save some data to a file. Doesn't matter *how* you got the data. You need to know how to open a file for writing and how to write to it and how to close it when you've finished. Look for the section in the tutorial about *files*. Better still, read *all* the sections in the tutorial :-) > > Scott David Daniels wrote: >> yinglcs at gmail.com wrote: >>> I am new to python. I read an example here about how to fetch data thru >>> a HTTP connection: >>> http://diveintopython.org/http_web_services/review.html, >>> >>> My question is how can i save the data to a file after reading it from >>> a http connection. >> Do the tutorial and this and many other things will become clear. >> >> Instead of just "print sometext", do something like: >> ... >> f = open('filename', 'w') >> ... >> print >>f, sometext >> ... (possibly more prints like the above). >> f.close() >> >> --Scott David Daniels >> scott.daniels at acm.org > From larry.bates at websafe.com Thu May 25 12:57:56 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 25 May 2006 11:57:56 -0500 Subject: os listdir access denied when run as a service In-Reply-To: <mailman.6178.1148529545.27775.python-list@python.org> References: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz><1146620207.56.7672@mint-julep.mondoinfo.com><002901c66e57$05a69090$346ea8c0@tintz.co.nz><1146624295.41.7841@mint-julep.mondoinfo.com><003501c66e64$316deb30$346ea8c0@tintz.co.nz><1146677203.2.7870@mint-julep.mondoinfo.com><00f701c673e5$a3af0860$346ea8c0@tintz.co.nz><1147292340.91.3040@mint-julep.mondoinfo.com><012d01c67473$09fc0450$346ea8c0@tintz.co.nz><1147305886.06.3304@mint-julep.mondoinfo.com><016201c67497$22a91d70$346ea8c0@tintz.co.nz> <1147311218.22.3304@mint-julep.mondoinfo.com> <mailman.6178.1148529545.27775.python-list@python.org> Message-ID: <OZSdnUL1u--Of-jZnZ2dnUVZ_vednZ2d@comcast.com> Thomas Thomas wrote: > Hi All, > > I am trying to access a mapped network drive folder. everything works fine > normally. But when i run the application as service I am getting the error > > Traceback (most recent call last): > File "docBoxApp.py", line 129, in ? > File "core\PollFiles.pyc", line 332, in doPoll > File "core\PollFiles.pyc", line 47, in createFileList > File "core\PollFiles.pyc", line 25, in addFolderFiles > WindowsError: [Errno 5] Access is denied: 'G:\\DT Hot Folder test/*.*' > > > below is my code > > > def addFolderFiles(folder,filelist=[]): > logger=ServerInterface.getErrorLogger() > folder = folder.encode('ascii') #convert path to ascii for File Method > for filename in os.listdir(folder):#line 25 > file=os.path.join(folder,filename) > logger.error("loop file :"+file); > if os.path.isfile(file): > logger.error("is file :"+file); > if ((not (file.find(".tmp")>=0)) and (not > (file.find("~")>=0))): > filelist.append(file) > elif os.path.isdir(file): > logger.error("file is a directory :"+file); > addFolderFiles(file,filelist) > > def createFileList(files,folders,filelist=[]): > logger=ServerInterface.getErrorLogger() > for file in files: > file = file.encode('ascii') #convert path to ascii for File Method > if os.path.isfile(file): > if ((not (file.find(".tmp")>=0)) and (not (file.find("~")>=0))): > filelist.append(file) > > for folder in folders: > logger.error("got a folder :"+folder); > logger.error("it was in the list :"+folders.__str__()); > addFolderFiles(folder,filelist) > return (1,filelist) > > anything I can do about this.. > > > ----------------------------------------------------- > Thomas Thomas > Remember that services run under a different context than the foreground login. You can configure services to run under a user context by editing that info in the service control panel applet under the Log On tab at the top. The default is to run the service under Local System account which probably doesn't have any mapped drives. -Larry Bates From jamesthiele.usenet at gmail.com Sun May 21 13:49:36 2006 From: jamesthiele.usenet at gmail.com (James Thiele) Date: 21 May 2006 10:49:36 -0700 Subject: escapes in regular expressions Message-ID: <1148233776.133200.59280@u72g2000cwu.googlegroups.com> I was helping a guy at work with regular expressions and found something I didn't expect: >>> re.match('\d', '7').group() '7' >>> re.match('\\d', '7').group() '7' >>> It's not clear to me why these are the same. Could someone please explain? From robert.kern at gmail.com Fri May 12 21:42:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 12 May 2006 20:42:08 -0500 Subject: How to install pyTrix? In-Reply-To: <44652d37$0$15982$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <44652d37$0$15982$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <e43dhf$ln3$1@sea.gmane.org> DeepBlue wrote: > Hi all, > > can any1 please tell me how to install pyTrix? Apparently, you put pytrix.py and any of the other modules that it depends on (you can look at the top of the file) where Python can see it. http://docs.python.org/tut/node8.html#SECTION008110000000000000000 -- 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 wim.verhavert at gmail.com Sun May 7 04:24:31 2006 From: wim.verhavert at gmail.com (Aengys) Date: 7 May 2006 01:24:31 -0700 Subject: GladeGen and initializing widgets at startup In-Reply-To: <mailman.5430.1146949725.27775.python-list@python.org> References: <1146947945.953256.164400@j33g2000cwa.googlegroups.com> <mailman.5430.1146949725.27775.python-list@python.org> Message-ID: <1146990271.569129.160990@y43g2000cwc.googlegroups.com> Thank you for your reply! I finally managed to do what I wanted. Maybe a little side-remark here. In the article you have said that all changes to the init-method are lost once you regenerate the file. I have tried it, and indeed all my changes were lost (which I had backed up before). So I've created a method which do the initialization and I call this method from the init-method. Maybe it would be a nice extention to include such a method by default; a method you can fill with all the code that needs to be done when initializing the window.... I'm not yet so familiar with the whole process, but I might have a look at it in the future. I'll keep you updated on that if it happens. Regarding the extension of the show method: how do I do that? And what benefit does it have to the solution mentioned above? Aengys From bdesth.quelquechose at free.quelquepart.fr Tue May 2 21:38:22 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 03:38:22 +0200 Subject: simultaneous assignment In-Reply-To: <RAN5g.2037$No6.43926@news.tufts.edu> References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <RAN5g.2037$No6.43926@news.tufts.edu> Message-ID: <4457dadd$0$9654$636a55ce@news.free.fr> John Salerno a ?crit : > bruno at modulix wrote: > >> Now if I may ask: what is your actual problem ? > > > Ok, since you're so curious. :) Sorry !-) > Here's a scan of the page from the puzzle book: > http://johnjsalerno.com/spies.png > > Basically I'm reading this book to give me little things to try out in > Python. There's no guarantee that this puzzle is even conducive to (or > worthy of) a programming solution. Well, this is probably a good exercice in boolean logic - which is something very important in CS. But my question (sorry, it may not have been clear) was more along the line of : "why do you worry about identity in the given snippet ?". Rebinding a name already bound to a given object doesn't affect other names bound to the same object. So in this case, multiple assignement is perfectly safe. From aylwyn at cantab.net Tue May 16 16:48:17 2006 From: aylwyn at cantab.net (achates) Date: 16 May 2006 13:48:17 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> Message-ID: <1147812497.596178.114500@38g2000cwa.googlegroups.com> Duncan Booth wrote: >Because it doesn't mean 'one level of indentation', it means 'move to next >tabstop' and a tabstop isn't necessarily the same as a level of >indentation. 'move to next tabstop' is how your editor interprets a tab character. 'one level of indentation' is how the language parser interprets it. The two are entirely consistent, in that they are both isomorphic mappings of the same source file. >In particular a common convention is to have indentations at 4 >spaces and tabs expanding to 8 spaces. Like all space-indenters, you seem to be hung up on the idea of a tab 'expanding' to n spaces. It only does that if you make your editor delete the tab character and replace it with spaces! Really, that is the only sense in which your statement makes any sense. If you want your indentation to have the width of four, eight, or nineteen spaces, set your tabstops accordingly. Seriously people, this is about separating the content of a source file from how it is displayed. It's about letting people work together while also allowing them to have control over their own environments, something which is and always has been central to the hacker ethos. From claird at lairds.us Wed May 3 13:07:46 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 03 May 2006 17:07:46 GMT Subject: Zope Guru... References: <mailman.5251.1146641484.27775.python-list@python.org> Message-ID: <ag1ni3-uit.ln1@lairds.us> In article <mailman.5251.1146641484.27775.python-list at python.org>, bruce <bedouglas at earthlink.net> wrote: >Hi.. > >In doing some research into Workflow apps regarding document management, I >came across Zope. Given that it's Python Based, I figured I'd shout to the >group here... > >Are there any Zope gurus that I can talk to regarding Zope, and what it >does/how it works? In particular, I'm looking for an app that I could use to >manage a pretty simple workflow for a bunch of scripts that are going to be >developed. > >I envision having a number of people on the team, each developing/testing >various scripts. I then need to somehow manage the process of the scripts >going from development to testing to production, which is the workflow. At >the same time, I have to implement/enforce some form of Access control for >the users, so they don't screw up with files that they shouldn't touch... > >If there's anyone on this list that I could talk to, I'd appreciate it.. . . . We have implemented workflow for several government agencies that have moved their granting process on-line. These are GREAT applications, in that they're such an advance on the paper-and-FAX systems they succeed. What you describe certainly is feasible with Zope. In this regard, the nicest thing about Zope is that it's sufficiently general-purpose and reliable that you won't be "caught" in a dead end. The bad thing is that it simply isn't as polished for specific domains as one might like, and as seems to have been achieved in some other communities ("shopping carts" for PHP, for example--note I'm not ratifying their security). Start by reading the documentation other follow-ups have al- ready mentioned. From m.yanowitz at kearfott.com Wed May 24 16:19:01 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Wed, 24 May 2006 16:19:01 -0400 Subject: Python Version Testing Tool? In-Reply-To: <1148495974.975395.12920@i40g2000cwc.googlegroups.com> Message-ID: <HGEOKIAPAMCIFPPBDALKOEKJCAAA.m.yanowitz@kearfott.com> Hello: Is there a version testing tool available for Python such that I can check to see if my code will still run in versions 2.2, 2.3, 2.4.3, and 1.1 (for example) (or whatever) without having to install all these different versions on my computer? Thanks in advance: Michael Yanowitz From john at castleamber.com Sun May 21 02:44:45 2006 From: john at castleamber.com (John Bokma) Date: 21 May 2006 06:44:45 GMT Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> <Xns97C9ADA375FCCcastleamber@130.133.1.4> <lFMbg.19879$Lm5.7431@newssvr12.news.prodigy.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> <Xns97C9B5C01B657castleamber@130.133.1.4> <1148172321.824018.207540@j33g2000cwa.googlegroups.com> <Xns97C9EDC00DC96castleamber@130.133.1.4> <1148189521.803453.142860@j73g2000cwa.googlegroups.com> Message-ID: <Xns97CA11C302CC1castleamber@130.133.1.4> "George Sakkis" <george.sakkis at gmail.com> wrote: > John Bokma wrote: >> "George Sakkis" <george.sakkis at gmail.com> wrote: [ Xah Lee ] >> [1] He is looking for another hoster btw. > > This must feel really empowering huh ? I am sure I've had quite some help. Also, you made quite a mistake. I have 0 power, I just reported what I saw: repeatedly cross posting to 5 groups for the sole purpose of trolling and spamvertizing a website. And I am afraid that 5 is a limit set by Google Groups, not by your kook buddy. Funny though, how you have a problem with a thread that side steps to Perl only for 4 or 5 postings, but have no problem with a hit & run post in 5 groups to spamvertize a site. Have fun with the pondering btw. -- 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 sybrenUSE at YOURthirdtower.com.imagination Wed May 3 15:02:42 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 3 May 2006 21:02:42 +0200 Subject: Gettings subdirectories References: <e3au5u$drm$1@news.in.tum.de> Message-ID: <slrne5hvii.ghi.sybrenUSE@schuimige.stuvel.eu> Florian Lindner enlightened us with: > how can I get all subdirectories of a given directories? > os.listdir() gives me all entries and I've found no way to tell if > an object is a file or a directory. Why, doesn't your os.path.isdir() function work? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From csw at k12hq.com Fri May 19 17:32:50 2006 From: csw at k12hq.com (Christopher Weimann) Date: Fri, 19 May 2006 17:32:50 -0400 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <Xns97C8546247008duncanbooth@127.0.0.1> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <mailman.5801.1147872851.27775.python-list@python.org> <pan.2006.05.18.07.37.44.126396@internode.on.net> <Xns97C760A237F69duncanbooth@127.0.0.1> <pan.2006.05.19.06.29.29.262257@internode.on.net> <Xns97C8546247008duncanbooth@127.0.0.1> Message-ID: <20060519213249.GA16975@tektite.k12usa.internal> On 05/19/2006-07:18AM, Duncan Booth wrote: > > My experience of programming with either spaces or tabs has taught me > that tabs are evil not for themselves, but simply because no matter how > hard you try they always end up being mixed with spaces. > Swap the word 'tabs' for the word 'spaces' and you get... My experience of programming with either tabs or spaces has taught me that spaces are evil not for themselves, but simply because no matter how hard you try they always end up being mixed with tabs. Which is just as vaild as the un-swapped paragraph. Both versions express a bias. The first is biased in favor of spaces. The second is biased in favor of tabs. Neither have any useful content. Mixing is bad but that fact doesn't favor spaces OR tabs. From rpdooling at gmail.com Wed May 10 11:45:17 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 10 May 2006 08:45:17 -0700 Subject: reusing parts of a string in RE matches? In-Reply-To: <mailman.5557.1147274047.27775.python-list@python.org> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> Message-ID: <1147275917.411823.15150@j73g2000cwa.googlegroups.com> Right about now somebody usually jumps in and shows you how to do this without using regex and using string methods instead. I'll watch. rd From rNOSPAMon at flownet.com Fri May 19 18:55:24 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 19 May 2006 15:55:24 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> <1147998139.268318.315250@y43g2000cwc.googlegroups.com> <rNOSPAMon-AC0C9B.18040918052006@news.gha.chartermi.net> <1148001708.183506.296240@g10g2000cwb.googlegroups.com> <rNOSPAMon-96A79F.00032619052006@news.gha.chartermi.net> <1148029074.083644.112370@i40g2000cwc.googlegroups.com> <1148038129.231027.118010@g10g2000cwb.googlegroups.com> Message-ID: <rNOSPAMon-0F2165.15552419052006@news.gha.chartermi.net> In article <1148038129.231027.118010 at g10g2000cwb.googlegroups.com>, "Serge Orlov" <Serge.Orlov at gmail.com> wrote: > Serge Orlov wrote: > > Ron Garret wrote: > > > In article <1148001708.183506.296240 at g10g2000cwb.googlegroups.com>, > > > "Serge Orlov" <Serge.Orlov at gmail.com> wrote: > > > > > > > Ron Garret wrote: > > > > > > > I'm using an OS X terminal to ssh to a Linux machine. > > > > > > > > > > > > In theory it should work out of the box. OS X terminal should set > > > > > > enviromental variable LANG=en_US.utf-8, then ssh should transfer > > > > > > this > > > > > > variable to Linux and python will know that your terminal is utf-8. > > > > > > Unfortunately AFAIK OS X terminal doesn't set that variable and > > > > > > most > > > > > > (all?) ssh clients don't transfer it between machines. As a > > > > > > workaround > > > > > > you can set that variable on linux yourself . This should work in > > > > > > the > > > > > > command line right away: > > > > > > > > > > > > LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > > > > > > > > > Or put the following line in ~/.bashrc and logout/login > > > > > > > > > > > > export LANG=en_US.utf-8 > > > > > > > > > > No joy. > > > > > > > > > > ron at www01:~$ LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > > Traceback (most recent call last): > > > > > File "<string>", line 1, in ? > > > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > > > > > position 0: ordinal not in range(128) > > > > > ron at www01:~$ > > > > > > > > What version of python and what shell do you run? What the following > > > > commands print: > > > > > > > > python -V > > > > echo $SHELL > > > > $SHELL --version > > > > > > ron at www01:~$ python -V > > > Python 2.3.4 > > > ron at www01:~$ echo $SHELL > > > /bin/bash > > > ron at www01:~$ $SHELL --version > > > GNU bash, version 2.05b.0(1)-release (i386-pc-linux-gnu) > > > Copyright (C) 2002 Free Software Foundation, Inc. > > > ron at www01:~$ > > > > That's recent enough. I guess the distribution you're using set LC_* > > variables for no good reason. Either unset all enviromental variables > > starting with LC_ and set LANG variable or overide LC_CTYPE variable: > > > > LC_CTYPE=en_US.utf-8 python -c "print unichr(0xbd)" > > > > Should be working now :) > > I've pulled myself together and installed linux in vwware player. > Apparently there is another way linux distributors can screw up. I > chose debian 3.1 minimal network install and after answering all > installation questions I found that only ascii and latin-1 english > locales were installed: > $ locale -a > C > en_US > en_US.iso88591 > POSIX > > In 2006, I would expect utf-8 english locale to be present even in > minimal install. I had to edit /etc/locale.gen and run locale-gen as > root. After that python started to print unicode characters. That's it. Thanks! rg From bignose+hates-spam at benfinney.id.au Wed May 3 18:07:14 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 May 2006 08:07:14 +1000 Subject: scope of variables References: <874q06bz4c.fsf@localhost.localdomain> Message-ID: <87ac9ydap9.fsf@benfinney.id.au> Gary Wessle <phddas at yahoo.com> writes: > is the code below correct? It's best to post an example that you've tried yourself, and that is small but completely demonstrates the issue in question. > b = 3 > def adding(a) > print a + b This, for example, would fail the syntax check (the 'def' statement needs a trailing colon). After that's fixed, the code runs, but shows no output. A complete, minimal, working example will help people answer your question. -- \ "[W]e are still the first generation of users, and for all that | `\ we may have invented the net, we still don't really get it." | _o__) -- Douglas Adams | Ben Finney From dadapapa at googlemail.com Tue May 16 12:22:00 2006 From: dadapapa at googlemail.com (Harold Fellermann) Date: 16 May 2006 09:22:00 -0700 Subject: Help System For Python Applications In-Reply-To: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> References: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> Message-ID: <1147796519.705478.151550@j33g2000cwa.googlegroups.com> I usually go for the webbrowser package that allows me to launch the systems webbrowser and opens my html help files. It is really simple: >>> import webbrowser >>> webbrowser.open("file:///path_to/help.html#topic") and thats all there is to do. - harold - From fredrik at pythonware.com Thu May 4 16:55:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 22:55:13 +0200 Subject: using urllib with ftp? References: <oqt6g.2048$No6.44127@news.tufts.edu> Message-ID: <e3dpnk$crm$1@sea.gmane.org> John Salerno wrote: > I've tried this already and it seems to work, but I'm curious if it's > okay to use urllib when trying to access a url that begins with ftp:// > instead of http://. Does this matter? It's only a text file, so it's not > really an FTP server I'm accessing, I don't think. I wasn't sure if > using ftplib would be overkill in this case, or if you even could use it > at all if you just want to get the page itself (the txt file). from the urllib documentation: Currently, only the following protocols are supported: HTTP, (versions 0.9 and 1.0), Gopher (but not Gopher-+), FTP, and local files. </F> From thomasbartkus at comcast.net Mon May 8 14:41:00 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Mon, 8 May 2006 13:41:00 -0500 Subject: python rounding problem. References: <mailman.5443.1146987087.27775.python-list@python.org> <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> Message-ID: <fPednfg-wOsvDcLZRVn-vQ@telcove.net> "Gary Wessle" <phddas at yahoo.com> wrote in message news:87ody9amsd.fsf at localhost.localdomain... > Erik Max Francis <max at alcyone.com> writes: > > > chun ping wang wrote: > > > > > Hey i have a stupid question. > > > How do i get python to print the result in only three decimal > > > place... > > > Example>>> round (2.995423333545555, 3) > > > 2.9950000000000001 > > > but i want to get rid of all trailing 0's..how would i do that? > > > > Floating point arithmetic is inherently imprecise. This is not a > > Python problem. > > does python support true rations, which means that 1/3 is a true > one-third and not 0.333333333 rounded off at some arbitrary precision? At risk of being boring ;-) - Python supports both rational and irrational numbers as floating point numbers the way any language on any digital computer does - imprecisely. A "true" (1/3) can only be expressed as a fraction. As soon as you express it as a floating point - you are in a bit of trouble because that's impossible. You can not express (1/3) as a floating point in Python any more than you can do it with pencil and paper. You can be precise and write "1/3" or you can surrender to arithmetic convenience and settle for the imprecise by writing "0.333333333", chopping it off at some arbitrary precision. Which is exactly what you did in your post ;-) Thomas Bartkus From bussieremaillist at gmail.com Wed May 24 02:36:20 2006 From: bussieremaillist at gmail.com (bussiere maillist) Date: Wed, 24 May 2006 08:36:20 +0200 Subject: python and QRcode ? Message-ID: <8a8f62c80605232336m4c1a2f0eo1a4f2f59c0ffe67@mail.gmail.com> i'am looking for some module and programs in ptyhon for making qrcode (special kind of barcode) But i only found documentation and programs in japanese. Does it exist program and documentation for python in qrcode in english ? regards Bussiere -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060524/6d6cad35/attachment.html> From deets at nospam.web.de Fri May 19 05:32:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 May 2006 11:32:47 +0200 Subject: Specific performance question - Python vs. Java References: <1148029505.407594.151900@i40g2000cwc.googlegroups.com> Message-ID: <4d5hm6F18u8rvU1@uni-berlin.de> reinsn wrote: > Hi, > > I have got a specific question on performance: Is the overhead of > object creation in Python lower than in Java? I mean, I would argue, in > Java by object creation, the complete class is the model and all > methods and attributes are generated for the object. > In Python, methods and objects are only generated, if reached: so could > this represent a performance advantage for Python? No, this is a misunderstanding on your side. In all OO-languages, the code (methods) are separated from the instance. Thus creating an object results in memory allocation _only_ for the members of that object, not any methods! In python, this boils down to a dictionary holding the members, JAVA/C++ allocate whatever the class makes them to. So, no, no performance advantage. Diez From johnzenger at gmail.com Wed May 3 16:39:08 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 3 May 2006 13:39:08 -0700 Subject: Possibly dumb question about dicts and __hash__() In-Reply-To: <1146686634.117498.313470@j73g2000cwa.googlegroups.com> References: <e3b0c0$g8o$1@news.lysator.liu.se> <1146686634.117498.313470@j73g2000cwa.googlegroups.com> Message-ID: <1146688748.486494.111430@j33g2000cwa.googlegroups.com> Actually, come to think of it, __str__ works just as well. >>> class NamedThing(object): def __init__(self, name): self.name = name def __str__(self): return self.name >>> d = {} >>> d[a] = 1 >>> d[b] = 50 >>> d {<__main__.NamedThing object at 0x00C528D0>: 1, <__main__.NamedThing object at 0x00C529B0>: 50} >>> d[a] 1 >>> d[b] 50 This is what you should use, instead of my first answer. From the docs for __repr__: "If at all possible, this should look like a valid Python expression that could be used to recreate an object with the same value (given an appropriate environment). If this is not possible, a string of the form "<...some useful description...>" should be returned. ... This is typically used for debugging, so it is important that the representation is information-rich and unambiguous." johnzenger at gmail.com wrote: > Use __repr__. Behold: > > >>> class NamedThing(object): > def __init__(self, name): > self.name = name > def __repr__(self): > return self.name > > >>> a = NamedThing("Delaware") > >>> b = NamedThing("Hawaii") > >>> d = {} > >>> d[a] = 1 > >>> d[b] = 50 > >>> print d > {Delaware: 1, Hawaii: 50} > >>> d[a] > 1 > >>> d[b] > 50 > > Although this is a bit illegal, because repr is not supposed to be used > this way. > > Joel Hedlund wrote: > > Hi! > > > > There's one thing about dictionaries and __hash__() methods that puzzle me. I > > have a class with several data members, one of which is 'name' (a str). I would > > like to store several of these objects in a dict for quick access > > ({name:object} style). Now, I was thinking that given a list of objects I might > > do something like > > > > d = {} > > for o in objects: > > d[o] = o > > > > and still be able to retrieve the data like so: > > > > d[name] > > > > if I just defined a __hash__ method like so: > > > > def __hash__(self): > > return self.name.__hash__() > > > > but this fails miserably. Feel free to laugh if you feel like it. I cooked up a > > little example with sample output below if you care to take the time. > > > > Code: > > --------------------------------------------------------------- > > class NamedThing(object): > > def __init__(self, name): > > self.name = name > > def __hash__(self): > > return self.name.__hash__() > > def __repr__(self): > > return '<foo>' > > name = 'moo' > > o = NamedThing(name) > > print "This output puzzles me:" > > d = {} > > d[o] = o > > d[name] = o > > print d > > print > > print "If I wrap all keys in hash() calls I'm fine:" > > d = {} > > d[hash(o)] = o > > d[hash(name)] = o > > print d > > print > > print "But how come the first method didn't work?" > > --------------------------------------------------------------- > > > > Output: > > --------------------------------------------------------------- > > This output puzzles me: > > {'moo': <foo>, <foo>: <foo>} > > > > If I wrap all keys in hash() calls I'm fine: > > {2038943316: <foo>} > > > > But how come the first method didn't work? > > --------------------------------------------------------------- > > > > I'd be grateful if anyone can shed a litte light on this, or point me to some > > docs I might have missed. > > > > Also: > > Am I in fact abusing the __hash__() method? If so - what's the intended use of > > the __hash__() method? > > > > Is there a better way of implementing this? > > > > I realise I could just write > > > > d[o.name] = o > > > > but this problem seems to pop up every now and then and I'm curious if there's > > some neat syntactic trick that I could legally apply here. > > > > Thanks for your time! > > /Joel Hedlund From defcon8 at gmail.com Mon May 15 12:03:38 2006 From: defcon8 at gmail.com (defcon8) Date: 15 May 2006 09:03:38 -0700 Subject: saving file permission denied on windows In-Reply-To: <1147708797.746442.19220@j73g2000cwa.googlegroups.com> References: <1147708797.746442.19220@j73g2000cwa.googlegroups.com> Message-ID: <1147709018.186441.245100@v46g2000cwv.googlegroups.com> Have you checked the persmissions to the folder? You can look from the properties of the folder to see. From ptmcg at austin.rr._bogus_.com Wed May 17 12:08:27 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 17 May 2006 16:08:27 GMT Subject: Pyparsing: Grammar Suggestion References: <mailman.5814.1147879481.27775.python-list@python.org> Message-ID: <%THag.33761$Qq.20842@tornado.texas.rr.com> "Khoa Nguyen" <khoa.coffee at gmail.com> wrote in message news:mailman.5814.1147879481.27775.python-list at python.org... I am trying to come up with a grammar that describes the following: record = f1,f2,...,fn END_RECORD All the f(i) has to be in that order. Any f(i) can be absent (e.g. f1,,f3,f4,,f6 END_RECORD) Number of f(i)'s can vary. For example, the followings are allowed: f1,f2 END_RECORD f1,f2,,f4,,f6 END_RECORD Any suggestions? Thanks, Khoa -------- pyparsing includes a built-in expression, commaSeparatedList, for just such a case. Here is a simple pyparsing program to crack your input text: data = """f1,f2,f3,f4,f5,f6 END_RECORD f1,f2 END_RECORD f1,f2,,f4,,f6 END_RECORD""" from pyparsing import commaSeparatedList for tokens,start,end in commaSeparatedList.scanString(data): print tokens This returns: ['f1', 'f2', 'f3', 'f4', 'f5', 'f6 END_RECORD'] ['f1', 'f2 END_RECORD'] ['f1', 'f2', '', 'f4', '', 'f6 END_RECORD'] Note that consecutive commas in the input return empty strings at the corresponding places in the results. Unfortunately, commaSeparatedList embeds its own definition of what is allowed between commas, so the last field looks like it always has END_RECORD added to the end. We could copy the definition of commaSeparatedList and exclude this, but it is simpler just to add a parse action to commaSeparatedList, to remove END_RECORD from the -1'th list element: def stripEND_RECORD(s,l,t): last = t[-1] if last.endswith("END_RECORD"): # return a copy of t with last element trimmed of "END_RECORD" return t[:-1] + [last[:-(len("END_RECORD"))].rstrip()] commaSeparatedList.setParseAction(stripEND_RECORD) for tokens,start,end in commaSeparatedList.scanString(data): print tokens This returns: ['f1', 'f2', 'f3', 'f4', 'f5', 'f6'] ['f1', 'f2'] ['f1', 'f2', '', 'f4', '', 'f6'] As one of my wife's 3rd graders concluded on a science report - "wah-lah!" Python also includes a csv module if this example doesn't work for you, but you asked for a pyparsing solution, so there it is. -- Paul From ptmcg at austin.rr._bogus_.com Fri May 19 14:56:53 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 18:56:53 GMT Subject: number of different lines in a file References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> <1148063935.859890.173230@u72g2000cwu.googlegroups.com> Message-ID: <Vxobg.46856$CH2.5271@tornado.texas.rr.com> "Paddy" <paddy3118 at netscape.net> wrote in message news:1148063935.859890.173230 at u72g2000cwu.googlegroups.com... > If the log has a lot of repeated lines in its original state then > running uniq twice, once up front to reduce what needs to be sorted, > might be quicker? > > uniq log_file | sort| uniq | wc -l > > - Pad. > Why would the second running of uniq remove any additional lines that weren't removed in the first pass? For that matter, if this is a log file, wont every line have a timestamp, making duplicates extremely unlikely? -- Paul From laurent.pointal at limsi.fr Mon May 29 09:47:46 2006 From: laurent.pointal at limsi.fr (Laurent Pointal) Date: Mon, 29 May 2006 15:47:46 +0200 Subject: Running Python scripts under a different user In-Reply-To: <mailman.6252.1148663883.27775.python-list@python.org> References: <mailman.6246.1148657024.27775.python-list@python.org> <4dolv4F1b8m87U1@uni-berlin.de> <447725C3.2000901@designaproduct.biz> <mailman.6252.1148663883.27775.python-list@python.org> Message-ID: <e5eu27$njm$1@upsn250.cri.u-psud.fr> Bernard Lebel a ?crit : > On 5/26/06, Laszlo Nagy <gandalf at designaproduct.biz> wrote: >> For Windows, you can use the 'runas.exe' program. But it requires a >> password too. >> >> From what you wrote, I think that you need to change architecture. You >> should write your own service rather than write tricky programs. This >> way you can develop your own security system, and restrict access to >> specific files/programs. You can write tools that can connect to your >> service. The service program can be ran on the background, with >> sufficient privileges. How does it sound? > > [Bermard] Any ressource you could point me to as to write services? > I'm totally unexperienced with that. As you run under Unix, you may be interrested into the daemon.py script. See Unix Daemon in page http://homepage.hispeed.ch/py430/python/index.html And too: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/278731 See also google links for python + daemon A+ Laurent. From mail at microcorp.co.za Sun May 14 13:28:31 2006 From: mail at microcorp.co.za (H J van Rooyen) Date: Sun, 14 May 2006 19:28:31 +0200 Subject: The best way of calculating and adding a block check character to a string Message-ID: <003001c6777b$f9b66200$03000080@hendrik> Hi All I am new to this language, and in using it to drive a serial port, I need to calculate classic block check characters - for the veterans amongst you - think "Burroughs Poll Select" or "Uniscope"... This is a program fragment that puts the string in an array of Bytes - is there a better way to do this job? - the annotated action starts after the ascii definitions of the first 32 control characters... # some ascii control character values defined nul = '\x00' # null char soh = '\x01' # start of header stx = '\x02' # start of text etx = '\x03' # end of text eot = '\x04' # end of transmission enq = '\x05' # enquiry ack = '\x06' # ack bel = '\x07' # bell char bs = '\x08' # backspace ht = '\x09' # horizontal tab lf = '\x0a' # line feed - linux newline vt = '\x0b' # vertical tab ff = '\x0c' # form feed cr = '\x0d' # carriage return so = '\x0e' # shift out si = '\x0f' # shift in dle = '\x10' # data link escape dc1 = '\x11' # data control 1 - aka xon dc2 = '\x12' # data control 2 dc3 = '\x13' # data control 3 - aka xoff dc4 = '\x14' # data control 4 nak = '\x15' # negative acknowledgement syn = '\x16' # sync char etb = '\x17' # end of transmission block can = '\x18' # cancel em = '\x19' # end of message sub = '\x1a' # sub esc = '\x1b' # escape fs = '\x1c' # field separator gs = '\x1d' # group separator rs = '\x1e' # record separator us = '\x1f' # unit separator # some strings defined poll = soh + 'P' + 'A' + stx + etx # rudimentary poll string bcc = nul # here starts the trouble: ar = array.array('B', poll) bccint = ar[0] # this is prolly dicey - what type and how big is this? for x in ar[1:]: bccint = bccint ^ x # this works, but is it the best way? print repr(bccint) ar.append(bccint) # this seems so left-handed - we make a string, then we put it in an array, # then we iterate over the array elements to calculate the # bcc (block check character), then we add it to the array - then we should # really make it all a string again to write it to the port... # it would be nice to be able to write: # nul = '\x00' # bcc = nul # poll = "some arbitrary string" # bcc = bcc ^ (x for x in poll[0:]) # calculate and # poll = poll + bcc # add the bcc to the string # port.write(poll) # and write the lot to the port # port.flush() # and on the way in: # numchars = 5 # some magic number depending on what we are expecting back # response = port.read(numchars) # or a more complicated char at a time function # bcc = nul # bcc = bcc ^ (x for x in response[0:]) # if bcc != nul: # error_routine(response) # so we would stay working with strings - the stuff from the port # coming in is a string, and we need a string to write again... # *grin* but of course the xor and strong typing won't allow the # string - to say nothing of the iterator... # here is a loop, demonstrating getting an arbitrary lf terminated string in, # and writing the fixed one with a bcc tagged on out as a response, along # with some debug printing. s = esc + '@' + esc + 'v' + lf # the line we are searching for while True: try: buffer = port.readline() # read in as a string, (unblocked) except KeyboardInterrupt: print "\n^C - Returning to Shell - Error is:", KeyboardInterrupt ret_val = 1 # ^C while waiting for input return buffer, ret_val # go out on error except IOError: continue # IOError on input - no record available if buffer == '': # empty string is rubbish - ignore it continue rawfile.write(buffer) # Keep the record as read print repr(buffer) # show how python sees it print repr(s) # show what our target looks like if s == buffer: print 'Bingo !!!' ar.tofile(port) # luckily there is this method, port.flush() # so we don't have to convert back to string... This lot was cut and pasted from the little test program I am using to debug the port stuff - there may be tab issues - the question I suppose has to do with the types that the xor supports, and I suppose I am saying that it would be nice if a single byte string (also from an iterator) would be supported by the xor operator... ( maybe a single char string...there's a difference between ascii and unicode...) As my program stands it works, but it seems long - winded and ugly.... - Hendrik van Rooyen -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060514/ea17ecff/attachment.html> From john at castleamber.com Sun May 21 19:14:59 2006 From: john at castleamber.com (John Bokma) Date: 21 May 2006 23:14:59 GMT Subject: Programming language productivity References: <mailman.5923.1148009336.27775.python-list@python.org> <Xns97C7E9ACF911Bcastleamber@130.133.1.4> <e4qeh9$l27$1@online.de> Message-ID: <Xns97CAB9A5A8300castleamber@130.133.1.4> Peter Maas <peter.maas at somewhere.com> wrote: > John Bokma wrote: >> Also note that Python programmers write more lines/hour which they >> need to finish in the same time as Perl programmers :-D. > > You probably want to say that a Python program tends to have more > lines than an equivalent Perl program. No, I was just making a joke based on the graphs given on the site mentioned earlier. > I think that a LOC comparison between a language that enforces line > breaks and another language that enables putting an lots of code in > one line doesn't make much sense. I wonder why comparisons aren't made > in terms of word count. Word count would include literals, constants, > variables, keywords, operators, bracket- and block delimiter pairs. No idea, I consider comparisons like this quite meaningless when people attempt to use them as a kind of quality measurement. -- 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 kentilton at gmail.com Tue May 16 16:08:40 2006 From: kentilton at gmail.com (Ken Tilton) Date: Tue, 16 May 2006 16:08:40 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <d6l3bf97v2t.fsf@vipunen.hut.fi> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> <d6lu07r7u0u.fsf@vipunen.hut.fi> <44681F95.9040400@gmail.com> <d6lpsif6sku.fsf@vipunen.hut.fi> <O15ag.337$RM1.120@fe12.lga> <d6l3bf97v2t.fsf@vipunen.hut.fi> Message-ID: <446A3148.4020801@gmail.com> Lasse Rasinen wrote: > Ken Tilton <kentilton at gmail.com> writes: > > >>If you want to insist on how perfect your code is, please go find >>ltktest-cells-inside.lisp in the source you downloaded and read the long >>comment detailing the requirements I have identified for "data integrity". >>Then (a) tell me how your code fails at integrity, (b) fix it, and (c) >>tell me again how easy Cells is. :) > > > Found it and read it; it was most enlightening. I claim my system fulfills > the first three requirements(*), while most likely failing gloriously on > the two last ones. <sigh> From #1: "recompute all and (for efficiency) only state computed off X (directly or indirectly through some intermediate datapoint)" Bzzzt! Another 47hrs, directions from a mentor, and a reference implementation and you /still/ do not even understand the requirements, let alone have a working port. The good news is that it is not an integrity requirement that is being missed, it is the efficiency requirement I snuck in there. The bad news is, see below. Want to find the efficiency shortcoming yourself, or should I tell you? You are entitled to the latter given the rules of the game (simulating a pythonista student making off with five thousand undeserved dollars). :) > > I'll postpone (b) while I've had a chance to think it over(**), but in the > face of the evidence I'm willing to admit my earlier work estimates (which > should have had a smiley next to them anyway ;-) were in error. Aw, shucks, then I will admit that, before today, I never actually looked at your code. :) Well, I followed the URL and glanced at it, but I missed the use of the timestamp. Speaking of which, Holy Granularity, Batman! You use Time.time() to determine currency of a computation?!: "time() Return the time as a floating point number expressed in seconds since the epoch, in UTC. Note that even though the time is always returned as a floating point number, not all systems provide time with a better precision than 1 second." One /second/?!!!!! Exactly how slow is Python? I know you guys love that issue as much as Lispniks. In un-compiled Lisp: CTK(4): (loop repeat 2 do (print (get-internal-real-time))) 464033837 464033837 And you have no idea how slow PRINT is. btw, I thought Python was portable. What is with the Time class and "not all systems..."? Check out the Lisp: (defun zoom () (loop with start = (get-internal-real-time) while (= start (get-internal-real-time)) count 1 into cities-destroyed finally (format t "~a cities destroyed in 1/~a of a second" cities-destroyed internal-time-units-per-second))) internal-time-units-per-second is (from the standard): "Constant Value: A positive integer, the magnitude of which is implementation-dependent. " So we vary, too, but my Lisp has to tell me so I can normalize. Anyway, running that repeatedly I get pretty wild variation. My high score is: CTK(18): 11637 cities destroyed in 1/1000 of a second My low was under a thousand! I guess I have to wait until we cross a millisecond boundary: (defun zoom () (symbol-macrolet ((now (get-internal-real-time))) (loop with start = (loop for mid = now while (= mid now) finally (return now)) while (= start now) count 1 into cities-destroyed finally (format t "~a cities destroyed in 1/~a of a second" cities-destroyed internal-time-units-per-second)))) Ok, now I am consistently taking out about 11.5k Russian cities. And you need to fix your system. Just use a counter -- does Python have bignums? if not, you'll have to worry about wrapping. (the sound you hear is a project schedule slipping. <g>) > > I won't admit to destroying Moscow, though. See (*). Sorry, you actually /have/ violated the data integrity requirement. You confess below to missing this one: "a corollary: should a client observer SETF a datapoint Y, all the above must happen with values current with not just X, but also with the value of Y /prior/ to the change to Y." Well, how can you claim integrity when some values do not get recalculated until the world has moved on to state N+2, if you will? State N+1 had the information that headed off the launch. Bye bye, Kremlin. The easiest way to construct such a scenario would be with an ephemeral cell. As you know... oops. Maybe you do not. Well, spreadsheets are kinda steady state in orientation. Given a world of other values, this is what my value should be. But what about events? You have been using your version of PyCells in real-world applications for a while... oops. No you have not. Well, when you start trying to handle events from an event loop, you will discover a need to model events. (Trust your mentor.) You need a slot that can be assigned normally, propagate according to the above rules and regulations, and then revert to a null state but /not/ as a state change -- neither propagating nor observer-notifying. They are, like, ephemeral, aka, "fleeting". Now as I said, I got away with such holes for /years/ in all sorts of hairy applications of Cells before finally, well, falling down those holes, but it does happen so the holes are really worth filling in. And wait till you see what this does to your algorithm. :) I was even tempted to ban observer writebacks, if you will, but I think someday I will write an application driven by such things, periodically calling Tcl_DoOneEvent to keep in touch with the outside world. Which means we cannot propagate on the stack, as your system would. <slip...slip...slip> > > (*) All values depending on the changed cell are marked as invalid before > anything else is done; trying to access an invalid value forces a > recalculation which also marks the cell as valid again, and so on > recursively down to cells that have already converged to a proper value. > > Setting input cells in callbacks will f*** that up, though. > > (**) Which probably doesn't occur until July or something ;( > > >>>[Decorator example] >> >>Wow. I thought Python did not have macros. > > > Calling decorators macros is an insult to CL macros ;-) > All they do is make it a bit more convinent to apply transformations to > functions, or as the abstract in the original spec[1] says: > > The current method for transforming functions and methods (for instance, > declaring them as a class or static method) is awkward and can lead to > code that is difficult to understand. Ideally, these transformations > should be made at the same point in the code where the declaration > itself is made. > > >>This project is looking better all the time. Thx. > > > In that case I have something else you might like: The "with" Statement[2] I had high hopes for that when I saw it, then was not sure. The good news is that Serious Pythonistas will be doing this, not me. I will just help them grok the requirements (and hope Ryan is taking notes <g>). > > From the abstract: > This PEP adds a new statement "with" to the Python language to make > it possible to factor out standard uses of try/finally statements. > > In practice one can use it implement some of the with-macros in a pretty > straightforward manner, especially those that are expanded into > (call-with-* (lambda () , at body)). I believe the previously advertised > with-integrity macro could also be made to work in a satisfying manner. > > To quote from the examples: > > 2. A template for opening a file that ensures the file is closed > when the block is left: > > @contextmanager > def opened(filename, mode="r"): > f = open(filename, mode) > try: > yield f > finally: > f.close() > > Used as follows: > > with opened("/etc/passwd") as f: > for line in f: > print line.rstrip() > > Does that last part look familiar to you?) > > The problem with this is that this is Python 2.5 syntax, which currently > appears to be planned for release in late August, a bit late for SoC. > Alpha(*) versions are available, so if you want to take a chance and live > on the bleeding edge, you can probably gain from it. That is up to the Pythonistas. As a rule, if there is advantage to be had, I go with the bleeding edge until it proves to me it is unusable. Thx for the heads up. Nice job on the code, btw. A lot better than my first efforts. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From kent at kentsjohnson.com Thu May 11 06:06:22 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Thu, 11 May 2006 06:06:22 -0400 Subject: Memory leak in Python In-Reply-To: <1147302164.557634.177170@v46g2000cwv.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <ccl062h5tc24b4qe3d66b7hvh7ujgrklcp@4ax.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> <slrne63ae3.96g.sybrenUSE@schuimige.stuvel.eu> <1147302164.557634.177170@v46g2000cwv.googlegroups.com> Message-ID: <44630c14$1_1@newspeer2.tds.net> diffuser78 at gmail.com wrote: > Sure, are there any available simulators...since i am modifying some > stuff i thought of creating one of my own. But if you know some > exisiting simlators , those can be of great help to me. http://simpy.sourceforge.net/ From aleaxit at yahoo.com Tue May 2 22:45:10 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Tue, 2 May 2006 19:45:10 -0700 Subject: Setting a module package to use new-style classes References: <1146496624.798907.327060@e56g2000cwe.googlegroups.com> <mailman.5196.1146519894.27775.python-list@python.org> Message-ID: <1hep9yl.1jolai11uq5ilbN%aleaxit@yahoo.com> Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > "Panos Laganakos" <panos.laganakos at gmail.com> writes: > > > Is there a way to have a whole module package use the new-style > > classes, without having to specify it per module-file or even worse, > > per class definition? > > TTBOMK, you do that with a single statement per module, before any > class definitions: > > __metaclass__ = object Almost: the assignment you need is __metaclass__ = type but yes, it has to be per-module. Alex From maxerickson at gmail.com Tue May 30 09:57:12 2006 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 30 May 2006 13:57:12 +0000 (UTC) Subject: create a text file References: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> <1148983561.469393.262430@j73g2000cwa.googlegroups.com> Message-ID: <Xns97D3657BA981Emaxericksongmailcom@80.91.229.5> "per9000" <per9000 at gmail.com> wrote: > # w is for writing > myfile = open('theoutfile',w) That won't work, the second argument to open needs to be a string: myfile = open('theoutfile', 'w') max From stijndesaeger at gmail.com Fri May 5 03:34:17 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 00:34:17 -0700 Subject: Tuple assignment and generators? In-Reply-To: <1146813639.825116.21780@g10g2000cwb.googlegroups.com> References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> Message-ID: <1146814457.388702.263120@i39g2000cwa.googlegroups.com> Wow, so, to see if I understand correctly: >>> r = 0 >>> s = 0 >>> t = 100001 >>> u = 100001 >>> r == s True >>> t == u True >>> r is s True >>> t is u False >>> ... ? what the...? does anybody else get mighty uncomfortable about this? s. From claudio.grondi at freenet.de Tue May 16 08:09:10 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 16 May 2006 14:09:10 +0200 Subject: Large Dictionaries In-Reply-To: <1147772420.405097@teuthos> References: <1147699064.107490@teuthos> <e49va0$m72$1@newsreader3.netcologne.de> <1147772420.405097@teuthos> Message-ID: <e4cfd3$rq$1@newsreader3.netcologne.de> Chris Foote wrote: > Claudio Grondi wrote: > >> Chris Foote wrote: >> >>> p.s. Disk-based DBs are out of the question because most >>> key lookups will result in a miss, and lookup time is >>> critical for this application. >>> >> Python Bindings (\Python24\Lib\bsddb vers. 4.3.0) and the DLL for >> BerkeleyDB (\Python24\DLLs\_bsddb.pyd vers. 4.2.52) are included in >> the standard Python 2.4 distribution. > > > However, please note that the Python bsddb module doesn't support > in-memory based databases - note the library documentation's[1] wording: > > "Files never intended to be preserved on disk may be created by > passing None as the filename." > > which closely mirrors the Sleepycat documentation[2]: > > "In-memory databases never intended to be preserved on disk > may be created by setting the file parameter to NULL." > > It does actually use a temporary file (in /var/tmp), for which > performance for my purposes is unsatisfactory: > > # keys dictionary metakit bsddb (all using psyco) > ------ ---------- ------- ----- > 1M 8.8s 22.2s 20m25s[3] > 2M 24.0s 43.7s N/A > 5M 115.3s 105.4s N/A > > Cheers, > Chris > > [1] bsddb docs: > http://www.python.org/doc/current/lib/module-bsddb.html > > [2] Sleepycat BerkeleyDB C API: > http://www.sleepycat.com/docs/api_c/db_open.html > > [3] Wall clock time. Storing the (long_integer, integer) key in string > form "long_integer:integer" since bsddb doesn't support keys that aren't > integers or strings. I have to admit, that I haven't wrote any own code to actually test this, but if 20m25s for storing of a single MByte of strings in a database table index column is really what you are getting, I can't get rid of the feeling, that there is something elementary wrong with your way doing it. Posting the code for your test cases appears to me to be the only option to see what is the reason for the mystery you are getting here (this will clarify also the other mysterious things considered by the posters to this thread up to now). Claudio From benji at benjiyork.com Fri May 5 11:39:33 2006 From: benji at benjiyork.com (Benji York) Date: Fri, 05 May 2006 11:39:33 -0400 Subject: Active Directory Authentication In-Reply-To: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> References: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> Message-ID: <445B71B5.90706@benjiyork.com> D wrote: > Is it possible to have Python authenticate with Active Directory? > Specifically what I'd like to do is have a user enter a > username/password, then have Python check the credentials with AD - if > what they entered is valid, for example, it returns a 1, otherwise a > 0.. Thanks! Install the Win32 extensions from http://starship.python.net/crew/skippy/win32/Downloads.html and do something like this: try: handle=win32security.LogonUser(username, None, password, win32security.LOGON32_LOGON_NETWORK, win32security.LOGON32_PROVIDER_DEFAULT) # We're not going to use the handle, just seeing if we can get it. handle.Close() return True except pywintypes.error, e: # Because of the sheer number of Windows-specific errors that can # occur here, we have to assume any of them mean that the # credentials were not valid. return False -- Benji York From caseyhHAMMER_TIME at istar.ca Sat May 13 02:56:47 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Sat, 13 May 2006 06:56:47 GMT Subject: Tail Call Optimization Decorator? References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> Message-ID: <4ura62hr2k2b8mse2npej2thgulhmojk55@4ax.com> Tail Call Optimization and Recursion are separate concepts! -- Regards, Casey From e.huda.ahmed at gmail.com Mon May 15 06:53:23 2006 From: e.huda.ahmed at gmail.com (huda ahmed) Date: Mon, 15 May 2006 13:53:23 +0300 Subject: please help me is sms with python Message-ID: <9815823b0605150353w78b80830q754f2a6c0c87db01@mail.gmail.com> hi >>>> please i need your help ..... how can i send sms from pc(windows xp) to mobile symbian 60 6630 by python i need your help please i hope you answer me as fast as u can thanks in advance...... From larry.bates at websafe.com Sat May 20 18:43:52 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 20 May 2006 17:43:52 -0500 Subject: python vs perl lines of code In-Reply-To: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> Message-ID: <446F9BA8.4040204@websafe.com> Edward Elliott wrote: > This is just anecdotal, but I still find it interesting. Take it for what > it's worth. I'm interested in hearing others' perspectives, just please > don't turn this into a pissing contest. > > I'm in the process of converting some old perl programs to python. These > programs use some network code and do a lot of list/dict data processing. > The old ones work fine but are a pain to extend. After two conversions, > the python versions are noticeably shorter. > > The first program does some http retrieval, sort of a poor-man's wget with > some extra features. In fact it could be written as a bash script with > wget, but the extra processing would make it very messy. Here are the > numbers on the two versions: > > Raw -Blanks -Comments > lines chars lines chars lines chars > mirror.py 167 4632 132 4597 118 4009 > mirror.pl 309 5836 211 5647 184 4790 > > I've listed line and character counts for three forms. Raw is the source > file as-is. -Blanks is the source with blank lines removed, including > lines with just a brace. -Comments removes both blanks and comment lines. > I think -Blanks is the better measure because comments are a function of > code complexity, but either works. > > By the numbers, the python code appears roughly 60% as long by line and 80% > as long by characters. The chars percentage being (higher relative to line > count) doesn't surprise me since things like list comprehensions and > explicit module calling produce lengthy but readable lines. > > I should point out this wasn't a straight line-for-line conversion, but the > basic code structure is extremely similar. I did make a number of > improvements in the Python version with stricter arg checks and better > error handling, plus added a couple minor new features. > > The second program is an smtp outbound filtering proxy. Same categories as > before: > > Raw -Blanks -Comments > lines chars lines chars lines chars > smtp-proxy.py 261 7788 222 7749 205 6964 > smtp-proxy.pl 966 24110 660 23469 452 14869 > > The numbers here look much more impressive but it's not a fair comparison. > I wasn't happy with any of the cpan libraries for smtp sending at the time > so I rolled my own. That accounts for 150 raw lines of difference. Another > 70 raw lines are logging functions that the python version does with the > standard library. The new version performs the same algorithms and data > manipulations as the original. I did do some major refactoring along the > way, but it wasn't the sort that greatly reduces line count by eliminating > redundancy; there is very little redundancy in either version. In any > case, these factors alone don't account for the entire difference, even if > you take 220 raw lines directly off the latter columns. > > The two versions were written about 5 years apart, all by me. At the time > of each, I had about 3 years experience in the given language and would > classify my skill level in it as midway between intermediate and advanced. > IOW I'm very comfortable with the language and library reference docs (minus > a few odd corners), but generally draw the line at mucking with interpreter > internals like symbol tables. > > I'd like to here from others what their experience converting between perl > and python is (either direction). I don't have the sense that either > language is particularly better suited for my problem domain than the > other, as they both handle network io and list/dict processing very well. > What are the differences like in other domains? Do you attribute those > differences to the language, the library, the programmer, or other > factors? What are the consistent differences across space and time, if > any? I'm interested in properties of the code itself, not performance. > > And just what is the question to the ultimate answer to life, the universe, > and everything anyway? ;) > Sorry, I don't buy this. I can write REALLY short programs that don't handle exceptions, don't provide for logging for debugging purposes, don't allow for future growth, etc. I find that 60% of my code has nothing to do with the actual algorithm or function I'm trying to accomplish. It has more to do with handling user's bad input, exceptions, recovering from hardware or communications failures, etc. Inexperienced programmers can write some pretty short programs that get the job done, but can't handle the real world. Also, many years ago I wrote a number of applications in APL. We often referred to programs written in APL as "write only code" because going back to read what you had written after-the-fact was very hard. You could write in one line of APL what takes 1000's of lines of C or even Python and it was pretty efficient also (for applications that needed to manipulate vectors or matrices). I understand what you are trying to say, but I can't support your conclusions as presented. -Larry Bates From robert.kern at gmail.com Wed May 24 12:32:58 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 24 May 2006 11:32:58 -0500 Subject: Scipy: vectorized function does not take scalars as arguments In-Reply-To: <1148480844.817338.69230@u72g2000cwu.googlegroups.com> References: <1148480844.817338.69230@u72g2000cwu.googlegroups.com> Message-ID: <e521ro$fmu$1@sea.gmane.org> ago wrote: > Once I vectorize a function it does not acccept scalars anymore. Es > > def f(x): return x*2 > vf = vectorize(f) > print vf(2) > > AttributeError: 'int' object has no attribute 'astype' > > Is this the intended behaviour? More or less. It would be nice if it transparently handled the scalars, too, so if you would like to work on that, we'd be happy to incorporate your changes. -- 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 Dennis.Benzinger at gmx.net Mon May 22 15:21:13 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Mon, 22 May 2006 21:21:13 +0200 Subject: Class probkem - getting msg that self not defined In-Reply-To: <37ocg.435$Sf2.424@newsread1.news.pas.earthlink.net> References: <12740frcoaju883@corp.supernews.com> <mFncg.420$Sf2.95@newsread1.news.pas.earthlink.net> <12742avhp3vmac8@corp.supernews.com> <37ocg.435$Sf2.424@newsread1.news.pas.earthlink.net> Message-ID: <44720f24$1@news.uni-ulm.de> wes weston schrieb: > Andrew Robert wrote: > >> wes weston wrote: >> >>> Andrew Robert wrote: >>> >>>> Hi Everyone, >>>> >>>> I am having a problem with a class and hope you can help. >>>> >>>> When I try to use the class listed below, I get the statement that self >>>> is not defined. >>>> test=TriggerMessage(data) >>> >>> self is not known here; only inside the class. >>> >>>> var = test.decode(self.qname) >>>> >> <snip> >> >> I guess I was barking up the wrong tree on that one. >> >> How would I go about getting the required values out of the class? >> >> Return self? > > > You can refer to the variables inside the class as test.version; > for example - as they are not protected. Or, you could add access > methods in the class like def GetVersion(self): return self.version > If you want to protect version, call it self.__version which mangles > the name from outside. > wes Or use the property function to define properties <http://docs.python.org/lib/built-in-funcs.html>. Dennis From telesphore4 at gmail.com Mon May 22 13:32:22 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 22 May 2006 10:32:22 -0700 Subject: Using metaclasses to inherit class variables In-Reply-To: <KvCdncoHsJN4bezZnZ2dnUVZ_sydnZ2d@comcast.com> References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> <1148315581.385405.204750@i40g2000cwc.googlegroups.com> <KvCdncoHsJN4bezZnZ2dnUVZ_sydnZ2d@comcast.com> Message-ID: <1148319142.378046.139930@u72g2000cwu.googlegroups.com> Much better. Thanks again. From erb_robert at yahoo.de Tue May 2 09:18:25 2006 From: erb_robert at yahoo.de (wyattroerb) Date: 2 May 2006 06:18:25 -0700 Subject: produce xml documents with python, and display it with xsl in a internet browser Message-ID: <1146575904.940968.31220@j73g2000cwa.googlegroups.com> Hi, like a lot of other newbies in xml i suffer from the various ways you can take for xml data processing in python. Here are my two major problems: Problem number one: A application written in python remote controls (demands actions) a HIL (Hardware in the loop) test stand and evaluate its actions (system reactions on the demand ) afterwards. The application puts all the results in a word protocol during the test. Now i would like to do the next step and represent the results in a proper data type document (xml - separate style from reference data). That means for python that it is in charge of provideing the necessary reference data for new xml documents and maybe more (changing xsl sheets if new test data elements were defined)?!?. I am not quite sure if it is better to specify a kind of source/basic xml document with all the >elements< and >attributes< according to the defined test results. In that case python has to modify the xml template with the new test results and save it as a new xml document (to keep the base template unchanged fort he next test). I suppose python could do the job with the help of DOM/SAX. I learned from reports in certain forums that it is also possible to use simply print statements. Does that mean i just have to do ordinary file handling? For example: f.open ("xml_file.xml", w) f.write ("<?xml version='1.0' encoding='ISO-8859-1'?>") f.write ("<!DOCTYPE fahrplan SYSTEM ,NachweisMetaDaten.dtd'">) f.write ("<?xml-stylesheet type='text/xsl' href='nachweismetadaten.xsl' ?>") f.write ("<meta_data>") f.write ("<section>") . . . f.close() If it works in the ordinary way what is the advantage and what is the disadvantage? Will I run in trouble if it comes to the transformation of tabs, and other xml related symbols. I guess with the file method i can create new elements and attributes in the python process/code without taking care of the basic xml template. Maybe it is also important to mention that i do not have the intention to process the test data in python after the test again. I would like to give the end-user (function developer in our lab) the possibility to check out the test data results with a internet browser and here is my second problem: To accomplish this i made a base xsl file which includes Buttons to give the end-user the possibility to call different xml templates (sort of clicking through the xml tree/displaying data result fragments). The trouble is that as far as i know the button feature ,,onclick" does not allow to call ,,xml:temlpates" just javascript functions. Is it just possible to use javascript functions with DOM methods if i would like to use buttons in html to extend and reduce displaying data from a xml document? If this is the case then the xml:template functions in xsl are useless, isn't it. I am quite sure that is not the case! Sorry that i have so many stupid questions but a fool with a tool is still a fool. Anyway! Many, many thanks for the slightest help. wyatt From fredrik at pythonware.com Fri May 26 05:13:24 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 May 2006 11:13:24 +0200 Subject: Can any body help me In-Reply-To: <1148624698.985455.57480@38g2000cwa.googlegroups.com> References: <1148621554.184942.155430@38g2000cwa.googlegroups.com> <1148624698.985455.57480@38g2000cwa.googlegroups.com> Message-ID: <e56grg$mmc$1@sea.gmane.org> Sidd wrote: > 1.Given a test file containing lines of words such as (abc, abb, > abd,abb, etc), write a script that prints, in order of frequency, how > many times each word appears in the file. > > Use dictionary datastructure in python and simple if-else statement. > Its simple give it a try. so what are you waiting for? ;-) (don't you think asking a mailing list for help with homework might be considered cheating? asking for help in figuring out why your attempt doesn't work might be okay, but asking someone else to write the code for you is a bit, well... I suggest starting out by looking at the relevant sections in the tutorial; dictionaries are discussed in the "data structures" chapter, and how to read stuff from files is discussed in the "input and output chapter". you can find the tutorial here: http://docs.python.org/tut/ ) </F> From chris.cavalaria at free.fr Thu May 4 10:14:07 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 04 May 2006 16:14:07 +0200 Subject: Because of multithreading semantics, this is not reliable. In-Reply-To: <1146751461.643033.119110@j33g2000cwa.googlegroups.com> References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <mailman.5280.1146690817.27775.python-list@python.org> <1146691613.911363.242620@e56g2000cwe.googlegroups.com> <4459c03b$0$2633$636a55ce@news.free.fr> <4459f1dd$1_2@newspeer2.tds.net> <445a014a$0$18281$636a55ce@news.free.fr> <1146751461.643033.119110@j33g2000cwa.googlegroups.com> Message-ID: <445a0c89$0$18272$636a55ce@news.free.fr> OlafMeding at gmail.com a ?crit : > Christophe > > >>Same reason that there is a warning in the "os.access" manual > > > I understand the if file exists open it code. > > I looked at the os.access documentation and see no "warning" or "not > reliable" wording there. > 6.1.4 Files and Directories > access(path, mode) > > > Olaf > 6.1.4 Files and Directories access( path, mode) Use the real uid/gid to test for access to path. Note that most operations will use the effective uid/gid, therefore this routine can be used in a suid/sgid environment to test if the invoking user has the specified access to path. mode should be F_OK to test the existence of path, or it can be the inclusive OR of one or more of R_OK, W_OK, and X_OK to test permissions. Return True if access is allowed, False if not. See the Unix man page access(2) for more information. Availability: Macintosh, Unix, Windows. Note: Using access() to check if a user is authorized to e.g. open a file before actually doing so using open() creates a security hole, because the user might exploit the short time interval between checking and opening the file to manipulate it. I call that note a warning. From pmartin at snakecard.com Fri May 5 11:46:26 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 10:46:26 -0500 Subject: Active Directory Authentication References: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> <mailman.5380.1146843580.27775.python-list@python.org> Message-ID: <mrK6g.8735$B42.1769@dukeread05> Benji York wrote: > D wrote: >> Is it possible to have Python authenticate with Active Directory? >> Specifically what I'd like to do is have a user enter a >> username/password, then have Python check the credentials with AD - if >> what they entered is valid, for example, it returns a 1, otherwise a >> 0.. Thanks! > > Install the Win32 extensions from > http://starship.python.net/crew/skippy/win32/Downloads.html and do > something like this: > > try: > handle=win32security.LogonUser(username, None, password, > win32security.LOGON32_LOGON_NETWORK, > win32security.LOGON32_PROVIDER_DEFAULT) > > # We're not going to use the handle, just seeing if we can get it. > handle.Close() > return True > except pywintypes.error, e: > # Because of the sheer number of Windows-specific errors that can > # occur here, we have to assume any of them mean that the > # credentials were not valid. > return False > -- > Benji York I assume then that you can also change user information using the same principle ? I'm trying to switch some VB6 code to python. Philippe From claudio.grondi at freenet.de Thu May 18 06:39:08 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Thu, 18 May 2006 12:39:08 +0200 Subject: Large Dictionaries In-Reply-To: <1147933058.405605@teuthos> References: <1147699064.107490@teuthos> <mailman.5711.1147697881.27775.python-list@python.org> <1147933058.405605@teuthos> Message-ID: <e4his7$pca$1@newsreader3.netcologne.de> Chris Foote wrote: > Richie Hindle wrote: >> [Chris] >>> Has anyone written a fast hash module which is more optimal for >>> large datasets ? >> >> PyJudy might be what you're looking for, though I've never used it: >> >> http://www.dalkescientific.com/Python/PyJudy.html >> >> "Judy's key benefits are scalability, high performance, and memory >> efficiency. A Judy array is extensible and can scale up to a very large >> number of elements, bounded only by machine memory." ... "PyJudy arrays >> are similar to Python dictionaries and sets." > > Thanks for the suggestion Richie. PyJudy works brilliantly :-) > > Cheers, > Chris It seems, that there is no Microsoft Windows version of Judy available, so for this reason PyJudy won't work on Windows - am I right? Claudio From feiborlar at yahoo.com Thu May 11 14:08:06 2006 From: feiborlar at yahoo.com (Movie World) Date: 11 May 2006 11:08:06 -0700 Subject: Factory pressed dvd movies, ps2, psp & xbox backups for sale !!! Message-ID: <1147370886.344404.213650@v46g2000cwv.googlegroups.com> We're offering all the latest factory pressed high quality dvd movies, ps2, psp and xbox silvers with factory printed colour inserts at fantastic prices, whether for personal use or reselling. We're shipping worldwide with various shipping methods. For resellers, please contact us for bulk discounts. For a complete list and prices, please email us at movieworld at time.net.my (Please state the type of list that you want and tell us your location as the prices varies for different locations. If you're reseller, please state the quantity you wish to order per shipment and we'll quote you a wholesale price depending on the quantity ordered.) * If you need references, we can provide them to you. From finite.automaton at gmail.com Tue May 9 17:38:35 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 9 May 2006 14:38:35 -0700 Subject: Deferred Evaluation in Recursive Expressions? References: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> <e3qc7h$ats$01$1@news.t-online.com> <1147189028.751527.157640@j73g2000cwa.googlegroups.com> Message-ID: <1147210715.294515.326280@v46g2000cwv.googlegroups.com> The first 'typedef' line will have a NameError when it tries to evaluate LinkedListB From Serge.Orlov at gmail.com Sun May 28 23:40:48 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 28 May 2006 20:40:48 -0700 Subject: q - including manpages in setup.py References: <pan.2006.05.28.20.17.09.245633@spam.me.please> Message-ID: <1148874048.669884.116870@i40g2000cwc.googlegroups.com> aum wrote: > Hi, > > What is the best way to incorporate manpages in a distutils setup.py > script? > > Is there any distro-independent way to find the most appropriate place to > put the manpages? > For instance, /usr/man/? /usr/share/man? /usr/local/man? > /usr/local/share/man? What do you mean distro? Linux? That should be /usr/local/man but AFAIK some distros are misconfigured and their man doesn't search /usr/local by default, YMMV. > Also - I've got .html conversions of the manpages, for the benefit of OSs > such as Windows which don't natively support manpages. What's the best > place to put these? your_tool --html-manual that uses os.start or webbrowser module to invoke html viewer. Or your_tool --man that dumps plain text on the screen. From aleax at mac.com Tue May 9 10:28:33 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 9 May 2006 07:28:33 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <joadnUiUIdmNsP3ZnZ2dnUVZ_tKdnZ2d@speakeasy.net> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> <87ac9r1tem.fsf@snobis.de> Message-ID: <1hf26zk.1uqniari93h7fN%aleax@mac.com> Stefan Nobis <snobis at gmx.de> wrote: > aleax at mac.com (Alex Martelli) writes: > > > if anonymous functions are available, they're used in even more > > cases where naming would help > > Yes, you're right. But don't stop here. What about expressions? Many > people write very complex expression, that are hard to understand. A > good language should forbid these abuse and don't allow expressions > with more than 2 or maybe 3 operators! That would _complicate_ the language (by adding a rule). I repeat what I've already stated repeatedly: a good criterion for deciding which good practices a language should enforce and which ones it should just facilitate is _language simplicity_. If the enforcement is done by adding rules or constructs it's probably not worth it; if the "enforcements" is done by NOT adding extra constructs it's a double win (keep the language simpler AND push good practices). Alex From grflanagan at yahoo.co.uk Tue May 30 08:59:09 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 30 May 2006 05:59:09 -0700 Subject: starting some Python script from C# In-Reply-To: <e5fl45$16ig$1@fegnews.vip.hr> References: <e58ta7$jns$1@fegnews.vip.hr> <1148728940.440692.166330@i39g2000cwa.googlegroups.com> <e5bp9c$la0$1@fegnews.vip.hr> <1148815194.860060.43810@j73g2000cwa.googlegroups.com> <e5fl45$16ig$1@fegnews.vip.hr> Message-ID: <1148993949.699443.250570@y43g2000cwc.googlegroups.com> > >> "Gerard Flanagan" <grflanagan at yahoo.co.uk> je napisao u poruci interesnoj > >> grupi:1148728940.440692.166330 at i39g2000cwa.googlegroups.com... > >> > tatamata wrote: > >> >> Hello. > >> >> > >> >> How can I run some Python script within C# program? > >> >> > >> > > >> > --------------------------------------------------------------------------------- > >> > ProcessStartInfo startInfo; > >> > Process process; > >> > string directory; > >> > string pyArgs; > >> > string script; > >> > > >> > startInfo = new ProcessStartInfo("python"); > >> > startInfo.WorkingDirectory = directory; > >> > startInfo.Arguments = script + " " + pyArgs; > >> > startInfo.UseShellExecute = false; > >> > startInfo.CreateNoWindow = true; > >> > startInfo.RedirectStandardOutput = true; > >> > startInfo.RedirectStandardError = true; > >> > > >> > process = new Process(); > >> > process.StartInfo = startInfo; > >> > process.Start(); > >> > > >> > string s; > >> > while ((s = process.StandardOutput.ReadLine()) != null) > >> > { > >> > //do something with s > >> > } > >> > --------------------------------------------------------------------------------- > >> > > > > > tatamata wrote: > >> Hello. I tried to implement ypour suggestion, but an error apears: > >> "Exception System.ComponentModel.Win32Exception was thrown in debugee: > >> The specified executable is not a valid Win32 application. > >> > >> namespace CS_script > >> { > >> class MainClass > >> { > >> public static void Main(string[] args) > >> { > >> > >> System.Diagnostics.ProcessStartInfo psi =new > >> System.Diagnostics.ProcessStartInfo(); > >> psi.FileName="my_script.py"; > >> psi.WorkingDirectory=Environment.CurrentDirectory; > >> psi.RedirectStandardOutput = true; > >> psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; > >> psi.UseShellExecute = false; > >> psi.CreateNoWindow = true; > >> > >> System.Diagnostics.Process script; > >> script = System.Diagnostics.Process.Start(psi); > >> > >> System.IO.StreamReader myOutput = script.StandardOutput; > >> script.WaitForExit(2000); > >> if (script.HasExited) > >> { > >> string output = myOutput.ReadToEnd(); > >> //this.processResults.Text = output; > >> } > >> MessageBox.Show("finished!"); > >> } > >> } > >> } > >> > >> When running the program, I have the following error: > >> > >> "Exception System.ComponentModel.Win32Exception was thrown in debugee: > >> The specified executable is not a valid Win32 application. > >> > >> StartWithCreateProcess() > >> Start() > >> Start() > >> Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop > >> Projects\CS_script\CS_script\Main.cs:32,5 " > >> > > > > > > I have no means of running C# programs at present and can't claim much > > expertise in any case. A guess is that a "valid Win32 application" > > means an '.exe' file, not a '.py' file. > > > > You are assuming that a Process object is as smart as the command > > interpreter ('cmd.exe') and will know to use 'python.exe' for a file > > with a 'py' extension? > > > > What happens if you use 'python.exe' (or 'cmd.exe') as your file and > > the script name as argument as in the code I posted? > > > > Gerard > > > > > > (PS. This group prefers that one doesn't top-post) > > tatamata wrote: > Hello. It seems that the following code works. And it seems that Process > object can automatically run script by using python.exe, but only if > standard output is not redirected... > > class MainClass > { > public static void Main(string[] args) > { > MyProcess myProcess = new MyProcess(); > myProcess.ExecuteScript(); > MessageBox.Show("Continue?","Application", > MessageBoxButtons.OKCancel); > } > } > public class MyProcess > { > // These are the Win32 error code for file not found or access > denied. > const int ERROR_FILE_NOT_FOUND =2; > const int ERROR_ACCESS_DENIED = 5; > > /// <summary> > /// Executes a python script. > /// </summary> > public void ExecuteScript() > { > Process myProcess = new Process(); > > try > { > // Get the path that stores the python script. > //string myDocumentsPath > =Environment.GetFolderPath(Environment.SpecialFolder.Personal); > //If the script is placed in the same folder as C# > executable, set the path to current directory: > string myDocumentsPath=Environment.CurrentDirectory; > > //Set the fully qualified script name > myProcess.StartInfo.FileName = myDocumentsPath + > "\\my_script.py"; > > //Execute the script: > myProcess.Start(); > > // Wait for it to die... > myProcess.WaitForExit(); > > MessageBox.Show ("Python script is successfully executed!"); > > } > catch (Win32Exception e) > { > if(e.NativeErrorCode == ERROR_FILE_NOT_FOUND) > { > Console.WriteLine(e.Message + ". Check the path."); > } > > else if (e.NativeErrorCode == ERROR_ACCESS_DENIED) > { > // Note that if your word processor might generate > exceptions > // such as this, which are handled first. > Console.WriteLine(e.Message + > ". You do not have permission to print this file."); > } > } > } > } > > Greetings, > > Zlatko > Ok. Glad you have a successful outcome. See the following for an asynchronous approach with multiple threads: http://www.codeproject.com/csharp/launchprocess.asp > > > > (PS. This group prefers that one doesn't top-post) > > Gerard From grante at visi.com Mon May 1 15:00:25 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 01 May 2006 19:00:25 -0000 Subject: How to efficiently read binary files? References: <zda5g.5247$nV4.1486@trnddc04> <125acgep357kbd8@corp.supernews.com> <mailman.5165.1146434636.27775.python-list@python.org> <125c8sbqsd7a952@corp.supernews.com> <mailman.5184.1146501930.27775.python-list@python.org> <125cfokq609se5d@corp.supernews.com> <mailman.5188.1146509722.27775.python-list@python.org> Message-ID: <125cmm985vbaf@corp.supernews.com> On 2006-05-01, Robert Kern <robert.kern at gmail.com> wrote: > Grant Edwards wrote: >> On 2006-05-01, Robert Kern <robert.kern at gmail.com> wrote: >> >>>>>>Perhaps the numarray module? >>>>> >>>>>numpy for new code, please. >>>> >>>>So numarray and numpy were both written to replace numeric? >>> >>>numpy was written to replace both Numeric and numarray. >> >> too many batteries... > > Too many cryptic complaints... Too easy to miss the intended humor on Usenet... -- Grant Edwards grante Yow! Where's my SOCIAL at WORKER? visi.com From aleaxit at yahoo.com Sat May 6 03:21:03 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 00:21:03 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> Message-ID: <1hew3d4.1x2eems1pb7o5N%aleaxit@yahoo.com> Steve R. Hastings <steve at hastings.org> wrote: ... > > But the key in the whole thread is simply that indentation will not > > scale. Nor will Python. > > This is a curious statement, given that Python is famous for scaling well. I think "ridiculous" is a better characterization than "curious", even if you're seriously into understatement. > I won't say more, since Alex Martelli already pointed out that Google is > doing big things with Python and it seems to scale well for them. And of course we're not the only ones. In fact, I believe that we're not even among the firms which have reported their experiences in the official "Python Success Stories" -- IBM, Industrial Light and Magic, NASA, etc, etc, are there, but we arent. I guess we just prefer to play our cards closer to our chest -- after all, if our competitors choose to use inferior languages, it's hardly to our advantage to change that;-). Alex From email at christoph-haas.de Fri May 5 09:23:58 2006 From: email at christoph-haas.de (Christoph Haas) Date: Fri, 5 May 2006 15:23:58 +0200 Subject: Active Directory Authentication In-Reply-To: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> References: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> Message-ID: <20060505132358.GC17891@torf.workaround.org> On Fri, May 05, 2006 at 05:39:08AM -0700, D wrote: > Is it possible to have Python authenticate with Active Directory? > Specifically what I'd like to do is have a user enter a > username/password, then have Python check the credentials with AD - if > what they entered is valid, for example, it returns a 1, otherwise a > 0.. Thanks! Can't you query the AD through LDAP? Then http://python-ldap.sourceforge.net/ might help. Kindly Christoph From onurb at xiludom.gro Tue May 23 04:22:35 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 23 May 2006 10:22:35 +0200 Subject: how to change sys.path? In-Reply-To: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> Message-ID: <4472c6b7$0$26894$626a54ce@news.free.fr> Ju Hui wrote: > is python search module by paths in sys.path? sys.path is the list of path where the Python interpreter will search modules, yes. > how to change it manuallly? "manually" ?-) You mean "dynamically, by code" ? If yes, it's just a list. You can modify it like you'd do for any other list. Else, you may want to look at the PYTHON_PATH environnement variable. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From johnjsal at NOSPAMgmail.com Tue May 23 13:42:37 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 17:42:37 GMT Subject: documentation for win32com? Message-ID: <hQHcg.2153$No6.46370@news.tufts.edu> Is there anything better to read on how to use this module for working with Office programs? This is not very heartening to read in the official docs: ----------------------- How do I know which objects are available? Good question. This is hard! You need to use the documentation with the products, or possibly a COM browser. Note however that COM browsers typically rely on these objects registering themselves in certain ways, and many objects to not do this. You are just expected to know. ----------------------- Yeah, thanks... So does this mean that the code can be different each time, or is there still a pre-determined way to refer to things, such as opening Excel, reading a spreadsheet and working with it, etc.? If so, where can I find a list of those objects and methods? Thanks. From userprogoogle-139 at yahoo.co.uk Tue May 23 07:05:41 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 23 May 2006 04:05:41 -0700 Subject: Win32: Detecting when system is locked or sleeping In-Reply-To: <1148310610.707825.97740@j33g2000cwa.googlegroups.com> References: <1148308038.487624.201690@i40g2000cwc.googlegroups.com> <mailman.6077.1148309513.27775.python-list@python.org> <zpkcg.77869$IQ1.5518@fe36.usenetserver.com> <1148310610.707825.97740@j33g2000cwa.googlegroups.com> Message-ID: <1148382341.719623.91660@i40g2000cwc.googlegroups.com> Further to my last post, I will try some of the tips presented above. Also the app writes to the screen display (or Active Desktop). As someone suggested, that could be where the problem is. Best. rod From kyoguan at gmail.com Thu May 4 07:45:50 2006 From: kyoguan at gmail.com (kyo guan) Date: Thu, 4 May 2006 19:45:50 +0800 Subject: about the implement of the PyString_InternFromString Message-ID: <000401c66f70$4e7923e0$3500a8c0@kyom> Hi : Hi guys: I have a question about the this API. PyObject * PyString_InternFromString(const char *cp) { PyObject *s = PyString_FromString(cp); if (s == NULL) return NULL; PyString_InternInPlace(&s); return s; } Why it always try to call PyString_FromString first? if char* cp is already in the interned dict, this PyString_FromString call is waster. so I think this API should implement as: 1. check the interned dict 2. if cp is not in the dict, then call PyString_FromString, and insert the new string in the dict 3. else : call Py_INCREF and return. Is this right? Kyo. From vipulagarwal.in at gmail.com Sat May 27 02:27:49 2006 From: vipulagarwal.in at gmail.com (vipulagarwal.in at gmail.com) Date: 26 May 2006 23:27:49 -0700 Subject: access serial port in python In-Reply-To: <0audnaDolMWd4erZRVn-jg@comcast.com> References: <1148678743.109181.259710@i40g2000cwc.googlegroups.com> <0audnaDolMWd4erZRVn-jg@comcast.com> Message-ID: <1148711269.318723.77150@i39g2000cwa.googlegroups.com> i can use the polling method to check for data on the serial port using pyserial...but i need to use the interrupt driven method .....am workin on a windows platform .... From vinogri at mcmaster.ca Fri May 5 17:46:47 2006 From: vinogri at mcmaster.ca (Ivan Vinogradov) Date: Fri, 5 May 2006 17:46:47 -0400 Subject: ConfigParser and multiple option names In-Reply-To: <1146831486.852415.5070@i39g2000cwa.googlegroups.com> References: <e37rji$c46$1@news.in.tum.de> <mailman.5236.1146607053.27775.python-list@python.org> <1146831486.852415.5070@i39g2000cwa.googlegroups.com> Message-ID: <AFC87207-3C85-4205-AD26-BCCB3F33EA42@mcmaster.ca> Another option is to use a dedicated section and simply omit values for options: [dirs] /path/1: /long/path/2: /etc: Then get options for section dirs. This approach precludes using ':' or '=' in paths though. From liupeimail at gmail.com Mon May 1 12:32:01 2006 From: liupeimail at gmail.com (liupei) Date: 1 May 2006 09:32:01 -0700 Subject: how to do with the multi-frame GIF Message-ID: <1146501121.792304.229120@g10g2000cwb.googlegroups.com> how to do with the multi-frame GIF, I used the PIL ,but it seems not support? From ptmcg at austin.rr._bogus_.com Fri May 19 16:39:58 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 20:39:58 GMT Subject: altering an object as you iterate over it? References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <WNpbg.2142$No6.46279@news.tufts.edu> Message-ID: <y2qbg.46875$CH2.9602@tornado.texas.rr.com> "John Salerno" <johnjsal at NOSPAMgmail.com> wrote in message news:WNpbg.2142$No6.46279 at news.tufts.edu... > Paul McGuire wrote: > > > Your coding style is a little dated - are you using an old version of > > Python? This style is the old-fashioned way: > > I'm sure it has more to do with the fact that I'm new to Python, but > what is old-fashioned about open()? Does file() do anything different? I > know they are synonymous, but I like open because it seems like it's > more self-describing than 'file'. > I think it is just part of the objectification trend - "f = open('xyzzy.dat')" is sort of a functional/verb concept, so it has to return something, and its something non-objecty like a file handle - urk! Instead, using "f = file('xyzzy.dat')" is more of an object construction concept - "I am creating a file object around 'xyzzy.dat' that I will interact with." In practice, yes, they both do the same thing. Note though, the asymmetry of "f = open('blah')" and "f.close()" - there is no "close(f)". I see now in the help for "file" this statement: Note: open() is an alias for file(). Sounds like some global namespace pollution that may be up for review come the new Python millennium (Py3K, that is). > > Now to your question about why '\n' lines persist into your new list. The > > answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!! > > Doh! I see that now! :) > Sorry about the ALL CAPS... I think I got a little rant-ish in that last post, didn't mean to shout. :) Thanks for being a good sport, -- Paul From johnjsal at NOSPAMgmail.com Sat May 13 00:19:54 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 13 May 2006 00:19:54 -0400 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <1147490582.719840.51200@i39g2000cwa.googlegroups.com> References: <jz09g.2091$No6.46071@news.tufts.edu> <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> <1147490582.719840.51200@i39g2000cwa.googlegroups.com> Message-ID: <44655f44$0$9414$c3e8da3@news.astraweb.com> BartlebyScrivener wrote: > Add the mysql db to your datasources using Administrative > Tools/Datasources(ODBC). Once that's done it's simple to access it, > using mxODBC. > > I'm assuing you are on Windows XP? > > Here's mxODBC > > http://www.egenix.com/files/python/mxODBC.html > > and you'll need the MySql connector > > http://dev.mysql.com/downloads/connector/odbc/3.51.html > > rick > Thanks. But is this like using a different module? I wouldn't be using MySQLdb anymore? From jim.lewis at miclog.com Sat May 27 07:34:31 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 27 May 2006 04:34:31 -0700 Subject: Pyrex speed References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> <4dqq38F1bi6btU1@uni-berlin.de> <1148728491.640293.298470@38g2000cwa.googlegroups.com> <1148728959.466305.23870@u72g2000cwu.googlegroups.com> Message-ID: <1148729670.982351.132060@j33g2000cwa.googlegroups.com> > main point of Pyrex is ease of wrapping, not of speeding-up. Supposedly the primes example is 50 times faster. From danmcleran at yahoo.com Fri May 26 13:12:11 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 26 May 2006 10:12:11 -0700 Subject: PIL problem with biprocessor hardware References: <1148661656.407762.147020@j73g2000cwa.googlegroups.com> Message-ID: <1148663531.254814.301790@i40g2000cwc.googlegroups.com> > If this application work on a PC mono-processor, I don't have any >problems. >If this application work instead on a PC bi-processor, the process >elaborates an image "corrupted": Sounds like you've got some thread synch issue. On a mono-processor system, your threads are running serially, but on an SMP system (i.e. bi-processor) your threads are truly running in parellel thru the CPU. I'd take a good look at any data you're locking currently, or should be locking. It's hard to make more concrete recommendations without knowing exactly what the code looks like. From antroy at gmail.com Wed May 24 07:43:34 2006 From: antroy at gmail.com (antroy at gmail.com) Date: 24 May 2006 04:43:34 -0700 Subject: Xah's Edu Corner: Criticism vs Constructive Criticism In-Reply-To: <Xns97B0B6F98479Ecastleamber@130.133.1.4> References: <1145992903.834316.198370@u72g2000cwu.googlegroups.com> <m2mze978dj.fsf@hermes.theari.com> <Xns97B0B6F98479Ecastleamber@130.133.1.4> Message-ID: <1148471014.814408.186930@u72g2000cwu.googlegroups.com> > 24. Learn when not to reply to a troll (and bother several groups while > doing so). 25. Learn when not to reply to a reply to a troll (and bother several groups while doing so). This could go on and on... ;-) From michele.simionato at gmail.com Wed May 24 06:04:37 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 24 May 2006 03:04:37 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1148411496.691868.53440@j73g2000cwa.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> <d6lu07r7u0u.fsf@vipunen.hut.fi> <44681F95.9040400@gmail.com> <1148411496.691868.53440@j73g2000cwa.googlegroups.com> Message-ID: <1148465076.973889.77040@i40g2000cwc.googlegroups.com> Kay Schluehr wrote: > http://www.fiber-space.de/EasyExtend/doc/EE.html Well, I have not read that page yet, but the name "fiber space" reminds me of old memories, when I was doing less prosaic things than now. Old times .. ;) Michele Simionato > It fits quite nice with Python and is conceptually simple, safe and > reasonably fast. Using EasyExtend PyCells could be made an own language > ( including Python ) defined in a Python package ( i.e. no C-code and > complex build process is required ). I would be interested in user > experience. I wouldn't consider EE as "experimental" i.e. open for > severe changes. It still lacks some comfort but it also improves > gradually in this respect. From florian.reiser at ra-bc.de Tue May 23 03:44:05 2006 From: florian.reiser at ra-bc.de (Florian Reiser) Date: Tue, 23 May 2006 09:44:05 +0200 Subject: New beginner to python for advice References: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> Message-ID: <e4ueg6$gfa$1@online.de> Hello Minlar, try: http://www.diveintopython.org/ It is written very cleary and helps you to get started very quickly. Mit freundlichen Gr?ssen Florian Reiser -- http://www.ra-bc.de RA Unternehmensberatung F?hren durch pr?zise Daten "Minlar Ginger" <zhaoyuanjiang at gmail.com> schrieb im Newsbeitrag news:1148367055.409713.51170 at j55g2000cwa.googlegroups.com... > HIi all: > I am a new beginner to python, would you like give me some advice on > studying it? > Welcome to list some book on python for me. > Thanks a lot. > From deets at nospam.web.de Wed May 10 19:57:06 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 May 2006 01:57:06 +0200 Subject: create a c++ wrapper for python class? In-Reply-To: <0Hu8g.70548$F_3.61654@newssvr29.news.prodigy.net> References: <0Hu8g.70548$F_3.61654@newssvr29.news.prodigy.net> Message-ID: <4cfcueF15mrj0U1@uni-berlin.de> Mark Harrison schrieb: > Right now I'm using Boost Python to wrap some C++ code so > that applications from both languages can use it. > > This is great, but I'm rapidly coming to the conclusion that > a lot of this work is better coded in Python. There's nothing > particularly CPU-bound, and the comprehensive Python library is a > big help. > > So, I'm looking for a C++ wrapper generator, so that I can > write a class in Python, and then have a .h and .cpp generated > that will give me a corresponding C++ class. > > Of course, the usual restrictions apply: no dynamically > added methods, accessing all instance data via getters > and setters, etc. > > It seems a first cut of this is pretty straightforward, > using introspection to get the required methods. Something > needs to be done to specify the C++ types of the parameters. > > Is there any work being done in this area? No - and I doubt there is much to do about that. C++ needs so many static information to form a proper class, you'd end up duplicating the whole declarational efforts in some awkward addition or complementary annotation to python's syntax that it just isn't feasible. There is shedskin, avery interesting project, but then this sufers from being a subset of python and AFAIK no seamless interoperability between python and C++. I don't know about boost - but I know my way around SIP a little bit. So what I would do is to declare whatever you need in C++ in a class with all virtual methods. SIP then should be able to let you subclass that class in python, and pass back instances of your python classes to your C++-core/library/whatever. Diez From khoa.coffee at gmail.com Wed May 17 11:24:39 2006 From: khoa.coffee at gmail.com (Khoa Nguyen) Date: Wed, 17 May 2006 11:24:39 -0400 Subject: Pyparsing: Grammar Suggestion Message-ID: <3d00e6dc0605170824q6abe919dq49e72970baf46244@mail.gmail.com> I am trying to come up with a grammar that describes the following: record = f1,f2,...,fn END_RECORD All the f(i) has to be in that order. Any f(i) can be absent (e.g. f1,,f3,f4,,f6 END_RECORD) Number of f(i)'s can vary. For example, the followings are allowed: f1,f2 END_RECORD f1,f2,,f4,,f6 END_RECORD Any suggestions? Thanks, Khoa From grante at visi.com Fri May 26 21:23:42 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 01:23:42 -0000 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com> <44778e7f$1@nntp0.pdx.net> <127f61eluend535@corp.supernews.com> <127f7rrn8i2qea3@corp.supernews.com> Message-ID: <127fagudgh3fa7e@corp.supernews.com> On 2006-05-27, Grant Edwards <grante at visi.com> wrote: > On 2006-05-27, Grant Edwards <grante at visi.com> wrote: >> On 2006-05-26, Scott David Daniels <scott.daniels at acm.org> wrote: >> >>>> I tried using the scipy sandbox delaunay module, but the >>>> interpolators don't work: the natural neighbor interpolator >>>> produces a surface with "holes" in it: the interpolator returns >>>> NaNs for no reason for certain regions within the convex hull >>>> (the convex hull looks right, and the input Z values in that >>>> region don't look any different that regions that work). >>> >>> Sounds like a great opportunity for you to contribute. >> >> I'll try, but it looks like I'm going to be working all weekend >> as it is. > > OTOH, it looks like I'm screwed either way. My python > interpolator is so hopelessly slow it's useless in practice. It > can only process 4 points per second and I need to process > arrays of 10,000 to 50,000 elements. :( I found another module that claims to do what I want http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/griddata.html But, no matter what data I pass, I get either all zeros or all NaNs back. :/ I'm 0 for 3 now. -- Grant Edwards grante Yow! I'm ZIPPY!! Are we at having FUN yet?? visi.com From runlevelten at gmail.com Wed May 31 06:25:56 2006 From: runlevelten at gmail.com (Ten) Date: Wed, 31 May 2006 11:25:56 +0100 Subject: John Bokma harassment In-Reply-To: <1148981788.547993.91320@g10g2000cwb.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <Xns97D294C4D81FCcastleamber@130.133.1.4> <1148981788.547993.91320@g10g2000cwb.googlegroups.com> Message-ID: <200605311125.56252.runlevelten@gmail.com> On Tuesday 30 May 2006 10:36, ilitzroth at gmail.com wrote: > >Your first question should be: Is it alright that Xah harasses 5 > >newsgroups? Or maybe work on your spelling, harass is with one r, but > >maybe you didn't read the subject, which wouldn't amaze me, since you > >sound like you should be spending time on MySpace OMG!. > > Dear John, > Should I ask myself the question about Xah first, or work on my > spelling? > I knew har*ass it had 1 or more r's in it but I couldn't figure out the > exact number. > That makes me suspect my spelling is good enough and I should dive > right into the > Xah issue. What do you think John? > I don't get the MySpace OMG reference, but rest assured John, you are > still my favorite > newsnet nazi. I know you have been feeling pretty insecure about this > Xah fellow, but > you know that is just silly, don't you? > Yours truly > Immanuel > > P.S Do not hesitate to comment on form, spelling or style of this > message. I am always > eager to learn. Immanuel, The guy cross-posts wildly off-topic posts as a flimsy pretext on which to plaster advertisements for his website. That's even if you don't consider the posts themselves drivel. He starts flame wars, or just maildrops and doesn't respond. He does so despite the way he does it being impolite, probably in violation of every TOS he crosses, and inconsiderate to those of us who just want to use the newsgroup. If you want to waste your time on mounting a tenacious defence of that, good luck to you, but consider the possibility that you may be wrong. Of course we can ignore the guy - I'm sure many do without giving it further thought, but being able to ignore a transgression or discourtesy doesn't magically mean the person isn't doing it does it? As for all this specious nonsense about freedom of speech - every organised forum for discussion has some level of regulation, varying from taking turns speaking, to staying a certain distance from the opposition, to wearing the appropriate hat, to not physically hitting your colleagues. To confuse that simple and civilised thing with some desire to *stifle* opinion or basic freedoms would be a little childish, wouldn't it? Isn't it just people wanting to use this resource as a place to discuss the topics at hand, without loads and loads of noise and cynical advertising at our expense? Cheers, Ten PS: Nice to see Godwin's ticking over nicely these days. :) -- There are 10 types of people in this world, those who understand binary, and those who don't. From scott.daniels at acm.org Sun May 28 14:32:21 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sun, 28 May 2006 11:32:21 -0700 Subject: Array? Please help. In-Reply-To: <4479df10$1@nntp0.pdx.net> References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> <4478bd43$1@nntp0.pdx.net> <kWieg.664$eB3.153@newsread3.news.pas.earthlink.net> <4479df10$1@nntp0.pdx.net> Message-ID: <4479e86b$1@nntp0.pdx.net> Scott David Daniels wrote: > Dr. Pastor wrote: >> Scott David Daniels wrote: >>> Dr. Pastor wrote: >>>> I need a row of 127 bytes that I will use as a >>>> circular buffer. Into the bytes (at unspecified times) >>>> a mark (0<mark<128) will be written, one after the other. >>>> After some time the "buffer" will contain the last 127 marks. >>> Sounds a lot like homework. >> No it is not home work. > > OK, taking you at your word, here's one way: > (and some untested code) As penance for posting untested code, here is a real implementation: import array class Circular(object): '''A circular buffer, holds only non-zero entries''' def __init__(self, size=127): '''Create as N-long circular buffer .data is the circular data store. .point is the index of the next value to write ''' self.data = array.array('b', [0] * size) self.point = 0 def mark(self, value): '''Add a single value (non-zero) to the buffer''' assert value self.data[self.point] = value self.point += 1 if self.point >= len(self.data): self.point = 0 def recent(self): '''Return the most recent values saved.''' result = self.data[self.point :] + self.data[: self.point] for n, v in enumerate(result): if v: return result[n :] return result[: 0] # an empty array Tests: c = Circular(3) assert list(c.recent()) == [] c.mark(12) assert list(c.recent()) == [12] c.mark(11) assert list(c.recent()) == [12, 11] c.mark(10) assert list(c.recent()) == [12, 11, 10] c.mark(9) assert list(c.recent()) == [11, 10, 9] --Scott David Daniels scott.daniels at acm.org From nobody at 127.0.0.1 Sat May 20 18:23:13 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 20 May 2006 22:23:13 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> <Xns97C9ADA375FCCcastleamber@130.133.1.4> Message-ID: <lFMbg.19879$Lm5.7431@newssvr12.news.prodigy.com> John Bokma wrote: > Edward Elliott <nobody at 127.0.0.1> wrote: > >> A little out-of-order execution seems useful here. ;) > > No, not interested in a pissing contest. Your statement that the Perl > community encourages importing is *encouraged* (over using OO without > importing) is false. The cookbook says otherwise. So it depends how you define community. You lecturing people on pissing contests, that's rich. Nice way to duck the issue and sound like a winner. Wake me when you decide to address the substance of my arguments. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From tim.golden at viacom-outdoor.co.uk Tue May 9 05:06:42 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 9 May 2006 10:06:42 +0100 Subject: Import data from Excel Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1A8@vogbs009.gb.vo.local> [Dale Strickland-Clark] | from win32com.client import GetObject, constants | | def GetExcelData(self, strFilePath): | """ Extract the data from the Excel sheet. | Returns tuple of tuples representing the rows and cells.""" | # The following line extracts | # all the data from sheet 1 of the spreadsheet | return GetObject(strFilePath).Sheets(1).UsedRange.Value Amazing! I never knew you could do that -- GetObject against a registered file path, I mean. Certainly beats my trying to remember whether you call .Open on an Excel Application, Workbook, Worksheet or something else altogether. Thanks, Dale. 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 fredrik at pythonware.com Mon May 8 09:51:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 May 2006 15:51:19 +0200 Subject: PYTHONPATH vs PATH? References: <445BA18C.3080600@kearfott.com> <HGEOKIAPAMCIFPPBDALKMEIGCAAA.m.yanowitz@kearfott.com> Message-ID: <e3nicb$1vm$1@sea.gmane.org> Michael Yanowitz wrote: > Someone on my team tried out installing my Python code and > found that setting PYTHONPATH does not work, but setting PATH > environment variable works the way PYTHONPATH should. Is that > how it supposed to be PATH is used by the operating system to find executables, and PYTHONPATH is used by Python to find Python modules. why setting the PATH helped in your case is impossible to tell, without knowing exactly what your application does. </F> From fredrik at pythonware.com Thu May 4 08:23:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 14:23:28 +0200 Subject: Swaying A Coder Away From Python References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com><W40839200.311.1532.1@mx-extra.net> <9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> Message-ID: <e3cro0$r6g$1@sea.gmane.org> Tim Williams wrote: > It was forwarded to me by someone who knows I use Python, and I > thought it might be of interest to a balanced list, especially as it > shows an external perspective of Python. Are we not allowed to post > negative things about Python anymore /.../ nope, but if we were to post to the list every time some random blogger says something about Python, we wouldn't have room for much other stuff. (and it doesn't show an external perspective of Python; it's a piece of lousy re- porting that treats some random guy as an authority, at a moment in time where the *real* story out there is that light-weight community-developed languages are beginning to seriously invade the spaces formerly occupied by monolithic environments controlled by Sun and Microsoft. there are lots of stuff going on out there these days...) </F> From sam at nuevageorgia.com Sun May 21 19:46:41 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 21 May 2006 16:46:41 -0700 Subject: Python - Web Display Technology In-Reply-To: <mailman.6050.1148253641.27775.python-list@python.org> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <mailman.6050.1148253641.27775.python-list@python.org> Message-ID: <1148255201.620047.66920@j55g2000cwa.googlegroups.com> As a final thought, seperate from the whole open source/search issue, which has obvious merit, it does seem Flash has many excellent ideas as a language/tool for creating/expressing non written ideas that are lacking in the HTML world. From thomas at localhost.localdomain Mon May 15 09:40:49 2006 From: thomas at localhost.localdomain (Thomas Dybdahl Ahle) Date: Mon, 15 May 2006 15:40:49 +0200 Subject: Decrypt DES by password Message-ID: <pan.2006.05.15.13.40.49.118144@localhost.localdomain> Hi, I've got some DES encrypted data, for which I know the password. The problem is that I have to generate an 8byte key from the password. I use python-crypto-2.0.1. I also know, that the C# way to do the decryption is: PasswordDeriveBytes bytes1 = new PasswordDeriveBytes("passwordString", null); byte[] array1 = new byte[8]; byte[] array2 = bytes1.CryptDeriveKey("DES", "MD5", 0, array1); DESCryptoServiceProvider provider1 = new DESCryptoServiceProvider(); FileStream fs = new FileStream("fileNameString", FileMode.Open, FileAccess.Read); CryptoStream cs = new CryptoStream(fs, provider1.CreateEncryptor(array2, array1), CryptoStreamMode.Read); Anybody know how to do this in python? -- Programmers should realize their critical importance and responsibility in a world gone digital. They are in many ways similar to the priests and monks of Europe's Dark Ages; they are the only ones with the training and insight to read and interpret the "scripture" of this age. From casevh at comcast.net Thu May 18 17:56:58 2006 From: casevh at comcast.net (casevh at comcast.net) Date: 18 May 2006 14:56:58 -0700 Subject: Python trig precision problem In-Reply-To: <newscache$13fhzi$5xd$1@lyris.knx.tva.gov> References: <newscache$13fhzi$5xd$1@lyris.knx.tva.gov> Message-ID: <1147989418.253313.3650@38g2000cwa.googlegroups.com> Cary West wrote: > Hello all, having a small problem with a trig routine using python math > module. This code is designed to convert geodetic coordinates to lambert > conformal conic coordinates. It implements the formulas found at > http://mathworld.wolfram.com/LambertConformalConicProjection.html . The > problem is that, at least on my machine, the precision is off to the tune of > around 1 km, which is unacceptable. (using the calculator found at > http://www.deh.gov.au/erin/tools/geo2lam-gda.html ) Anyone have any ideas? > here is the offending code. > I'd assume you are exceeding the precision available with standard 64-bit floating point. Here is a library for extended precision floating point, including trig functions. http://calcrpnpy.sourceforge.net/clnumManual.html casevh From yaronb at telus.net Tue May 23 13:20:14 2006 From: yaronb at telus.net (Yaron Butterfield) Date: Tue, 23 May 2006 10:20:14 -0700 Subject: graphs and charts Message-ID: <4473444E.4060102@telus.net> Hi, What's the best way to on-the-fly graphs and charts using Python? Or is Python not really the best way to do this? Thanks you! Yaron From tdwdotnet at gmail.com Mon May 1 11:43:27 2006 From: tdwdotnet at gmail.com (Tim Williams) Date: Mon, 1 May 2006 16:43:27 +0100 Subject: list*list In-Reply-To: <B40595726.31.57252.1@mx-extra.net> References: <B40595726.31.57252.1@mx-extra.net> Message-ID: <9afea2ac0605010843x4e4d8bedn735f3f120d05ce7f@mail.gmail.com> On 1 May 2006 08:28:12 -0700, BBands <bbands at gmail.com> wrote: > > There must be a better way to multiply the elements of one list by > another: > > a = [1,2,3] > b = [1,2,3] > c = [] > for i in range(len(a)): > c.append(a[i]*b[i]) > a = c > print a > [1, 4, 9] > > Something like: >>> [ x * y for x,y in zip(a,b) ] [1, 4, 9] :) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060501/79e5fb25/attachment.html> From provato at gmail.com Sun May 28 18:13:04 2006 From: provato at gmail.com (DK) Date: 28 May 2006 15:13:04 -0700 Subject: pygame and wxpython Message-ID: <1148854384.549915.135950@j73g2000cwa.googlegroups.com> I'm somewhat new to Python but not to programming. I just want to know if it's possible to have a SINGLE wxPython frame containing two sections where one will contain widgets and the other will host an animation done using PyGame. More specifically, I want to have a list of names of animations on the left and depending on what is selected, run the PyGame animation in the main area. From sjmachin at lexicon.net Mon May 8 09:37:09 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 08 May 2006 23:37:09 +1000 Subject: Python's regular expression? In-Reply-To: <e3ngcn$s4r$1@mlucom4.urz.uni-halle.de> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> <e3ndsm$rfa$1@mlucom4.urz.uni-halle.de> <445F4093.4070505@lexicon.net> <e3ngcn$s4r$1@mlucom4.urz.uni-halle.de> Message-ID: <445F4985.10707@lexicon.net> On 8/05/2006 11:13 PM, Mirco Wahab wrote: > Hi John > >>> import re >>> >>> t = 'blue socks and red shoes' >>> p = re.compile('(blue|white|red)') >>> if p.match(t): >> What do you expect when t == "green socks and red shoes"? Is it possible >> that you mean to use search() rather than match()? > > This is interesting. > What's in this example the difference then between: I suggest that you (a) read the description on the difference between search and match in the manual (b) try out search and match on both your original string and the one I proposed. > > import re > > t = 'blue socks and red shoes' > if re.compile('blue|white|red').match(t): > print t > > and > > t = 'blue socks and red shoes' > if re.search('blue|white|red', t): > print t [snip] > > But what would be an appropriate use > of search() vs. match()? When to use what? ReadTheFantasticManual :-) From ketil+news at ii.uib.no Wed May 10 04:36:03 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Wed, 10 May 2006 10:36:03 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1147194791.809735.251500@g10g2000cwb.googlegroups.com> <1hf33s3.1bdn2e4juoow0N%aleax@mac.com> Message-ID: <egmzdqcm4s.fsf@polarvier.ii.uib.no> aleax at mac.com (Alex Martelli) writes: > But if we can agree to name every function except continuations I'll be > content FWIW, I disagree: A simple example, doubling each entry in a list: map (*2) xs vs. let double x = x*2 in map double xs Here's another example, extracting all lines that contain at least one word: filter (not.null) . map words . lines Note that I'm using the following anonymous functions: not . null filter (not . null) map words filter (not.null) . map words Would it really improve anything if I named these? It seems incredibly pedestrian, along the lines of requiring a comments for every source line: x++; /* increase x by one */ a[x] = ' '; /* insert a space in a at position x */ Sometimes the best documentation is the code itself. Sometimes the best name for a function is the code itself. -k -- If I haven't seen further, it is by standing in the footprints of giants From m.sloyko at gmail.com Thu May 4 06:43:32 2006 From: m.sloyko at gmail.com (Maxim Sloyko) Date: 4 May 2006 03:43:32 -0700 Subject: ZSI usage Message-ID: <1146739412.265658.124130@j73g2000cwa.googlegroups.com> Hi all! I'm trying to make a simple SOAP call from python to SOAP::Lite (perl) SOAP server. My SOAP server has https://myserv.com/open-api URI, the function open_session has the "QW/API" namespace. SO I do the following: from ZSI.client import Binding fp = open('debug.out', 'a') client = Binding(url='/open-api', host='myserv.com', port=443, ssl=1, tracefile=fp) client.SetNS("QW/API") sid = client.open_session(1) However, I get the following error: ZSI.FaultException: SOAPAction shall match 'uri#method' if present (got '""', expected 'QW/API#open_session' If I look at SOAP packet I see the following: [snip] <session_open> <Eo8138f18 xsi:type="xsd:integer">1</Eo8138f18> </session_open> [snip] SO the question is, why ZSI seem to ignore that NS setting? How to fix that? Thanks in advance! -- Maxim From bignose+hates-spam at benfinney.id.au Wed May 17 01:05:29 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 15:05:29 +1000 Subject: assignment in a for loop References: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> Message-ID: <8764k5p7fq.fsf@benfinney.id.au> "MackS" <mackstevenson at hotmail.com> writes: > >>> l = [1,2] > >>> for i in l: > ... i = i + 1 > ... > >>> l > [1, 2] > > I understand (I think!) that this is due to the fact that in Python > what looks like "assignment" really is binding a name to an > object. The result is that inside the loop I am creating an object > with value (i+1) and then "pointing" the name i at it. Therefore, > the object to which i previously pointed (an element of list l) > remains unchanged. That's a fair explanation, yes. > Two brief questions: > > 1) Is what I wrote above (minimally) correct? Correct for what? You can tell if it's *syntactically* correct by simply running it. As for any other "correct", define that. Does it do what you want it to do? > 2) Independently of the answer to 1, is there a way for me to assign > to elements of a list inside a loop and without resorting to C-style > ugliness of > > for i in range(len(l)) > l[i] = l[i] + 1 You can build a new list from your operations on the old one. new_list = [] for x in old_list: new_list.append(x+1) You can also do it more succinctly with a list comprehension expression. > (Note: not using a list comprehension.) What's preventing the use of list comprehensions? new_list = [x+1 for x in old_list] -- \ "Smoking cures weight problems. Eventually." -- Steven Wright | `\ | _o__) | Ben Finney From tamatea.raust at gmail.com Tue May 16 11:12:42 2006 From: tamatea.raust at gmail.com (Tama) Date: 16 May 2006 08:12:42 -0700 Subject: Windows & Apache 1.3 & mod_python.dll Message-ID: <1147792362.619557.74360@j33g2000cwa.googlegroups.com> Hello, I've didn't find any answer to my problem so I start a new topic. I have installed Apache 1.3.33 on Windows XP. I've also downloaded and installed ActivePython form http://www.activestate.com/. Then I went to http://www.modpython.org/ and search how to use python script with my web pages. I've tried all the version of mod_python under 2.7.11. As I'm under Windows XP, I can only install mod_python.dll and I've done what is here http://www.modpython.org/live/mod_python-2.7.8/doc-html/app-wininst.html So now my problem is that when I start my Apache server I get this error : "cannot load c:/easy-php1-8/apache/module/mod_python.dll into server : (126) ..." Do you have any solution or do you know a .dll ou a .so file that work ? Thank for your help. From hapaboy2059 at gmail.com Tue May 2 14:38:17 2006 From: hapaboy2059 at gmail.com (hapaboy2059 at gmail.com) Date: 2 May 2006 11:38:17 -0700 Subject: SGML parsing tags and leeping track In-Reply-To: <1146543123.663415.48640@g10g2000cwb.googlegroups.com> References: <1146543123.663415.48640@g10g2000cwb.googlegroups.com> Message-ID: <1146595097.141061.318390@g10g2000cwb.googlegroups.com> could i make a global variable and keep track of each tag count? Also how would i make a list or dictionary of tags that is found? how can i handle any tag that is given? From info at stratolab.com Fri May 5 18:49:52 2006 From: info at stratolab.com (Winston Wolff) Date: Fri, 05 May 2006 18:49:52 -0400 Subject: MakeBot - IDE for learning Python Message-ID: <eEQ6g.941$5J6.169@newsread1.mlpsca01.us.to.verio.net> I have just released a Windows and Macintosh OS X version of MakeBot, an IDE intended for students learning Python. It includes a very nice graphics/video game package based on PyGame. You can read all about it here: http://stratolab.com/misc/makebot/ -Winston From dave at waveform.plus.com Wed May 10 13:25:36 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 10 May 2006 17:25:36 GMT Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <44605c5f$0$7085$626a54ce@news.free.fr> <fZf8g.70357$F_3.15098@newssvr29.news.prodigy.net> <ups3625s7oodjshrjm9e3u65m4uh2t85ff@4ax.com> Message-ID: <44622210$0$2561$ed2619ec@ptn-nntp-reader01.plus.net> Dave Hansen wrote: > On Wed, 10 May 2006 06:44:27 GMT in comp.lang.python, Edward Elliott > <nobody at 127.0.0.1> wrote: > > > > > > Would I recommend perl for readable, maintainable code? No, not > > when better options like Python are available. But it can be done > > with some effort. > > I'm reminded of a comment made a few years ago by John Levine, > moderator of comp.compilers. He said something like "It's clearly > possible to write good code in C++. It's just that no one does." Reminds me of the quote that used to appear on the front page of the ViewCVS project (seems to have gone now that they've moved and renamed themselves to ViewVC). Can't recall the attribution off the top of my head: "[Perl] combines the power of C with the readability of PostScript" Scathing ... but very funny :-) Dave. -- From lashkariNO at SPAMworldviz.com Tue May 9 14:54:19 2006 From: lashkariNO at SPAMworldviz.com (Farshid Lashkari) Date: Tue, 09 May 2006 11:54:19 -0700 Subject: Calling python functions from C In-Reply-To: <1147194348.285669.218280@g10g2000cwb.googlegroups.com> References: <1147194348.285669.218280@g10g2000cwb.googlegroups.com> Message-ID: <Cz58g.176027$bm6.8320@fed1read04> robert.differentone at gmail.com wrote: > I want to call add from C. Could anybody please help me? Look at the "Pure Embedding" section of the python documentation. It contains an example program that does exactly what you want. Here is a link to the page: http://www.python.org/doc/ext/pure-embedding.html -Farshid From reply.in.the.newsgroup at my.address.is.invalid Tue May 2 17:28:56 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Tue, 02 May 2006 23:28:56 +0200 Subject: data regex match References: <87r73cdtmk.fsf@localhost.localdomain> Message-ID: <m7jf52dj9a3k9tr4neikq3u5kvtqtcgf5v@4ax.com> Gary Wessle: >tx = "now 04/30/2006 then" >data = re.compile('(\d{2})/\1/\1\1', re.IGNORECASE) >d = data.search(tx) >print d > >Nono >I was expecting 04/30/2006 You should expect: NameError: name 're' is not defined > what went wrong? \1 matches the content of the first group, which is '04'. It doesn't match '30', '20' and '06'. Also, you'll need to use a raw string, or backslash your backslashes. >>> import re >>> tx = "now 04/04/0404 then" >>> data = re.compile(r'(\d{2})/\1/\1\1', re.IGNORECASE) >>> d = data.search(tx) >>> print d <_sre.SRE_Match object at 0x01287F60> -- Ren? Pijlman From gherron at islandtraining.com Wed May 31 11:56:13 2006 From: gherron at islandtraining.com (Gary Herron) Date: Wed, 31 May 2006 08:56:13 -0700 Subject: Strange behavior with iterables - is this a bug? In-Reply-To: <1149087772.403131.270480@f6g2000cwb.googlegroups.com> References: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> <mailman.6341.1149028250.27775.python-list@python.org> <1149087772.403131.270480@f6g2000cwb.googlegroups.com> Message-ID: <447DBC9D.4060104@islandtraining.com> akameswaran at gmail.com wrote: >Gary Herron wrote: > > >>List comprehension is a great shortcut, but when the shortcut starts >>causing trouble, better to go with the old ways. You need to reopen each >>file each time you want to iterate through it. You should be able to >>understand the difference between these two bits of code. >> >>The first bit opens each file but uses (two of them) multiple times. >>Reading from a file at EOF returns an empty sequence. >> >>The second bit opened the file each time you want to reuse it. That >>works correctly. >> >>And that suggest the third bit of correctly working code which uses list >>comprehension. >> >># Fails because files are opened once but reused >>f1 = open('word1.txt') >>f2 = open('word2.txt') >>f3 = open('word3.txt') >>for i1 in f1: >> for i2 in f2: >> for i3 in f3: >> print (i1.strip(),i2.strip(),i3.strip()) >> >>and >> >># Works because files are reopened for each reuse: >>f1 = open('word1.txt') >>for i1 in f1: >>f2 = open('word2.txt') >>for i2 in f2: >>f3 = open('word3.txt') >>for i3 in f3: >>print (i1.strip(),i2.strip(),i3.strip()) >> >>and >> >># Also works because files are reopened for each use: >>print [(i1.strip(),i2.strip(),i3.strip()) >> for i1 in open('word1.txt') >> for i2 in open('word2.txt') >> for i3 in open('word3.txt')] >> >>Hope that's clear! >> >>Gary Herron >> >> > > >My original problem was with recursion. I explicitly nested it out to >try and understand the behavior - and foolishly looked in the wrong >spot for the problem, namely that file is not reitreable. In truth I >was never concerned about file objects, the problem was failing with my >own custom iterators (wich also were not reiterable) and I switched to >file, to eliminate possible code deficiencies on my own part. I was >simply chasing down the wrong problem. As was pointed out to me in a >nother thread - the cleanest implementation which would allow me to use >one copy of the file (in my example the files are identical) would be >to use a trivial iterator class that opens the file, uses tell to track >position and seek to set position, and returns the appropriate line for >that instance - thus eliminating unnecessary file opens and closes. > > > I see. I wouldn't call "tell" and "seek" clean. Here's another suggestion. Use l1 = open(...).readlines() to read the whole file into a (nicely reiterable) list residing in memory, and then iterate through the list as you wish. Only if your files are MANY megabytes long would this be a problem with memory consumption. (But if they were that big, you wouldn't be trying to find all permutations would you!) Gary Herron From defcon8 at gmail.com Sun May 14 04:44:58 2006 From: defcon8 at gmail.com (defcon8) Date: 14 May 2006 01:44:58 -0700 Subject: Cellular automata and image manipulation In-Reply-To: <1147595982.184878.25800@d71g2000cwd.googlegroups.com> References: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> <i4OdnQZa45PQ7_vZUSdV9g@ptd.net> <1147595982.184878.25800@d71g2000cwd.googlegroups.com> Message-ID: <1147596298.106352.245420@j33g2000cwa.googlegroups.com> import Image x = [] buff = [] buff = [[0 for y in range(41)] for x in range(21)] buff[0][(len(buff)-1)/2] = 1 def rule1(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: if buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j-1] == 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1: buff[i+1][j] = 1 def rule2(): for i in range(len(buff)-1): for j in range(len(buff[0])-1): if i == len(buff)-1: break elif j == 0: if buff[i][j+1] == 1: buff[i+1][j] = 1 elif j == len(buff[0])-1: buff[i+1][j] = 1 elif buff[i][j-1] == 1 and buff[i][j+1] != 1: buff[i+1][j] = 1 elif buff[i][j+1] == 1 and buff[i][j-1] != 1: buff[i+1][j] = 1 rule2() nim = Image.new("1", (400,600)) nim.putdata(buff) nim.resize((400,600)).save("output.png") for a in buff: for x in a: if x == 1: print "X", else: print " ", print "" That is my code. Could you tell me what maybe is wrong? Rule2 makes the fibonacci triangle btw. From bearophileHUGS at lycos.com Sat May 27 04:06:42 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 27 May 2006 01:06:42 -0700 Subject: chop() and empty() functions In-Reply-To: <mailman.6260.1148678121.27775.python-list@python.org> References: <mailman.6253.1148664337.27775.python-list@python.org> <44776377.7090304@lexicon.net> <mailman.6260.1148678121.27775.python-list@python.org> Message-ID: <1148717202.713707.167440@j33g2000cwa.googlegroups.com> Jeremy L. Moles>It's just an iterative way to say, "Okay, give me some default behavior for everything, and I'll come back around later and set the explicit handlers later."< There's some correlation with the Null Object pattern: http://www.cs.oberlin.edu/~jwalker/nullObjPattern/ Bye, bearophile From blair.bethwaite at gmail.com Mon May 8 23:48:38 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 8 May 2006 20:48:38 -0700 Subject: Enumerating Regular Expressions Message-ID: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> Hi all, Does anybody know of a module that allows you to enumerate all the strings a particular regular expression describes? Cheers, -Blair From deets at nospam.web.de Mon May 15 09:33:24 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 15:33:24 +0200 Subject: Web development with python. References: <1147699600.770756.123120@v46g2000cwv.googlegroups.com> Message-ID: <4cre9eF1751ntU1@uni-berlin.de> j.paston.cooper at gmail.com wrote: > Is Plone analoguous to ASP.NET? Is it a python web developing platform? No, if anything ZOPE is analogous to ASP.NET. Plone is an CMS (Conetent Management System) application written on top of ZOPE. > I am confused on what Turbogears is aswell because of the lack of > documentation for it. TurboGears is also like ASP.NET Diez From nobody at 127.0.0.1 Sun May 14 23:28:29 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 15 May 2006 03:28:29 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> Message-ID: <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> Eli Gottlieb wrote: > Actually, spaces are better for indenting code. The exact amount of > space taken up by one space character will always (or at least tend to > be) the same, while every combination of keyboard driver, operating > system, text editor, content/file format, and character encoding all > change precisely what the tab key does. What you see as tabs' weakness is their strength. They encode '1 level of indentation', not a fixed width. Of course tabs are rendered differently by different editors -- that's the point. If you like indentation to be 2 or 3 or 7 chars wide, you can view your preference without forcing it on the rest of the world. It's a logical rather than a fixed encoding. > There's no use in typing "tab" for indentation when my text editor will > simply convert it to three spaces, or worse, autoindent and mix tabs > with spaces so that I have no idea how many actual whitespace characters > of what kinds are really taking up all that whitespace. I admit it > doesn't usually matter, but then you go back to try and make your code > prettier and find yourself asking "WTF?" Sounds like the problem is your editor, not tabs. But I wouldn't rule out PEBCAK either. ;) > Undoubtedly adding the second spark to the holy war, Undoubtedly. Let's keep it civil, shall we? And please limit the cross-posting to a minimum. (directed at the group, not you personally Eli). -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From mwilson-to at sympatico.ca Fri May 5 16:18:11 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 05 May 2006 16:18:11 -0400 Subject: Tuple assignment and generators? In-Reply-To: <1146839183.981537.216320@y43g2000cwc.googlegroups.com> References: <mailman.5334.1146755400.27775.python-list@python.org> <1146826136.746268.4060@i40g2000cwc.googlegroups.com> <445b3960$1_3@news.bluewin.ch> <1146831804.396839.316070@v46g2000cwv.googlegroups.com> <syi*BxTfr@news.chiark.greenend.org.uk> <1146839183.981537.216320@y43g2000cwc.googlegroups.com> Message-ID: <GsO6g.2374$VV2.168419@news20.bellglobal.com> vdrab wrote: > I guess the take-away lesson is to steer clear from any reliance on > object identity checks, if at all possible. Are there any other such > "optimizations" one should like to know about? Object identity checks are just the thing/numero uno/ichiban for checking object identity. A code snipped like def broadcast (self, message): "Broadcast a message to all the other game players." for p in all_players: if p is not self: p.send (message) does just what I want and expect it to. Mel. From johnjsal at NOSPAMgmail.com Wed May 17 22:45:09 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 22:45:09 -0400 Subject: I'm just not cut out for web programming, I guess :) In-Reply-To: <446bbec5$0$5359$c3e8da3@news.astraweb.com> References: <%0Mag.2117$No6.46299@news.tufts.edu> <mailman.5844.1147901804.27775.python-list@python.org> <446bbec5$0$5359$c3e8da3@news.astraweb.com> Message-ID: <446be105$0$11726$c3e8da3@news.astraweb.com> John Salerno wrote: > Paul McNett wrote: > >> Are you sure the python that the web server runs has the cryptogen >> module available? > > Yes, this module and the cryptogen module (and the quotes.txt file) are > all in the same directory on the server. > >> Have you set the execute bit on your script? > > Yes, I have them both set to 755. > >> What's >> the output in your web server error log? > > Well, I can't seem to find any error logs. In my logs folder, there are > files called 'access.log' and 'ftp.log', but nothing that looks like an > error log. Hmmm, looks like they don't do error logging: Creating own error logs for debugging php scripts. Since we dont provide access to Apache error logs on shared hosting packages for technical reasons, you can create your own error logs for debugging PHP Scripts. Please insert the following code in your PHP script (or create separate file and and add the code in it. Include the file using "include()") error_reporting(0); $old_error_handler = set_error_handler("userErrorHandler"); function userErrorHandler ($errno, $errmsg, $filename, $linenum, $vars) { $time=date("d M Y H:i:s"); // Get the error type from the error number $errortype = array (1 => "Error", 2 => "Warning", 4 => "Parsing Error", 8 => "Notice", 16 => "Core Error", 32 => "Core Warning", 64 => "Compile Error", 128 => "Compile Warning", 256 => "User Error", 512 => "User Warning", 1024 => "User Notice"); $errlevel=$errortype[$errno]; //Write error to log file (CSV format) $errfile=fopen("errors.csv","a"); fputs($errfile,"\"$time\",\"$filename: $linenum\",\"($errlevel) $errmsg\"\r\n"); fclose($errfile); if($errno!=2 && $errno!=8) { //Terminate script if fatal errror die("A fatal error has occured. Script execution has been aborted"); } } From fredrik at pythonware.com Mon May 8 10:44:20 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 8 May 2006 16:44:20 +0200 Subject: Retrieving event descriptors in Tkinter References: <1147098160.527716.100700@y43g2000cwc.googlegroups.com> Message-ID: <e3nlg6$e2u$1@sea.gmane.org> Avi Kak wrote: > Does Tkinter provide a function that returns all the event descriptors > for a given widget class? I am looking for something similar to what > you get in Perl/Tk when you call bind() with a single explicit > argument. For example, in Perl/Tk, > > $widget->bind( Tk::Button ) > > returns a list like > > <Key-Return> > <Key-space> > <ButtonRelease-1> > .... > > Is it possible to do the same in Tkinter? I have looked through > Fredrik Lundh's on-line reference and also the one by John Shipman. I > am unable to locate the function I need. Perhaps I have not looked hard > enough. Any help would be much appreciated. Tkinter matches Tk quite closely, and there's no way to get *all* bindings for a standard widget with a single call at the Tk level (afaik). to extract the same information from a Tkinter widget, you should first call bindtags() on the widget to get a list of binding classes used for this widget, and you can then use bind_class(cls) to get the events for that class. to get all events, you can use something like: >>> bindings = set() >>> for cls in b.bindtags(): ... bindings |= set(b.bind_class(cls)) ... >>> bindings set(['<Alt-KeyRelease>', '<Leave>', '<Enter>', '<KeyRelease-Alt_L>', '<Key-Alt_R>', '<<PrevWindow>>', '<Key-F10>', '<KeyRelease-F10>', '<Key-space>', '<Alt-Key>', '<Button-1>', '<ButtonRelease-1>', '<KeyRelease-Alt_R>', '<Key-Tab>', '<Key-Alt_L>']) </F> From usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo Sat May 20 18:28:05 2006 From: usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo (KW) Date: Sun, 21 May 2006 00:28:05 +0200 Subject: PHP's openssl_sign() using M2Crypto? Message-ID: <slrne6v5vk.f2c.usenet2@localhost.localdomain> I'm trying to convert some PHP code using OpenSSL to Python and I'm stuck on openssl_sign() which uses an RSA private key to compute a signature. Example PHP code: $privkeyid = openssl_get_privatekey($priv_key, $key_pass); openssl_sign($data, $signature, $privkeyid); openssl_free_key($privkeyid); I've tried several permutations of the stuff in M2Crypto.EVP but I can't get it to work... The openssl module in PHP basicly does this (C code): EVP_SignInit(&md_ctx, EVP_sha1()); EVP_SignUpdate(&md_ctx, data, data_len); EVP_SignFinal(&md_ctx, sigbuf, &siglen, pkey); Looks like some magic is used to get pkey, I think that's what I'm missing. See php_openssl_evp_from_zval() in PHP's ext/openssl/openssl.c. I've tried the following: key = M2Crypto.EVP.load_key(keyfile, lambda x: passphr) hmac = M2Crypto.EVP.HMAC(key, 'sha1') hmac.update(message) hmac.final() But this results in: File "/usr/lib/python2.4/site-packages/M2Crypto/EVP.py", line 39, in __init__ m2.hmac_init(self.ctx, key, self.md) TypeError: expected a readable buffer object Segmentation fault Unfortunately M2Crypto documentation is practically nonexistent.. Best regards, -- Konrad From ptmcg at austin.rr._bogus_.com Tue May 23 02:01:43 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 23 May 2006 06:01:43 GMT Subject: groupby References: <mailman.6096.1148354906.27775.python-list@python.org><1148356503.165982.247800@y43g2000cwc.googlegroups.com> <mailman.6100.1148362738.27775.python-list@python.org> Message-ID: <bzxcg.53765$Qq.42913@tornado.texas.rr.com> "Bryan" <belred at gmail.com> wrote in message news:mailman.6100.1148362738.27775.python-list at python.org... > George Sakkis wrote: <snip> > > "The returned group is itself an iterator that shares the underlying > > iterable with groupby(). Because the source is shared, when the groupby > > object is advanced, the previous group is no longer visible. So, if > > that data is needed later, it should be stored as a list" > > > > George > > > > i read that description in the docs so many times before i posted here. now that > i read it about 10 more times, i finally get it. there's just something about > the wording that kept tripping me up, but i can't explain why :) > > thanks, > > bryan > So here's how to save the values from the iterators while iterating over the groupby: >>> m = [(x,list(y)) for x,y in groupby([1, 1, 1, 2, 2, 3])] >>> m [(1, [1, 1, 1]), (2, [2, 2]), (3, [3])] -- Paul From timr at probo.com Wed May 24 00:12:33 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 24 May 2006 04:12:33 GMT Subject: PEP-xxx: Unification of for statement and list-comp syntax References: <200605211711.25043.me+python@modelnine.org> <mailman.6034.1148237188.27775.python-list@python.org> <1148237544.579470.43420@i40g2000cwc.googlegroups.com> <mailman.6035.1148237860.27775.python-list@python.org> <1148247633.377696.157820@38g2000cwa.googlegroups.com> <rz5cg.20468$Lm5.8909@newssvr12.news.prodigy.com> <44717726$0$10541$636a55ce@news.free.fr> <55mcg.90656$dW3.37192@newssvr21.news.prodigy.com> Message-ID: <n5n7729kollvunmi8qolkp796j7l0l6sa9@4ax.com> Edward Elliott <nobody at 127.0.0.1> wrote: >bruno at modulix wrote: > >> Edward Elliott wrote: >>> You mean like this: >>> >>> s = "foo" + "bar" >>> s = 'foo' + 'bar' >>> s = 'foo' 'bar' >>> s = '%s%s' % ('foo', 'bar') >[snip] >> The real mantra is actually : >> "There should be one-- and preferably only one --obvious way to do it" >> >> Please note the "should", "preferably", and "obvious". > >Touche. Please tell me which of the above should obviously be the >preferable way to concatenate strings. All those weasel words prove my >point: it's a vague and watered-down guideline that gives way in the face >of other considerations. Well, there's really no difference between the first two, and this would work just as well: s = """foo""" + '''bar''' The third line only works for string constants, not for string variables. IMHO, it would be the preferred method for concatenating string constants. At one time, it was said that the "%" operator was the fastest way to concatenate strings, because it was implemented in C, whereas the + operator was interpreted. However, as I recall, the difference was hardly measurable, and may not even exist any longer. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From webraviteja at gmail.com Sun May 28 16:40:26 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 28 May 2006 13:40:26 -0700 Subject: Fancy GUI with Python In-Reply-To: <1148840759.152708.200750@u72g2000cwu.googlegroups.com> References: <1148840759.152708.200750@u72g2000cwu.googlegroups.com> Message-ID: <1148848826.938307.172320@u72g2000cwu.googlegroups.com> > Hi all. I just downloaded and installed the new Office suite from MS > with their new 'ribbon' based UI. I think it's pretty cool and AFT* > for a new UI paradigm. I hope it sticks. > Anyway, I'm wondering how to implement a gui like this with Python. I haven't seen their new Office suit (apart form a few screenshots). Judging from the past, the code is probably statically linked to MS Office. Many of the previous iterations of MS Office did introduce their own look and feels, effects and widgets. Third party Windows developers soon followed suit reimplementing the widgets. Delphi community for example focuses a lot on UI and UI effects (Python community does not). VCL libraries can be compiled to ActiveX components and you should then be able to use them from Python, at least on Windows. Or maybe someone will make a .NET assembly and you will be able to drive it from IronPython or Python for .NET. If you are lucky, it may even be cross-platform via Mono. > So I'm not sure if this is a Python question, a xxx-Python question > (where xxx is the widget toolkit of choice), or a windows API type of > question. This is NOT a Python specific issue. It is a widget library and FFI (Foreign Function Interface) issue. If another language can get at the functionality, so can Python. From dkuhlman at rexx.com Tue May 23 17:22:56 2006 From: dkuhlman at rexx.com (Dave Kuhlman) Date: Tue, 23 May 2006 21:22:56 GMT Subject: FAQ for XML with Python References: <3esbg.19024$Lm5.1740@newssvr12.news.prodigy.com> <slrne6skeo.o93.sybrenUSE@schuimige.stuvel.eu> Message-ID: <Q2Lcg.91149$dW3.15129@newssvr21.news.prodigy.com> Sybren Stuvel wrote: > Dave Kuhlman enlightened us with: >> For those who are beginners to using Python to process XML, I've >> recently updated my Python XML FAQ (PyXMLFaq). It has a number >> of code samples that may help you get started. > > You might want to include a list of things you assume the reader > already knows, including links to pages where the reader can learn > about them if it's not the case. > Good idea. I've added a couple of links near the top of the document to two sites (The XML Cover Pages and the XML page at Wikipedia) that explain these things better than I could. Thanks for the suggestion. Dave -- http://www.rexx.com/~dkuhlman From usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo Mon May 22 17:24:56 2006 From: usenet2 at wojasfoo.vvtpfoo.tudelftfoo.nlfoo (KW) Date: Mon, 22 May 2006 23:24:56 +0200 Subject: PHP's openssl_sign() using M2Crypto? References: <slrne6v5vk.f2c.usenet2@localhost.localdomain> <1148319025.745324.171890@i40g2000cwc.googlegroups.com> Message-ID: <slrne74b18.92s.usenet2@localhost.localdomain> On 2006-05-22, heikki at osafoundation.org wrote: > Does this work?: > > key = M2Crypto.EVP.load_key(keyfile, lambda x: passphr) > key.sign_init() > key.sign_update(message) > signature = key.final() No, I get this: AttributeError: PKey instance has no attribute 'sign_init' Best regards, -- Konrad From george.sakkis at gmail.com Thu May 18 13:27:48 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 May 2006 10:27:48 -0700 Subject: Feature request: sorting a list slice Message-ID: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> It would be useful if list.sort() accepted two more optional parameters, start and stop, so that you can sort a slice in place. In other words, x = range(1000000) x.sort(start=3, stop=-1) would be equivalent to x[3:-1] = sorted(x[3:-1]) but more efficient and without repeating the slice twice. If it's not too late for feature additions, I'd love to see this in 2.5. George From andrew.arobert at gmail.com Sun May 14 14:51:05 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sun, 14 May 2006 14:51:05 -0400 Subject: Question regarding checksuming of a file In-Reply-To: <7xhd3tav56.fsf@ruckus.brouhaha.com> References: <126d1u4ke4itg7f@corp.supernews.com> <roy-1E8950.21485413052006@reader1.panix.com> <126d3g8tkfovs19@corp.supernews.com> <1147593420.907522.325920@i40g2000cwc.googlegroups.com> <7xhd3tav56.fsf@ruckus.brouhaha.com> Message-ID: <126ev127h04e2bb@corp.supernews.com> When I run the script, I get an error that the file object does not have the attribute getblocks. Did you mean this instead? def getblocks(f, blocksize=1024): while True: s = f.read(blocksize) if not s: return yield s def getsum(self): md5sum = md5.new() f = open(self.file_name, 'rb') for line in getblocks(f) : md5sum.update(line) f.close() return md5sum.hexdigest() From maxm at mxm.dk Wed May 31 06:10:18 2006 From: maxm at mxm.dk (Max M) Date: Wed, 31 May 2006 12:10:18 +0200 Subject: Best Python Editor In-Reply-To: <mailman.6359.1149069835.27775.python-list@python.org> References: <mailman.6359.1149069835.27775.python-list@python.org> Message-ID: <447d6b4d$0$38672$edfadb0f@dread12.news.tele.dk> Manoj Kumar P wrote: > Hi, > > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. pydev on top of eclipse is a nice tool. -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From conanelbarbaro at gmail.com Mon May 29 10:20:43 2006 From: conanelbarbaro at gmail.com (conan) Date: 29 May 2006 07:20:43 -0700 Subject: unexpected behaviour for python regexp: caret symbol almost useless? In-Reply-To: <e5c2gt$duk$03$1@news.t-online.com> References: <1148815719.082410.313870@38g2000cwa.googlegroups.com> <e5c2gt$duk$03$1@news.t-online.com> Message-ID: <1148912443.789547.116000@j73g2000cwa.googlegroups.com> Thank you, i have read this but somehow a missed it when the issue arose. From tkpmep at hotmail.com Wed May 10 08:54:42 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 10 May 2006 05:54:42 -0700 Subject: PyExcelerator: How does one close a file? References: <1147211877.683702.272710@i40g2000cwc.googlegroups.com> <44611F77.4090207@lexicon.net> Message-ID: <1147265682.461615.57590@v46g2000cwv.googlegroups.com> John, I had spelled PyExcelerator with a capital P, but it worked just fine. I then checked the directory it was installed in, and found it read C:\Python24\Lib\site-packages\PyExcelerator. As soon as I changed the directory name to C:\Python24\Lib\site-packages\pyExcelerator, my programs stopped working! I then changed PyExcelerator to pyExcelerator in my programs and they worked alll over again. After much playing around, I discovered that I had incorrectly indented the call to writeData, so that it ran only once, after a loop was exited, and not for every iteration through the loop. Thanks Thomas Philips From vbgunz at gmail.com Fri May 12 11:45:43 2006 From: vbgunz at gmail.com (vbgunz) Date: 12 May 2006 08:45:43 -0700 Subject: find all index positions References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <1147374826.341124.129260@g10g2000cwb.googlegroups.com> <4463C188.3030202@lexicon.net> Message-ID: <1147448743.445465.124200@u72g2000cwu.googlegroups.com> Hello John, Thank you very much for your pointers! I decided to redo it and try to implement your suggestion. I think I did a fair job and because of your suggestion have a better iterator. Thank you! def indexer(string, substring, overlap=1): '''indexer(string, substring, [overlap=1]) -> int indexer takes a string and searches it to return all substring indexes. by default indexer is set to overlap all occurrences. to get the index to whole words only, set the overlap argument to the length of the substring. The only pitfall to indexer is it will return the substring whether it stansalone or not. >>> list(indexer('ababababa', 'aba')) [0, 2, 4, 6] >>> list(indexer('ababababa', 'aba', len('aba'))) [0, 4] >>> list(indexer('ababababa', 'xxx')) [] >>> list(indexer('show chow', 'how')) [1, 6] ''' index = string.find(substring) if index != -1: yield index while index != -1: index = string.find(substring, index + overlap) if index == -1: continue yield index if __name__ == '__main__': print list(indexer('ababababa', 'aba')) # -> [0, 2, 4, 6] print list(indexer('ababababa', 'aba', len('aba'))) # -> [0, 4] print list(indexer('ababababa', 'xxx')) # -> [] print list(indexer('show chow', 'how')) # -> [1, 6] From mirandacascade at yahoo.com Sat May 6 17:21:21 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 6 May 2006 14:21:21 -0700 Subject: the print statement Message-ID: <1146950481.610645.39710@j33g2000cwa.googlegroups.com> O/S: Win2K Vsn of Python: 2.4 Here is copy/paste from interactive window of pythonwin: >>> x = "Joe's desk" >>> y = 'Joe\x92s desk' >>> type(x) <type 'str'> >>> type(y) <type 'str'> >>> print x Joe's desk >>> print y Joe's desk >>> if x == y: ... print 'equal' ... else: ... print 'not equal' ... not equal >>> len(x) 10 >>> len(y) 10 >>> ord(x[3]) 39 >>> ord(y[3]) 146 >>> My questions are: 1) is the 'x' character within the variable y a signal that what follows is a hex value? 2) is it more than just a coincidence that 146 (the result of ord(y[3])) is the decimal equivalent of the hex number 92? 3) is there any character set in which 146 represents the single-quote/apostrophe character? if so, which character set? 4) what is the role/function of the backslash character in the variable y? 5) how did the print statement know to transform the contents of y ('Joe\x92s desk') to something that gets displayed as: Joe's desk ? 6) Would it be correct to infer that the print statement is aware of characters beyond the 128 characters in the ascii character set? From tim.peters at gmail.com Tue May 16 20:50:22 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 16 May 2006 20:50:22 -0400 Subject: advice modifying re library to support more than 100 named captures. In-Reply-To: <f98c79100605161734ia4d9ed2t84651c0ff6d4b9e9@mail.gmail.com> References: <f98c79100605161734ia4d9ed2t84651c0ff6d4b9e9@mail.gmail.com> Message-ID: <1f7befae0605161750ifca953fwca92fea33adca3@mail.gmail.com> [Richard Meraz] > We need to capture more than 99 named groups using python regular > expressions. > ... > its clear why the language designers have decided on this limitation. For > our system, however, it is essential that we be able to capture an arbitrary > number of groups. > > Could anyone on the list suggest what parts of the library code make > assumptions about this restriction? We'd like to make some local changes to > the core library to allow us to continue the development of our system (we > don't want to switch to another language). We removed the condition in > sre_compile.py that raises an exception for compiled regexps with more than > 100 groups. This allowed us to compile a regular expression with more than > 100 groups, but subsequent attempts to match or search with that regular > expression resulted in segfaults. Which is a good clue that you'll have to understand the C code implementing regexps. That's in Modules/_sre.c. In the absence of understanding, your best bet is to get in a debugger, see where it's segfaulting, guess at the cause, try to fix it, and start over. For a start, you'll certainly need to boost the value of this #define in sre.h: #define SRE_MARK_SIZE 200 Sorry, but I have no idea whether you'll need more than just that. From pydecker at gmail.com Wed May 24 20:49:24 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 24 May 2006 20:49:24 -0400 Subject: John Bokma harassment In-Reply-To: <Xns97CD6A2A4F305castleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> Message-ID: <ca55a9900605241749ucc6b4e8re6772a76a432e309@mail.gmail.com> On 24 May 2006 15:26:12 GMT, John Bokma <john at castleamber.com> wrote: > "Ant" <antroy at gmail.com> wrote: > > > I have no particular affinity for Xah's views, but what does get up my > > nose is usenet Nazism. > > That's because you're clueless. Sounds like your one of those Bush ass-lickers who think that being different is a crime. Intelligent people can handle weirdos. It's only uptight jerks who want everyone to fall into line with state/corporate policy. Sunshine is the best disinfectant. -- # p.d. From piet at cs.uu.nl Sat May 27 07:11:27 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Sat, 27 May 2006 13:11:27 +0200 Subject: getattr for modules not classes References: <5f56302b0605211252k79b642efl5ff4653fe7d17768@mail.gmail.com> <mailman.6044.1148244711.27775.python-list@python.org> <m2d5e3k06c.fsf@ordesa.cs.uu.nl> <mailman.6229.1148639913.27775.python-list@python.org> Message-ID: <m2k687iuxs.fsf@ordesa.cs.uu.nl> >>>>> Heiko Wundram <me+python at modelnine.org> (HW) schreef: >HW> from x import test as x >HW> print x.one >HW> print x.two >HW> print x.three Or replace test by x in x.py :=) -- Piet van Oostrum <piet at cs.uu.nl> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From timo.stamm at arcor.de Wed May 24 07:54:06 2006 From: timo.stamm at arcor.de (Timo Stamm) Date: Wed, 24 May 2006 13:54:06 +0200 Subject: John Bokma harassment In-Reply-To: <1148470149.596188.18500@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> Message-ID: <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> Tim N. van der Leeuw schrieb: > ilitzroth at gmail.com wrote: >> I agree there are limits to you right to free speech, but I believe Xah >> Lee is not crossing >> any boundaries. If he starts taking over newspapers and TV stations be >> sure to notify me, >> I might revise my position. >> Immanuel > > Perhaps he's not crossing boundaries of free speech, but he's > repeatedly crossing boundaries on usenet nettiquette, even though > repeatedly he's being asked not to do so. And repeatedly, others have encouraged him because they appreciate his posts. > but since I've stopped following threads originated by him That's all you need to do if you are not interested in his posts. Timo From mcfletch at vrplumber.com Sun May 14 09:49:00 2006 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Sun, 14 May 2006 09:49:00 -0400 Subject: State of the "Vaults of Parnassus" In-Reply-To: <e41s8n$thk$1@online.de> References: <e41s8n$thk$1@online.de> Message-ID: <4467354C.8060709@vrplumber.com> Christoph Zwerschke wrote: > Does anybody know what happened to the "Vaults of Parnassus" site at > http://www.vex.net/~x/parnassus/? > > "Dr Dobb's weekly Python news" still claims that it "ambitiously > collects references to all sorts of Python resources." But I have the > impression that it does not do this any more since April 2005, probably > because we have the Cheese Shop now. It's strange that the site does not > mention that it is not maintained any more, and it is still possible to > submit and update entries, but these changes seem to be discarded. > That's not very nice. Also, I found no contact address on the whole > website. Who is in charge of it? > > -- Christoph > The Vaults are run by one of my colleagues, who is (as it seems we all are), rather overworked these days. Last I heard he had someone who was helping him every once in a while to review the new submissions, but that was quite a while ago. I don't *think* there's any discarding, but rather a delay so long in publishing that it would feel like a discard... Take care, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From reply.in.the.newsgroup at my.address.is.invalid Mon May 8 03:51:24 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 08 May 2006 09:51:24 +0200 Subject: Getting HTTP responses - a python linkchecking script. References: <1147056628.354150.116120@y43g2000cwc.googlegroups.com> <3vqt52hb9b1k1ddk1pkqu9k1qb0kalcmor@4ax.com> <1147072270.475178.321030@v46g2000cwv.googlegroups.com> Message-ID: <o0ut525mher1oskjd0vt8tv0p3bm0j4c7p@4ax.com> blair.bethwaite at gmail.com: >Rene Pijlman wrote: >> blair.bethwaite at gmail.com: >> >with urllib2 it doesn't seem possible to get HTTP status codes. >> >> except urllib2.HTTPError, e: >> if e.code == 403: > >Thanks. Is there documentation for this available somewhere online, I >can't see it to obviously in the library reference? No, this seems to be missing from the documentation. -- Ren? Pijlman From alexander.kozlovsky at gmail.com Sun May 21 10:31:34 2006 From: alexander.kozlovsky at gmail.com (Alexander Kozlovsky) Date: Sun, 21 May 2006 18:31:34 +0400 Subject: dict!ident as equivalent of dict["ident"] In-Reply-To: <roy-D7CEAE.08522221052006@reader1.panix.com> References: <mailman.6027.1148213981.27775.python-list@python.org> <roy-D7CEAE.08522221052006@reader1.panix.com> Message-ID: <1883530248.20060521183134@gmail.com> Roy Smith wrote: > Define a class (perhaps a subclass of dict, if you like) > with a __getattr__ method. Then you can just do > > foo.bar.baz.x = y > > with no changes needed to the language. I think, your solution is very error-prone. If such enhanced dictionary contains "keys" key, what is meaning of d.keys? Is it bound method or dictionary item? After you introduce such dictionary, you cannot add any new method for it, because it may destroy user code, if acciddent name clashing take place. Consider SQLTable class, which have "name" attribute, and bunch of dynamically created named columns. With __getattr__ method you can use SQLTable.column_1 syntax for column access, but what if same column have name "name"? It may be very psychologically inconvenient for user of such class to use same foo.bar syntax for two different purposes. In most real cases it is important to distinguish between two different namespaces - "members" namespace with methods properties etc., and "items" namespace with truly dynamic content. In todays Python such distinction accomplished with two different methods - __getattr(ibute)__ and __getitem__. It is not possible to successfully use only __getattr__ to serve two different purposes. Hense I suggest use __getitem__ for its direct purpose, and only add some syntactic sugar for it Dan Sommers wrote: > Take a look at the "Bunch" recipe in the Python Cookbook: > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 This recipe is what is stated in its name - "collector of a bunch of named stuff". It is not suitable for elaborate classes with many methods (such as SQLTable), for above mentioned reason - name cluttering between methods, properties and dynamic content. -- Best regards, Alexander mailto:alexander.kozlovsky at gmail.com From rcs at bgoark.no Sun May 21 16:29:19 2006 From: rcs at bgoark.no (baalbek) Date: Sun, 21 May 2006 22:29:19 +0200 Subject: Using python for a CAD program In-Reply-To: <mailman.6000.1148109587.27775.python-list@python.org> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <e4ham3$1td$1@sea.gmane.org> <446C8950.3070107@anansispaceworks.com> <mailman.6000.1148109587.27775.python-list@python.org> Message-ID: <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> David Cuthbert wrote: > Some kind of transactionality is needed for undo/redo, but this is > usually done in a different (some might say "more efficient", others > might say "hackier") method than how transactions are implemented for > RDBMS (that I've dealt with, anyway). I suspect this can be attributed > to two major factors: concurrent access is never an issue in such > systems, and the number of database objects representing a given state > is far larger than in, say, e-commerce. No, concurrent access is highly relevant; for example, on a team of about 50 architects working on design and production drawings for a new hospital, each floor was one 'drawing' (dwg file), and thus stored on disk as a separate entity from the other floors. Now, only one architect could work on one floor at any time! And as info from the project goes (sums and statistics of data, for example areas), the only reliable (an efficient) way to gather this was to hack an in-house application that collected the desired info from the various binary dwgs stored on disk, and saved this data this to a RDBMS, for further report processing. And as far as administering the dwgs (see to it that the mass of drawings follow one dimensioning convention, similar fonts etc) the CAD systems today are a pure joke: roughly 10-30% of the time the architects spend on CAD is pure "hacking" each drawing to conform to standard, problems with layers being out of sync with the rest, internal blocks not being uptodate, etc etc etc. And just to work on one small area of a huge floor, the architect has to load the whole freaking floor... This is in 2006, not 1986! All of these problems (the technical ones, as well as problems of concurrency) would be neatly solved if the data had been stored in a RDBMS, instead being spread around on thousands of files on disk. The Autocad DWG format is already in a database like structure (tables being joined by keys etc), so the technical difficulty is not the show-stopper here; I suspect the management at Autodesk will simply not touch the milk-cow that Autocad has become, and does not understand the needs of the average CAD user anyway... I'm myself really fed up with the CAD situation of today, having battled for 10 years the various problems that comes with todays stone-age CAD systems. Jeez, 2006, and the state of the art CAD, Autocad, is still basically a primitive, one-user binary application. What a pathetic joke! Baalbek From iainking at gmail.com Fri May 19 09:32:59 2006 From: iainking at gmail.com (Iain King) Date: 19 May 2006 06:32:59 -0700 Subject: noob import question In-Reply-To: <mailman.5945.1148045097.27775.python-list@python.org> References: <mailman.5945.1148045097.27775.python-list@python.org> Message-ID: <1148045579.403909.110530@y43g2000cwc.googlegroups.com> Brian Blazer wrote: > OK, I have a very simple class here: > > class Student: > """Defines the student class""" > > def __init__(self, lName, fName, mi): > self.lName = lName > self.fName = fName > self.mi = mi > > Then I have a small script that I am using as a test: > > from Student import * > > s1 = Student("Brian", "Smith", "N") > > print s1.lName > > This works as expected. However, if I change the import statement to: > import Student > > I get an error: > TypeError: 'module' object is not callable > > I have tried to look up what is going on, but I have not found > anything. Would it be possible for someone to take a minute and give > an explanation? > I take it you are getting the error on the line s1 = Student("Brian", "Smith", "N") This is because when you use 'import Student', it loads the file Student.py into a namespace called Student (unlike the 'from' statement, which loads it into the main namespace). to access anything from your Student module, prepend with Student. , so your line becomes: s1 = Student.Student("Brian", "Smith", "N") Iain > Thank you - your time is appreciated. > > Brian > brian at brianandkate.com From chris.van.bael at gmail.com Wed May 24 02:48:43 2006 From: chris.van.bael at gmail.com (Chris_147) Date: 23 May 2006 23:48:43 -0700 Subject: can't figure out error: module has no attribute... In-Reply-To: <44732ee1$1_3@newspeer2.tds.net> References: <1148392551.118437.255680@i39g2000cwa.googlegroups.com> <44732ee1$1_3@newspeer2.tds.net> Message-ID: <1148453323.005374.160470@i40g2000cwc.googlegroups.com> Thanks for the reply. you are indeed right, they were included from different places. from C:\Python24\Lib and D:\mydir But the strange thing is: anywhere on C: the file from C:\Python24\Lib was included. in D:\mydir the one from that directory BUT: anywhere else on D: apparantly the one from D:\mydir was included ?! I would expect it would come from c:\Python24\Lib. Now I changed the files and of course I cannot reproduce it anymore. Oh well, now it works. From fredrik at pythonware.com Thu May 4 15:53:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 21:53:40 +0200 Subject: Swaying A Coder Away From Python References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com><mailman.5315.1146743831.27775.python-list@python.org><R40843717.445.3845.1@mx-extra.net><mailman.5329.1146749986.27775.python-list@python.org><C-l*WBOfr@news.chiark.greenend.org.uk> <mn.24307d65c4d4c37d.43626@yahoo.fr.invalid> Message-ID: <e3dm47$eh$1@sea.gmane.org> Rony Steelandt wrote: > What s wrong with VI ??? :) it's spelled "vim". </F> From birchb at ozemail.com.au Tue May 9 08:12:22 2006 From: birchb at ozemail.com.au (birchb at ozemail.com.au) Date: 9 May 2006 05:12:22 -0700 Subject: Deferred Evaluation in Recursive Expressions? Message-ID: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> While working on type expressions I am rather stuck for a way to express recursive types. A simple example of this is a singly-linked list of integers. In some languages you have compiler syntax which suspends evaluation so you can have recursive types. e.g. typedef Linked_List := int, Linked_List In LISP I would use a macro. I have tried using classes: class Linked_List(object): typedef = (int, Linked_List) The closest I have got in Python is the following: Linked_List = (int, lambda: Linked_List) # linked list of int this is OK, because lambda makes closure which is not executed. However it required the user of the type expression to call any lfunctions found whilst traversing the tree. To make this a little more OO, I could use a constructor to wrap the function: Linked_List = (int, recursive(lambda: Linked_List)) # linked list of int but I am not satisfied with the "look". Any suggestions? From __peter__ at web.de Sat May 20 09:13:42 2006 From: __peter__ at web.de (Peter Otten) Date: Sat, 20 May 2006 15:13:42 +0200 Subject: misleading prefix ++ References: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> Message-ID: <e4n4i6$s26$03$1@news.t-online.com> LuciferLeo at gmail.com wrote: > but when I input: >>>> ++i > and the interpreter replies > 0 > > Don't you think it is misleading when you expect a variable to > increment? You have been warned... $ cat pp.py i = 42 ++i print i --i $ pychecker pp.py Processing pp... 42 Warnings... pp.py:2: Operator (++) doesn't exist, statement has no effect pp.py:4: Operator (--) doesn't exist, statement has no effect ...or you would have been, had you used the pychecker :-) Now I'm not recommending >>> class Int(object): ... def __init__(self, value=0): ... self.value = 0 ... self.half = False ... def __pos__(self): ... if self.half: ... self.value += 1 ... self.half = not self.half ... return self ... def __str__(self): ... return str(self.value) ... __repr__ = __str__ ... >>> i = Int() >>> i 0 >>> ++i 1 >>> ++i 2 >>> i 2 which is slightly harder to fix than to break but gives some (weak) motivation not to rule out multiple prefixed signs. Peter From dacut at kanga.org Mon May 22 10:56:41 2006 From: dacut at kanga.org (David Cuthbert) Date: Mon, 22 May 2006 07:56:41 -0700 Subject: Using python for a CAD program In-Reply-To: <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <e4ham3$1td$1@sea.gmane.org> <446C8950.3070107@anansispaceworks.com> <mailman.6000.1148109587.27775.python-list@python.org> <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> <mailman.6062.1148282177.27775.python-list@python.org> <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> Message-ID: <e4sjfa$g7m$1@sea.gmane.org> baalbek wrote: > David Cuthbert wrote: >> This does not mean the design itself should be stored as an RDBMS. As >> I've stated previously, CAD data (both electrical and, it appears, >> mechanical) does not lend itself to RDBMS relationship modeling. > > I simply do not agree with this. > > A CAD program (like Autocad) is nothing > but an advanced database editor: the program loads data from a binary > file and creates its object (in memory) from the tables that it reads > from the file on the disk. Well, then, good luck with this. Let us know when you've rediscovered that simply structuring data in a table does not make an RDBMS. From lance at augustmail.com Tue May 16 17:48:02 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Tue, 16 May 2006 16:48:02 -0500 Subject: arrays, even, roundup, odd round down ? Message-ID: <446a4891$0$61165$ae4e5890@news.nationwide.net> So, I have using the following to grab numbers from MS Word. I discovered that that there is a "special" rule being used for rounding. If a ??.5 is even the number is to rounded down (20.5 = 20) if a ??.5 is odd the number is to rounded up (21.5 = 22) Brands = ["B1","B2"] A1 = [] A1 = [ re.search(r"(?m)(?s)\r%s.*?SECOND.*?(?:(\d{1,3}\.\d)\s+){2}" % i, target_table).group(1) for i in Brands ] A1 = [int(float(str(x))+0.5) for x in A1 ] print A1 Any solutions for this line with the above conditions? Just as a note, any other number ??.3,??.7 follows the normal pattern of rounding (21.3 = 21, 20.3 = 20, 21.7 = 22, 20.7 = 21) A1 = [int(float(str(x))+0.5) for x in A1 ] Lance From bignose+hates-spam at benfinney.id.au Tue May 23 18:00:45 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 24 May 2006 08:00:45 +1000 Subject: real time info to web browser from apache side ? References: <1148408900.176202.281530@g10g2000cwb.googlegroups.com> Message-ID: <874pzg2ygi.fsf@benfinney.id.au> "Joseph" <spmok2 at canada.com> writes: > So I am looking more for a push technology than a pull from teh > browser (user hit Ctrl-R to refresh is a pull). Not necessarily; just write the web page so that it instructs the browser to do the pull automatically, without refreshing the entire page. This has come to be known as AJAX (though, because this is the sort of thing JavaScript was designed for, some just call it JavaScript). -- \ "During my service in the United States Congress, I took the | `\ initiative in creating the Internet." -- Al Gore | _o__) | Ben Finney From roy at panix.com Wed May 10 13:57:19 2006 From: roy at panix.com (Roy Smith) Date: Wed, 10 May 2006 17:57:19 +0000 (UTC) Subject: unittest: How to fail if environment does not allow execution? References: <44622274.5040907@verizonbusiness.com> Message-ID: <e3t9hv$4a6$1@reader1.panix.com> Kai Grossjohann <kai.grossjohann at verizonbusiness.com> wrote: > I wrote a test case that depends on a certain file existing in the > environment. In theory, unit tests should not depend on any external factors, but we all know the difference between theory and practice, right? > So, I guess I should test that the file exists in the > setUp method. But what if it doesn't exist? How do I fail in that case? def setUp (self): try: open ("myEssentialTestFile") except IOError: self.fail ("Hey, dummy, myEssentialTestFile is missing!") From larry.bates at websafe.com Thu May 25 12:44:41 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 25 May 2006 11:44:41 -0500 Subject: Web frameworks and credit cards In-Reply-To: <mailman.6171.1148514649.27775.python-list@python.org> References: <mailman.6171.1148514649.27775.python-list@python.org> Message-ID: <4475DEF9.4050808@websafe.com> TrustCommerce (www.trustcommerce.com) has an easy to use Python interface (they other interfaces as well) that I've used on a large Zope project recently. -Larry Bates Ed Leafe wrote: > I may have an opportunity to develop an online ordering system for a > client, and will have the ability to develop using any tool I choose. > Given the fact that there are more web frameworks in Python than > keywords ;-) , what I need to know is any experience anyone out there > has had integrating credit card processing with the various Python web > frameworks. Until now, my only practical experience is with Zope 2.x, > but I'm open to any and all alternatives, so long as it's Python! > > -- Ed Leafe > -- http://leafe.com > -- http://dabodev.com > > > From tfb at conquest.OCF.Berkeley.EDU Thu May 11 05:41:38 2006 From: tfb at conquest.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 11 May 2006 02:41:38 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> <NUP7g.17$G22.12@fe11.lga> <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> <ubn362tg2ft4la26hq4so0ron8lsj7fvqe@4ax.com> <mao8g.5$CQ6.4@fe11.lga> Message-ID: <xcvejz0dhkd.fsf@conquest.OCF.Berkeley.EDU> Ken Tilton <kentilton at gmail.com> writes: > David C. Ullrich wrote: > > > But duh, if that's how things are then we can't have transitive > > dependencies working out right; surely we > > want to be able to have B depend on A and then C > > depend on B... > > (And also if A and B are allowed to depend on each > > other then the programmer has to ensure that the > > two rules are inverses of each other, which seems > > like a bad constraint in general, something non-trivial > > that the programmer has to get right.) > > Right, when I considered multi-way dependencies I realized I would > have to figure out some new syntax to declare in one place the rules > for two slots, and that would be weird because in Cells it is the > instance that gets a rule at make-instance time, so i would really > have to have some new make-instance-pair capability. Talk about a > slippery slope. IMO, the big constraints research program kicked off > by Steele's thesis withered into a niche technology because they > sniffed at the "trivial" spreadsheet model of linear dataflow and > tried to do partial and multi-way dependencies. I call it "a bridge > too far", and in my experience of Cells (ten years of pretty intense > use), guess what?, all we need as developers is one-way, linear, > fully-specified dependencies. It may also be that the bridge too far was in trying to do big, multi-way constraints in a general-purpose manner. Cells provides you with the basics, and you can build a special-purpose multi-way system on top of it, much like you can use it as a toolkit for doing KR. From NOatkinwSPAM at rpi.edu Sun May 7 04:53:20 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 04:53:20 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> Message-ID: <87mzducj27.fsf@rpi.edu> "Serge Orlov" <Serge.Orlov at gmail.com> writes: > Bill Atkins wrote: >> "Serge Orlov" <Serge.Orlov at gmail.com> writes: >> >> > Ken Tilton wrote: >> >> It is vastly more disappointing that an alleged tech genius would sniff >> >> at the chance to take undeserved credit for PyCells, something probably >> >> better than a similar project on which Adobe (your superiors at >> >> software, right?) has bet the ranch. This is the Grail, dude, Brooks's >> >> long lost Silver Bullet. And you want to pass????? >> >> >> >> C'mon, Alex, I just want you as co-mentor for your star quality. Of >> >> course you won't have to do a thing, just identify for me a True Python >> >> Geek and she and I will take it from there. >> >> >> >> Here's the link in case you lost it: >> >> >> >> http://www.lispnyc.org/wiki.clp?page=PyCells >> >> >> >> :) >> >> >> >> peace, kenny >> >> >> >> ps. flaming aside, PyCells really would be amazingly good for Python. >> >> And so Google. (Now your job is on the line. <g>) k >> > >> > Perhaps I'm missing something but what's the big deal about PyCells? >> > Here is 22-lines barebones implementation of spreadsheet in Python, >> > later I create 2 cells "a" and "b", "b" depends on a and evaluate all >> > the cells. The output is >> > >> > a = negate(sin(pi/2)+one) = -2.0 >> > b = negate(a)*10 = 20.0 >> > >> > =================== spreadsheet.py ================== >> > class Spreadsheet(dict): >> > def __init__(self, **kwd): >> > self.namespace = kwd >> > def __getitem__(self, cell_name): >> > item = self.namespace[cell_name] >> > if hasattr(item, "formula"): >> > return item() >> > return item >> > def evaluate(self, formula): >> > return eval(formula, self) >> > def cell(self, cell_name, formula): >> > "Create a cell defined by formula" >> > def evaluate_cell(): >> > return self.evaluate(formula) >> > evaluate_cell.formula = formula >> > self.namespace[cell_name] = evaluate_cell >> > def cells(self): >> > "Yield all cells of the spreadsheet along with current values >> > and formulas" >> > for cell_name, value in self.namespace.items(): >> > if not hasattr(value, "formula"): >> > continue >> > yield cell_name, self[cell_name], value.formula >> > >> > import math >> > def negate(x): >> > return -x >> > sheet1 = Spreadsheet(one=1, sin=math.sin, pi=math.pi, negate=negate) >> > sheet1.cell("a", "negate(sin(pi/2)+one)") >> > sheet1.cell("b", "negate(a)*10") >> > for name, value, formula in sheet1.cells(): >> > print name, "=", formula, "=", value >> > >> >> I hope Ken doesn't mind me answering for him, but Cells is not a >> spreadsheet (where did you get that idea?). > > It's written on the page linked above, second sentence: "Think of the > slots as cells in a spreadsheet, and you've got the right idea". I'm > not claiming that my code is full PyCell implementation. Unfortunately, it's *nothing* like a full PyCell implementation. I explained what Cells is above. It is not merely a spreadsheet - it is an extension that allows the programmer to specify how the value of some slot (Lisp lingo for "member variable") can be computed. It frees the programmer from having to recompute slot values since Cells can transparently update them. It has to do with extending the object system, not with merely setting tables in a hash and then retrieving them. >> It does apply the basic >> idea of a spreadsheet to software - that is, instead of updating value >> when some event occurs, you specify in advance how that value can be >> computed and then you stop worrying about keeping it updated. > > The result is the same. Of course, I don't track dependances in such a > tiny barebones example. But when you retrieve a cell you will get the > same value as with dependances. Adding dependances is left as an > exercise. > >> >> Incidentally, is this supposed to be an example of Python's supposed >> "aesthetic pleasantness"? > > Nope. This is an example that you don't need macros and > multi-statements. Ken writes: "While the absence of macros and > multi-statement lambda in Python will make coding more cumbersome". I'd > like to see Python code doing the same if the language had macros and > multi-statement lambda. Will it be more simple? More expressive? FWIW (absolutely nothing, I imagine), here is my take on your spreadsheet: http://paste.lisp.org/display/19766 It is longer, for sure, but it does more and I haven't made any attempt to stick to some minimum number of lines. >> I find it a little hideous, even giving you >> the benefit of the doubt and pretending there are newlines between >> each function. There's nothing like a word wrapped in pairs of >> underscores to totally ruin an aesthetic experience. > > I don't think anyone who is not a master of a language can judge > readability. You're just distracted by insignificant details, they > don't matter if you code in that language for many years. I'm not going > to tell you how Lisp Cell code looks to me ;) > >> P.S. Is this really a spreadsheet? It looks like it's a flat >> hashtable... > > Does it matter if it's flat or 2D? > Not really, because this is not Cells. -- This is a song that took me ten years to live and two years to write. - Bob Dylan From aleax at mac.com Tue May 23 23:01:53 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 23 May 2006 20:01:53 -0700 Subject: performance difference between OSx and Windows References: <1148250271.923728.271670@j73g2000cwa.googlegroups.com> <1148421261.164171.3310@g10g2000cwb.googlegroups.com> <1148427623.839043.208960@u72g2000cwu.googlegroups.com> Message-ID: <1hft3bp.mg6sa419t53ioN%aleax@mac.com> Brian <bnblazer at gmail.com> wrote: > dfj225 at gmail.com wrote: > > Hi Brian, > > > > You may have already considered this, but since I didn't see it > > mentioned in your post, I'll reply anyway. > > > > I believe the Python binaries that Apple includes with OS X are always > > slightly behind the latest that you can get from the official sources. > > I'm not infront of my Mac right now, so I can't tell you the disparity. > > You are right. Apple is quite far behind. I upgraded to 2.4.2 from > 2.3.x. The MS box has the same version. There's an excellent Universal version of 2.4.3 for MacOSX out on python.org and I suggest you get it. BTW, as I recently posted to rec.games.bridge and in more detail to it.comp.macintosh (in Italian), these days in my spare time I'm porting a library originally coded for Windows by Bo Haglund (whom I thank for giving me the sources, albeit under NDA), which does double-dummy analysis of bridge hands, to run as a Python extension under MacOSX and Linux (see http://www.aleax.it/Bridge ). Elapsed time per deal for hundreds of thousands of deals in a particularly difficult class (totally flat hands of middling strength playing at NT) is about: 1.26 seconds iBook G4 12" (1.33 GHz) 0.88 seconds Pentium 4 3.20 GHz (on Linux -- gcc 3.2) 0.80 seconds Powermac G5 dual 1.8 GHz 0.65 seconds Macbook Pro 2.0 GHz all w/Python 2.4.3, all save the Pentium w/gcc 4 and MacOSX 10.4, all times for using a single core/processor (I just run two processes when I want to max out BOTH cores/processors -- the analysis, which is a very sophisticated version of alpha-beta-pruning tree-search, easily takes 99 to 100% of CPU time with little memory, disk or other I/O use). Alex From john at castleamber.com Fri May 26 12:33:00 2006 From: john at castleamber.com (John Bokma) Date: 26 May 2006 16:33:00 GMT Subject: OT: Quote ? [was: John Bokma harassment] References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> <Xns97CE807F1ADC6castleamber@130.133.1.4> <Zpmdg.2874$%Z2.298786@news20.bellglobal.com> <4476efed$2$649$bed64819@news.gradwell.net> Message-ID: <Xns97CF757E136D6castleamber@130.133.1.4> "Chris Uppal" <chris.uppal at metagnostic.REMOVE-THIS.org> wrote: > [apologies to the whole flaming crowd for sending this to the whole > flaming crowd...] > > Geoffrey Summerhayes wrote: > >> After you kill Navarth, will it be nothing but gruff and deedle >> with a little wobbly to fill in the chinks? > > Where does that come from ? It sounds like a quote, and Navarth is a > Jack Vance name (and /what/ a character), but I don't remember the > rest of it occurring in Vance. Navarth is very present in "the palace of dreams" (Demon princes series) The gruff, deedle and wobbly is mentioned IIRC in Wyst (Alastor 1716), but not sure about it. IIRC it's all you need in the egalistic world of Wyst. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From sjmachin at lexicon.net Tue May 16 18:44:28 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 May 2006 15:44:28 -0700 Subject: Unable to extract Python source code using Windows References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> <446a0229$1@nntp0.pdx.net> <1147803456.431686.258380@i39g2000cwa.googlegroups.com> <s%oag.10539$B42.3092@dukeread05> Message-ID: <1147819468.448397.79650@y43g2000cwc.googlegroups.com> > http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tar.bz2 And the reason for posting that would be what? WinZip doesn't support bzip2 compression. http://www.python.org/ftp/python/2.4.3/Python-2.4.3.tgz (a gzipped tar file) is what the OP would be better pointed at. FWIW, I have just downloaded the above tgz file and successfully unpacked it with WinZip versions 9 and 10, and with 7-Zip. FWIW2, 7-Zip is *free* and handles bz2 files. I would suggest that the OP's copy of WinZip v10 is stuffed, or his whole download mechanism is stuffed. If he were to investigate properly (as suggested by ScottDD) instead of thrashing about, .... From johnjsal at NOSPAMgmail.com Tue May 16 10:31:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 14:31:00 GMT Subject: do/while structure needed In-Reply-To: <84li629bgn1cjogggr4lgc82hjna5l8tij@4ax.com> References: <4466bddd$0$18984$c3e8da3@news.astraweb.com><1147585422.693953.292480@u72g2000cwu.googlegroups.com> <4467786c$0$1956$c3e8da3@news.astraweb.com> <mailman.5725.1147714197.27775.python-list@python.org> <fz3ag.2094$No6.46227@news.tufts.edu> <84li629bgn1cjogggr4lgc82hjna5l8tij@4ax.com> Message-ID: <Emlag.2105$No6.46131@news.tufts.edu> Dennis Lee Bieber wrote: > And what syntax would you propose? I guess something like: do: stuff goes here and here and here while (condition) The absence of a colon after the while statement can be the signal that it isn't a regular while statement with a following block, but instead the final statement of a do/while loop. Or would that cause an issue? From ryanf at cs.uoregon.edu Tue May 23 15:27:37 2006 From: ryanf at cs.uoregon.edu (Ryan Forsythe) Date: Tue, 23 May 2006 12:27:37 -0700 Subject: Accessing object parent properties In-Reply-To: <af3c42f10605231127w4af23544ob52e877e9292a117@mail.gmail.com> References: <af3c42f10605230527o75d06818x42a177f41e480d6e@mail.gmail.com> <Xns97CC5F55ECF8Bmaxericksongmailcom@80.91.229.5> <af3c42f10605231127w4af23544ob52e877e9292a117@mail.gmail.com> Message-ID: <44736229.5070501@cs.uoregon.edu> Cloudthunder wrote: > How can I set up method delegation so that I can do the following: > > A.run() > > and have this call refer to the run() method within the boo instance? Also, > what if I have tons of functions like run() within the boo instance and I > want all them to be directly accessible as if they were part of their > parent > (the Foo instance)? Are you sure you don't want to use a child class for this? In [1]: class A: ...: def foo(self): print "A defined me." ...: In [2]: class B(A): ...: def bar(self): print "B defined me." ...: In [3]: b = B() In [4]: b.foo() A defined me. In [5]: b.bar() B defined me. Otherwise, for every element of the A object in B you'd have to create an accessor function: In [12]: class C: ....: a = A() ....: def foo(self): self.a.foo() ....: In [13]: c = C() In [14]: c.foo() A defined me. There are ways to do this kind of automatically: In [16]: class D: ....: a = A() ....: def __getattr__(self, name): ....: return getattr(self.a, name) ....: In [17]: d = D() In [18]: d.foo() A defined me. ... but I doubt you need them. From tim.peters at gmail.com Tue May 2 21:27:43 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 2 May 2006 21:27:43 -0400 Subject: Strange result with math.atan2() In-Reply-To: <chuji3xd2m.ln2@pollux.home> References: <chuji3xd2m.ln2@pollux.home> Message-ID: <1f7befae0605021827k7b604406w7e2f6dd9881ad3a7@mail.gmail.com> [Vedran Fura?] > I think that this results must be the same: > > In [3]: math.atan2(-0.0,-1) > Out[3]: -3.1415926535897931 Whether -0.0 and 0.0 are different floats internally depends on your hardware floating-point; on most machines today, they are different floats, but _compare_ equal to each other. > In [4]: math.atan2(-0,-1) > Out[4]: 3.1415926535897931 "0" and "1" are integer literals, and there is no current hardware on which -0 produces a different bit pattern internally than 0. Of course you can _want_ them to be different, but you'll hope in vain ;-) > In [5]: -0 == -0.0 > Out[5]: True You'll also find that -0.0 == +0.0 returns True, despite that atan2 may treat them differently. The IEEE 754 standard for floating-point arithmetic requires that they compare equal, BTW. > This is python 2.4.4c0 on Debian GNU/Linux. Doesn't much matter. The hardware may matter, though, and so may the C library implementing atan2, and so may the set of option flags passed to the platform C compiler when Python is compiled. For example, DEC Alpha hardware has little native support for signed zeroes, and compilers for that box accept the HW limitations by default. Bottom line: if you want atan2 to treat signed zeroes differently, never use integer arguments (or results computed from integers), and even then don't expect it to be portable. From nephish at xit.net Mon May 22 10:14:57 2006 From: nephish at xit.net (nephish at xit.net) Date: 22 May 2006 07:14:57 -0700 Subject: problem with writing a simple module In-Reply-To: <4471C4D9.8020806@websafe.com> References: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> <4471C4D9.8020806@websafe.com> Message-ID: <1148307297.076724.128310@j33g2000cwa.googlegroups.com> ok, cool, and thanks very much. That worked. thanks for the info too. i am still new at the OO thing, just tired of doing a copy and paste over and over again. thanks again From apavluck at gmail.com Wed May 17 12:41:23 2006 From: apavluck at gmail.com (Alex Pavluck) Date: 17 May 2006 09:41:23 -0700 Subject: \t not working In-Reply-To: <1147883344.070704.127080@g10g2000cwb.googlegroups.com> References: <1147883344.070704.127080@g10g2000cwb.googlegroups.com> Message-ID: <1147884083.116465.304140@i40g2000cwc.googlegroups.com> Sorry, I just realized that if I run it as a script it just drops a line and doesn't tab but if I run it from the shell it outputs perfectly. Thanks for the help. From johnjsal at NOSPAMgmail.com Tue May 2 22:12:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 22:12:31 -0400 Subject: what is the 'host' for SMTP? Message-ID: <44581205$0$25583$c3e8da3@news.astraweb.com> If I want to write a cgi script that reads the contents of an HTML form and emails it to me, what would I use as the host parameter for my SMTP instance? The example in the docs is 'localhost', but I don't know what that means or refers to. I imagine I would have to use something that was tied to me specifically, but tied to what? My computer? My email address? From duncan.booth at invalid.invalid Sun May 14 10:39:14 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 14 May 2006 14:39:14 GMT Subject: any plans to make pprint() a builtin? References: <44669e46$0$5337$c3e8da3@news.astraweb.com> <Xns97C3667B2DA19duncanbooth@127.0.0.1> <1147613722.812929.23760@j73g2000cwa.googlegroups.com> Message-ID: <Xns97C397098238Aduncanbooth@127.0.0.1> Tim Golden wrote: > Duncan Booth wrote: >> Personally I'd just like to see 'python' a builtin shorthand for >> importing a name you aren't going to use much >> e.g. >> >> python.pprint.pprint(x) > > I think that's what the py.lib people have done with > their py.std module: > > http://codespeak.net/py/current/doc/misc.html#the-py-std-hook > > (At least, it looks like it; I've never used it myself). > Yes, I know it is easy enough to implement. I'm just suggesting that it might be useful as a builtin. After all, if I have to import something to use it I'd mostly just do the imports I needed instead. From bignose+hates-spam at benfinney.id.au Sun May 28 19:21:11 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 29 May 2006 09:21:11 +1000 Subject: send an email with picture/rich text format in the body References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <iAJ9g.76667$H71.54770@newssvr13.news.prodigy.com> <1148797671.937857.151250@y43g2000cwc.googlegroups.com> Message-ID: <87d5dx20t4.fsf@benfinney.id.au> "anya" <anyab5 at gmail.com> writes: > Acctualy there is a solution: > see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 Again, sending anything but plain text as the message body ensures that your message is unreadable to a large number of people using a variety of software. It's your choice whether to restrict your audience in this way, but know that that's what you're doing. If your message is going to be accompanied by a plain text body anyway (as advised by the recipe you refer to), that plain text body is either sufficient to give the necessary information, or not. If the plain text is sufficient, please don't bloat the message with the same information in an inefficient, non-standard message body. If the plain text is not sufficient to say what you want to say, please use a means of distributing it other than email. > and , if you will set all the neccessary parametrs, it won't be > recognized as a spam, For many people, who have trained their spam classifier with the majority of spam they receive, the simple fact that it contains HTML and images *at all* is enough to classify it as spam. -- \ "Prediction is very difficult, especially of the future." -- | `\ Niels Bohr | _o__) | Ben Finney From bignose+hates-spam at benfinney.id.au Wed May 17 19:22:38 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 09:22:38 +1000 Subject: How to tell if function was passed a list or a string? References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> <mailman.5848.1147906051.27775.python-list@python.org> <roy-7FE2C0.18573117052006@reader1.panix.com> Message-ID: <8764k4nsn5.fsf@benfinney.id.au> Roy Smith <roy at panix.com> writes: > Ben Finney <bignose+hates-spam at benfinney.id.au> wrote: > > Currently there's no good duck-typing way to differentiate strings > > from other sequences. > > I suppose you could do something like: > > try: > foo.isalpha > except AttributeError: > print "foo is not a string" > > but other than proving that you don't *have* to use isinstance(), I > don't think that approach has much going for it. Duck typing preserves one very important feature of Python: a class doesn't have to *inherit from* type 'foo' to be a *substitute for* type 'foo'. An 'isinstance' check will fail on objects that don't inherit from the string types, but do implement the interface adequately. In this example, if an object 'x' implements the behaviour you're going to use, but doesn't inherit from 'basestring', refusing it just because 'isinstance(x, basestring)' is False would be the wrong choice. -- \ "I planted some bird seed. A bird came up. Now I don't know | `\ what to feed it." -- Steven Wright | _o__) | Ben Finney From maric at aristote.info Sat May 13 11:32:12 2006 From: maric at aristote.info (Maric Michaud) Date: Sat, 13 May 2006 17:32:12 +0200 Subject: Package that imports with name of dependent package In-Reply-To: <4465E7AF.5030006@eastlink.ca> References: <4465E7AF.5030006@eastlink.ca> Message-ID: <200605131732.13211.maric@aristote.info> Le Samedi 13 Mai 2006 16:05, David Pratt a ?crit?: > I'd appreciate hearing of what I can do in an __init__ file or what > other strategy could make this work. Many thanks. you should leave the original package intact and patch it with new mehod and moddule; for example (A is the original package): A/__init__.py A/B/__init__.py A/B/C.py X/__init__.py X/B/__init__.py X/B/C.py just write in X/__init__.py : import A.B.C, B.C A.B.C = B.C and all "from A.B import C" following an import of X will return X.B.C. This is how we "monkeypatch" products in Zope. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From vbgunz at gmail.com Thu May 25 11:50:14 2006 From: vbgunz at gmail.com (vbgunz) Date: 25 May 2006 08:50:14 -0700 Subject: how to clear up a List in python? In-Reply-To: <e54gtn$grs$1@ulysses.news.tiscali.de> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <e54gtn$grs$1@ulysses.news.tiscali.de> Message-ID: <1148572214.017643.16210@i39g2000cwa.googlegroups.com> > del list1[:] thank you for that reply. I never thought of [:] cause to be me I thought it would immediately make a copy of the list or if anything that it would delete a copy so I never played with it. nice :) > del list1[:-1000] # keep max. last 1000 appended items in the list > list1[:]=replace_list very much thanks for the tips. they're great! From nobody at 127.0.0.1 Fri May 12 14:40:54 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 18:40:54 GMT Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> <m2irobbjtf.fsf@ordesa.lan> Message-ID: <WE49g.86156$dW3.50737@newssvr21.news.prodigy.com> Piet van Oostrum wrote: >>>>>> tsaar2003 at yahoo.com (T) wrote: > >>T> As you can see, the "constant" A can be modified this easily. But if >>T> there were an intuitive mechanism to declare a symbol to be immutable, >>T> then there won't be this problem. > > Mutability is not a property of symbols but of values. So it doesn't make > sense to declare an identifier to be immutable. And mutability is tied to > the object's type, not to individual instances. I think he meant immutable binding, not immutable symbol. So rebinding/overshadowing a "constant" A would raise an error, but mutating the underlying object A refers to would not (unless it too were immutable). As far objects themselves, adding an ability to make any object immutable regardless of type is exactly what he suggests. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From tzot at sil-tec.gr Tue May 2 04:48:44 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 02 May 2006 11:48:44 +0300 Subject: returning none when it should be returning a list? References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> <4455A4A1.7020807@lexicon.net> <1146493188.096280.83040@y43g2000cwc.googlegroups.com> Message-ID: <d17e52hfkuh69dbhpe7vtumk9lnqb3hv3j@4ax.com> On 1 May 2006 07:19:48 -0700, rumours say that randomtalk at gmail.com might have written: >I'm not sure what "falls off the end" of the function means, i searched >online, it seems to mean that the function has reached the end >prematurely and returned a default identifier to signal success or >not.. Can you please explain what that means? I think that you haven't grasped the fact that a chain of calls of a recursive function needs a return for *every* invocation of the function (but I could be wrong :) Check the following function, analogous to your own: >>> def f(x): if x > 4: print " returning", x return x else: print " start recursion" f(x+1) print " end recursion" >>> print f(0) start recursion start recursion start recursion start recursion start recursion returning 5 end recursion end recursion end recursion end recursion end recursion None Do you see why the function returns None? -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From python.list at tim.thechases.com Tue May 2 18:07:10 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 02 May 2006 17:07:10 -0500 Subject: search file for tabs In-Reply-To: <1146606666.249084.12810@j73g2000cwa.googlegroups.com> References: <1146606666.249084.12810@j73g2000cwa.googlegroups.com> Message-ID: <4457D80E.6000201@tim.thechases.com> > The following code to search a file for tabs does not > work, at least on Windows XP. Could someone please tell > me what's wrong? Thanks. > > xfile = "file_with_tabs.txt" > for text in open(xfile,"r"): > text = text.strip() > if ("\t" in text): > print text Well, are the tabs embedded, or at the beginning/end of the line? If they're at the beginning/end of the line, you're removing them with the strip() call. Solution: don't do that. :) Patient: "Doctor! It hurts when I press here." Doctor: "Well don't press there" tim at rubbish:~/tmp$ cat -A file_with_tabs.txt ^Ione^Itwo three^I $ five^Isix $ ^I seven^Ieight^I$ ^Inine^Iten ^I$ ^Ieleven^I$ twelve^I$ ^Ithirteen$ With this file, and without the strip() line in your original, I get all the lines. With the strip, I don't get the "eleven" line or following. If you were using strip() to get rid of the newlines, you can easily enough do that with text = text[:-1] Or, depending on what your needs are, rstrip() may do the trick for you. Hope this helps, -tkc From Florian.Lindner at xgm.de Wed May 10 17:31:33 2006 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Wed, 10 May 2006 23:31:33 +0200 Subject: ConfigParser and multiple option names References: <e37rji$c46$1@news.in.tum.de> <mailman.5236.1146607053.27775.python-list@python.org> <1146831486.852415.5070@i39g2000cwa.googlegroups.com> Message-ID: <e3tm5j$dn8$1@news.in.tum.de> jorge.vargas at gmail.com wrote: > that will break horribly in windows, remenber it install all it's crap > in c:\Program Files Why should this break? If you split at the \n character? Florian From nogradi at gmail.com Mon May 1 14:01:13 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 1 May 2006 20:01:13 +0200 Subject: how to do with the multi-frame GIF In-Reply-To: <1146501122.180961.11580@i39g2000cwa.googlegroups.com> References: <1146501122.180961.11580@i39g2000cwa.googlegroups.com> Message-ID: <5f56302b0605011101ia970684p5ccffdba5115ac83@mail.gmail.com> > how to do with the multi-frame GIF, I used the PIL ,but it seems not > support? The source distribution of the 1.1.4 version comes with a Scripts directory where you can find player.py, gifmaker.py and explode.py which all deal with animated gif. I don't know if they work with version 1.1.5 though. The 1.1.4 source is here: http://effbot.org/downloads/Imaging-1.1.4.tar.gz From johnjsal at NOSPAMgmail.com Mon May 8 10:04:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 14:04:34 GMT Subject: utility functions within a class? In-Reply-To: <USH7g.2052$No6.45672@news.tufts.edu> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <USH7g.2052$No6.45672@news.tufts.edu> Message-ID: <SdI7g.2055$No6.45780@news.tufts.edu> John Salerno wrote: > blair.bethwaite at gmail.com wrote: >> John Salerno wrote: >>> What I originally meant was that they would not be called from an >>> instance *outside* the class itself, i.e. they won't be used when >>> writing another script, they are only used by the class itself. >> >> Yep, so you want to encapsulate the functionality that those methods >> provide, which is the whole point of building them in a class in the >> first place. And you want them to be private to the class so that they >> do not form part of the classes public/external interface. > > But it's right that they should still be regular instance methods? So > from within the class I still call them as self._generate_head(), etc.? I tried the underscore method, but I was still able to call it as a regular instance method in the interpreter. Is that what's supposed to happen? From lance at augustmail.com Thu May 18 00:50:05 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Wed, 17 May 2006 23:50:05 -0500 Subject: excel centering columns In-Reply-To: <mailman.5858.1147917210.27775.python-list@python.org> References: <446ba8bd$0$61161$ae4e5890@news.nationwide.net> <mailman.5858.1147917210.27775.python-list@python.org> Message-ID: <446bfcfa$0$61163$ae4e5890@news.nationwide.net> Once I imported the EXCEL 10.0 library using 'makepy utility' everything worked fine. And, yes, my typing mistake. Should have been 'constants' and not 'constant' Lance From aleaxit at yahoo.com Fri May 5 10:06:29 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Fri, 5 May 2006 07:06:29 -0700 Subject: Python for Perl programmers References: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> <mailman.5340.1146765144.27775.python-list@python.org> Message-ID: <1heu1uo.13kryiryy0u8wN%aleaxit@yahoo.com> John J. Lee <jjl at pobox.com> wrote: > "A.M" <alanalan at newsgroup.nospam> writes: > > > Is there any efficient online resource or book that help experienced Perl > > programmers to Python? > > Worry instead about how you're going to keep maintaining your Perl > code after you've developed an allergic response to it. Nah, that's easy -- you port it to Python (that's what I did back in the day, and I've heard at least three others relate similar choices). Alex From snobis at gmx.de Tue May 9 04:42:09 2006 From: snobis at gmx.de (Stefan Nobis) Date: Tue, 09 May 2006 10:42:09 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <joadnUiUIdmNsP3ZnZ2dnUVZ_tKdnZ2d@speakeasy.net> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> Message-ID: <87ac9r1tem.fsf@snobis.de> aleax at mac.com (Alex Martelli) writes: > if anonymous functions are available, they're used in even more > cases where naming would help Yes, you're right. But don't stop here. What about expressions? Many people write very complex expression, that are hard to understand. A good language should forbid these abuse and don't allow expressions with more than 2 or maybe 3 operators! Forbid everything that might be abused and you have a perfect language? I like Python and I teach Python, I'm also used to Java and C#. But one of the best solutions to problems of beginners and not so brilliant programmers is something like the Dr. Scheme enviroment: Choose your language level yourself. Everyting (allowed constructs, error messages,...) will be adjusted to your choosen level. And experts have all at their fingertips they want and need. Code isn't blowed up and screwed with workaround for language limitations (that are aimed at beginners and less capable programmers). Why only adjust to the less capable people? Give everyone what they need and want! :) -- Stefan. From john at castleamber.com Thu May 25 14:58:11 2006 From: john at castleamber.com (John Bokma) Date: 25 May 2006 18:58:11 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> <Xns97CE807F1ADC6castleamber@130.133.1.4> <Zpmdg.2874$%Z2.298786@news20.bellglobal.com> Message-ID: <Xns97CE8E1B64A6Bcastleamber@130.133.1.4> "Geoffrey Summerhayes" <sRuEmMrOnVoEt at hotmail.com> wrote: > After you kill Navarth, will it be nothing but gruff and deedle > with a little wobbly to fill in the chinks? Comparing Navarth with Xah is a huge insult to Jack Vance. You should be ashamed of yourself for even thinking about it, let alone write it down. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From maxerickson at gmail.com Tue May 30 17:14:28 2006 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 30 May 2006 21:14:28 +0000 (UTC) Subject: create a text file References: <Xns97D3657BA981Emaxericksongmailcom@80.91.229.5> <e5htg5$89d$1@sea.gmane.org> Message-ID: <Xns97D3AF9FB8581maxericksongmailcom@80.91.229.5> Fredrik Lundh <fredrik at pythonware.com> wrote: > Max Erickson wrote: > >>> # w is for writing >>> myfile = open('theoutfile',w) >> >> That won't work, the second argument to open needs to be a string: > > w = 'w' > > </F> > Is it inappropriate to call the w on the left side of the equal's sign a string? I.e., w refers to a string(object) that contains 'w'? My goal was to point out that the code would not work as posted. max From richard at nospam.com Fri May 19 17:00:34 2006 From: richard at nospam.com (Richard Townsend) Date: Fri, 19 May 2006 22:00:34 +0100 Subject: altering an object as you iterate over it? References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <e4la8j$od9$1@daisy.noc.ucla.edu> Message-ID: <gna24m8llepz$.xxuybbscn0nn$.dlg@40tude.net> On Fri, 19 May 2006 13:36:35 -0700, James Stroud wrote: > Paul McGuire wrote: >> Your coding style is a little dated - are you using an old version of >> Python? This style is the old-fashioned way: > [clip] >> 1. open("xxx") still works - not sure if it's even deprecated or not - but >> the new style is to use the file class > > > Python 2.3.4 (#4, Oct 25 2004, 21:40:10) > [GCC 3.3.2 (Mandrake Linux 10.0 3.3.2-6mdk)] on linux2 > Type "help", "copyright", "credits" or "license" for more information. > py> open is file > True > > James As part of a discussion on Python-Dev in 2004 about using open() or file() Guido replied: > Then should the following line in the reference be changed? > > "The file() constructor is new in Python 2.2. The previous spelling, > open(), is retained for compatibility, and is an alias for file()." > > That *strongly* suggests that the preferred spelling is file(), and > that open() shouldn't be used for new code. Oops, yes. I didn't write that, and it doesn't convey my feelings about file() vs. open(). Here's a suggestion for better words: "The file class is new in Python 2.2. It represents the type (class) of objects returned by the built-in open() function. Its constructor is an alias for open(), but for future and backwards compatibility, open() remains preferred." See: http://mail.python.org/pipermail/python-dev/2004-July/045931.html -- Richard From roy at panix.com Tue May 16 16:15:18 2006 From: roy at panix.com (Roy Smith) Date: Tue, 16 May 2006 20:15:18 +0000 (UTC) Subject: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? References: <1147657728.064817.214850@j73g2000cwa.googlegroups.com> <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> <1147804326.793291.53410@j55g2000cwa.googlegroups.com> <mailman.5762.1147805604.27775.python-list@python.org> Message-ID: <e4dbsm$b9q$1@reader1.panix.com> In article <mailman.5762.1147805604.27775.python-list at python.org>, <skip at pobox.com> wrote: > > Graham> Looking up a key in a dictionary is done in constant-time, > Graham> i.e. it doesn't matter how large the dictionary is. > >Doesn't that depend on how many keys hash to the same value? For small >dictionaries keeping the max keys that hash to the same value small isn't a >huge problem. For large dictionaries (millions of keys) might you have some >long chains? Or in an effort to reduce the chain length, wind up using so >much virtual memory that you wind up wrecking performance by swapping? If you're getting long hash chains, you're either using a bad hash function, or your table isn't big enough. From fredrik at pythonware.com Wed May 10 14:20:36 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 10 May 2006 20:20:36 +0200 Subject: syntax for -c cmd References: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> Message-ID: <e3tatm$8oa$1@sea.gmane.org> James wrote: > Wrong syntax is shown below. What should be the delimiter before else? > > python -c 'if 1==1: print "yes"; else print "no"' there is no such delimiter. Python's syntax doesn't allow you to put multiple clauses on a single line. if your shell supports it, use a "here document", or embedded newlines. if not, use a script. </F> From Serge.Orlov at gmail.com Mon May 22 21:42:52 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 22 May 2006 18:42:52 -0700 Subject: NEWB: reverse traversal of xml file References: <1148344898.351787.159540@i40g2000cwc.googlegroups.com> Message-ID: <1148348572.610824.137750@j33g2000cwa.googlegroups.com> manstey wrote: > Hi, > > I have an xml file of about 140Mb like this: > > <book> > <record> > ... > <wordpartWTS>1</wordpartWTS> > </record> > <record> > ... > <wordpartWTS>2</wordpartWTS> > </record> > <record> > ... > <wordpartWTS>1</wordpartWTS> > </record> > </book> > > I want to traverse it from bottom to top and add another field to each > record <totalWordPart>1</totalWordPart> > which would give the highest value of wordpartWTS for each record for > each word > > so if wordparts for the first ten records were 1 2 1 1 1 2 3 4 1 2 > I want totalWordPart to be 2 2 1 1 4 4 4 4 2 2 > > I figure the easiest way to do this is to go thru the file backwards. > > Any ideas how to do this with an xml data file? You need to iterate from the beginning and use itertools.groupby: from itertools import groupby def enumerate_words(parts): word_num = 0 prev = 0 for part in parts: if prev >= part: word_num += 1 prev = part yield word_num, part def get_word_num(item): return item[0] parts = 1,2,1,1,1,2,3,4,1,2 for word_num, word in groupby(enumerate_words(parts), get_word_num): parts_list = list(word) max_part = parts_list[-1][1] for word_num, part_num in parts_list: print max_part, part_num prints: 2 1 2 2 1 1 1 1 4 1 4 2 4 3 4 4 2 1 2 2 From onurb at xiludom.gro Tue May 2 13:54:17 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 02 May 2006 19:54:17 +0200 Subject: simultaneous assignment In-Reply-To: <iqM5g.2032$No6.43913@news.tufts.edu> References: <8dM5g.2031$No6.43874@news.tufts.edu> <445792a3$1_2@news.bluewin.ch> <iqM5g.2032$No6.43913@news.tufts.edu> Message-ID: <44579d25$0$23113$626a54ce@news.free.fr> John Salerno wrote: > Boris Borcic wrote: > >> >>> w == x >> False >> >>> w is x >> True >> >>> > > > That's the opposite of what I want to happen. And that wouldn't be really helpful anyway !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jg.campbell.ng at gmail.com Sun May 28 12:20:56 2006 From: jg.campbell.ng at gmail.com (jg.campbell.ng at gmail.com) Date: 28 May 2006 09:20:56 -0700 Subject: Beginner Python OpenGL difficulties Message-ID: <1148833256.751748.291270@j55g2000cwa.googlegroups.com> I'm beginning learning Python and OpenGL in Python. Python fine. But difficulties with OpenGL; presumably with the installation of OpenGL. OS = Linux FC5. Python program gl_test.py: from OpenGL.GLUT import * from OpenGL.GLU import * from OpenGL.GL import * name = "Hello, World" height = 400 etc. jc at localhost~/etc/python>$ python2 gl_test.py Traceback (most recent call last): File "gl_test.py", line 1, in ? from OpenGL.GLUT import * ImportError: No module named OpenGL.GLUT jc at localhost~/etc/python>$ echo $PYTHONPATH /usr/lib/python2.2/site-packages/OpenGL jc at localhost/usr/lib/python2.2/site-packages/OpenGL>$ ll total 1076 drwxr-xr-x 13 root root 4096 May 28 15:17 Demo/ drwxr-xr-x 3 root root 4096 May 28 15:17 doc/ drwxr-xr-x 25 root root 4096 May 28 15:17 GL/ -rwxr-xr-x 1 root root 624927 Jan 2 2005 GLE.so* drwxr-xr-x 4 root root 4096 May 28 15:17 GLU/ -rwxr-xr-x 1 root root 312612 Jan 2 2005 GLUT.so* drwxr-xr-x 6 root root 4096 May 28 15:17 GLX/ -rw-r--r-- 1 root root 868 Mar 12 2004 __init__.py -rw-r--r-- 1 root root 1466 Jan 2 2005 __init__.pyc etc ... Any suggestions. TIA, Jon C. From scott.daniels at acm.org Mon May 8 14:20:04 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 11:20:04 -0700 Subject: utility functions within a class? In-Reply-To: <SdI7g.2055$No6.45780@news.tufts.edu> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <USH7g.2052$No6.45672@news.tufts.edu> <SdI7g.2055$No6.45780@news.tufts.edu> Message-ID: <445f881b$1@nntp0.pdx.net> John Salerno wrote: > John Salerno wrote: >> blair.bethwaite at gmail.com wrote: >>> John Salerno wrote: >>>> What I originally meant was that they would not be called from an >>>> instance *outside* the class itself, i.e. they won't be used when >>>> writing another script, they are only used by the class itself. >>> >>> Yep, so you want to encapsulate the functionality that those methods >>> provide, which is the whole point of building them in a class in the >>> first place. And you want them to be private to the class so that they >>> do not form part of the classes public/external interface. >> >> But it's right that they should still be regular instance methods? So >> from within the class I still call them as self._generate_head(), etc.? > > I tried the underscore method, but I was still able to call it as a > regular instance method in the interpreter. Is that what's supposed to > happen? If you called it, "__generate_head" you'd get more of what you expect. The Python philosophy is "we're all adults here," and the single leading underscore is meant to tell other users that the method is not for general use. Remember, you can't stop a user who insists on making mistakes. The double leading underscore is really meant for something else (names in "mixin" classes that don't accidentally collide with names in subclasses, for example). IMO, distutils, for example, over-uses the double leading underscore names; it makes it awkward for me to get to information that I'd like to obtain. The double leading underscore should be there if there is no reasonable use to getting to this info. I suspect leading double underscore names are more frequently written by Java and C++ fugitives who still have the "save the user from himself" attitude. --Scott David Daniels scott.daniels at acm.org From chris.cavalaria at free.fr Wed May 3 06:06:03 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 03 May 2006 12:06:03 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <mailman.5248.1146637412.27775.python-list@python.org> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com><4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> <mailman.5248.1146637412.27775.python-list@python.org> Message-ID: <445880e8$0$27057$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > tsaar2003 at yahoo.com wrote: > > >>For example: >> >> >>>>>A = [] # let's declare a "constant" here >>>>>b = A # and let's assign the constant here >>>>>b.append('1') # OOPS! >>>>>c = A >>>>>print A >> >>['1'] >> >>>>>print b >> >>['1'] >> >>>>>print c >> >>['1'] >> >>As you can see, the "constant" A can be modified this easily. But if >>there were an intuitive mechanism to declare a symbol to be immutable, >>then there won't be this problem. > > > why are you using mutable objects as constants? > > (insert obligatory "it hurts when I do this" joke here) > > btw, given a hypothetical "object that symbol points to is immutable" syntax, > what would you expect this to do ? > > >>> constant A = [] > > >>> b = [A] > > >>> # much later > >>> b[0].append('1') That's easy, since A is a symbolic constant know at compile time, and since it's a known mutable objet, the code once compiled will be equivalent to: >>> b = [[]] >>> # much later >>> b|0].append('1') From nobody at 127.0.0.1 Sat May 6 14:55:19 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 06 May 2006 18:55:19 GMT Subject: Newbie question on code vetting References: <yvT5g.132$yh.117@trnddc04> <mailman.5299.1146719004.27775.python-list@python.org> <_%w6g.44217$C63.42016@trnddc06> <cBz6g.67490$F_3.12273@newssvr29.news.prodigy.net> <TGV6g.112$W83.13@trnddc07> <mailman.5415.1146898161.27775.python-list@python.org> Message-ID: <ri67g.22464$4L1.12703@newssvr11.news.prodigy.com> I'm replying to Ben because William's post is no longer on my news server. <william.boquist at gte.net> wrote: > I would like to offer a couple of links to the kind of stuff I am talking > about w.r.t. the "transparency" issue. > First, some from Eclipse: > http://www.eclipse.org/legal/ See especially the "committer resources" > > Here are a couple more from the Apache software foundation. > http://www.apache.org/foundation/how-it-works.html Interesting, those links have nothing to do with checking the source of code and everything to do with the projects covering their asses. Which is perfectly reasonable behavior on their part, but it gives you, the end user, almost no protection. Suppose company X proves that project Foo incorporated some of their unlicensed code. Copyright infringement is a strict liability action. X can obtain an injunction against distributing Foo and impoundment/destruction of all infringing copies. Waivers like those above may indemnify Foo against monetary damages and legal fees, but end users are in the same position as without the waivers: their software Foo can be seized and destroyed. How exactly are you better off trusting Foo? Now maybe you could claim that merely using the waivers forces everyone to think long and hard about IP, avoiding potential issues, but that strikes me as more than a little dubious. People often don't even read what they sign, much less think about the implications. I am not a lawyer (yet), but I have studied US copyright law. > My thinking is that if that kind of documentation were more widely > available, the process of doing appropriate diligence on the part of the > consuming organizations would be easier and more repeatable. Looking for boilerplate waivers sounds more like CYA than diligence to me. > Asking the higher-ups at > work to reach technology management decisions based on my gut feel is an > uphill climb. And foolish. If you can't make a convincing case based on everything said in this thread, you may as well give up because your higher-ups aren't listening. > The overall goal is to remove a barrier to more widespread use of Open > Source - growing the mindshare dedicated to it and potentially shrinking > the mindshare dedicated to commercially-produced software. Ben already mentioned the false dichotomy here. Let me just say I think both your goal and his (spreading free software at the expense of non-free) are counterproductive. Organizations (and people) should look for the software that best fits their needs. Sometimes that means highest technical quality. Sometimes it means open standards or open source. Sometimes it means features X, Y, and Z. Sometimes it means vendor support. Often it's a combination. A successful project should focus on discovering and meeting its users' needs. Spreading open source for its own sake helps no one. > but > if the Open Source movement can cause Bill Gates to show his code to the > Chinese government, who knows what else it can do? Really, open source did that? Here I thought it was the the Chinese govt strongarming Microsoft over the promise of 1.3 billion potential consumers. > I think the Open > Source movement is leading, not following, commercial code producers. If > there is a better way to do business, I would like to see Open Source get > there first. "We must move forward, not backward, upward, not forward, and always twirling, twirling, twirling towards freedom!" Seriously, I think you're kidding yourself. Community-based, volunteer-driven open source projects handle some things very well. Closed, commercial projects excel at others. In between there's a lot of overlap with mixed attributes of each (not to imply these are merely two ends along a single spectrum, there are more dimensions involved). I think the market success of communal software shows that some software is becoming commoditized. Because software is a nonrivalous good (making copies is essentially free), it's usually more economically efficient for users to pool development costs and only pay for support than to pay for profits on each copy produced. Where it makes sense, the market is moving towards software as a public good rather than software as a product. Instead of digging out a huge canyon and charging for access to it (Microsoft/Oracle model), it's hiring out a river guide just to those who want one (Linux/MySQL model). Each has its place and neither is going away. Also note the public good approach doesn't require open source -- it works just as well with freely available binaries, a la Sun's Java VM. From scott.daniels at acm.org Tue May 16 18:07:26 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 16 May 2006 15:07:26 -0700 Subject: Unable to extract Python source code using Windows In-Reply-To: <1147803594.844448.271640@i39g2000cwa.googlegroups.com> References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> <446a0229$1@nntp0.pdx.net> <1147803594.844448.271640@i39g2000cwa.googlegroups.com> Message-ID: <446a492b$1@nntp0.pdx.net> Elric02 at rogers.com wrote: > Scott , > I tried downloading for different archives, (different versions of > Python) I can't believe they are all garbled. But they all don't work > with WinZip. > OK, against my better judgment (you haven't shown your work so far): I get an md5 for python-2.4.3.tar.bz2 of: 141c683447d5e76be1d2bd4829574f02 Next read about the tarfile module, where you may discover: import tarfile archive = tarfile.TarFile.open('python-2.4.3.tar.bz2', 'r:bz2') might give you something interesting. -- -Scott David Daniels scott.daniels at acm.org From onurb at xiludom.gro Tue May 2 13:50:54 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 02 May 2006 19:50:54 +0200 Subject: simultaneous assignment In-Reply-To: <8dM5g.2031$No6.43874@news.tufts.edu> References: <8dM5g.2031$No6.43874@news.tufts.edu> Message-ID: <44579c58$0$23113$626a54ce@news.free.fr> John Salerno wrote: > Is there a way to assign multiple variables to the same value, > but so > that an identity test still evaluates to False? re-phrase it according to how Python works, and you'll get the answer: "Is there a way to bind multiple names to the same object, but so the identity of this object is different from the identity of this object ?" > e.g.: > >>>> w = x = y = z = False the statement: a = False doesn't mean "assign the value False to the variable a", but "make the name 'a' reference the object False" - which is quite different. >>> a = False >>> b = False >>> a is b True >>> id(False) 46912499309888 >>> id(a) 46912499309888 >>> id(b) 46912499309888 >>> >>>> w > False >>>> x > False >>>> w == x > True >>>> w is x > True # not sure if this is harmful Using identity test for boolean tests is usually not a good idea since many other objects evals to True or False in a boolean context while not being neither the True nor the False objects. > The first line above is the only way I know to do it, but it seems to > necessarily lead to the true identity test. It does. Now if I may ask: what is your actual problem ? -- 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 Sun May 14 19:33:00 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 14 May 2006 16:33:00 -0700 Subject: comparing values in two sets In-Reply-To: <1147649349.305075.319740@j55g2000cwa.googlegroups.com> References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> <1147649349.305075.319740@j55g2000cwa.googlegroups.com> Message-ID: <1147649580.622549.155890@j33g2000cwa.googlegroups.com> So you probably have to change the function test_sets name, because it's not much useful on real sets. Can't you use the == or != operators on those sequences? Bye, bearophile From rpdooling at gmail.com Mon May 15 14:03:58 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 May 2006 11:03:58 -0700 Subject: keyword help in Pythonwin interpreter In-Reply-To: <e4a4im$7bn$01$1@news.t-online.com> References: <1147702380.665861.106540@g10g2000cwb.googlegroups.com> <e4a4im$7bn$01$1@news.t-online.com> Message-ID: <1147716237.952927.26990@j55g2000cwa.googlegroups.com> Peter, I filed a bug report. Thanks, rick From john at castleamber.com Thu May 18 17:12:33 2006 From: john at castleamber.com (John Bokma) Date: 18 May 2006 21:12:33 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: <Xns97C7A4E344C7Dcastleamber@130.133.1.4> "akameswaran at gmail.com" <akameswaran at gmail.com> wrote: > It seems to me the discussion could actually be beneficial. If several > different coders gave similar responses, ie code line/character count > comparisons, we might be able to see if there is a trend of any sort - > the more "anecdotes" given and we start to have trends - or maybe we > don't. What's the point? So you can say: Perl code has on average 1.727 more lines compared to Python? What's the point, both are tools. People who use both Perl and Python pick one to solve a problem because they want to pick what they believe is the right tool. I doubt that the number of lines is often on their mind. People who just know either Perl or Python don't care much about such figures, or so I hope. > Lastly, Ed - can you post the code? That may be putting your head in > the lion's mouth so to speak and make the whole thread even worse - and > your coding style will get shredded by perl advocates... ok nevermind > don't post it.' And not by Python advocates? > Ok I'm going to end with a flamebait - but I would posit, ALL OTHER > THINGS BEING EQUAL - that a smaller number of characters and lines in > code is more maintainable than larger number of characters and lines in > the code. And I think that's why a lot of people posted very negative, in the hope that people would not be tempted to make the above very dumb statement. -- 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 phpbird at gmail.com Fri May 19 02:28:01 2006 From: phpbird at gmail.com (Ju Hui) Date: 18 May 2006 23:28:01 -0700 Subject: Getting URL's In-Reply-To: <1148019975.277742.253400@y43g2000cwc.googlegroups.com> References: <1148019975.277742.253400@y43g2000cwc.googlegroups.com> Message-ID: <1148020081.055817.281770@38g2000cwa.googlegroups.com> use htmlparser or regular expression From NOatkinwSPAM at rpi.edu Sun May 7 15:56:18 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sun, 07 May 2006 15:56:18 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> <1hew3d4.1x2eems1pb7o5N%aleaxit@yahoo.com> <1147030835.498512.314110@u72g2000cwu.googlegroups.com> Message-ID: <87k68xy5gd.fsf@rpi.edu> olsongt at verizon.net writes: > Alex Martelli wrote: >> Steve R. Hastings <steve at hastings.org> wrote: >> ... >> > > But the key in the whole thread is simply that indentation will not >> > > scale. Nor will Python. >> > >> > This is a curious statement, given that Python is famous for scaling well. >> >> I think "ridiculous" is a better characterization than "curious", even >> if you're seriously into understatement. >> > > When you consider that there was just a big flamewar on comp.lang.lisp > about the lack of standard mechanisms for both threading and sockets in > Common Lisp (with the lispers arguing that it wasn't needed) I find it > "curious" that someone can say Common Lisp scales well. > It's not all that curious. Every Common Lisp implementation supports sockets, and most support threads. The "flamewar" was about whether these mechanisms should be (or could be) standardized across all implementation. It has little to do with CL's ability to scale well. You simply use the socket and thread API provided by your implementation; if you need to move to another, you write a thin compatibility layer. In Python, since there is no standard and only one implementation that counts, you write code for that implementation the same way you write for the socket and thread API provided by your Lisp implementation. I still dislike the phrase "scales well," but I don't see how differences in socket and thread API's across implementations can be interpreted as causing Lisp to "scale badly." Can you elaborate on what you mean? -- This is a song that took me ten years to live and two years to write. - Bob Dylan From rcs at bgoark.no Tue May 16 18:41:25 2006 From: rcs at bgoark.no (baalbek) Date: Wed, 17 May 2006 00:41:25 +0200 Subject: Using python for a CAD program In-Reply-To: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Message-ID: <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> > 1. Databases. I don't mean sql type database, but design databases, If you really want to revolutionize the CAD business, PLEASE don't base your CAD system on a file based system (ala Autocad). CAD systems available today (Autocad, Archicad, Architectural Desktop, etc) have one huge flaw: they don't store data to a SQL database, but to binary files. This fact has created so much problems (user problems as well as technical problems) in projects that involve several people. I know, I have 15 years of experience supporting teams using CAD, as well as CAD programming (mostly C++). The fact that Autodesk still to this day has not produced an Autocad version for a SQL database, shows how little innovation there is in large companies. I don't know where to start to list the numerous problems with a CAD system based on raw binary files, so I won't bother. Regards, and Good Luck, Baalbek From me+python at modelnine.org Wed May 24 02:54:38 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 24 May 2006 08:54:38 +0200 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <n5n7729kollvunmi8qolkp796j7l0l6sa9@4ax.com> References: <200605211711.25043.me+python@modelnine.org> <55mcg.90656$dW3.37192@newssvr21.news.prodigy.com> <n5n7729kollvunmi8qolkp796j7l0l6sa9@4ax.com> Message-ID: <200605240854.38886.me+python@modelnine.org> Am Mittwoch 24 Mai 2006 06:12 schrieb Tim Roberts: > At one time, it was said that the "%" operator was the fastest way to > concatenate strings, because it was implemented in C, whereas the + > operator was interpreted. However, as I recall, the difference was hardly > measurable, and may not even exist any longer. The difference doesn't exist anymore for CPython (if you join a lot of strings), but for Jython (and several other dialects), the fastest way to join strings is still "".join(), because there are no optimizations on a += b and the likes of it (replacement for the % operator, e.g.). --- Heiko. From rpw3 at rpw3.org Mon May 15 23:09:54 2006 From: rpw3 at rpw3.org (Rob Warnock) Date: Mon, 15 May 2006 22:09:54 -0500 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <44681F95.9040400@gmail.com> <d6lpsif6sku.fsf@vipunen.hut.fi> <O15ag.337$RM1.120@fe12.lga> Message-ID: <Saadne_UivQf3_TZnZ2dnUVZ_tSdnZ2d@speakeasy.net> Ken Tilton <kentilton at gmail.com> wrote: +--------------- | Having the reference implementation is the only thing that makes this | conceivably doable in a summer. What you are missing is something I have | often also gotten wrong: the core, cool functionality always comes easy | in the proof-of-concept stage. We make these ridiculous extrapolations | from that to a shipped product and come in five times over budget. +--------------- Or as Fred Brooks said it in "The Mythical Man-Month" [paraphrased], if a program takes one unit of effort, a programming *system* takes three units of effort, and a programming systems *product* takes nine units of effort. -Rob ----- Rob Warnock <rpw3 at rpw3.org> 627 26th Avenue <URL:http://rpw3.org/> San Mateo, CA 94403 (650)572-2607 From yasmeen_alkadi at yahoo.com Thu May 25 07:09:15 2006 From: yasmeen_alkadi at yahoo.com (Yasmeen Alkadi) Date: Thu, 25 May 2006 04:09:15 -0700 (PDT) Subject: pc 2 mobile via bluetooth Message-ID: <20060525110915.78164.qmail@web51407.mail.yahoo.com> hello :) could some1 help me plzzz is there a python script to connect my windows pc with my s60 mobile via bluetooth on both so i could send text files from my pc and recivee them on my phone thank u so much . . --------------------------------- How low will we go? Check out Yahoo! Messenger?s low PC-to-Phone call rates. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060525/22199674/attachment.html> From tdw at tdw.net Tue May 2 06:51:06 2006 From: tdw at tdw.net (Tim Williams) Date: Tue, 2 May 2006 11:51:06 +0100 Subject: stripping In-Reply-To: <W40649344.961.442.1@mx-extra.net> References: <W40649344.961.442.1@mx-extra.net> Message-ID: <9afea2ac0605020351w46e816fehdbbcd8e30b29f41@mail.gmail.com> On 1 May 2006 23:20:56 -0700, micklee74 at hotmail.com <micklee74 at hotmail.com> wrote: > > hi > i have a file test.dat eg > > abcdefgh > ijklmn > <-----newline > opqrs > tuvwxyz > <---newline > > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break > #if not re.findall(r'^$',line): > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all..? The break is terminating the while loop after the first blank line, replacing it with a continue would solve the problem in your script. However: f = open("test.dat") while 1: line = f.readline().rstrip("\n") if line: print line is simpler and easier to read. And: >>> f = open("test.dat").read() # read the whole file at once into string f >>> print f.replace('\n\n','\n') abcdefgh ijklmn opqrs tuvwxyz >>> even simpler, as long as the file isn't huge. If you need the final newline removed, use: >>>print f.replace('\n\n','\n')[:-1] abcdefgh ijklmn opqrs tuvwxyz >>> HTH :) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060502/ddcc69b8/attachment.html> From sybrenUSE at YOURthirdtower.com.imagination Tue May 16 05:01:23 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 16 May 2006 11:01:23 +0200 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> Message-ID: <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> Duncan Booth enlightened us with: > That is true so far as it goes, but equally if your editor inserts a > tab character when you press the tab key it is as broken as though > it inserted a backspace character when you press the backspace key. > In both of these cases you have an operation (move to next tabstop, > move back one space) and an ascii control character which is > intended to reflect that operation when rendering the file to an > output device. That all depends on the setting of your editor. After all, a TAB character could be the proper control character for the operation 'move to the next tabstop'. > An editor should be capable of letting you create or modify files > containing control characters without gratuitously corrupting them, > but the keys should perform the expected operations I agree with that. > not insert the characters. But not with that, since it is contradicting. "Inserting the characters" could very well be the same as "performing the expected operations". Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From chad at imvu.com Tue May 2 17:25:32 2006 From: chad at imvu.com (Chad Austin) Date: Tue, 02 May 2006 14:25:32 -0700 Subject: clearerr called on NULL FILE* ? Message-ID: <4457CE4C.9000800@imvu.com> Hi all, My first post to the list. :) I'm debugging one of our application crashes, and I thought maybe one of you has seen something similar before. Our application is mostly Python, with some work being done in a native C++ module. Anyway, I'm getting a memory access violation at the following stack: CRASHING THREAD EXCEPTION POINTERS: 0x0012e424 ExceptionRecord: 0x0012e518 ExceptionCode: 0xc0000005 EXCEPTION_ACCESS_VIOLATION ExceptionFlags: 0x00000000 ExceptionAddress: 0x7c901010 NumberParameters: 2 ExceptionInformation[0]: 0x00000000 ExceptionInformation[1]: 0x00000034 ExceptionRecord: 0x00000000 THREAD ID: 10b0 frame count: 4 PYTHON23!0x000baa00 - PyFile_Type PYTHON23!0x0003ac27 - PyFile_SetEncoding MSVCRT!0x00030a06 - clearerr ntdll!0x00001010 - RtlEnterCriticalSection Here's my understanding: something is getting called on a PyFileObject where f_fp is NULL, and clearerr in the multithreaded runtime tries to enter an invalid critical section. It looks like PyFile_SetEncoding in the stack, but I can't figure out how in the Python source how SetEncoding calls clearerr. Based on the timing of the crashes, I also think it might have something to do with log rollovers in RotatingFileHandler. Has anyone run into something similar? I don't expect anyone to spend a lot of time on this, but if there are any quick tips, they would be greatly appreciated... We're using Python 2.3.5 and Visual C++ 6. -- Chad Austin http://imvu.com/technology From swordsp at gmail.com Fri May 19 04:55:35 2006 From: swordsp at gmail.com (swordsp at gmail.com) Date: 19 May 2006 01:55:35 -0700 Subject: ftplib.ftpcp(), undocumented function? Message-ID: <1148028935.558821.198210@j33g2000cwa.googlegroups.com> Hi all, I found this function recently when I read the source code of ftplib module, I almost omit it at all and have tried to write it myself for FXP work. It seems exist long long ago, but never appeared in any document, anyone knows why? Is its implementation broken or planed to be removed from standard library? -- Gong Li From perlefar at gmail.com Wed May 24 10:31:14 2006 From: perlefar at gmail.com (Zameer) Date: 24 May 2006 07:31:14 -0700 Subject: Best way to handle exceptions with try/finally In-Reply-To: <pan.2006.05.24.11.59.47.24496@thomas-guettler.de> References: <mailman.6122.1148413632.27775.python-list@python.org> <pan.2006.05.24.11.59.47.24496@thomas-guettler.de> Message-ID: <1148481073.976420.316970@j55g2000cwa.googlegroups.com> Doing cleaup in except is not the Python way. This is what finally is for. Using except you would have to at least say: try: stuff() cleanup() except: cleanup() raise Duplicate code - not nice. finally is the Python way: try: stuff() finally: cleanup() That's it. But the return statement should not be a part of finally if you want exceptions to propagate out of the function containing try/finally. As mentioned multiple times in the thread. From rasmussen.bryan at gmail.com Thu May 4 08:15:37 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Thu, 4 May 2006 14:15:37 +0200 Subject: Pythoncard question In-Reply-To: <3bb44c6e0605040513r39663182w565589f0c43e86ae@mail.gmail.com> References: <4459e6b8@127.0.0.1> <3bb44c6e0605040513r39663182w565589f0c43e86ae@mail.gmail.com> Message-ID: <3bb44c6e0605040515q30b494a0u5b70cafa07c251ab@mail.gmail.com> oops, sorry about that. I copied the message over in gmail but forgot to change the subject. Sorry, Bryan Rasmussen From onurb at xiludom.gro Mon May 15 11:13:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 15 May 2006 17:13:22 +0200 Subject: How to organise classes and modules In-Reply-To: <mailman.5712.1147700233.27775.python-list@python.org> References: <mailman.5703.1147691931.27775.python-list@python.org> <44686c81$0$6834$626a54ce@news.free.fr> <mailman.5712.1147700233.27775.python-list@python.org> Message-ID: <44689af8$0$7026$636a55ce@news.free.fr> Alex wrote: > On 5/15/06, bruno at modulix <onurb at xiludom.gro> wrote: > (snip) > > Thanks for taking your time to help me out. :) You have cleared out > many of my doubts. BTW, should I post "thank you" stuff here Ain't that what you just did ?-) > or does > it just clutter? Nope, 'thank you' are always welcomes - eventually, take time to snip irrelevant material (no use to repost 100+ lines just to add 'thank you' at the bottom). > I tried sending an email to your personal email > listed (the one from which you send that mail to the list), but I got > this error: > > PERM_FAILURE: DNS Error: Domain name not found hint : have a look at my signature. > So I guess the entire list will have to be thanked for the help. : > ) indeed. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From nobody at 127.0.0.1 Tue May 16 14:25:27 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 16 May 2006 18:25:27 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> Message-ID: <rOoag.87512$dW3.76083@newssvr21.news.prodigy.com> achates wrote: > With spaces for indentation, this just isn't possible, because I have > to conform to your viewing preferences, and that makes me unhappy. Why > would you want to make me unhappy? +5 QOTW -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From steve at hastings.org Mon May 8 14:50:05 2006 From: steve at hastings.org (Steve R. Hastings) Date: Mon, 08 May 2006 11:50:05 -0700 Subject: Using StopIteration References: <1147112608.374083.99030@u72g2000cwu.googlegroups.com> Message-ID: <pan.2006.05.08.18.50.04.449783@hastings.org> On Mon, 08 May 2006 11:23:28 -0700, tkpmep wrote: > I create list of files, open each file in turn, skip past all the blank > lines, and then process the first line that starts with a number (see > code below) Here is what I suggest for you: filenames=glob.glob("C:/*.txt") for fn in filenames: for line in open(fn): if line[0] in digits: ProcessLine(line) break -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From mariano.difelice at gmail.com Fri May 19 10:28:47 2006 From: mariano.difelice at gmail.com (mardif) Date: 19 May 2006 07:28:47 -0700 Subject: open file with whitespaces Message-ID: <1148048927.878854.97120@y43g2000cwc.googlegroups.com> Hi guys. I've a very big big big problem: I've in my windows computer a file named cicciobello.html, located in c:\documents and settings\username\desktop\cicciobello.html. Now, I MUST open this file with os.spawn(os.P_WAIT ...., because I must wait the user cancel the explorer window, ok? And so, I write: import os os.spawnl(os.P_WAIT, "c:\programmi\internet explorer\iexplorer.exe", "c:\documents and settings\username\desktop\cicciobello.html") the python process don't fail, but explorer don't visualize correctly the file opened: i receive an "not found" error message. I've found that the whitespaces in file path are the problem. If you see to explorer address bar, you will find the address completely wrong... I've found no solution! Can you help me, please?? thx very very very much!!! From me+python at modelnine.org Sun May 21 16:54:53 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 21 May 2006 22:54:53 +0200 Subject: escapes in regular expressions In-Reply-To: <1148233776.133200.59280@u72g2000cwu.googlegroups.com> References: <1148233776.133200.59280@u72g2000cwu.googlegroups.com> Message-ID: <200605212254.53701.me+python@modelnine.org> Am Sonntag 21 Mai 2006 19:49 schrieb James Thiele: > >>> re.match('\d', '7').group() >>> print '\d' \d > >>> re.match('\\d', '7').group() >>> print '\\d' \d '\d' evaluates to \d, because d is not a valid escape sequence. '\n' evaluates to newline, because n is a valid escape sequence. '\\' evaluates to \, because \ is a valid escape sequence. --- Heiko. From bucodi at yahoo.fr.invalid Wed May 24 09:11:58 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Wed, 24 May 2006 15:11:58 +0200 Subject: Python keywords vs. English grammar References: <roy-CEC3E3.08573224052006@reader1.panix.com> Message-ID: <mn.c38f7d65a9a5e421.43626@yahoo.fr.invalid> I'm not a english speaker, so I just accepted it...; I understood it as : 'Try' allways to execute this code, 'except' when it doesn't work do this.... > I noticed something interesting today. In C++, you write: > > try { > throw foo; > } catch { > } > > and all three keywords are verbs, so when you describe the code, you can > use the same English words as in the program source, "You try to execute > some code, but it throws a foo, which is caught by the handler". > > In Python, you write: > > try: > raise foo > except: > > and now you've got a mix of verbs and (I think), a preposition. You can't > say, "You try to execute some code, but it raises a foo, which is excepted > by the handler". It just doesn't work grammatically. > > Sigh. -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From wrffruntre at tznvy.pbz.ROT13 Tue May 2 14:55:19 2006 From: wrffruntre at tznvy.pbz.ROT13 (Jesse Hager) Date: Tue, 02 May 2006 14:55:19 -0400 Subject: Multi-Monitor Support In-Reply-To: <-uGdnYcAYvZarsvZnZ2dnUVZ_s-dnZ2d@comcast.com> References: <-uGdnYcAYvZarsvZnZ2dnUVZ_s-dnZ2d@comcast.com> Message-ID: <125faob8fc0dma5@corp.supernews.com> Mark rainess wrote: > Hello, > > > Does Python or wxPython include any support for multiple monitors. In my > application multiple monitors are located at a distance. It is not > convenient to move a window from the main monitor to one of the others. > I want to have the option to open an an application on any connected > monitor. I am using wxPython. Does anyone know how to do it? > > Thanks > > Mark Rainess import wx app = wx.App() #To get the count of displays num_displays = wx.Display.GetCount() #Open a frame on each display for display_num in range(num_displays): #Get a display object display = wx.Display(display_num) #To get a wx.Rect that gives the geometry of a display geometry = display.GetGeometry() #Create a frame on the display frame = wx.Frame(None,-1,"Display %d"%display_num, geometry.GetTopLeft(),geometry.GetSize()) #Make the frame visible frame.Show() app.MainLoop() Creating a window on a different display is the same as creating one on the main display, all you need to do is specify coordinates somewhere on the alternate display when calling the constructor. Use wx.Display to find out about the displays on the system, it also lets you query and set the current video mode for a display. Hope this helps. -- Jesse Hager email = "wrffruntre at tznvy.pbz".decode("rot13") From tdwdotnet at gmail.com Thu May 25 05:53:25 2006 From: tdwdotnet at gmail.com (Tim Williams) Date: Thu, 25 May 2006 10:53:25 +0100 Subject: wincerapi Message-ID: <9afea2ac0605250253s2ee8d279o1c71da375767ec73@mail.gmail.com> Does anyone have a copy of the wincerapi module. It appears not to be in the win32 extensions anymore, and I've googled lots but not found it available anywhere. Thanks -- Tim Williams From test at test.test Tue May 9 01:54:00 2006 From: test at test.test (test at test.test) Date: Tue, 09 May 2006 00:54:00 -0500 Subject: Problem - Serving web pages on the desktop (SimpleHTTPServer) Message-ID: <fjb062999r1icbp5cavcktvifvsiijsj3e@4ax.com> Hi there, Perhaps someone can help me. For some reason, when my Python script runs and loads an HTML page in a new browser window at the local host (desktop), the links to my stylesheet and all the images are broken. I did check the HTML file by itself...everything loaded fine ;) Here's my script: -------------------- # File: webbrowser-test.py import webbrowser, SimpleHTTPServer from StringIO import StringIO f=open('testpage.html', 'rb') myPage = f.read() class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def send_head(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() return StringIO(myPage) webbrowser.open("http://127.0.0.1:8000", new=0, autoraise=1) SimpleHTTPServer.test(MyRequestHandler) -------------------- Here's my sample directory: --------------------------------- webbrowser-test.py testpage.html m_files/ |_____stylesheet.css |_____logo.gif -------------------------------- Thanks for having a look. My next step is to process form input using AJAX. I'll post working snippets of code here as I progress. Ben From webraviteja at gmail.com Wed May 10 04:19:52 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 10 May 2006 01:19:52 -0700 Subject: Can Python installation be as clean as PHP? In-Reply-To: <1147246996.480879.89910@v46g2000cwv.googlegroups.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> <1147211815.312069.135140@u72g2000cwu.googlegroups.com> <1147231092.546800.100860@j73g2000cwa.googlegroups.com> <1147234711.208138.160320@y43g2000cwc.googlegroups.com> <1147238991.889910.309190@j33g2000cwa.googlegroups.com> <1147246996.480879.89910@v46g2000cwv.googlegroups.com> Message-ID: <1147249192.645679.293690@i39g2000cwa.googlegroups.com> No! mod_python needs Python. It is simply an integration module for Apache and Python, not an interpreter. From jordan.taylor2 at gmail.com Tue May 23 13:13:55 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 23 May 2006 10:13:55 -0700 Subject: What's with the @ sign Message-ID: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> What's with code that has the @ symbol in front of classes or functions? This has probably already been asked but I can't find any info on it. Here is a slice of code I found that uses this, can someone please explain what the @'s for?? :: def option_error_decorator(func): def wrapper(*a, **k): try: return func(*a, **k) except _socket.error, (errno, info): raise SocketOptionError(errno, info) return wrapper def BoolOption(level, option): @option_error_decorator def getter(self): return bool(self._sock.getsockopt(level, option)) @option_error_decorator def setter(self, value): return self._sock.setsockopt(level, option, int(value)) return property(getter, setter) :: Thanks in advance, Jordan From nospam at nospam.nospam Tue May 30 03:51:47 2006 From: nospam at nospam.nospam (Nic) Date: Tue, 30 May 2006 09:51:47 +0200 Subject: Ricerca Programmatore Python References: <447ad3bd$0$36933$4fafbaef@reader3.news.tin.it> <447b07eb$1_3@news.bluewin.ch> Message-ID: <447bf999$0$14783$4fafbaef@reader4.news.tin.it> I read your replies and am really sorry for the trouble. Best regards, Nic "Boris Borcic" <bborcic at gmail.com> ha scritto nel messaggio news:447b07eb$1_3 at news.bluewin.ch... > Nic wrote: >> Please accept my apologies for the use of the Italian language. > > accepted From claird at lairds.us Tue May 9 07:44:54 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 9 May 2006 11:44:54 +0000 Subject: Econometrics in Panel data? References: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <07l062li47gjhuskkkqsai7kji82fpfjnq@4ax.com> <44606dd5$0$3285$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <mub6j3-sne.ln1@lairds.us> In article <44606dd5$0$3285$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>, DeepBlue <123 at 321.com> wrote: >so are you saying that Python is not an appropriate language for doing >econometrics stuff? > > >Dennis Lee Bieber wrote: >> On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <123 at 321.com> declaimed the >> following in comp.lang.python: >> >>> Hi all, >>> >>> I am new to Python. Just wondering can Python able to do econometric >>> regression in either Time-series or pooled (panel) data? As well as test >>> for hetero, autocorrelation, or endogeneity? >> >> Can you do such in FORTRAN, COBOL, SNOBOL, APL, C, Matlab, Maple, >> Excel, Turing Machine? Most likely... >> >> Is there a pre-built library to compute such? No idea... . . . While I count on Dennis to speak for himself, I'll interrupt and say that, yes, Python is an appropriate language for econometrics--but not an ideal one. There's been quite a bit of Python-based work on financial analytics in the past. I don't have a convenient handle on who all has done this, and what they've done, but I'm certain that research will yield results. Python boasts quite a few general advantages that make it apt for these tasks. There is not, however, a readily-accessible library targeted for this sort of work. If I had the opportunity to work in econometrics now, I'd think seriously about R, Lisp, and Mathematica, and see what's available among the functional languages, along with Python. From france.macchi at tele2.it Wed May 10 10:01:08 2006 From: france.macchi at tele2.it (Heavy) Date: 10 May 2006 07:01:08 -0700 Subject: problemi con POST References: <1147208587.275024.317410@i40g2000cwc.googlegroups.com> Message-ID: <1147269667.987862.104680@v46g2000cwv.googlegroups.com> Sorry, you got reason, I thought I can write in my language, cause this is the first time that I post a question in this group... My problem is that I have to receive parameters from a POST method, i try to read them from the socket 'rfile', but this action is blocking, it never finish to read. Is there some existing method that can help me? Can you help me? thanks... From paddy3118 at netscape.net Sat May 6 09:27:39 2006 From: paddy3118 at netscape.net (Paddy) Date: 6 May 2006 06:27:39 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> Message-ID: <1146922059.922802.29230@y43g2000cwc.googlegroups.com> Also addressing the Python and scaling question is the kamaelia.sourceforge.net project whos objective is to solve the problems of putting the BBCs vast archives on the web, and who use Python. -- Pad. From michele.simionato at gmail.com Tue May 16 05:16:06 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 16 May 2006 02:16:06 -0700 Subject: Multiple inheritance : waht does this error mean ? In-Reply-To: <1147750957.673439.154420@g10g2000cwb.googlegroups.com> References: <1147750957.673439.154420@g10g2000cwb.googlegroups.com> Message-ID: <1147770966.835917.185740@i40g2000cwc.googlegroups.com> jnair at ensim.com wrote: > I am using Python 2.4.3 > > >>>class K(object,list): > ...: pass > ...: > ------------------------------------------------------------ > Traceback (most recent call last): > File "<console>", line 1, in ? > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases object, list It is explained here: http://www.python.org/download/releases/2.3/mro/ Michele Simionato From bucodi at yahoo.fr.invalid Wed May 24 09:08:16 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Wed, 24 May 2006 15:08:16 +0200 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <mn.c36f7d65ac4090ff.43626@yahoo.fr.invalid> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> Message-ID: <mn.c38c7d6513194206.43626@yahoo.fr.invalid> Since I'm a professional developper,I don't think that my personnal view on those books would be of any use to you. I actually have no idea how to start Python if you're not a developper, I know it is possible since quit a lot of matimatical engineers use it. But I'm sure some people here will give you good advise. > Thanks, if you don't mind could I have a small <b>personal</b> > description on the quality of the books (pros, cons). > > I also am interested if anyone has used "Python Programming: An > Introduction to Computer Science" and if I could be given a detailes > evaluation about it. > > Thanks again. -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From deets at nospam.web.de Mon May 15 08:07:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 14:07:14 +0200 Subject: How to organise classes and modules References: <mailman.5703.1147691931.27775.python-list@python.org> Message-ID: <4cr97sF172steU1@uni-berlin.de> > Some unbound method error. Have I missunderstood something or am I on > the right track here? You misunderstood that you'd have to create an instance first before invoking a method on that very instance. That is the same in C++, btw. > But in my opinion, this is very ugly. Especially if the class names > are long, like my module/class TileDataBaseManager. But is this the > "right" way in python? I'm not sure what you mean by ugly. If you mean by ugly that you have to instantiate an object before using it - that is the way it works in _all_ OO languages. If you mean that you find it ugly to have long modulenames that are the same as the class-name - yes it is ugly - but that is utterly your personal decision to do so. In python, modules usually contain several classes, and the module name groups them by function and has a name related to that function. So most of the times one writes import module o = module.Class() Which is not ugly - IMHO at least :) Especially not more ugly than using C++ namespaces, isn't it? And that is what a module essentially is: a namespace. > Very clean from the outside. I would like something like this. But, > here, I loose the __init__ function. I have to call it manually that > is, which s not good. Also, maybe the biggest drawback, its no longer > in a class. Maybe its not that important in python but from what Ive > learned (in c++) object orientation is something to strive for. You seem to have some troubles with OO in general and with the way python does it. So I think it is kind of funny if you claim it is something to strive for. OO is no silver bullet - if you have something that can be dealt with using a function, it's perfectly good design to use one. Having objects just for the sake of it introduces all sorts of problems, related to unnecessary state, unclear implementation smeared over several methods an the like. > So, to sum it up, I have one class in one file, both with the same > name. How do I store/import/handle it in a nice, clean and python-like > manner? Group classes that belong to the same domain in one module. Import that, possibly using an alias like import MyLongDescriptiveModuleName as mn don't fall for the temptation to use from MyLongDescriptiveModuleName import * as it will cause only more headache! Diez From __peter__ at web.de Thu May 4 02:48:01 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 May 2006 08:48:01 +0200 Subject: Possibly dumb question about dicts and __hash__() References: <e3b0c0$g8o$1@news.lysator.liu.se> Message-ID: <e3c7vt$8u4$01$1@news.t-online.com> Joel Hedlund wrote: > There's one thing about dictionaries and __hash__() methods that puzzle > me. I have a class with several data members, one of which is 'name' (a > str). I would like to store several of these objects in a dict for quick > access ({name:object} style). Now, I was thinking that given a list of > objects I might do something like > > d = {} > for o in objects: > d[o]?=?o > > and still be able to retrieve the data like so: > > d[name] > > if I just defined a __hash__ method like so: > > def __hash__(self): > return?self.name.__hash__() Just the hash is not enough. You need to define equality, too: >>> class Named(object): ... def __init__(self, name): ... self.name = name ... def __hash__(self): ... return hash(self.name) ... def __eq__(self, other): ... try: ... other_name = other.name ... except AttributeError: ... return self.name == other ... return self.name == other_name ... def __repr__(self): ... return "Named(name=%r)" % self.name ... >>> items = [Named(n) for n in "alpha beta gamma".split()] >>> d = dict(zip(items, items)) >>> d["alpha"] Named(name='alpha') Peter From grante at visi.com Tue May 30 10:28:51 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 30 May 2006 14:28:51 -0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <447c52d7$0$696$fa0fcedb@news.zen.co.uk> Message-ID: <127oll38vlc3t0a@corp.supernews.com> On 2006-05-30, Peter Corlett <abuse at dopiaza.cabal.org.uk> wrote: > A dirty hack that might work is to rename /dev/ttyS* off somewhere else and > replace them with named pipes. Have a process monitor the named pipes and > relay data back and forth to the actual serial ports while logging it. The > serial ioctls won't work to the named pipe, but the application might not > notice it failed. If so, then that would be one pretty crappy application. ;) The slsnif program uses a pty so it will support at least some of the ioctl calls that a serial port does. -- Grant Edwards grante Yow! Yow! Is my fallout at shelter termite proof? visi.com From kent at kentsjohnson.com Fri May 19 05:56:01 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 19 May 2006 05:56:01 -0400 Subject: who can give me the detailed introduction of re modle? In-Reply-To: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: <446d957c$1_1@newspeer2.tds.net> softwindow wrote: > the re module is too large and difficult to study > > i need a detaild introduction. > http://www.amk.ca/python/howto/regex/ Kent From cristian.codorean at gmail.com Thu May 11 09:58:28 2006 From: cristian.codorean at gmail.com (Cristian.Codorean) Date: 11 May 2006 06:58:28 -0700 Subject: String concatenation performance Message-ID: <1147355908.655992.5720@g10g2000cwb.googlegroups.com> I was just reading a "Python Speed/Performance Tips" article on the Python wiki http://wiki.python.org/moin/PythonSpeed/PerformanceTips and I got to the part that talks about string concatenation and that it is faster when using join instead of += because of strings being immutable. So I have tried it: from time import time t=time() s='almfklasmfkmaskmkmasfkmkqemkmqeqw' for x in range(40): #s+= s[len(s)/2:] s="".join((s,s[len(s)/2:])) print 'duration', time() - t And I get 1.55016708374 for the concatenation and 3.01116681099 for the join. I have also tried to put the join outside but it is still a little bit over 3. I'm using Python 2.4.2, GCC 3.3.3 (SuSE Linux). So what am I doing wrong ? From python.list at tim.thechases.com Mon May 1 11:51:28 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Mon, 01 May 2006 10:51:28 -0500 Subject: list*list In-Reply-To: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> Message-ID: <44562E80.8040504@tim.thechases.com> > There must be a better way to multiply the elements of one list by > another: > > a = [1,2,3] > b = [1,2,3] > c = [] > for i in range(len(a)): > c.append(a[i]*b[i]) > a = c > print a > [1, 4, 9] > > Perhaps a list comprehension or is this better addressed by NumPy? a = [1,2,3] b = [1,2,3] c = [q*r for q,r in zip(a,b)] seems to do the trick for me. -tim From python.list at tim.thechases.com Wed May 24 16:36:24 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 24 May 2006 15:36:24 -0500 Subject: Finding Upper-case characters in regexps, unicode friendly. In-Reply-To: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> References: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> Message-ID: <4474C3C8.8080204@tim.thechases.com> > I'm trying to make a unicode friendly regexp to grab sentences > reasonably reliably for as many unicode languages as > possible, focusing on european languages first, hence it'd be > useful to be able to refer to any uppercase unicode character > instead of just the typical [A-Z], which doesn't include, for > example ?. Is there a way to do this, or do I have to stick > with using the isupper method of the string class? Well, assuming you pass in the UNICODE or LOCALE specifier, the following portion of a regexp *should* find what you're describing: ############################################### import re tests = [("1", False), ("a", True), ("Hello", True), ("2bad", False), ("bad1", False), ("a c", False) ] r = re.compile(r'^(?:(?=\w)[^\d_])*$') for test, expected_result in tests: if r.match(test): passed = expected_result else: passed = not expected_result print "[%s] expected [%s] passed [%s]" % ( test, expected_result, passed) ############################################### That looks for a "word" character ("\w") but doesn't swallow it ("(?=...)"), and then asserts that the character is not ("^") a digit ("\d") or an underscore. It looks for any number of "these things" ("(?:...)*"), which you can tweak to your own taste. For Unicode-ification, just pass the re.UNICODE parameter to compile(). Hope this makes sense and helps, -tkc From Joel.Hedlund at gmail.com Sat May 6 13:21:50 2006 From: Joel.Hedlund at gmail.com (Joel.Hedlund at gmail.com) Date: 6 May 2006 10:21:50 -0700 Subject: Is this a good use of __metaclass__? In-Reply-To: <445baf1a$0$2386$626a54ce@news.free.fr> References: <e3f96d$3oi$1@news.lysator.liu.se> <445baf1a$0$2386$626a54ce@news.free.fr> Message-ID: <1146936110.590076.295050@y43g2000cwc.googlegroups.com> Hi! Thank you for a quick and informative response! > I'd go for 'manually decorating' anyway. Metaclasses can be really handy > for framework-like stuff, but for the use case you describe, I think the > explicit decorator option is much more, well, explicit - and also more > flexible - than metaclass black magic. Yes, point taken. > This may also help you distinguish 'published' API from implementation (which is what > CherryPy do) Hmm... I'm not sure I understand how manually decorating would help me do that? With SimpleXMLRPCServer.register_instance(obj) all public methods of obj are published for XMLRPC, decorated or not. Off course, I could write a @do_not_publish decorator, but that seems backwards to me... I'm not familiar with how CherryPy works either, I'm sorry to say. > And finally, this may let you organize your code more freely - you > can mix methods needing different decorators in a same class. One can still do that, even if one would use a metaclass to set the "bare necessities" decorators. All you have to do is add the extra ones manually. I just meant to let the metaclass do the really, really important ones for me (the validator for each API class). The ones that I can't, won't, mustn't forget to add lest the Script Kiddies of the Internet come brutalizing my data. :-) > You would then have a 'server' class that just provides common > services and dispatch to specialized objects. Neat. It won't play nice with dir() or SimpleXMLRPCServer's introspection functions though (system.listMethods(), system.methodHelp()). That may be a showstopper, or do you know of any fixes? > My 2 cents... Thanks! Those were what I was hoping for, after all. Thanks for your help! /Joel From david at david-steuber.com Thu May 25 00:11:19 2006 From: david at david-steuber.com (David Steuber) Date: 25 May 2006 00:11:19 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <87hd3ehhg8.fsf@david-steuber.com> I'm loath to crosspost this but I don't know which (if any) news group Xah actually reads. I also don't want to make just a private response to Xah's email to a public post. Anyway, the TOS of dreamhost.com is here: http://www.dreamhost.com/tos.html Two important sections I'll quote: <blockquote> INTERNET ETIQUETTE Electronic forums such as mail distribution lists and Usenet news groups all have expectations regarding subject area and appropriate etiquette for posting. Users of these forums should be considerate of the expectations and sensitivities of others on the network when posting material for electronic distribution. The network resources of DreamHost Webhosting may not be used to impersonate another person or misrepresent authorization to act on behalf of others or DreamHost Webhosting. All messages transmitted via DreamHost Webhosting should correctly identify the sender; users may not alter the attribution of origin in electronic mail messages or posting. Users must not attempt to undermine the security or integrity of computing systems or networks and must not attempt to gain unauthorized access. This includes (but is not limited to) such things as port scanning of either DreamHost or external computers and Denial Of Service attacks of any kind. TERMINATION This contract may be terminated by either party, without cause, by giving the other party 30 days written notice. DreamHost Webhosting will accept termination by electronic mail. Notwithstanding the above, DreamHost Webhosting may terminate service under this contract at any time, without penalty, if the Customer fails to comply with the terms of this contract, including non-payment. DreamHost Webhosting reserves the right to charge a reinstatement fee. </blockquote> IANAL, but it looks like you can have your account canceled, Xah. Although to tell the truth, even though I find your crossposting excessive and your rants uninteresting I don't think it is frequent enough to bitch about. I do hope that no refund policy doesn't apply when they terminate your account. You would probably stand a good chance of keeping your account if you stop crossposting so much. Dreamhosting has defined internet etiquette for you. Stick within those bounds and you can defend yourself against people who complain. Good luck -- http://www.david-steuber.com/ 1998 Subaru Impreza Outback Sport 2006 Honda 599 Hornet (CB600F) x 2 Crash & Slider The lithobraker. Zero distance stops at any speed. From NOatkinwSPAM at rpi.edu Wed May 24 12:13:48 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Wed, 24 May 2006 12:13:48 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> <1148485967.164221.304310@y43g2000cwc.googlegroups.com> <Xns97CD70C3D2CEEcastleamber@130.133.1.4> Message-ID: <87y7wre6yr.fsf@rpi.edu> John Bokma <john at castleamber.com> writes: > If Xah posts to just one group, on topic, the problem is gone. But Xah > is spamvertizing his website, and hence posts to 5 groups (since I guess > that's a limit GG sets, not Xah), so he doesn't care that a post on > whitespace in Python ends up in a group on Java or Perl. [snip] > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html Interesting. Doesn't your signature contain advertisements for your website? Aren't you posting to five different groups? -- You fool! You fell victim to one of the classic blunders! The most famous is, "Never get involved in a land war in Asia", but only slightly less well-known is this: "Never go in against a Sicilian when death is on the line"! From irmen.NOSPAM at xs4all.nl Tue May 9 09:39:43 2006 From: irmen.NOSPAM at xs4all.nl (Irmen de Jong) Date: Tue, 09 May 2006 15:39:43 +0200 Subject: do "some action" once a minute In-Reply-To: <1147165909.579147.216030@g10g2000cwb.googlegroups.com> References: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> <tjl062lu3m6d96d8e67ve2h1m7kleijakh@4ax.com> <1147165909.579147.216030@g10g2000cwb.googlegroups.com> Message-ID: <44609b9c$0$31654$e4fe514c@news.xs4all.nl> Petr Jakes wrote: > OK, to be more specific, I would like to run the code, when the value > of seconds in the timestamp become say "00". > The whole code will run in the infinitive loop and other actions will > be executed as well, so it can not "sleep" for 60 seconds :). Have a look at my 'Kronos' task scheduler (based on the sched module). Available via http://www.razorvine.net/downloads.html It may provide the functionality you want. --Irmen From bborcic at gmail.com Tue May 2 13:11:17 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 19:11:17 +0200 Subject: simultaneous assignment In-Reply-To: <8dM5g.2031$No6.43874@news.tufts.edu> References: <8dM5g.2031$No6.43874@news.tufts.edu> Message-ID: <445792a3$1_2@news.bluewin.ch> John Salerno wrote: > Is there a way to assign multiple variables to the same value, but so > that an identity test still evaluates to False? > > e.g.: > > >>> w = x = y = z = False > >>> w > False > >>> x > False > >>> w == x > True > >>> w is x > True # not sure if this is harmful > > The first line above is the only way I know to do it, but it seems to > necessarily lead to the true identity test. >>> class Foo : def __eq__(*blah) : return False >>> w = x = y = z = Foo() >>> w == x False >>> w is x True >>> From johnjsal at NOSPAMgmail.com Fri May 5 13:26:15 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 05 May 2006 17:26:15 GMT Subject: using urllib with ftp? In-Reply-To: <mailman.5378.1146842004.27775.python-list@python.org> References: <oqt6g.2048$No6.44127@news.tufts.edu><mailman.5347.1146776157.27775.python-list@python.org> <445abddd$0$9424$c3e8da3@news.astraweb.com> <mailman.5378.1146842004.27775.python-list@python.org> Message-ID: <XUL6g.2049$No6.45542@news.tufts.edu> Fredrik Lundh wrote: > John Salerno wrote: > >> Thanks. So the ftp:// is something different than actually using ftplib >> to connect to an FTP server, right? I've used both urllib and ftplib, so >> I know what they do, I just was a little unclear about whether they can >> sometimes do each other's work as well. > > urllib uses ftplib under the hood, but all you can do is to fetch files or directory > listings. Thanks! That makes perfect sense now that I know that. From bdesth.quelquechose at free.quelquepart.fr Wed May 3 00:27:14 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 06:27:14 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <mailman.5241.1146613795.27775.python-list@python.org> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <mailman.5241.1146613795.27775.python-list@python.org> Message-ID: <44580270$0$4903$626a54ce@news.free.fr> Ben Finney a ?crit : > Edward Elliott <nobody at 127.0.0.1> writes: > > >>Compiler, interpreter, magic-codey-runny-thingy, whatever, at some point >>something has to translate this source code >> def method (self, a, b): something >>into a function object (or whatever you're calling the runnable code this >>week). Call this translator Foo. Whatever Foo is, it can insert 'self' >>into the parameter list for method, e.g. when it sees "def method (a,b)" it >>pretend like it saw "def method (self,a,b)" and proceed as usual. Once it >>does that, everything is exactly the same as before. > > > So now you're proposing that this be a special case when a function is > declared by that particular syntax, and it should be different to when > a function is created outside the class definition and added as a > method to the object at run-time. > > Thus breaking not only "explicit is better than implicit", This one can be subject to discussion. Actually, we must explicitely declare the instance in the params list, but it's implicitely passed at calltime by the method descriptor. > but also > "special cases aren't special enough to break the rules". Yeps, I think this is what I don't like here. > Still -1. I'm not yet ready to vote for Edward's proposition - as you say, it makes 'def statements into a class statement' a special case, and I don't like special cases too much (OTOH, there actually *are* special cases - __new__() being an example) - *but* it's not that silly either IMHO, and I think this should not be dismissed on a purely reactional basis. IOW, let's give Edward some time to come up with enough rope so we can hang him to the nearest (AS) Tree !-) From rasmussen.bryan at gmail.com Thu May 4 08:13:17 2006 From: rasmussen.bryan at gmail.com (bryan rasmussen) Date: Thu, 4 May 2006 14:13:17 +0200 Subject: Pythoncard question In-Reply-To: <4459e6b8@127.0.0.1> References: <4459e6b8@127.0.0.1> Message-ID: <3bb44c6e0605040513r39663182w565589f0c43e86ae@mail.gmail.com> Hi, I'm doing a sort of symbolic linking app in Windows for my own enjoyment, and figured I would do it in python for the same reason + learning the language. The following functions could obviously do with some refactoring. One obvious thing would be to make wordsetter and wordsforfolder more generic, and just pass a few extra parameters. But that seems sort of stupid. Any suggestions on refactoring here? other improvements? def getwordslist(word): thisword = wordpath + word + ".xml" if exists(thisword): doc = xml.dom.minidom.parse(thisword) loc = doc.childNodes[0] for i in range(0, len(loc.childNodes)): if (loc.childNodes[i].firstChild.data == thispath): break else: wordsetter(thisword,doc,loc) else : doc = xml.dom.minidom.Document() loc = doc.createElementNS("", "locations") doc.appendChild(loc) wordsetter(thisword,doc,loc) return None def getfolderwords(word): if exists(normpath(folderwords)): doc = xml.dom.minidom.parse(folderwords) loc = doc.childNodes[0] wordsforfolder(word,doc,loc) else : doc = xml.dom.minidom.Document() loc = doc.createElementNS("", "wordlist") doc.appendChild(loc) xml.dom.ext.PrettyPrint(doc, open(normpath(folderwords), "w")) wordsforfolder(word,doc,loc) return None def wordsetter(word,doc,loc): thisloc = doc.createElementNS("", "location") xexpr= "//location[.='" + thispath + "']" xp = Evaluate(xexpr,doc.documentElement) if len(xp) < 1: loc.appendChild(thisloc) text = doc.createTextNode(thispath) thisloc.appendChild(text) fi = open(word, "w") fi.write(doc.toxml()) def wordsforfolder(word,doc,loc): thisloc = doc.createElementNS("", "word") xexpr= "//word[.='" + word + "']" xp = Evaluate(xexpr,doc.documentElement) if len(xp) < 1: loc.appendChild(thisloc) text = doc.createTextNode(word) thisloc.appendChild(text) fi = open(folderwords, "w") fi.write(doc.toxml()) Cheers, Bryan Rasmussen From miki.tebeka at gmail.com Thu May 18 04:12:17 2006 From: miki.tebeka at gmail.com (Miki) Date: 18 May 2006 01:12:17 -0700 Subject: How to couple pyunit with GUI? In-Reply-To: <1147879480.640335.252950@y43g2000cwc.googlegroups.com> References: <1147879480.640335.252950@y43g2000cwc.googlegroups.com> Message-ID: <1147939937.192370.293530@g10g2000cwb.googlegroups.com> Hello volcano, http://pyunit.sourceforge.net/ has unittestgui.py (bit old though) HTH, Miki http://pythonwise.blogspot.com/ From eval.apply at gmail.com Tue May 9 13:13:11 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 9 May 2006 10:13:11 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> Message-ID: <1147194791.809735.251500@g10g2000cwb.googlegroups.com> Alex Martelli wrote: > > I think it's reasonable to make a name a part of functions, classes and > modules because they may often be involved in tracebacks (in case of > uncaught errors): to me, it makes sense to let an error-diagnosing > tracebacks display packages, modules, classes and functions/methods > involved in the chain of calls leading to the point of error _by name_. > > I think it's reasonable to make a name a part of types for a different > reason: new types are rarely meant to be used "just once"; but also, if > during debugging any object is displayed, it's nice to be able to show, > as part of the display, "this object is of type X and ...", with X shown > as a name rather than as a complete (thus lengthy) description. (any > decent interactive shell/debugger will let you drill down into the > details as and when you need to, of course, but a well-chosen name can > be often sufficient during such interactive exploration/debugging > sessions, and therefore save time and effort). I agree that symbolic debugging info is a good thing. > Indeed, "given an object, how do I get its NAME" (for inspection and > debugging purposes) is the most frequently asked question on > comp.lang.python, and I've grown a bit tired of answering "you can't, an > object in general intrinsically ``has no name'', it might have many or > none at all, blah blah" -- yeah, this is technically true (in today's > Python), but there's no real reason why it should stay that way forever > (IMHO). If we at least ALLOWED named objects everywhere, this would > further promote the use of names as against mysterious "magic numbers", > since the programmer would KNOW that after > VAT_MULTIPLIER = 1.19 > then displaying in a debugger or other interactive session that > PARTICULAR instance of the value 1.19 would show the name string > 'VAT_MULTIPLIER' as well (or no doubt a more structured name constructed > on the fly, identifying package and module-within-package too). The problem is that a `name' is a mapping from a symbolic identifier to an object and that this mapping must either be global (with the attendant name collision issues) or within a context (with the attendant question of `in which context'). > Mandating names for _everything_ would complicate the language by > forcing it to provide builtin names for a lot of elementary building > blocks: so for most types of objects it's best to "gently nudge". For > functions, classes, modules, and packages, I think the naming is > important enough (as explained above) to warrant a syntax including the > name; better, therefore, not to complicate the language by providing > another different syntax in each case just to allow the name to be > omitted -- why encourage a pratice that's best discouraged, at the price > of language simplicity? I agree. This is why I write (defun foo (x) ...) rather than (setf (symbol-function 'foo) (lambda (x) ...)) However, there are places where names are cumbersome. They are certainly cumbersome for most literal objects like numbers and strings. There are circumstances where they are cumbersome for function objects. The function (lambda (x) (+ x 3)) doesn't really need a name. It isn't any big deal if you give it a name, but it's a trivial annoyance to be forced to give it a name. It becomes a major annoyance when you write code in continuation-passing-style or monadic style. It is an annoyance when refactoring code, too. Suppose you had written (mapcar #'sin list-of-numbers) and you realize that the numbers are in degrees. With an unnamed function, this is an easy fix: (mapcar (lambda (x) (sin (deg->rad x))) list-of-numbers) With a named function, you have to do one of these: (flet ((sin-d (x) (sin (deg->rad x)))) (mapcar #'sin-d list-of-numbers)) or (mapcar (flet ((sin-d (x) (sin (deg->rad x)))) #'sin-d) list-of-numbers) Matthias Felleisen once suggested that *every* internal function should be named. I just said `continuations'. He immediately amended his statement with `except those'. From hymort at hotmail.com Mon May 1 18:17:25 2006 From: hymort at hotmail.com (hymort at hotmail.com) Date: 1 May 2006 15:17:25 -0700 Subject: set partitioning In-Reply-To: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> Message-ID: <1146521845.342649.291650@u72g2000cwu.googlegroups.com> Also, if I do not care about the number of subsets, what is a good algorithm to partition a set of n elements into non-empty, disjoint subsets of size k? From tim.golden at viacom-outdoor.co.uk Tue May 23 03:42:20 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Tue, 23 May 2006 08:42:20 +0100 Subject: COM Server crashing when returning large arrays Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1E8@vogbs009.gb.vo.local> [Alastair Alexander] | Hi ... I'm using pythoncom to create a python COM server | application that needs to be able to return large arrays | to COM client apps. For example, I need to be able to | return an array to Excel that is 500 by 10, with each | element of the array holding a 32 byte string. | | If I run the code for smaller arrays, say 10 by 10, it works | fine. If I allow the server to try to return the entire 500 | by 10 array, pythonw.exe causes a memory access violation and | dies and I get an "automation exception" error message in the | client app. | | I assume I'm violating some upper limit for data transfer | from pythoncom into COM. Anyone know if such limitations | exist? Is there a way around them? Can anyone point me in | the right direction? OK, no straight answer from me, merely a few hints: This is going to be *very* specific to the pywin32 stuff and Python & Win32 in general. In case you haven't come across it, there is a mailing list aimed at these things: http://mail.python.org/mailman/listinfo/python-win32 While I'm sure a lot of its readers (myself included) also follow c.l.py, it's possible that some usefully knowledgeable ones don't. In particular, Mark Hammond who is the author of the pythoncom stuff: I don't remember seeing him post on c.l.py while he's definitely there on python-win32. (Altho' you've said you're new to newsgroups etc., it's not clear how new you are to Python & Win32; I might just be teaching my Grandmother...) Worth running the code from a straight console, ie not PythonWin / pythonw.exe just in case something there is getting in the way. You didn't post any sample code, but if you could narrow the example down to a few lines with the COM server framework and post it, I at least am quite happy to try to test it to see if perhaps the issue is machine / configuration specific. Other than that, I'm afraid you're down to people with far more knowledge than me of the pythoncom internals. (Which is, let's face it, most people). 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 bborcic at gmail.com Wed May 10 12:59:45 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 10 May 2006 18:59:45 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <vyn8g.2$%L2.1@fe12.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> <yfshd41yeaj.fsf@oc.ex.ac.uk> <O7A7g.59$sC4.54@fe09.lga> <1147068524.966560.52210@y43g2000cwc.googlegroups.com> <0UG7g.8$u17.6@fe08.lga> <4461b9d5_3@news.bluewin.ch> <vyn8g.2$%L2.1@fe12.lga> Message-ID: <44621c10_1@news.bluewin.ch> Ken Tilton wrote: > > > Boris Borcic wrote: >> Ken Tilton wrote: >> >>> "Now if you are like most people, you think that means X. It does not." >> >> >> As far as natural language and understanding are concerned, "to mean" >> means conformity to what most people understand, Humpty Dumpties >> notwithstanding. > > Nonsense. :) > You are confusing that quality of natural language with most > people's quality of being sloppy readers, or in your case, a sloppy > thinker. Misapplying an analogy is not a question of usage -- when I > said spreadsheet and they thought of spreadsheets, so far so good, > right? No, as Adam Jones pointed out. Like Bush speaking of "crUSAde" after 9/11. > -- it just sloppiness and laziness. > > I do it, too, all the time. :) Right. From bdesth.quelquechose at free.quelquepart.fr Fri May 19 22:51:07 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 May 2006 04:51:07 +0200 Subject: altering an object as you iterate over it? In-Reply-To: <D%obg.2140$No6.46498@news.tufts.edu> References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> Message-ID: <446e54f0$0$4856$626a54ce@news.free.fr> John Salerno a ?crit : > John Salerno wrote: > >> What is the best way of altering something (in my case, a file) while >> you are iterating over it? I've tried this before by accident and got >> an error, naturally. >> >> I'm trying to read the lines of a file and remove all the blank ones. >> One solution I tried is to open the file and use readlines(), then >> copy that list into another variable, but this doesn't seem very >> efficient to have two variables representing the file. >> >> Perhaps there's also some better to do it than this, including using >> readlines(), but I'm most interested in just how you edit something as >> you are iterating with it. >> >> Thanks. > > > Slightly new question as well. here's my code: > > phonelist = open('file').readlines() readlines() reads the whole file in memory. Take care, you may have problem with huge files. > new_phonelist = phonelist Woops ! Gotcha ! Try adding this: assert(new_phonelist is phonelist) Got it ? Python 'variables' are really name/object ref pairs, so here you just made new_phonelist an alias to phonelist. > > for line in phonelist: > if line == '\n': replace this with: if not line.strip() > new_phonelist.remove(line) And end up modifying the list in place while iterating over it - which is usually a very bad idea. Also, FWIW, you'd have the same result with: phonelist = filter(None, open('file')) > import pprint > pprint.pprint(new_phonelist) > > But I notice that there are still several lines that print out as '\n', > so why doesn't it work for all lines? Apart from the fact that it's usually safer to use line.strip(), the main problem is that you modify the list in place while iterating over it. From danb_83 at yahoo.com Tue May 9 15:36:41 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 9 May 2006 12:36:41 -0700 Subject: python rounding problem. In-Reply-To: <125vedc9n2q3m55@corp.supernews.com> References: <mailman.5443.1146987087.27775.python-list@python.org> <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> <fPednfg-wOsvDcLZRVn-vQ@telcove.net> <125v9g8q00o1d52@corp.supernews.com> <gp6dnXfkodcrLcLZRVn-sg@telcove.net> <125vedc9n2q3m55@corp.supernews.com> Message-ID: <1147203401.653076.109230@i39g2000cwa.googlegroups.com> Grant Edwards wrote: ... > Did they actually have 60 unique number symbols and use > place-weighting in a manner similar to the arabic/indian system > we use? The Bablyonians did use a place-value system, but they only had two basic numerals: a Y-like symbol for 1 and a <-like symbol for ten. These were combined to make base-60 digits. For example, 59 was represented by < YYY < < YYY < < YYY Zero (used as a placeholder, but not as a number in itself) was represented by a space. From invalidemail at aerojockey.com Sat May 13 02:23:11 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 12 May 2006 23:23:11 -0700 Subject: distributing a app frozen by cx_freeze References: <1147482467.404798.187530@y43g2000cwc.googlegroups.com> Message-ID: <1147501391.800070.265860@g10g2000cwb.googlegroups.com> Flavio wrote: > Traceback (most recent call last): > File > "/home/fccoelho/Downloads/cx_Freeze-3.0.2/initscripts/Console.py", line > 26, in ? > File "epigrass.py", line 4, in ? > ImportError: /home/flavio/freeze/qt.so: undefined symbol: > _ZNK9QSGIStyle9classNameEv > > It is looking for the Original cx_freeze installation!! I doubt it is. Do you have the QT installed on the second system? If you do, is it the same version as on the original system? Are you sure you copied all the files over? It looks like qt.so is trying to access a C++ symbol in another library (libqt.so perhaps?), but that other library isn't installed. cx_freeze probably only packages the Python module binding to the QT library; not the library itself. If so, you'll need to install QT on the other system, or get cx_freeze to bundle up the QT shared library (if the license allows it, of course), or rebuild the qt.so with the static QT libraries. Carl Banks From No.Spam at Spam.none Wed May 10 12:43:20 2006 From: No.Spam at Spam.none (I. Myself) Date: Wed, 10 May 2006 16:43:20 GMT Subject: SciPy - I need an example of use of linalg.lstsq() In-Reply-To: <mailman.5545.1147238569.27775.python-list@python.org> References: <Jxe8g.145597$WI1.143954@pd7tw2no> <mailman.5545.1147238569.27775.python-list@python.org> Message-ID: <IKo8g.145693$P01.39850@pd7tw3no> Robert Kern wrote: > I. Myself wrote: > >> And it has to run on Windows, so it can't use xplt. >> > > Huh? > > A. xplt runs on Windows, too. > B. xplt has nothing to do with linalg.lstsq(). > C. xplt has been removed from scipy. > Thank you. I have been misled by the Scipy Tutorial by Travis Oliphant. It has an example which uses xplt; it also mentions that xplt is only for x-windows. Your example below seems like just what I'm looking for. I will try it out. Thanks again. Mitchell Timin > >> I would prefer that it use the simplest multi-dimensional model, z = k + >> a*x1 + b*x2 + c*x3 + d*x4 >> > > In [1]: import numpy as np > > In [2]: np.linalg.lstsq? > Type: function > Base Class: <type 'function'> > String Form: <function lstsq at 0x6d3f30> > Namespace: Interactive > File: > /Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/site-packages/numpy-0.9.7.2476-py2.4-macosx-10.4-ppc.egg/numpy/linalg/linalg.py > Definition: np.linalg.lstsq(a, b, rcond=1e-10) > Docstring: > returns x,resids,rank,s > where x minimizes 2-norm(|b - Ax|) > resids is the sum square residuals > rank is the rank of A > s is the rank of the singular values of A in descending order > > If b is a matrix then x is also a matrix with corresponding columns. > If the rank of A is less than the number of columns of A or greater than > the number of rows, then residuals will be returned as an empty array > otherwise resids = sum((b-dot(A,x)**2). > Singular values less than s[0]*rcond are treated as zero. > > > In [3]: z = np.rand(10) > > In [4]: x1 = np.rand(10) > > In [5]: x2 = np.rand(10) > > In [6]: x3 = np.rand(10) > > In [7]: x4 = np.rand(10) > > In [8]: A = np.column_stack([x1, x2, x3, x4, np.ones(10, float)]) > > In [9]: A > Out[9]: > array([[ 0.07257264, 0.36544251, 0.68467294, 0.33813333, 1. ], > [ 0.09520828, 0.27102091, 0.04673061, 0.12905473, 1. ], > [ 0.839834 , 0.46010114, 0.3949568 , 0.38983012, 1. ], > [ 0.49776387, 0.70666191, 0.85005579, 0.47738743, 1. ], > [ 0.25457977, 0.93335912, 0.88441593, 0.05255062, 1. ], > [ 0.85982216, 0.97920853, 0.27991214, 0.94230651, 1. ], > [ 0.03224487, 0.1275237 , 0.66943552, 0.320765 , 1. ], > [ 0.86807363, 0.63800103, 0.67153924, 0.69125023, 1. ], > [ 0.26571213, 0.68845408, 0.06478114, 0.03657494, 1. ], > [ 0.46615143, 0.99464106, 0.9303421 , 0.61363703, 1. ]]) > > In [10]: np.linalg.lstsq(A, z) > Out[10]: > (array([-0.32421087, -0.23330787, 0.13369118, -0.28334431, 0.84010014]), > array([ 0.22958042]), > 5, > array([ 4.59505886, 1.1181838 , 0.85704672, 0.70211311, 0.4420187 ])) > > > If you have more scipy questions, you will probably want to ask on the > scipy-user list: > > http://www.scipy.org/Mailing_Lists > > -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From bucodi at yahoo.fr.invalid Thu May 4 12:00:35 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Thu, 04 May 2006 18:00:35 +0200 Subject: Progamming python without a keyboard Message-ID: <mn.24387d656d1f89f2.43626@yahoo.fr.invalid> http://www.newscientisttech.com/article/dn9066 To nice to be true ? R_ -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From graham.fawcett at gmail.com Tue May 16 14:32:06 2006 From: graham.fawcett at gmail.com (Graham Fawcett) Date: 16 May 2006 11:32:06 -0700 Subject: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? In-Reply-To: <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> References: <1147657728.064817.214850@j73g2000cwa.googlegroups.com> <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> Message-ID: <1147804326.793291.53410@j55g2000cwa.googlegroups.com> Casey Hawthorne wrote: > For Large Dictionaries Could One Use Separate Dictionaries Where Each > Dictionary Covers an Interval of the Input Range? One Could, But Why? :-) You wouldn't see any performance improvements. Looking up a key in a dictionary is done in constant-time, i.e. it doesn't matter how large the dictionary is. Graham From mailper at gmail.com Fri May 5 07:57:56 2006 From: mailper at gmail.com (Per) Date: 5 May 2006 04:57:56 -0700 Subject: (question) How to use python get access to google search without query quota limit In-Reply-To: <mailman.5364.1146829768.27775.python-list@python.org> References: <1146829024.301402.282540@e56g2000cwe.googlegroups.com> <mailman.5364.1146829768.27775.python-list@python.org> Message-ID: <1146830276.737390.116010@y43g2000cwc.googlegroups.com> Yeah, Thanks Am, I can be considered as an advanced google user, presumably.. But I am not a advanced programmer yet. If everyone can generate unlimited number of queries, soon the user-query-data, which I believe is google's most advantage, will be in chaos. Can they simply ignore some queries from a certain licence key or.. so that they can keep their user-query-statistics normal and yet provide cranky queriers reseanable response? From sybrenUSE at YOURthirdtower.com.imagination Wed May 31 06:15:10 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 31 May 2006 12:15:10 +0200 Subject: Best Python Editor References: <mailman.24508.1149069603.27774.python-list@python.org> <mailman.6359.1149069835.27775.python-list@python.org> Message-ID: <slrne7qr5e.8hi.sybrenUSE@schuimige.stuvel.eu> Manoj Kumar P enlightened us with: > Can anyone tell me a good python editor/IDE? > It would be great if you can provide the download link also. VIM 7 is great, http://www.vim.org/ Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From kkylheku at gmail.com Thu May 11 14:37:33 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 11 May 2006 11:37:33 -0700 Subject: Multi-line lambda proposal. In-Reply-To: <Xns97C0BA97B69E5duncanbooth@127.0.0.1> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <slrne63ahp.dac.apardon@rcpc42.vub.ac.be> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> <1147333696.789718.189050@v46g2000cwv.googlegroups.com> <Xns97C066238ECA4duncanbooth@127.0.0.1> <1147366331.637492.129980@i39g2000cwa.googlegroups.com> <Xns97C0BA97B69E5duncanbooth@127.0.0.1> Message-ID: <1147372653.028788.295100@u72g2000cwu.googlegroups.com> Duncan Booth wrote: > Kaz Kylheku wrote: > > > Duncan Booth wrote: > >> One big problem with this is that with the decorator the function has > >> a name but with a lambda you have anonymous functions so your > >> tracebacks are really going to suck. > > > > Is this an issue with this particular design that is addressed by > > other designs? > > Yes. Decorators don't interfere with the name of the underlying function > displayed in tracebacks. No, I mean do other multi-line lambda design fix this problem somehow? It looks to me like the programmer's choice, quite simply. Both programs shown by yairchu at gmail.com use lambda. The first one uses a decorator to actually define the wrapped function: @arg_range(5, 17) def f(arg): return arg*2 The arg_range function uses a nesting of two lambdas, yet the decorated function still has a name that nicely shows up in tracebacks. So in other words, lambdas and decorators play along nicely. f = arg_range(5, 17, lambda(arg)): return arg*2 Here, the programmer made a decision to define a global function using an assigment operator instead of def. The underlying function is the lambda itself. That is not a problem with the multi-line lambda. A lambda feature is not even required to do create a version of this problem: foo = arg_range(5, 17, bar) Now the function is called as foo(), but what the programmer sees in the traceback is "bar", which is potentially confusing. The traceback will show that bar() is being called from some given file and line number, but when that is inspected, there is no bar() there, only an expression which contains the function call foo() (and possibly other calls). I'm only interested in discussing the relative merits of my multi-line lambda proposal versus others. I'm not interested in debating people who think that other people who want multi-line lambdas should not have them. I also hope that everyone understands that lambdas, multi-line or not, are not the best tool for every situation for which they are a possible candidate. I agree with that, and am not interested in debating it either. It's off topic to the question of designing that labmda, except insofar as the design of the lambda influences whether or not lambda is a good choice in a situation. I.e. "lambda is a bad choice for this situation if it is designed like this, but not (or less so) if it is designed like this." > > Are the existing one-line lambdas free from this problem? > > No, but since a single line lambda does virtually nothing it isn't as > serious. Decorators are useful enough that in some situation you might > decorate every method in a class (e.g. for a web application you might > apply security settings with decorators). In that situation you have just > messed up every stack frame in every traceback. The problem there is that the programmer uses anonymous functions for class methods, rather than decorating named class methods. (Are anonymous class methods even possible? Lambdas can take an object as their first argument, but that's not the same thing.) > I end up reading tracebacks quite a lot, and it is the sequence of the function > names which matter first, I don't usually need to go and look at the file > and code lines. > > > > Let me make the observation that name of an inner function is, alone, > > insufficient to identify that function in a debugging scenario. If you > > have some inner function called I, defined within function F, you need > > to know that it's the I inside F, and not some other I. > > > If the stack frame shows I called from F then it is usually a pretty good > guess that it means the I inside F. "Pretty good guess" doesn't cut it. Fact is, that the identities of these functions are not unambiguously pinned down by their name alone; moreover, the line number and file information alone actually does precisely pinpoint the location of the exception. If only the names of functions appeared in the traceback, it would be less useful. If foo calls bar in three different places, you would not know which of those three places is responsible for the call of bar from foo. Moreover, in the bottom-most frame, you would not know which line in the function actually triggered the traceback. So I do not believe your claim that you rarely need to look at the line number information when comprehending tracebacks. From per9000 at gmail.com Wed May 31 04:37:36 2006 From: per9000 at gmail.com (per9000) Date: 31 May 2006 01:37:36 -0700 Subject: create a text file References: <Xns97D3657BA981Emaxericksongmailcom@80.91.229.5> <e5htg5$89d$1@sea.gmane.org> <mailman.6336.1149023697.27775.python-list@python.org> Message-ID: <1149062005.973225.181740@y43g2000cwc.googlegroups.com> Ooops, w must be 'w' - sorry for adding more confusion :-D I would also like to add that this is a more realistic useage appendix = '.txt' # or '.csv' or whatever # some code c += 1 filetitle = 'result_' + zeropadding(c) + str(c) myfile = open(filetitle+appendix,'w') # etc Hope that was a little better. /P9K From scott.daniels at acm.org Wed May 3 19:01:54 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 03 May 2006 16:01:54 -0700 Subject: __init__.py, __path__ and packaging In-Reply-To: <slrne5i46s.3hc.sandro@bluff.diade.it> References: <slrne5i46s.3hc.sandro@bluff.diade.it> Message-ID: <445932cc$1@nntp0.pdx.net> Sandro Dentella wrote: > The structure of my package: > > python/ > `-- dbg/ > |-- __init__.py > `-- lib > |-- __init__.py > |-- debug.py > `-- gtk_dbg.py > > my sys.path includes 'python' and I wanted that the content of debug.py was > simply included by: 'import dbg', so I wrote dbg/__init__.py as follows: > > import os > Dir = os.path.dirname(__file__) > __path__ = [os.path.join(Dir, 'lib')] > from debug import * What you probably want in python/dbg/__init__.py to get values is: from dbg.lib.debug import * > BUT, if I set some variables they are not correctly seen: > import dbg > dbg.DBG = 1 > function test included in debug.py raises NameError: > def test(): > print DBG > NameError: global name 'DBG' is not defined` > > What's happening? DBG seems to be set, as shown by dir(dbg)... any hints? You misunderstand modules and python variables. Each module has a dictionary associating the names of its globals and their current values. After: import dbg.lib.debug, dbg.lib.gtk_dbg you have four modules: dbg # Corresponds to python/dbg/__init__.py dbg.lib # Corresponds to python/dbg/lib/__init__.py dbg.lib.debug # Corresponds to python/dbg/lib/debug.py dbg.lib.gtk_dbg # Corresponds to python/dbg/lib/gtk_dbg.py Each has its own globals. after: dbg.DBG = 1 the dbg module's global dictionary contains an entry mapping 'DBG' to 1 after: dbg.DBG = 1+2 the dbg module's global dictionary contains an entry mapping 'DBG' to 3 In no case will an assignment to a global in dbg cause an assignment to anything in dbg.lib.debug. The "from dbg.lib.debug import *" statement can be seen as a module import followed by a fancy multiple assignment, where module dbg.lib.debug is first imported, then its globals are assigned to globals of the same names in module dbg. --Scott David Daniels scott.daniels at acm.org From 63q2o4i02 at sneakemail.com Wed May 17 12:40:25 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 17 May 2006 09:40:25 -0700 Subject: Using python for a CAD program References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> Message-ID: <1147884024.698257.53000@y43g2000cwc.googlegroups.com> Hi, Actually, I've wondered about using a custom-rolled binary or text-based database, vs. something that uses the OpenEDA standard, vs a 'real' database like sql. I guess my impression is that something like SQL is not designed for something as multi-... uh, dimensional? as an EE design. Perhaps it would be good for just storing the data, but can it also store relationships or other meta-things besides the raw literalness of a design? I'd imagine it can store arbitrary binary data, but then what's the advantage over a custom binary file? If the application provides a nice API for geting into its custom binary file, then what's the problem? ms From grflanagan at yahoo.co.uk Sat May 20 13:34:01 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 20 May 2006 10:34:01 -0700 Subject: Generating Cutter numbers References: <1148114166.590393.176250@u72g2000cwu.googlegroups.com> <1148133784.844430.23130@38g2000cwa.googlegroups.com> Message-ID: <1148146441.412605.163750@j55g2000cwa.googlegroups.com> skryskalla at gmail.com wrote: > Gerard Flanagan wrote: > > All > > > > would anyone happen to have code to generate Cutter Numbers: > > > > eg. http://www1.kfupm.edu.sa/library/cod-web/Cutter-numbers.htm > > > > or is anyone looking for something to do?-) (I'm under pressure!) > > > > def cutter(lname, fname, book_title): > > > > What do you use lname and fname (author first name and last name?) for? > The page you linked to does not have any information (that I could > see) about first names or last names. > Sorry, couldn't find a better link, I'm struggling to find anything definitive about this. I'm cataloging a small library and want to generate a unique id (called a 'call number') for each book. This id is composed of: * Dewey 3-digit Subject Classification Number * Dewey Decimal (always 0 for the minute) * Cutter Number * Copy number (multiple copies or volumes) (That Celestial Emporium again...) I haven't researched it much but it seems the Cutter number is used to distinguish between authors with the same name, and between different books written by the same author - so you need last name, first name and title. But it may be as much art as science. > I wrote a script to see if I could capture what the table is doing on > the page you linked to. It gets the Cutter number right about 50% of > the time, otherwise its off by a few digits. > > I am stumped about what to do when the first letter is Q not followed > by U. It says to use numbers 2-29 for the second letters a-t, but that > is obviously not right (for one thing t would be 21, not 29). > > Since you seem a little bit more experienced in library science could > you explain what is going on? :) > > you can find the script here: > http://lost-theory.org/python/cutter.txt > Thanks very much for taking the time - I'll have to go study it now! But I don't think it will be as simple now since the Cutter may depend on books already in the database. Maybe I'll just stick a random string on the end of what your function produces! Thanks again. Gerard From nobody at 127.0.0.1 Mon May 15 14:07:24 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 15 May 2006 18:07:24 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <qz2ag.6572$fb2.2976@newssvr27.news.prodigy.net> <mailman.5724.1147713946.27775.python-list@python.org> Message-ID: <wr3ag.6604$fb2.3531@newssvr27.news.prodigy.net> Brian Quinlan wrote: > The problem with tabs is that people use tabs for alignment e.g. > > def foo(): > ->query = """SELECT * > -> -> -> FROM sometable > -> -> -> WHERE condition""" Sure it's a problem. When programmers do bad things, what is your response? Slap his nose and say 'Bad, don't do that'? Or take away his toys so he can't do that? Therein lies your answer to tabs or spaces. Both are rational. > Of course, a very disciplined group of people could be trained to > never use tabs except to align with the current block level but, in > practice, that doesn't work. Therefore tabs are bad. Consistency is always hard for people and easy for machines. If you make it a machine task instead of a people task, it can easily work in practice, just like Python easily enforces no mixing of tabs and spaces with the -tt flag. Get editors that use different (background) colors for tabs and spaces so you can easily pick them out even when the above alignment problem isn't noticeable. Use editors that automatically pick the right character when indenting: tabs to the level of indentation of the current block, then spaces afterward for line continuations. Run the code through parsers that detect and flag inconsistencies on check-in. If such tools are lacking, use substitutes in the meantime. Don't allow any code to be checked in where a line departs more than one tab indentation level from its neighbors. It's not perfect, but it eliminates the worst offenses. Good enough often is. Not saying you should do this, just pointing out how tabs are viable. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From bignose+hates-spam at benfinney.id.au Thu May 18 21:37:21 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 May 2006 11:37:21 +1000 Subject: Quoting relevant material for response (was: Re: python vs perl lines of code) References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <Xns97C7BC8549BA0castleamber@130.133.1.4> <1147996169.818933.252420@u72g2000cwu.googlegroups.com> <Xns97C7C31D1A937castleamber@130.133.1.4> <1148002073.419819.295180@38g2000cwa.googlegroups.com> Message-ID: <8764k2lrqm.fsf_-_@benfinney.id.au> "akameswaran at gmail.com" <akameswaran at gmail.com> writes: > Hmm, and I thought it was respectful to actually address someone you > are talking to. On Usenet, it's respectful to all readers if you give a short quoted passage from the message you're responding to, so we can follow the discussion with context. gmail allows you to do this. You have the option to edit a quoted version of the message, removing the parts irrelevant to your response, and putting your response following each relevant part. > Must every statement be a reaction to a quotable comment? Not necessarily. But if you're only making new statements, you should compose your message as a new topic, instead of as a reply to an existing message. > In any case, I realize I was completley wrong. Please allow me to > retract my statement. It's hard to see what that is, since you don't provide any context. Are we expected to re-read the entire thread to guess what you're referring to? -- \ "Not using Microsoft products is like being a non-smoker 40 or | `\ 50 years ago: You can choose not to smoke, yourself, but it's | _o__) hard to avoid second-hand smoke." -- Michael Tiemann | Ben Finney From gene.tani at gmail.com Sun May 7 09:08:33 2006 From: gene.tani at gmail.com (gene tani) Date: 7 May 2006 06:08:33 -0700 Subject: python rounding problem. In-Reply-To: <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> References: <mailman.5443.1146987087.27775.python-list@python.org> <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> Message-ID: <1147007313.776946.90250@v46g2000cwv.googlegroups.com> Erik Max Francis wrote: > chun ping wang wrote: > > > Hey i have a stupid question. > > > > How do i get python to print the result in only three decimal place... > > > > Example>>> round (2.995423333545555, 3) > > 2.9950000000000001 > > > > but i want to get rid of all trailing 0's..how would i do that? > > Floating point arithmetic is inherently imprecise. This is not a Python > problem. > http://www2.hursley.ibm.com/decimal/ (read about IEEE754 here) From junkytownMAKNI at gmail.com Wed May 31 06:12:01 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Wed, 31 May 2006 12:12:01 +0200 Subject: shuffling elements of a list In-Reply-To: <1149048606.100581.119980@y43g2000cwc.googlegroups.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <mailman.6344.1149046001.27775.python-list@python.org> <1149048606.100581.119980@y43g2000cwc.googlegroups.com> Message-ID: <e5jq5h$psl$1@ss408.t-com.hr> greenflame wrote: > Zhang Fan wrote: >> On 30 May 2006 20:18:19 -0700, greenflame <alikakakhel at yahoo.com> wrote: >>> Second of all, I would like to have >>> other methods of shuffling, prefererably riffle shuffling and just >>> plain randomly arranging the elements of the list. >> The random module has a `shuffle' method. It "Shuffle the sequence x >> in place". >> It may be help for you > > I am sorry but this does not help much. In my version of python (2.3) > this method does not seem to exist. Also from the documentation, it > seems that this method would give a random number. > You should update your Python then ;) It's a very nice method: >>> import random >>> random.seed() >>> >>> list = [1,21,23,4,5] >>> random.shuffle(list) >>> print list [5, 4, 23, 1, 21] From sybrenUSE at YOURthirdtower.com.imagination Fri May 19 08:08:55 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 19 May 2006 14:08:55 +0200 Subject: How to append to a dictionary References: <1148039985.232831.56040@i40g2000cwc.googlegroups.com> Message-ID: <slrne6rdan.mnv.sybrenUSE@schuimige.stuvel.eu> Harlin Seritt enlightened us with: > I have some code here: > > groups = {'IRISH' : 'green', 'AMERICAN' : 'blue'} > > I want to add another key: 'ITALIAN' : 'orange' > > How do I append this to 'groups'? groups['ITALIAN'] = 'orange' Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From levub137 at wi.rr.com Sat May 20 07:07:11 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 20 May 2006 11:07:11 GMT Subject: Decimal and Exponentiation In-Reply-To: <mailman.5981.1148073533.27775.python-list@python.org> References: <1148060287.088387.41150@j55g2000cwa.googlegroups.com> <mailman.5981.1148073533.27775.python-list@python.org> Message-ID: <zLCbg.3265$8T4.567@tornado.rdc-kc.rr.com> Tim Peters wrote: <snip> > The GNU GMP library (for which Python bindings are available) also > supports "big floats", but their power operation is also restricted to > integer powers and/or exact roots. This can be painful even to try; > e.g., > > >>> from gmpy import mpf > >>> mpf("1e10000") ** mpf("3.01") > > consumed well over a minute of CPU time (on a 3.4 GHz box) before dying > with > > ValueError: mpq.pow fractional exponent, inexact-root > <snip> The clnum module handles this calculation very quickly: >>> from clnum import mpf >>> mpf("1e10000") ** mpf("3.01") mpf('9.9999999999999999999999932861e30099',26) >>> x=_ >>> x ** (1/mpf("3.01")) mpf('9.9999999999999999999999953924e9999',26) See http://calcrpnpy.sourceforge.net/clnumManual.html From mtobis at gmail.com Wed May 17 18:51:01 2006 From: mtobis at gmail.com (Michael Tobis) Date: 17 May 2006 15:51:01 -0700 Subject: python vs perl lines of code In-Reply-To: <e4g2lf$icl$1@panix2.panix.com> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> Message-ID: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> "The plural of anecdote is not data." It's a pithy quote, but it isn't QOTW in my book, simply because it isn't true in general. Talk to some paleoclimatologists. There is no way to get uniform measures of ancient climate. What should we do then? Should we ignore the information we have? Are the fortuitously preserved fossils of the very deep past to be ignored just because we can't get an unbiased sample? In fact, the more difficult it is to get systematic data, the more valuable the anecdote. There is a number that represents the character ratio for equivalent skill applied to equivalent tasks across all domains to which both languages are applied. A single programmer's results on this matter do in fact constitute a sample. A single sample is not a very good estimator, but it is not devoid of skill or information either. In the present case Edward gave us some advice that he thought he was making a fair comparison, one which would appear counterintuitive to anyone who has worked in both languages. Perlists tend to giggle and cackle every time they save a keystroke; Pythonistas do not have this personality quirk. If Python is nevertheless terser it is a strong argument in Python's favor vis-a-vis Perl. Edward also asked if others had similar experiences. If others did, the assemblage of their opinions would in fact consttitute data. I have no idea why people are giving him such grief over this request. My only data point, er, anecdotal evidence, is this. To take things to an unrealistic extreme, consider the puzzle at http://pycontest.net (Python Golf). When I first thought about this, I assumed that Perl would defeat Python in the character count, but as I worked at the puzzle I came to the (to me) counterintuitive realization that it probably would not. I'd be interested in seeing the results of an inter-language golf contest. Of course, such games don't tell us much about real code, but I'm inclined to agree with Edward's impression that Python is, in practice, terse compared to Perl, and I, too, would like to hear about other examples, and because I think the plural of "anecdote" is, in fact, "data". mt From tim.golden at viacom-outdoor.co.uk Wed May 24 03:31:13 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 24 May 2006 00:31:13 -0700 Subject: newbie: windows xp scripting In-Reply-To: <pcq7725oei18c77hqgdo3rchctpou54vcr@4ax.com> References: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> <mailman.6032.1148231638.27775.python-list@python.org> <1148239856.998371.160700@u72g2000cwu.googlegroups.com> <pcq7725oei18c77hqgdo3rchctpou54vcr@4ax.com> Message-ID: <1148455873.224011.298450@u72g2000cwu.googlegroups.com> Tim Roberts wrote: > "oscartheduck" <oscartheduck at gmail.com> wrote: > > > >It wasn't, but after seeing your success I discovered what was wrong. > >My destination directory didn't exist, and for some reason windows > >wasn't automatically creating it to dump the files in. > > Right. The "copy" command never creates directories. It will copy each > individual file, in turn, to a file with whatever the last name in the list > is. Not terribly useful, but it is a behavior inherited from DOS 1. > > On the other hand, the "xcopy" command will do it: > > xcopy /i C:\DIR1 C:\DIR2 > > That will create DIR2 if it does not already exist. I've done a v. simple comparison of a few techniques for copying things on Win32. Might be of some use: http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html TJG From duncan.booth at invalid.invalid Fri May 26 10:25:22 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 26 May 2006 14:25:22 GMT Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> <1148650269.190130.209840@i39g2000cwa.googlegroups.com> Message-ID: <Xns97CF9CDFFB09Cduncanbooth@127.0.0.1> George Sakkis wrote: > Perhaps you fail to understand that the given feature is > 1) redundant (see above). Yes, but a certain degree of redundancy in the language is inevitable, and when it exists (as in this case) to make people's life easier it may be a good thing. Obviously the tradeoff between increasing complexity vs increasing ease-of-use has to be discussed before such new features are added, and in this case I believe it was. > 2) restricting in a more serious sense: the future addition of optional > keyword arguments that affect the dict's behaviour. Google for "default > dict" or "dictionary accumulator". There is nothing to stop dictionaries being created using factory functions (e.g. see dict.fromkeys). So one possible way to implement defaults would be to extend the dict class with a new classmethod 'withdefault' which takes a default value as an argument. However, given that the default argument isn't actually needed during construction, it doesn't seem to me that it fits either as a constructor parameter nor a factory method. I don't see why it shouldn't just be set on an existing dictionary (or dictionary subclass) when you need it. From ptmcg at austin.rr._bogus_.com Wed May 10 18:35:27 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 10 May 2006 22:35:27 GMT Subject: syntax for -c cmd References: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> Message-ID: <PUt8g.15534$Qq.7248@tornado.texas.rr.com> "James" <hslee911 at yahoo.com> wrote in message news:1147284798.136873.237730 at i40g2000cwc.googlegroups.com... > Wrong syntax is shown below. What should be the delimiter before else? > > python -c 'if 1==1: print "yes"; else print "no"' > > James > So you can approximate this same logic with a boolean expression: print (1==1 and "yes" or "no") This is because Python short-circuits boolean and's and or's, and returns the last evaluated value. So the expanded logic here is: evaluate 1==1 -> True evaluate "yes" -> True - we are done, return "yes" if the expression were (math.pi==3 and "yes" or "no"), we would get: evaluate math.pi==3 -> False (skip evaluation of "yes", first part failed so go straight to or term) evaluate "no" -> well, doesn't matter if this is True or False, it's the last thing we have to evaluate, return it Generally this gets idiomatically expressed as: (condition and trueConditionValue or falseConditionValue) This is currently (Python 2.4) the closest Python gets to C's ternary operator. Note that there are some risks, for example, this rendition *wont* work. numberOfApples = 1 print "I have %d apple%s" % ( numberOfApples, (numberOfApples ==1 and "" or "s")) This is because "" evaluates boolean-ly to False, so the conditional conjunction of (numberOfApples==1) and "" is False, so we continue to evaluate the expression, and wind up printing "I have 1 apples". The resolution is to invert the test: numberOfApples = 1 print "I have %d apple%s" % ( numberOfApples, (numberOfApples !=1 and "s" or "")) (If I have zero of something, I prefer to say "I have 0 somethings" - if you like to say "I have 0 something" then make the test read (numberOfApples > 1 and "s" or "") ) In the coming 2.5 version of Python, there is a ternary-like expression: numberOfApples = 1 print "I have %d apple%s" % ( numberOfApples, ("" if numberOfApples ==1 else "s")) Python 2.5 is still in preliminary releases though, and will not be generally available until this coming fall. This will allow you to spell out if-then-else conditions on the command line. In general scripting, though, compaction of code into one-liners is not always considered a virtue. This code: print "I have %s apple%s" % (numberOfApples==0 and "no" or numberOfApples, numberOfApples !=1 and "s" or "") will not win you points with your software maintenance team. -- Paul From gherron at islandtraining.com Thu May 18 12:59:04 2006 From: gherron at islandtraining.com (Gary Herron) Date: Thu, 18 May 2006 09:59:04 -0700 Subject: Complex evaluation bug In-Reply-To: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> Message-ID: <446CA7D8.1060406@islandtraining.com> of wrote: >a = 1+3j >complex(str(a)) > >Why does this not work ? It should > > Says who? By normal conventions in Python, "str" attempts only to make a "nice" human readable representation. The function "repr" is usually expected to provide output that can be parsed back into the original object. (Although for the numeric complex type the two produce identical results.) Further, constructors are rarely expected to parse a string representation to return an object. The function "eval" is usually expected to provide that functionality. So, putting them together, you could expect eval(repr(a)) to reproduce a, and in fact it does so. Gary Herron From bnblazer at gmail.com Mon May 22 20:19:12 2006 From: bnblazer at gmail.com (Brian) Date: 22 May 2006 17:19:12 -0700 Subject: Too big of a list? and other problems Message-ID: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> First off, I am sorry for cluttering this group with my inept questions, but I am stuck again despite a few hours of hair pulling. I have a function (below) that takes a list of html pages that have images on them (not porn but boats). This function then (supposedly) goes through and extracts the links to those images and puts them into a list, appending with each iteration of the for loop. The list of html pages is 82 items long and each page has multiple image links. When the function gets to item 77 or so, the list gets all funky. Sometimes it goes empty, and others it is a much more abbreviated list than I expect - it should have roughly 750 image links. When I looked at it while running, it appears as if my regex is actually appending a tuple (I think) of the results it finds to the list. My best guess is that the list is getting too big and croaks. Since one of the objects of the function is also to be able to count the items in the list, I am getting some strange errors there as well. Here is the code: def countPics(linkList): foundPics = [] count = 0 for link in linkList: picPage = urllib.urlopen("http://continuouswave.com/whaler/cetacea/" + link) count = count +1 print 'got page', count html = picPage.read() picPage.close() pics = re.compile(r"images/.*\.jpeg") foundPics.append(pics.findall(html)) #print len(foundPics) print "found", len(foundPics), "pictures" print foundPics Again, I sincerely appreciate the answers, time and patience this group is giving me. Thank you for any help you can provide in showing me where I am going wrong. Brian From mwilson-to at sympatico.ca Thu May 18 13:41:11 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Thu, 18 May 2006 13:41:11 -0400 Subject: Complex evaluation bug In-Reply-To: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> Message-ID: <Yk2bg.8862$aa4.296336@news20.bellglobal.com> of wrote: > a = 1+3j > complex(str(a)) > > Why does this not work ? It should It would be nice. Looks like str(1+3j) is returning an expression in string form. Maybe there is no actual complex literal. eval (str(1+3j)) works. Python 2.4.2 (#1, Jan 23 2006, 21:24:54) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1+3j (1+3j) >>> str(1+3j) '(1+3j)' >>> complex (str(1+3j)) Traceback (most recent call last): File "<stdin>", line 1, in ? ValueError: complex() arg is a malformed string >>> eval (str(1+3j)) (1+3j) >>> eval(str(1+3j))**2 (-8+6j) From zhushenli at gmail.com Tue May 9 03:20:18 2006 From: zhushenli at gmail.com (Davy) Date: 9 May 2006 00:20:18 -0700 Subject: PythonWin's Check (any other Lint tool) ? Message-ID: <1147159218.850130.103110@j73g2000cwa.googlegroups.com> Hi all, I am using PythonWin from ActivePython. And I use the GUI button 'Check' to check the .py file. But the Check did not give out a check list. It just show "Check failed" or "Check successful". Is the Check list saved in other where or is there any other Lint tool? Any suggestions will be appreciated! Best regards, Davy From vbgunz at gmail.com Fri May 26 08:03:11 2006 From: vbgunz at gmail.com (vbgunz) Date: 26 May 2006 05:03:11 -0700 Subject: Python for my mum In-Reply-To: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> References: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> Message-ID: <1148644991.633948.32260@j55g2000cwa.googlegroups.com> maybe you can tell your moms what to do and what binaries to download or maybe you can download them for her and either send it to her through email or put it on a disc for her... I understand the Windows XP installation binary is easy enough for anyone to get going. Just follow the prompts. Once Python is installed, double clicking .py files would be almost like clicking on executables. If a gui should pop up and the Python installation went in OK, she should be able to see a Gui and not know any different in regards to what exactly is happening in the background... Start with the binary, get it installed and double click the .py files. It should just work. Good luck! From duncan.booth at invalid.invalid Fri May 5 06:44:24 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 May 2006 10:44:24 GMT Subject: Tuple assignment and generators? References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <e-idndayO-NancbZRVn-sQ@speakeasy.net> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> <e3f5p6$7jn$1@sea.gmane.org> <mailman.5360.1146822522.27775.python-list@python.org> Message-ID: <Xns97BA77682318Fduncanbooth@127.0.0.1> Daniel Nogradi wrote: >>>> a = 10 >>>> b = 10 >>>> id(a) > 134536516 >>>> id(b) > 134536516 > > So the two memory addesses are the same, but > >>>> a = 10000 >>>> b = 10000 >>>> id(a) > 134604216 >>>> id(b) > 134604252 > > and they are not the same (I restarted the interpreter between the two > cases). So how is this now? Sorry if it's too trivial, but I simply > don't get it. > If two immutable values are the same, then the interpreter has the right to simply reuse the same value. Apart from the guarantee that it will do this with None everything else is left open. The current C-Python implementation will reuse small integers but not large integers, it also reuses some strings. It reuses the empty tuple but not (so far as I know) any other tuples. This could change at any time and other Python implementations may do totally different things here. Just because you saw it reusing a small value such as 10 doesn't mean that there cannot be other small integers with the value 10 which aren't the same as that one. Back before Python had a separate bool type, it used to use two different integers for 0 (and two for 1), so you could (by an accident of implementation) tell whether a value had been created by a comparison operator. So far as I know, there is nothing stopping the author of an extension written in C continuing to create their own versions of small numbers today. From OlafMeding at gmail.com Wed May 3 16:09:09 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 13:09:09 -0700 Subject: Because of multithreading semantics, this is not reliable. Message-ID: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> Because of multithreading semantics, this is not reliable. This sentence is found in the Python documentation for "7.8.1 Queue Objects". This scares me! Why would Queue.qsize(), Queue.empty( ), and a Queue.full() not be reliable? Looking at the source code of Queue.py, all 3 calls use a mutex (based on thread.allocate_lock()). Does this mean that the thread.allocate_lock() mechanism is not reliable (scary indeed) or does this have to do with other implementation details? Many thanks for explaining this mystery. Olaf From johnjsal at NOSPAMgmail.com Fri May 19 15:28:35 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 19:28:35 GMT Subject: altering an object as you iterate over it? In-Reply-To: <1Mobg.2139$No6.46432@news.tufts.edu> References: <1Mobg.2139$No6.46432@news.tufts.edu> Message-ID: <D%obg.2140$No6.46498@news.tufts.edu> John Salerno wrote: > What is the best way of altering something (in my case, a file) while > you are iterating over it? I've tried this before by accident and got an > error, naturally. > > I'm trying to read the lines of a file and remove all the blank ones. > One solution I tried is to open the file and use readlines(), then copy > that list into another variable, but this doesn't seem very efficient to > have two variables representing the file. > > Perhaps there's also some better to do it than this, including using > readlines(), but I'm most interested in just how you edit something as > you are iterating with it. > > Thanks. Slightly new question as well. here's my code: phonelist = open('file').readlines() new_phonelist = phonelist for line in phonelist: if line == '\n': new_phonelist.remove(line) import pprint pprint.pprint(new_phonelist) But I notice that there are still several lines that print out as '\n', so why doesn't it work for all lines? From mscottschilling at hotmail.com Fri May 26 17:20:19 2006 From: mscottschilling at hotmail.com (Mike Schilling) Date: Fri, 26 May 2006 21:20:19 GMT Subject: OT: Quote ? [was: John Bokma harassment] References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> <Xns97CE807F1ADC6castleamber@130.133.1.4> <Zpmdg.2874$%Z2.298786@news20.bellglobal.com> <4476efed$2$649$bed64819@news.gradwell.net> <Xns97CF757E136D6castleamber@130.133.1.4> <7QJdg.17594$fb2.11320@newssvr27.news.prodigy.net> <Xns97CFA2545F010castleamber@130.133.1.4> Message-ID: <niKdg.17601$fb2.10023@newssvr27.news.prodigy.net> "John Bokma" <john at castleamber.com> wrote in message news:Xns97CFA2545F010castleamber at 130.133.1.4... > "Mike Schilling" <mscottschilling at hotmail.com> wrote: > >> >> "John Bokma" <john at castleamber.com> wrote in message >> news:Xns97CF757E136D6castleamber at 130.133.1.4... >>> "Chris Uppal" <chris.uppal at metagnostic.REMOVE-THIS.org> wrote: >>> >>>> [apologies to the whole flaming crowd for sending this to the whole >>>> flaming crowd...] >>>> >>>> Geoffrey Summerhayes wrote: >>>> >>>>> After you kill Navarth, will it be nothing but gruff and deedle >>>>> with a little wobbly to fill in the chinks? >>>> >>>> Where does that come from ? It sounds like a quote, and Navarth is >>>> a Jack Vance name (and /what/ a character), but I don't remember the >>>> rest of it occurring in Vance. >>> >>> Navarth is very present in "the palace of dreams" (Demon princes >>> series) >> >> Nitpick: _The Palace of Love_ > > Aargh! The only excuse I can give for that huge mistake is that I am > currently reading "In the net of dreams" :-( You have another excuse in the last Demon Princes title: _The Book of Dreams_. From rpdooling at gmail.com Tue May 2 12:00:36 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 2 May 2006 09:00:36 -0700 Subject: Python and Windows new Powershell Message-ID: <1146585636.121440.178890@e56g2000cwe.googlegroups.com> The Windows Powershell is available, fka Monad. Any special Python tricks? Just breezing through the manual, they seemed to have borrowed from any language they wanted in making a new scripting language. http://tinyurl.com/l9ghj rd From Serge.Orlov at gmail.com Thu May 18 18:52:03 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 18 May 2006 15:52:03 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> Message-ID: <1147992722.970761.220840@j73g2000cwa.googlegroups.com> Ron Garret wrote: > In article <mailman.5906.1147989402.27775.python-list at python.org>, > Robert Kern <robert.kern at gmail.com> wrote: > > > Ron Garret wrote: > > > > > I forgot to mention: > > > > > >>>>sys.getdefaultencoding() > > > > > > 'utf-8' > > > > A) You shouldn't be able to do that. > > What can I say? I can. > > > B) Don't do that. > > OK. What should I do instead? Exact answer depends on what OS and terminal you are using and what your program is supposed to do, are you going to distribute the program or it's just for internal use. From scott.daniels at acm.org Wed May 17 17:28:34 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 17 May 2006 14:28:34 -0700 Subject: constucting a lookup table In-Reply-To: <1147884480.797594.265760@u72g2000cwu.googlegroups.com> References: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> <9aCdnR10Sej7bPTZnZ2dnUVZ_sidnZ2d@comcast.com> <1147831768.783996.10630@j33g2000cwa.googlegroups.com> <1147884480.797594.265760@u72g2000cwu.googlegroups.com> Message-ID: <446b9188$1@nntp0.pdx.net> mhodkin at comcast.net wrote: > BTW, just for kicks to compare languages, how would one implement the > same "lookup" table using C/C++? It would be a good lesson in high > level vs. lower level programming.... > Something vaguely like: unsigned char hwdict[89 - 60][401 - 80]; int setsize(int height, int weight, int size) { int result; /* non-zero (old size) if changes an already set size */ assert(60 <= height && height<= 88 && 80 <= weight && weight<= 400); result = hwdict[height - 60][weight - 80]; hwdict[height - 60][weight - 80] = size; return result; } int getsize(int height, int weight, int size) { assert(60 <= height && height<= 88 && 80 <= weight && weight<= 400); return hwdict[height - 60][weight - 80]; } --Scott David Daniels scott.daniels at acm.org From runlevelten at gmail.com Sun May 28 15:11:20 2006 From: runlevelten at gmail.com (Ten) Date: Sun, 28 May 2006 20:11:20 +0100 Subject: Fancy GUI with Python In-Reply-To: <1148840759.152708.200750@u72g2000cwu.googlegroups.com> References: <1148840759.152708.200750@u72g2000cwu.googlegroups.com> Message-ID: <200605282011.20870.runlevelten@gmail.com> On Sunday 28 May 2006 19:25, 63q2o4i02 at sneakemail.com wrote: > Hi all. I just downloaded and installed the new Office suite from MS > with their new 'ribbon' based UI. I think it's pretty cool and AFT* > for a new UI paradigm. I hope it sticks. > > Anyway, I'm wondering how to implement a gui like this with Python. I > don't think wx or qt or gtk or tkinter support this sort of fading and > glowing type of effects... or do they? I played with wx way back in > 2000 or so (C++ version), and it certainly didn't have any of that. I > don't know if this stuff is now built into XP, or if it's specialized > libraries only accessible to MS for their purposes. Can a python gui > framework be redirected to use the new gui? Or is this something that > has to be manually emulated from a low-level if python is to make use > of it? What about under linux? > > So I'm not sure if this is a Python question, a xxx-Python question > (where xxx is the widget toolkit of choice), or a windows API type of > question. > > How does one make fancy fading guis with python? (cross-platform if > possible) > > thanks > ms > > *AFT = about freakin' time Unless I'm missing something (I haven't examined it exhaustively), everything therein seems quite easily doable using python and Qt. I'd check it out. Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. From tzot at sil-tec.gr Tue May 2 06:26:42 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Tue, 02 May 2006 13:26:42 +0300 Subject: returning none when it should be returning a list? References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> <4455A4A1.7020807@lexicon.net> <1146564225.815477.137750@u72g2000cwu.googlegroups.com> Message-ID: <msce521t8ufbb843h8mase9nr7hikcgjrm@4ax.com> On 2 May 2006 03:03:45 -0700, rumours say that "Iain King" <iainking at gmail.com> might have written: >John Machin wrote: >> >> # Doh! Looks like recursion not necessary. Google 'eliminate tail >> recursion' :-) > >I did, and found this: >http://www.biglist.com/lists/dssslist/archives/199907/msg00389.html >which explains that the Scheme compiler optimises (obvious) tail >recursion into iterative code. I'm wondering if the python compiler >does the same? No, it doesn't so far. More info: <URL:http://groups.google.com/groups/search?q=group%3Acomp.lang.python+tail+recursion+optimization&qt_s=Search> -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From joel.hedlund at gmail.com Wed May 3 16:18:12 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Wed, 03 May 2006 22:18:12 +0200 Subject: Possibly dumb question about dicts and __hash__() In-Reply-To: <1146686634.117498.313470@j73g2000cwa.googlegroups.com> References: <e3b0c0$g8o$1@news.lysator.liu.se> <1146686634.117498.313470@j73g2000cwa.googlegroups.com> Message-ID: <e3b2n3$gsu$1@news.lysator.liu.se> Hi! Thanks for the quick response! > Although this is a bit illegal, because repr is not supposed to be used > this way. How illegal is it? If I document it and put it in an opensource project, will people throw tomatoes? /Joel johnzenger at gmail.com wrote: > Use __repr__. Behold: > > >>>>class NamedThing(object): > > def __init__(self, name): > self.name = name > def __repr__(self): > return self.name > > >>>>a = NamedThing("Delaware") >>>>b = NamedThing("Hawaii") >>>>d = {} >>>>d[a] = 1 >>>>d[b] = 50 >>>>print d > > {Delaware: 1, Hawaii: 50} > >>>>d[a] > > 1 > >>>>d[b] > > 50 > > Although this is a bit illegal, because repr is not supposed to be used > this way. > > Joel Hedlund wrote: > >>Hi! >> >>There's one thing about dictionaries and __hash__() methods that puzzle me. I >>have a class with several data members, one of which is 'name' (a str). I would >>like to store several of these objects in a dict for quick access >>({name:object} style). Now, I was thinking that given a list of objects I might >>do something like >> >>d = {} >>for o in objects: >> d[o] = o >> >>and still be able to retrieve the data like so: >> >>d[name] >> >>if I just defined a __hash__ method like so: >> >>def __hash__(self): >> return self.name.__hash__() >> >>but this fails miserably. Feel free to laugh if you feel like it. I cooked up a >>little example with sample output below if you care to take the time. >> >>Code: >>--------------------------------------------------------------- >>class NamedThing(object): >> def __init__(self, name): >> self.name = name >> def __hash__(self): >> return self.name.__hash__() >> def __repr__(self): >> return '<foo>' >>name = 'moo' >>o = NamedThing(name) >>print "This output puzzles me:" >>d = {} >>d[o] = o >>d[name] = o >>print d >>print >>print "If I wrap all keys in hash() calls I'm fine:" >>d = {} >>d[hash(o)] = o >>d[hash(name)] = o >>print d >>print >>print "But how come the first method didn't work?" >>--------------------------------------------------------------- >> >>Output: >>--------------------------------------------------------------- >>This output puzzles me: >>{'moo': <foo>, <foo>: <foo>} >> >>If I wrap all keys in hash() calls I'm fine: >>{2038943316: <foo>} >> >>But how come the first method didn't work? >>--------------------------------------------------------------- >> >>I'd be grateful if anyone can shed a litte light on this, or point me to some >>docs I might have missed. >> >>Also: >>Am I in fact abusing the __hash__() method? If so - what's the intended use of >>the __hash__() method? >> >>Is there a better way of implementing this? >> >>I realise I could just write >> >>d[o.name] = o >> >>but this problem seems to pop up every now and then and I'm curious if there's >>some neat syntactic trick that I could legally apply here. >> >>Thanks for your time! >>/Joel Hedlund > > From scott.daniels at acm.org Mon May 1 17:44:46 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 01 May 2006 14:44:46 -0700 Subject: Add file to zip, or replace file in zip In-Reply-To: <2uu5g.483$fb2.452@newssvr27.news.prodigy.net> References: <1146226281.040805.252450@j33g2000cwa.googlegroups.com> <1146257509.963417.250250@g10g2000cwb.googlegroups.com> <4455010f@nntp0.pdx.net> <ka95g.65983$F_3.36061@newssvr29.news.prodigy.net> <4456464c$1@nntp0.pdx.net> <2uu5g.483$fb2.452@newssvr27.news.prodigy.net> Message-ID: <44567dc7$1@nntp0.pdx.net> Edward Elliott wrote: > Scott David Daniels wrote: > >> Edward Elliott wrote: >>> Scott David Daniels wrote: >>>> ... >> > ... You windows kids and your crazy data formats. >> There were a few oth OS's than Linux and Windows. Maybe you >> should call me "you crazy Tenex kid." > > Windows popularized the zip format, but if you insist: > You crazy Tenex kids, with your char-at-a-time raw password checking and > new-fangled virtual memory. Back in my day, all we had was Multics and we > liked it that way. Actually I think it was a combination of CP/M and DOS that popularized the ZIP format; essentially the floppy-disk set, for whom the zip format was a godsend. -- -Scott David Daniels scott.daniels at acm.org From onurb at xiludom.gro Fri May 19 14:02:58 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 20:02:58 +0200 Subject: Exception style In-Reply-To: <mailman.5960.1148053232.27775.python-list@python.org> References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com><mailman.5934.1148032680.27775.python-list@python.org><446da180$0$10184$636a55ce@news.free.fr><126rjus43k450df@corp.supernews.com> <9121k3-hjm.ln1@lairds.us> <mailman.5960.1148053232.27775.python-list@python.org> Message-ID: <446e08ba$0$12795$636a55ce@news.free.fr> Fredrik Lundh wrote: > Cameron Laird wrote: > > >>Guys, I try--I try *hard*--to accept the BetterToAskForgiveness >>gospel, but this situation illustrates the discomfort I consistently >>feel: how do I know that the NameError means VARIABLE didn't resolve, >>rather than that it did, but that evaluation of commands.VARIABLE() >>itself didn't throw a NameError? My usual answer: umm, unless I go >>to efforts to prevent it, I *don't* know that didn't happen. > > > two notes: > > 1) getattr() raises an AttributeError if the attribute doesn't exist, not a NameError. oops ! My bad :( -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From grante at visi.com Fri May 26 20:07:10 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 00:07:10 -0000 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com> <44778e7f$1@nntp0.pdx.net> Message-ID: <127f61eluend535@corp.supernews.com> On 2006-05-26, Scott David Daniels <scott.daniels at acm.org> wrote: >> I tried using the scipy sandbox delaunay module, but the >> interpolators don't work: the natural neighbor interpolator >> produces a surface with "holes" in it: the interpolator returns >> NaNs for no reason for certain regions within the convex hull >> (the convex hull looks right, and the input Z values in that >> region don't look any different that regions that work). > > Sounds like a great opportunity for you to contribute. I'll try, but it looks like I'm going to be working all weekend as it is. > The easiest contribution would be to find as small a case as > you can that demonstrates the problem, fixing it and add a > test case would be, obviously, a greater contribution. -- Grant Edwards grante Yow! Hmmm... an arrogant at bouquet with a subtle visi.com suggestion of POLYVINYL CHLORIDE... From praveenkumar.117 at gmail.com Thu May 4 06:32:54 2006 From: praveenkumar.117 at gmail.com (praveenkumar.117 at gmail.com) Date: 4 May 2006 03:32:54 -0700 Subject: Usage of single click or double click in Tix programming Message-ID: <1146738774.715365.138770@y43g2000cwc.googlegroups.com> Dear all, I am developing an GUI application using Tix I want to trigger a window on single or double click on a name displayed in the GUI. How to go about using Python your help is very much appreciated regards praveen From robert.kern at gmail.com Fri May 12 14:05:55 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 12 May 2006 13:05:55 -0500 Subject: which windows python to use? In-Reply-To: <e40t7m$ull$1@daisy.noc.ucla.edu> References: <mailman.5589.1147359382.27775.python-list@python.org> <e406rp$dvt$1@daisy.noc.ucla.edu> <mailman.5608.1147380021.27775.python-list@python.org> <e40t7m$ull$1@daisy.noc.ucla.edu> Message-ID: <e42iq2$b0i$1@sea.gmane.org> James Stroud wrote: > Robert Kern wrote: > >>James Stroud wrote: >> >>>Enthought does not play well with cygwin, I've noticed. >> >>In what way? Does the mingw gcc that we distribute interfere with Cygwin's gcc? > > One can not run the enthought python interactive interpreter from a > cygwin x-window session, it locks up. Our build person tells me that he sees the same problem with the standard build of Python. http://svn.enthought.com/enthought/ticket/715 -- 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 Fri May 19 13:31:58 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 17:31:58 GMT Subject: newb: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <4d4chmF185ohoU1@uni-berlin.de> <1148038726.023455.145900@j73g2000cwa.googlegroups.com> Message-ID: <iinbg.46843$CH2.19533@tornado.texas.rr.com> "John Machin" <sjmachin at lexicon.net> wrote in message news:1148038726.023455.145900 at j73g2000cwa.googlegroups.com... > In that case, the problem can be solved in O(n) time by a simple loop > which counts the number of differences and notes the position of the > first (if any) difference. Any full-distance Levenshtein method that > does no pre-processing must take O(n**2) time. It is possible to take > advantage of the fact that the OP doesn't care about what the distance > is exactly if it is not 1; 0 is just as bad as 2, 3, 4, etc. > Here is a class that implements 4 different approaches to this comparison problem, with a configurable number of maximum mismatches (where a and b are the strings being compared): 1. use sum(map(lambda (x,y): x!=y, itertools.izip(a,b))) to count mismatches - no short-circuiting 2. use sum(map(abs, itertools.starmap(cmp, itertools.izip(a,b)))) to count mismatches - no short-circuiting 3. use explicit for loop to compare each tuple returned from itertools.izip(a,b) - short-circuits when number of mismatches exceeds allowable number 4. use for loop over itertools.takewhile to count mismatches - short-circuits when number of mismatches exceeds allowable number Also note the short-circuiting in the initializer - if the strings being compared are shorter in length then the number of allowed mismatches, than they will always match, no comparisons required. (In the OP's specific case, any two one-character strings will match within one character). Of course this does nothing to address the larger issue of the program design - I just wanted to learn a little more about itertools. :) -- Paul from itertools import izip,starmap,takewhile class offByNoMoreThanOneCharacter(object): def __init__(self,a,b,maxMismatches=1): len_a = len(a) self.val = None if len_a != len(b): self.val = False elif len_a <= maxMismatches: self.val = True else: self.a = a self.b = b self.maxMismatches = maxMismatches def eval1(self): # one-liner using map with lambda - sum counts mismatches self.val = sum(map(lambda (x,y): x!=y, izip(self.a,self.b))) <= self.maxMismatches def eval2(self): # one-liner using map with abs and cmp - sum counts mismatches self.val = sum(map(abs, starmap(cmp, izip(self.a,self.b)))) <= self.maxMismatches def eval3(self): # explicit traversal, with short-circuit when too many mismatches found mismatches = 0 for (ac,bc) in izip(self.a,self.b): if ac != bc: mismatches += 1 if mismatches > self.maxMismatches: self.val = False break else: self.val = True def eval4(self): # traversal using takewhile, also short-circuits when too many mismatches found numMismatches = 0 maxMismatches = self.maxMismatches stillOk = lambda (s,t)=(None,None) : numMismatches <= maxMismatches for (ac,bc) in takewhile(stillOk, izip(self.a,self.b)): numMismatches += (ac != bc) self.val = stillOk() # special instance method to return "boolean-ness" of this object def __nonzero__(self): if self.val is None: # change this line to use whichever eval method you want to test self.eval1() return self.val def test(a,b): print a,b print bool(offByNoMoreThanOneCharacter(a,b)) print test("abc","abd") test("abc","axd") test("yaqtil","yaqtel") test("yiqtol","yaqtel") From devlai at gmail.com Thu May 25 21:06:09 2006 From: devlai at gmail.com (Devan L) Date: 25 May 2006 18:06:09 -0700 Subject: Creating instances of untrusted new-style classes Message-ID: <1148605569.607231.41640@j73g2000cwa.googlegroups.com> Is there any safe way to create an instance of an untrusted class without consulting the class in any way? With old-style classes, I can recreate an instance from another one without worrying about malicious code (ignoring, for now, malicious code involving attribute access) as shown below. >>> import types >>> class Foo: ... def __init__(self, who, knows, what, args): ... self.mystery_args = (who, knows, what, args) ... print "Your code didn't expect the Spanish inquisition!" ... >>> f = Foo('spam','eggs','ham','bacon') # This would be in a restricted environment, though. Your code didn't expect the Spanish inquisition! >>> types.InstanceType(Foo, f.__dict__) # This wouldn't, but we never run that code, anyways. <__main__.Foo instance at 0x008B5FD0> >>> I'm not sure how to do the same for new-style classes, if it's at all possible to do from within Python. Is there any way to accomplish this, or is there no practical way to do so? Thanks, - Devan From john at castleamber.com Wed May 24 12:19:39 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 16:19:39 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> <447479A1.8050809@hotORgooMAIL.invalid> <Xns97CD6AB19B4F3castleamber@130.133.1.4> <447485B6.4070507@hotORgooMAIL.invalid> Message-ID: <Xns97CD733A1B9ABcastleamber@130.133.1.4> fup to poster Mitch <spudtheimpaler at hotORgooMAIL.invalid> wrote: > John Bokma wrote: [...] >> Funny how people who always think they can "change Usenet" have no >> clue about what Usenet is and how it works in the first place. > > Who said anything about changing it? I like it just the way it is. You don't. >> Usenet is just that, each server participating can be thought of as >> being the back yard of the news master. [ .. ] > here. You know what you are getting into when you sign in, and it is > your responsibility to deal with those you don't agree with > personally. I did. > I understand you consider his writings spam, and so can see why you > have reported him. All I'm saying is that as long as the articles are > remotely on topic, I believe he has a right to post his opinions here. Where is *here*? That's exactly my point. All his posts go to 5 groups, as the replies to his posts. I have no problem if he posts in one of those groups, or even three if he sets a follow-up to. But Xah just dumps his load in 5 groups, no matter if it's on topic in any of them. And since they all promote his website, and Xah never joins the discussion (except to cry wolf when he has been "harassed", overlooking that he has been harassing Usenet for quite some time) I consider his posts spam. Yet I report it as excessive cross posting. > As these are all opinions, I don't see any need to "back up" any of > it. "My" opinion is shared by his hosting provider, and probably the next as well, unless Xah decides to pay a bit more. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From fabiofz at gmail.com Fri May 5 11:51:30 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Fri, 5 May 2006 12:51:30 -0300 Subject: Best IDE for Python? In-Reply-To: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> Message-ID: <cfb578b20605050851l7f1b8fe4x8619ae4c9018105e@mail.gmail.com> Have you checked: http://wiki.python.org/moin/IntegratedDevelopmentEnvironments I like pydev (for Eclipse), but as I also develop it I might be a little biased, so, I'd reccomend checking it and taking your own conclusions. -- Fabio On 5 May 2006 08:28:00 -0700, Saurabh Sardeshpande <saurabh.ss at gmail.com> wrote: > > Pardon if this is already discussed extensively. But what is the best > IDE for Python for a newbie? I have experience in C++ and Java and this > is the first time I am learning a scripting language. > Thanks in advance > > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060505/870e7ef4/attachment.html> From nobody at 127.0.0.1 Wed May 17 19:29:55 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 23:29:55 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <170520061603434552%brian.d.foy@gmail.com> Message-ID: <TlOag.28639$4L1.6911@newssvr11.news.prodigy.com> brian d foy wrote: > You have to note that rewriting a program, even in the same language, > tends to make it shorter, too. These things are measures of programmer > skill, not the usefulness or merit of a particular language. I completely agree. But you have to start somewhere. > Shorter doesn't really mean anything though, and line count means even > less. The number of statements or the statement density might be > slightly more meaningful. Furthermore, you can't judge a script by just > the lines you see. Count the lines of all the libraries and support > files that come into play. Even then, that's next to meaningless unless > the two things do exactly the same thing and have exactly the same > features and capabilities. For an objective measure of which language/environment is more optimal for a given task, your statement is completely accurate. OTOH for a quick-and-dirty real-world comparison of line counts, and possibly a rough approximation of complexity, the libraries don't matter if they offer more-or-less comparable functionality. Especially if those libraries are the standard ones most people rely on. I'm not attaching any special significance to line counts. They're just a data point that's easy to quantify. What if anything do they mean? How does one measure statement density? What's the divisor in the density ratio - lines, characters, units of work, etc? These are all interesting questions with no easy answers. > I can write a one line (or very short) program (in any language) that > does the same thing your scripts do just by hiding the good stuff in a > library. One of my friends likes to talk about his program that > implements Tetris in one statement (because he hardwired everything > into a chip). That doesn't lead us to any greater understanding of > anything though. Of course. Extreme cases are just that. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From lcaamano at gmail.com Tue May 9 10:12:00 2006 From: lcaamano at gmail.com (lcaamano) Date: 9 May 2006 07:12:00 -0700 Subject: Finding defining class in a decorator Message-ID: <1147183919.996287.60140@j73g2000cwa.googlegroups.com> We have a tracing decorator that automatically logs enter/exits to/from functions and methods and it also figures out by itself the function call arguments values and the class or module the function/method is defined on. Finding the name of the class where the method we just entered was defined in is a bit tricky. Here's a snippet of the test code: class Base: @tracelevel(1) def foomethod(self, x, y=5, **kwds): return x+y class TClass(Base): @tracelevel(1) def foomethod(self, x, y=1, **kwds): return Base.foomethod(self, x, **kwds) + x + y t = TClass() t.foomethod(4, d=1) return The output format is irrelevant at this point but it should be something like: TClass:foomethod ... Base:foomethod ... correctly showing the name of the class where the entered method was defined on. We are also using the proposed decorator function in the future functools module, which looks like this: def _update_wrapper(decorated, func, deco_func): # Support naive introspection decorated.__module__ = func.__module__ decorated.__name__ = func.__name__ decorated.__doc__ = func.__doc__ decorated.__dict__.update(func.__dict__) decorated.__decorator__ = deco_func decorated.__decorates__ = func def decorator(deco_func): """Wrap a function as an introspection friendly decorator function""" def wrapper(func): decorated = deco_func(func) if decorated is func: return func _update_wrapper(decorated, func, deco_func) return decorated # Manually make this decorator introspection friendly _update_wrapper(wrapper, deco_func, functools_decorator) return wrapper In our decorator, the part that figures out the name of the class where the wrapped method was defined in has to start with the assumption that the first argument is self and then find the defining class from it. This code fragment is in the wrapper function of the decorator: if numargs > 0: # at definition time, class methods are not methods # yet because the class doesn't exist when the # decorators get called and thus, we have to figure # out classname at runtime via self # # assume first arg is self, see if f.__name__ is there # as a method and if so, then grab it's class name # self = args[0] if type(self) == types.InstanceType: # getattr will find the method anywhere in the # class tree so start from the top bases = list(inspect.getmro(self.__class__)) bases.reverse() for c in bases: # f was given to us in the deco_func meth = getattr(c, f.__name__, None) # we found a method with that name, which # it's probably this same wrapper function # we used to wrap the original method with. ofunc = getattr(meth, '__decorates__', False) if ofunc and ofunc.func_code == f.func_code: # got it clsname = meth.im_class.__name__ break Is there a way to do this without the __decorates__ attribute? -- Luis P Caamano Atlanta, GA, USA From john at castleamber.com Tue May 30 14:04:06 2006 From: john at castleamber.com (John Bokma) Date: 30 May 2006 18:04:06 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> <Xns97D294C4D81FCcastleamber@130.133.1.4> <1148981788.547993.91320@g10g2000cwb.googlegroups.com> Message-ID: <Xns97D384EF9F6E6castleamber@130.133.1.4> ilitzroth at gmail.com wrote: > I don't get the MySpace OMG reference, but rest assured John, you are > still my favorite > newsnet nazi. I know you have been feeling pretty insecure about this > Xah fellow, but Funny that someone diagnosing insecurity needs to refer to Nazi's in an attempt to promote a feeling. -- 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 zombek at gmail.com Mon May 15 11:59:57 2006 From: zombek at gmail.com (zombek at gmail.com) Date: 15 May 2006 08:59:57 -0700 Subject: saving file permission denied on windows Message-ID: <1147708797.746442.19220@j73g2000cwa.googlegroups.com> I'm making a small program which takes a folder with images and generates optimized normal-sized images and thumbnails using Python Imaging Lbrary (PIL). The problem is here: .... os.mkdir(self.output) .... img = Image.open(os.path.join(self.dir,file)) img = img.resize(self.imgSize) # and here comes the error img.save(self.output, "JPEG", optimize=1) IOError: [Errno 13] Permission Denied "D:\\Szymek\\python\\pythumb\\images\\proba" I don't know what's going on, I didn't have any problems with it in the past. I tried to save it to a pre-made directory but the effect is the same, so I don't think it's connected with os.mkdir. From chris.uppal at metagnostic.REMOVE-THIS.org Wed May 10 04:18:18 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Wed, 10 May 2006 09:18:18 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <44606502$2$645$bed64819@news.gradwell.net> <e3s1af$715$1@news.contactel.cz> Message-ID: <4461c69d$0$647$bed64819@news.gradwell.net> Petr Prikryl wrote: > for element in aCollection: > if element > 0: > return True > return False [I'm not sure whether this is supposed to be an example of some specific language (Python ?) or just a generic illustration. I'll take it as the latter, since it makes my point easier to express. I'll also exaggerate, just a little...] But now, in order to hack around the absence of a sensible and useful feature -- /only/ in order to do so -- you have added two horrible new complications to your language. You have introduced a special syntax to express conditionals, and (worse!) a special syntax to express looping. Not only does that add a huge burden of complexity to the syntax, and semantics, of the language (and, to a lesser extent, its implementation), but it also throws out any semblance of uniformity. Once you've started down that route then you've lost all hope of user-defined control structures which operate on a par with the built-in ones. And please note that "control structures" are not limited to C-style "for" "while" etc. E.g. in Java there's an unresolved, and irresolvable, tension between whether a failing operation should return an error condition or throw an exception -- the problem is that exceptions are (IMO and most other peoples' here) intended for exceptional conditions, and for many operations "failure" is not exceptional. One, highly effective, resolution to the problem is for the operation to be parameterised with the action to take if it fails (defaulting to code to raise an exception). In Java that approach, though technically possible, is totally infeasible due to the pathetic overuse of unwanted syntax, and the underuse of simple and powerful primitives. E.g. can you add three-way comparisons (less-than, same-as, greater-than to, say, Python with corresponding three-way conditional control structures to supplement "if" etc ? Are they on a semantic and syntactic par with the existing ones ? In Smalltalk that is trivial (too trivial to be particularly interesting, even), and I presume the same must be true of Lisp (though I suspect you might be forced to use macros). I should say that if your example /is/ in fact Python, then I believe that language allows fairly deep hooks into the execution mechanism, so that at least the "for" bit can be mediated by the collection itself -- which is better than nothing, but nowhere near what I would call "good". -- chris From miki.tebeka at gmail.com Wed May 24 02:56:02 2006 From: miki.tebeka at gmail.com (Miki) Date: 23 May 2006 23:56:02 -0700 Subject: pickling multiple dictionaries In-Reply-To: <1148444653.078683.194750@u72g2000cwu.googlegroups.com> References: <1148444653.078683.194750@u72g2000cwu.googlegroups.com> Message-ID: <1148453762.765287.289240@j33g2000cwa.googlegroups.com> Hello Matthew, You can try either http://docs.python.org/lib/module-shelve.html or any other database bindings with blobs. HTH, Miki http://pythonwise.blogspot.com From wesbrooks at gmail.com Tue May 9 05:28:28 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Tue, 9 May 2006 10:28:28 +0100 Subject: Controlling non-python programs with python Message-ID: <eec9f8ee0605090228x244c387fnc1a426176f200bf3@mail.gmail.com> Dear All, Tried to post once before but it seemed to get trapped in the system due to a suspect heading. I would like to create and pass keyboard, mouse, and analogue device events another program in order to control it, perhaps over a network if it requires too much processing power to be done on the same machine. I'm trying to see if it is possible to control another application using python. In this case I'm trying to control a car simulator by taking screen shots, and passsing the control events to the program. I'm guessing this must be possible as people have written python based vnc software. Cheers for your help. Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060509/828d5245/attachment.html> From lorenzo at nospamthethurmans.com Mon May 15 15:51:14 2006 From: lorenzo at nospamthethurmans.com (Lorenzo Thurman) Date: Mon, 15 May 2006 14:51:14 -0500 Subject: Aggregate funuctions broken in MySQLdb? References: <lorenzo-33D2D1.20511013052006@hedley.internal.thethurmans.com> <1147623011.319336.11820@v46g2000cwv.googlegroups.com> Message-ID: <lorenzo-CCA9BC.14511415052006@hedley.thethurmans.com> Thanks, that was my problem. Can you point me to some documentation on MySQLdb? I've been googling to get answers and that obviously has not been working. In article <1147623011.319336.11820 at v46g2000cwv.googlegroups.com>, "Wade Leftwich" <wleftwich at gmail.com> wrote: > Works fine for me, and I certainly hope MySQLdb is ready for prime > time, because I use the heck out of it. Maybe you're getting fooled by > the fact that cursor.execute() returns the count of result rows. To > actually see the result rows, you have to say cursor.fetchone() or > fetchall() -- > > In [34]: cur.execute("select article_id from articles limit 10") > Out[34]: 10L > > In [35]: cur.fetchall() > Out[35]: ((3L,), (4L,), (5L,), (6L,), (7L,), (8L,), (9L,), (10L,), > (11L,), (12L,)) > > In [36]: cur.execute("select count(article_id) from articles where > article_id < 13") > Out[36]: 1L > > In [37]: cur.fetchall() > Out[37]: ((10L,),) > > In [38]: cur.execute("select sum(article_id) from articles where > article_id < 13") > Out[38]: 1L > > In [39]: cur.fetchone() > Out[39]: (75.0,) > > In [40]: cur.execute("select avg(article_id) from articles where > article_id < 13") > Out[40]: 1L > > In [41]: cur.fetchone() > Out[41]: (7.5,) From bignose+hates-spam at benfinney.id.au Thu May 18 09:15:17 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 23:15:17 +1000 Subject: Which is More Efficient? References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> Message-ID: <87u07nlbiy.fsf@benfinney.id.au> "Dustan" <DustanGroups at gmail.com> writes: > I have a program that uses up a lot of CPU and want to make it is > efficient as possible with what I have to work with it. Profile your program and find the precise parts that are the slowest. Attempting to optimise before that is a waste of your time. > So which of the following would be more efficient, knowing that l is > a list and size is a number? > > l=l[:size] > del l[size:] Which one is more efficient in your program, when you profile its performance? <URL:http://docs.python.org/lib/profile.html> -- \ "Working out the social politics of who you can trust and why | `\ is, quite literally, what a very large part of our brain has | _o__) evolved to do." -- Douglas Adams | Ben Finney From jairodsl at gmail.com Wed May 3 00:19:11 2006 From: jairodsl at gmail.com (jairodsl) Date: 2 May 2006 21:19:11 -0700 Subject: UPGMA algorithm ??? Message-ID: <1146629951.014136.121890@y43g2000cwc.googlegroups.com> Hello ! I have searching this algorithm (UPGMA) writting in python, i didnt found, could anybody help me ??? Thanks a lot!!! Cordially, jDSL From sjmachin at lexicon.net Fri May 26 20:20:40 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 27 May 2006 10:20:40 +1000 Subject: stupid perl question In-Reply-To: <mailman.6263.1148686209.27775.python-list@python.org> References: <mailman.6263.1148686209.27775.python-list@python.org> Message-ID: <44779B58.7020105@lexicon.net> On 27/05/2006 9:15 AM, M.N.A.Smadi wrote: > hi guys; > > sorry for sending a perl question here, but python guy "HAD TO" look at > perl code; > > how can i split a string that contains white spaces and '_' > > any clue? > > thanks > moe smadi Well the screamingly obvious way to do in Python what I think your imprecise question is asking is: >>> "foo_bar zot plugh _ xyzzy".replace("_", " ").split() ['foo', 'bar', 'zot', 'plugh', 'xyzzy'] >>> Talking about screaming, I fled screaming from perl at about the perl 3 stage -- I can't help you any further; I don't want to turn into a pillar of salt. Why don't you ask stupid perl questions on comp.lang.perl?? Cheers, John From nobody at 127.0.0.1 Sun May 21 18:30:37 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 22:30:37 GMT Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> Message-ID: <hS5cg.20475$Lm5.4605@newssvr12.news.prodigy.com> foxtree at gmail.com wrote: > Flash also behaves consistently cross-browser, cross/platform -- and > features cannot be disabled by the user. ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ And that's a good thing? Maybe for Macromedia, not for us. This smells like astroturf. > Flash can load and play external MP3 audio. > Flash can render text... > Flash can load/parse/serialize/send XML. > Flash can access you webcam, allowing you to create your own video > chat/IM app. > Flash can programatically-build vector shapes, gradients, and fills. It dices! It splices! Flash can heat your coffee, walk your dog, and change your baby! It's the stupendous, miraculous, fantabulous app you can't live without! > Flash can #animate# stuff!!! > > Flash is like a 2 MB download that works in almost *every* browser out > there. ...it's pretty phenomenal that all those features could have > been crammed into it. (like: a built-in interpreter for a > late-version-EcmaScript-compliant scripting language -- that, in many > ways, is far more capable than what is available w/ JavaScript in most > browsers!) > > *** This feature can be used for a web-based CMS! It would blow-away > anything (non-Java) now available for managing and uploading assets. > - Show quoted text - Ugh, definitely astroturf. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From kentilton at gmail.com Fri May 5 21:16:50 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 05 May 2006 21:16:50 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Message-ID: <6OS6g.78$Ey5.74@fe12.lga> Xah Lee wrote: > Python, Lambda, and Guido van Rossum > > Xah Lee, 2006-05-05 > > In this post, i'd like to deconstruct one of Guido's recent blog about > lambda in Python. > > In Guido's blog written in 2006-02-10 at > http://www.artima.com/weblogs/viewpost.jsp?thread=147358 > > is first of all, the title ?Language Design Is Not Just Solving > Puzzles?. In the outset, and in between the lines, we are told that > ?I'm the supreme intellect, and I created Python?. > > This seems impressive, except that the tech geekers due to their > ignorance of sociology as well as lack of analytic abilities of the > mathematician, do not know that creating a language is a act that > requires little qualifications. However, creating a language that is > used by a lot people takes considerable skill, and a big part of that > skill is salesmanship. Guido seems to have done it well and seems to > continue selling it well, where, he can put up a title of belittlement > and get away with it too. > > Gaudy title aside, let's look at the content of his say. If you peruse > the 700 words, you'll find that it amounts to that Guido does not like > the suggested lambda fix due to its multi-line nature, and says that he > don't think there could possibly be any proposal he'll like. The > reason? Not much! Zen is bantered about, mathematician's impractical > ways is waved, undefinable qualities are given, human's right brain is > mentioned for support (neuroscience!), Rube Goldberg contrivance > phraseology is thrown, I think this is what you missed in your deconstruction. The upshot of what he wrote is that it would be really hard to make semantically meaningful indentation work with lambda. Guido did not mean it, but the Rube Goldberg slam is actually against indentation as syntax. "Yes, print statements in a while loop would be helpful, but..." it would be so hard, let's go shopping. ie, GvR and Python have hit a ceiling. That's OK, it was never meant to be anything more than a scripting language anyway. But the key in the whole thread is simply that indentation will not scale. Nor will Python. > and coolness of Google Inc is reminded for the > tech geekers (in juxtaposition of a big notice that Guido works > there.). > > If you are serious, doesn't this writing sounds bigger than its > content? Look at the gorgeous ending: ?This is also the reason why > Python will never have continuations, and even why I'm uninterested in > optimizing tail recursion. But that's for another installment.?. This > benevolent geeker is gonna give us another INSTALLMENT! > > There is a computer language leader by the name of Larry Wall, who said > that ?The three chief virtues of a programmer are: Laziness, > Impatience and Hubris? among quite a lot of other ingenious > outpourings. It seems to me, the more i learn about Python and its > leader, the more similarities i see. > > So Guido, i understand that selling oneself is a inherent and necessary > part of being a human animal. But i think the lesser beings should be > educated enough to know that fact. So that when minions follow a > leader, they have a clear understanding of why and what. Oh, my, you are preaching to the herd (?!) of lemmings?! Please tell me you are aware that lemmings do not have ears. You should just do Lisp all day and add to the open source libraries to speed Lisp's ascendance. The lemmings will be liberated the day Wired puts John McCarthy on the cover, and not a day sooner anyway. kenny (wondering what to call a flock (?!) of lemmings) -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From phddas at yahoo.com Sun May 14 16:33:55 2006 From: phddas at yahoo.com (Gary Wessle) Date: 15 May 2006 06:33:55 +1000 Subject: continue out of a loop in pdb References: <87mzdkwke3.fsf@localhost.localdomain> <PIK9g.28632$CH2.27494@tornado.texas.rr.com> Message-ID: <87ac9kwdl8.fsf@localhost.localdomain> "Paul McGuire" <ptmcg at austin.rr._bogus_.com> writes: > "Gary Wessle" <phddas at yahoo.com> wrote in message > news:87mzdkwke3.fsf at localhost.localdomain... > > Hi > > > > using the debugger, I happen to be on a line inside a loop, after > > looping few times with "n" and wanting to get out of the loop to the > > next line, I set a break point on a line after the loop structure and > > hit c, that does not continue out of the loop and stop at the break > > line, how is it down, I read the ref docs on pdb but could not figure > > it out. > > > > thanks > > This is exactly how I do this operation using pdb, and it works for me, so > you are on the right track. Is it possible that something inside the loop > is raising an exception, thereby jumping past your breakpoint? Try putting > the loop inside a try-except. > > -- Paul the code works with no problem, I am playing around with the pdb, i.e **************** from pdb import * set_trace() for i in range(1,500000): print i print "tired of this" print "I am out" **************** fred at debian:~/python/practic$ python practic.py > /home/fred/python/practic/practic.py(4)?() -> for i in range(1,500000): (Pdb) n > /home/fred/python/practic/practic.py(5)?() -> print i (Pdb) n 1 > /home/fred/python/practic/practic.py(4)?() -> for i in range(1,500000): (Pdb) b 6 Breakpoint 1 at /home/fred/python/practic/practic.py:6 (Pdb) c > /home/fred/python/practic/practic.py(5)?() -> print i <<<< I expected (print "tired of this") (Pdb) From peace.is.our.profession at gmx.de Thu May 11 10:41:16 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Thu, 11 May 2006 16:41:16 +0200 Subject: reusing parts of a string in RE matches? In-Reply-To: <GGH8g.2085$No6.45839@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> <E6r8g.2083$No6.45931@news.tufts.edu> <eir8g.2084$No6.45965@news.tufts.edu> <1147291197.423570.242440@g10g2000cwb.googlegroups.com> <e3v387$9tt$1@mlucom4.urz.uni-halle.de> <GGH8g.2085$No6.45839@news.tufts.edu> Message-ID: <e3vikl$ecv$1@mlucom4.urz.uni-halle.de> Hi John > rg = r'(\w)(?=(.)\1)' > > That would at least isolate the number, although you'd still have to get > it out of the list/tuple. I have no idea how to do this in Python in a terse way - but I'll try ;-) In Perl, its easy. Here, the "match construct" (\w)(?=(.)\1) returns all captures in a list (a 1 a 2 a 4 b 7 c 9) because we capture 2 fields per comparision: The first is (\w), needed for backreference, the second is the dot (.), which finds the number in the center (or any- thing else). So, in perl you 'filter' by the 'grep' function on each list element: grep{ /\d/ } - this means, only numbers (\d) will pass through: $_ = 'a1a2a3Aa4a35a6b7b8c9c'; print grep{/\d/} /(\w)(?=(.)\1)/g; #prints => 1 2 4 7 9 I'll try to fiddle somthing out that works in Python too ... Regards M. From steve at hastings.org Wed May 3 15:30:27 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 03 May 2006 12:30:27 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <I9O5g.2039$No6.43918@news.tufts.edu> <pan.2006.05.02.19.35.15.219815@hastings.org> <4457b69b$1_1@news.bluewin.ch> <pan.2006.05.03.04.02.14.139249@hastings.org> <b466g.72406$H71.46987@newssvr13.news.prodigy.com> Message-ID: <pan.2006.05.03.19.30.25.695458@hastings.org> On Wed, 03 May 2006 17:51:03 +0000, Edward Elliott wrote: > Steve R. Hastings wrote: >> You could also use a function that counts all different values in a list, >> reducing the list to a dictionary whose keys are the unique values from >> the list. > > Wouldn't reducing to a set instead of a dict make more sense if all you want > to do is count uniq elements? My apologies for not explaining tally() better. The dict has one key for each unique element, and the value associated with each key is a count of how many times that element appeared in the original list. lst = ['a', 'b', 'b', 'c', 'c', 'c'] d = iterwrap.tally(lst) print d # prints something like: {'a': 1, 'c': 3, 'b': 2} If you didn't care how many times the values appeared in the original list, and just just wanted the unique values, then a set would be perfect. If you happen to have tally(), it is an easy way to solve the original problem: figure out whether a list has exactly one true value in it. d = tally(bool(x) for x in lst) if d[True] == 1: print "and there was much rejoicing" -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From deets at nospam.web.de Fri May 5 08:43:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 14:43:20 +0200 Subject: Method acting on arguements passed References: <1146832062.017259.265700@y43g2000cwc.googlegroups.com> Message-ID: <4c0vkbF132r1oU1@uni-berlin.de> Panos Laganakos wrote: > I want a class method to take action depending on the type of the > arguement passed to it. > > ie: > getBook(id) # get the book by ID > getBook(name) # get the book by name > ... > > Other languages use the term function/method overloading to cope with > this. And when I googled about it seems that GvR is testing it for 3.0 > inclusion or so. > > I was thinking of right after the function declaration check for the > parameter passed by isinstance() or type() and use if..elif..else to > act. > > Is this the pythonic way/best practice to apply here? google for gnosis multimethods for a clean approach. Diez From jweida at gmail.com Tue May 23 12:04:51 2006 From: jweida at gmail.com (Jerry) Date: 23 May 2006 09:04:51 -0700 Subject: How to open https Site and pass request? In-Reply-To: <mailman.6110.1148388676.27775.python-list@python.org> References: <4472F2E6.9040204@gmail.com> <mailman.6110.1148388676.27775.python-list@python.org> Message-ID: <1148400291.836030.200840@y43g2000cwc.googlegroups.com> That depends on your OS. In Windows, I believe you would have to recompile Python from source. On Linux, you could probably just get a package. From Debian, I know that it's python-ssl. I'm sure most the others would have one as well. -- Jerry From onurb at xiludom.gro Thu May 18 09:34:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 15:34:18 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147952916.536664.260700@38g2000cwa.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <446c3b2b$0$17368$636a55ce@news.free.fr> <1147947048.303912.109150@38g2000cwa.googlegroups.com> <446c5a80$0$7024$636a55ce@news.free.fr> <1147952916.536664.260700@38g2000cwa.googlegroups.com> Message-ID: <446c7842$0$4847$626a54ce@news.free.fr> glomde wrote: >>Adding ugly and unintuitive "operators" to try to turn a general purpose >>programming language into a half-backed unusable HTML templating >>language is of course *much* more pythonic... > > > IT is not only for HTML. I do think html and xml are the biggest > creators of > hierarcical treestructures. What is a 'non-hierarchical treestructure' ? A list ?-) > But it would work for any package that > manipulates, > creates hierarchical data. FWIW, filesystems are trees, most RDBMS use BTrees, and almost any OO program is a graph of objects - trees being a subset of graphs.. Strange enough, working with trees is nothing new, and it seems that almost anyone managed to get by without cryptic 'operators' stuff. > I used HTML as example since it is a good > example and > most people would understand the intention. Sorry for being dumb. > But could you elaborate on your comment that it is unusable. Ask all the coders that switched from Perl to Python why they did so... > Do you > think all template systems are unusable Nope - I use template systems everyday. Please don't take it wrong: there's surely something to do to ease declarative XML-like (including JSON, Yaml etc...) datastructure construction. But I think the pythonic way to go would rely on metaprogramming - not on ugly perlish syntax. -- 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 Tue May 16 06:12:02 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 May 2006 03:12:02 -0700 Subject: Large Dictionaries In-Reply-To: <1147751294.699031@teuthos> References: <1147699064.107490@teuthos> <roy-765731.09112115052006@reader1.panix.com> <1147751294.699031@teuthos> Message-ID: <1147774322.797789.132510@y43g2000cwc.googlegroups.com> > (my dictionary values are all None). So in fact all you need is a set. Have you experimented with the Python 2.5 alpha? From OlafMeding at gmail.com Wed May 3 17:09:37 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 3 May 2006 14:09:37 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <mailman.5279.1146689738.27775.python-list@python.org> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <mailman.5279.1146689738.27775.python-list@python.org> Message-ID: <1146690577.890220.53370@y43g2000cwc.googlegroups.com> Tim > Do you want someone running this test to hit the ENTER key, or not? The purpose of the "sys.stdin.read(1)" statement is simply to prevent the main thread from exiting and thus ending the test. And yes, I also get an exception when I press the enter key. Olaf From lahirister at gmail.com Wed May 24 15:41:06 2006 From: lahirister at gmail.com (lahirister at gmail.com) Date: 24 May 2006 12:41:06 -0700 Subject: simple print is not working.. Message-ID: <1148499666.824598.313720@i40g2000cwc.googlegroups.com> What is wrong with this script? #!/usr/bin/python fsfile = open('/tmp/fs_info.al', 'r') for line in fsfiles.readlines(): print line fsfile.close() #./get_fs_info.py File "./get_fs_info.py", line 4 print line ^ SyntaxError: invalid syntax Any ideas? Thanks AL From __peter__ at web.de Wed May 10 01:53:09 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 May 2006 07:53:09 +0200 Subject: Deferred Evaluation in Recursive Expressions? References: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> <e3qc7h$ats$01$1@news.t-online.com> <1147189028.751527.157640@j73g2000cwa.googlegroups.com> <e3qej4$o8j$02$1@news.t-online.com> <1147234531.245540.307990@g10g2000cwb.googlegroups.com> Message-ID: <e3rv0m$juo$00$1@news.t-online.com> birchb at ozemail.com.au wrote: > That's a good fix. But I have misgivngs about needing a global name > registry. I need to support anonymous types and types with local > (lexical) scope. For example: > > def makeAnonymousRecursiveType(T): > # anonymous type expression with local scope > LinkedList = (T, lambda: LinkedList) > return LinkedList > > local = makeAnonymousRecursiveType(int) class Names(object): def __getattribute__(self, name): return name types = Names() class Type(type): all = {} def __new__(mcl, name, bases, dict): assert "_typedef" not in dict dict["_typedef"] = dict.pop("typedef", ()) cls = type.__new__(mcl, name, bases, dict) cls.all[name] = cls return cls def get_typedef(cls): def get(item): result = cls.all.get(item) if result is None: result = type(cls).all.get(item, item) return result return tuple(get(item) for item in cls._typedef) def set_typedef(cls, value): cls._typedef = value typedef = property(get_typedef, set_typedef) class TypeDef: __metaclass__ = Type class LinkedListA(TypeDef): typedef = (int, types.LinkedListB) class LinkedListB(TypeDef): typedef = (int, types.LinkedListA) print LinkedListA.typedef print LinkedListB.typedef print LinkedListA.typedef def LocalTypeDef(): class LocalTypeDef(TypeDef): all = {} return LocalTypeDef def makeAnonymousRecursiveType(T): class LinkedList(LocalTypeDef()): typedef = (T, types.LinkedList) return LinkedList print makeAnonymousRecursiveType(int).typedef print makeAnonymousRecursiveType(str).typedef Go with lambda, I'd say... Peter From roy at panix.com Wed May 24 08:11:06 2006 From: roy at panix.com (Roy Smith) Date: Wed, 24 May 2006 08:11:06 -0400 Subject: Best way to handle exceptions with try/finally References: <mailman.6122.1148413632.27775.python-list@python.org> <1148457332.582609.98490@38g2000cwa.googlegroups.com> Message-ID: <roy-BB3D38.08110624052006@reader1.panix.com> In article <1148457332.582609.98490 at 38g2000cwa.googlegroups.com>, "Maxim Sloyko" <m.sloyko at gmail.com> wrote: > I guess the following standard method will help : > > class MyLocker(object): > def __init__(self, lock): > self.lock = lock > self.lock.acquire() > > def __del__(self): > self.lock.release() > > Then whenever you need to acquire a lock: > templock = MyLocker(self.__mutex) > > del templock # will release the lock (provided you didn't create an > extra link to this object) Warning! Danger, Will Robinson! Evil space aliens are trying to write C++ in Python! Quick, we must get back to the ship before they eat our brains! The problem here is that there is no guarantee that __del__() will get called at any predictable time (if at all). C++ uses deterministic object destruction. Python doesn't destroy (finalize?) objects until the garbage collector runs. See PEP-343 (http://www.python.org/dev/peps/pep-0343/) for the new "with" statement which should solve problems like this. If I understand things right, "with" will be included in Python-2.5, which is due out Real Soon Now. From nobody at 127.0.0.1 Tue May 2 04:45:59 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 08:45:59 GMT Subject: set partitioning References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> <1146522121.798317.206180@i39g2000cwa.googlegroups.com> <1146523373.778624.142510@y43g2000cwc.googlegroups.com> <mailman.5197.1146525436.27775.python-list@python.org> <1146530789.867089.75160@i39g2000cwa.googlegroups.com> Message-ID: <b%E5g.64464$_S7.36952@newssvr14.news.prodigy.com> hymort at hotmail.com wrote: > For the list [1,2,3,4], I'm looking for the following for k = 2: > > [[1,2], [3,4]] > [[1,3], [2,4]] > [[1,4], [2,3]] That's not what you asked for the first time. You said you wanted "m non-empty, disjoint subsets", but the subsets above are clearly not all disjoint; only those on the same line are. It sounds like what you really want is the "powerset of non-empty, disjoint partitions of size k". From nospam at foo.com Fri May 12 19:07:12 2006 From: nospam at foo.com (jayessay) Date: 12 May 2006 19:07:12 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <yV49g.15$Id.13@fe10.lga> <yfsody3t4jd.fsf@oc.ex.ac.uk> Message-ID: <m34pzuq1un.fsf@rigel.goldenthreadtech.com> Alexander Schmolck <a.schmolck at gmail.com> writes: > Ken Tilton <kentilton at gmail.com> writes: > > > In Common Lisp we would have: > > > > (defvar *x*) ;; makes it special > > (setf *x* 1) > > (print *x*) ;;-> 1 > > (let ((*x* 2)) > > (print *x*)) ;; -> 2 > > (print *x*) ;; -> 1 > > You seem to think that conflating special variable binding and lexical > variable binding is a feature and not a bug. What's your rationale? And the particularly ugly, crappy, half baked python emulation is what? A feature? Right. /Jon -- 'j' - a n t h o n y at romeo/charley/november com From nobody at 127.0.0.1 Thu May 11 16:12:55 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 11 May 2006 20:12:55 GMT Subject: syntax for -c cmd References: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> Message-ID: <bVM8g.85722$dW3.77269@newssvr21.news.prodigy.com> James wrote: > Wrong syntax is shown below. What should be the delimiter before else? > > python -c 'if 1==1: print "yes"; else print "no"' Now this is interesting. I broke the line up into separate arguments and it seemed to work fine: $ python -c 'if 1==1: print "yes"' 'else: print "no"' yes But then I tested the else branch and it produces no output: $ python -c 'if 1==0: print "yes"' 'else: print "no"' $ If putting the else in a separate arg unbinds it from the if, I would expect a syntax error. If OTOH naked elses are allowed on the command line for some odd reason, then this shouldn't happen: $ python -c 'else: print "no"' File "<string>", line 1 else: print "no" ^ SyntaxError: invalid syntax What's with the silent failure in the two-arg version? If the else arg is syntactically acceptable, why doesn't it behave as expected? From skip at pobox.com Mon May 8 21:43:31 2006 From: skip at pobox.com (skip at pobox.com) Date: Mon, 8 May 2006 20:43:31 -0500 Subject: advanced number recognition in strings? In-Reply-To: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> References: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> Message-ID: <17503.62403.621368.986261@montanaro.dyndns.org> Sebastian> we want extract numbers from strings and wonder if there is Sebastian> already a module around for doing this. An example in our Sebastian> case would look like this: Sebastian> 0.032 +/- 0.5 x 10(-4) Sebastian> it would even be helpful to have a routine which does not Sebastian> recognise the +/- , but at least the 10(-4). How about the tokenize module? >>> import tokenize >>> lines = ["0.032 +/- 0.5 x 10(-4)\n"] >>> def readline(): ... if lines: ... line = lines.pop(0) ... return line ... return "" ... >>> tokenize.tokenize(readline) 1,0-1,5: NUMBER '0.032' 1,6-1,7: OP '+' 1,7-1,8: OP '/' 1,8-1,9: OP '-' 1,10-1,13: NUMBER '0.5' 1,14-1,15: NAME 'x' 1,16-1,18: NUMBER '10' 1,18-1,19: OP '(' 1,19-1,20: OP '-' 1,20-1,21: NUMBER '4' 1,21-1,22: OP ')' 1,22-1,23: NEWLINE '\n' 2,0-2,0: ENDMARKER '' Skip From go at away.com Sun May 28 20:19:58 2006 From: go at away.com (3rdshiftcoder) Date: Mon, 29 May 2006 00:19:58 GMT Subject: pyswt SWT.NULL Message-ID: <O6reg.2716$HV1.383@trndny01> hi- i am trying to make a pyswt gui and when it gets to this line: colType = Combo(self.shell, SWT.NULL) i get: colType = Combo(self.shell, SWT.NULL) AttributeError: NULL when using swt with java i had to have lots of imports at the beginning of a swt file. are they not needed when using pyswt? thanks for any help, jim From robert.kern at gmail.com Mon May 22 10:42:12 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 May 2006 09:42:12 -0500 Subject: enumerate() question In-Reply-To: <1148308146.493287.323770@38g2000cwa.googlegroups.com> References: <1148308146.493287.323770@38g2000cwa.googlegroups.com> Message-ID: <e4sik4$csg$1@sea.gmane.org> Gregory Petrosyan wrote: > Hello! > I have a question for the developer[s] of enumerate(). Consider the > following code: > > for x,y in coords(dots): > print x, y > > When I want to iterate over enumerated sequence I expect this to work: > > for i,x,y in enumerate(coords(dots)): > print i, x, y > > Unfortunately, it doesn't =( and I should use (IMHO) ugly > > for i,pair in enumerate(coords(dots)): > print i, pair[0], pair[1] > > So, why enumerate() works this way Special cases aren't special enough to break the rules. enumerate shouldn't behave differently for different types of items. > and is there any chance of changing > the behaviour? No, not really. Instead, try this: for i, (x, y) in enumerate(coords(dots)): print i, x, y -- 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 kay.schluehr at gmx.net Tue May 16 01:53:22 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 15 May 2006 22:53:22 -0700 Subject: Far from complete Message-ID: <1147758802.408740.131700@u72g2000cwu.googlegroups.com> Section 2.3 of the Python 2.5. tutorial "The following sections describe the standard types that are built into the interpreter. Historically, Python's built-in types have differed from user-defined types because it was not possible to use the built-in types as the basis for object-oriented inheritance. With the 2.2 release this situation has started to change, although the intended unification of user-defined and built-in types is as yet far from complete. " "Far from complete"? Have I missed something? From john at castleamber.com Wed May 24 11:02:51 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:02:51 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <4474240a$1@news.wineasy.se> Message-ID: <Xns97CD66353D866castleamber@130.133.1.4> "Dag Sunde" <me at dagsunde.com> wrote: > "Xah Lee" <xah at xahlee.org> skrev i melding > news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... >> I'm sorry to trouble everyone. But as you might know, due to my >> controversial writings and style, recently John Bokma lobbied people to >> complaint to my web hosting provider. After exchanging a few emails, my >> web hosting provider sent me a 30-day account cancellation notice last >> Friday. > > The solution to your problem is very simple: > > Stop posting your "controversial writings and style" to public > newgroups, and keep them on your web-server where they belong. Or post them to one, and just one, relevant news group instead of spamvertizing your site with a hit & run post in 5 (which is a Google Groups limit, if it was 10, Xah would use 10) -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From manstey at csu.edu.au Tue May 23 18:14:59 2006 From: manstey at csu.edu.au (manstey) Date: 23 May 2006 15:14:59 -0700 Subject: NEWB: reverse traversal of xml file In-Reply-To: <1148348572.610824.137750@j33g2000cwa.googlegroups.com> References: <1148344898.351787.159540@i40g2000cwc.googlegroups.com> <1148348572.610824.137750@j33g2000cwa.googlegroups.com> Message-ID: <1148422499.812056.134120@u72g2000cwu.googlegroups.com> But will this work if I don't know parts in advance. I only know parts by reading through the file, which has 450,000 lines. From dongdonglove8 at hotmail.com Mon May 22 07:53:34 2006 From: dongdonglove8 at hotmail.com (python) Date: 22 May 2006 04:53:34 -0700 Subject: about py2exe, I installed it, but can't find py2exe.exe in my computer. In-Reply-To: <mailman.5947.1148046426.27775.python-list@python.org> References: <1148045399.833782.106910@g10g2000cwb.googlegroups.com> <mailman.5947.1148046426.27775.python-list@python.org> Message-ID: <1148298814.490374.115070@j33g2000cwa.googlegroups.com> it prompt: invalid command 'py2exe'. I have import py2exe in setup.py file. From ptmcg at austin.rr._bogus_.com Tue May 16 02:49:55 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 16 May 2006 06:49:55 GMT Subject: using target words from arrays in regex, pythons version of perls 'map' References: <44691fc2$0$61162$ae4e5890@news.nationwide.net> <41mi62hih1d3i53nnhdkfi9tpil77bfdp7@4ax.com> Message-ID: <nCeag.29137$Qq.14092@tornado.texas.rr.com> "Dennis Lee Bieber" <wlfraed at ix.netcom.com> wrote in message news:41mi62hih1d3i53nnhdkfi9tpil77bfdp7 at 4ax.com... > On Mon, 15 May 2006 19:41:39 -0500, Lance Hoffmeyer > <lance at augustmail.com> declaimed the following in comp.lang.python: > > I would have something similar to perl above: > > > > > > targets = ['OVERALL RATING', > > 'CLOTHING', ITEMS', > > 'ACCESSORIES', > > 'SHOES', > > 'FINE JEWELRY'] > > > > PROPOSED CODE: > > > > match2 = re.search(targets[i].*?(?:(\d{1,3}\.\d)\s+){3} ', file2);m[i] = match2.group(1) > > > > > I don't do regex's, and I also don't find packing multiple statements on one line attractive. I concur - this kind of multiple-statements-per-line-ishness feels gratuitous. Yes, I know they line up nicely when all 6 statements are printed out together, but the repetition of "mNN = match2.group(1) ;print mNN" should tell you that this might be better done with a for loop. DRY. > > However... Why don't you basically do what you say you do in > Python... Substitute you targets into the expression while inside a > loop... > > targets = [ "OVERALL RATING", > "CLOTHING", > "ITEMS", > "ACCESSORIES", > "SHOES", > "FINE JEWELRY" ] > > results = [] > for t in target: > m2 = re.search("%s.*?(?:(\d{1,3}\.\d)\s+){3}" % t, file2) > results.append(m2.group(1)) > -- # by contrast, here is a reasonably Pythonic one-liner, if one-liner it must be results = [ re.search(r"%s.*?(?:(\d{1,3}\.\d)\s+){3}" % t, file2).group(1) for t in targets ] # or for improved readability (sometimes 2 lines are better than 1): reSearchFunc = lamdba tt,ff : re.search(tt + r".*?(?:(\d{1,3}\.\d)\s+){3}", ff).group(1) results = [ reSearchFunc(t,file2) for t in targets ] Resisting-the-urge-to-plug-pyparsing-ly yours, -- Paul From jmdeschamps at gmail.com Wed May 31 11:20:38 2006 From: jmdeschamps at gmail.com (jmdeschamps at gmail.com) Date: 31 May 2006 08:20:38 -0700 Subject: Best Python Editor In-Reply-To: <447d8314$0$10284$626a54ce@news.free.fr> References: <mailman.6359.1149069835.27775.python-list@python.org> <447d8314$0$10284$626a54ce@news.free.fr> Message-ID: <1149088838.578644.17890@g10g2000cwb.googlegroups.com> bruno at modulix wrote: > Manoj Kumar P wrote: > > Hi, > > > > Can anyone tell me a good python editor/IDE? > > It would be great if you can provide the download link also. > > I hate to be the one answering this, but this is *really* a FAQ - as you > would have known if you had google'd this group for this. > ... and/or consider this page from python.org http://wiki.python.org/moin/PythonEditors since there are many possibilities of *good editors*, and advocacy generally stems from personal preferences ;-) jm From ketil+news at ii.uib.no Tue May 9 02:44:40 2006 From: ketil+news at ii.uib.no (Ketil Malde) Date: Tue, 09 May 2006 08:44:40 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <joadnUiUIdmNsP3ZnZ2dnUVZ_tKdnZ2d@speakeasy.net> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> Message-ID: <egwtcvelyf.fsf@polarvier.ii.uib.no> aleax at mac.com (Alex Martelli) writes: >> Any time you want an anonymous function (or class, or type, or number) >> it would be because that thing is sufficiently small and simple that the >> best name for it is the code itself. > In the real world, people don't choose anonymous functions only in > these alleged cases where anonymous is best In the real world, people do a lot of things they shouldn't. Any feature can be abused, and poor style is possible in any language. I just checked my code for lambdas, and they are exclusively short half-liners passed as parameters to higher order functions. Naming them would only complicate the code, just like naming (other) intermediate results would. > if anonymous functions are available, they're used in even more > cases where naming would help Perhps, but not necessarily. But how about the converse: if every function must be named, they will be named even where naming them hurts. -k -- If I haven't seen further, it is by standing in the footprints of giants From wrongbad at gmail.com Fri May 5 21:59:39 2006 From: wrongbad at gmail.com (I V) Date: Fri, 05 May 2006 18:59:39 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Message-ID: <pan.2006.05.06.01.59.38.15904@gmail.com> On Fri, 05 May 2006 17:26:26 -0700, Xah Lee wrote: > Regarding the lambda in Python situation... conceivably you are right > that Python lambda is perhaps at best left as it is crippled, or even > eliminated. However, this is what i want: I want Python literatures, > and also in Wikipedia, to cease and desist stating that Python supports > functional programing. (this is not necessarily a bad publicity) And, I What does lambda have to do with supporting or not supporting functional programming? From zannablu at libero.it Sun May 28 14:43:14 2006 From: zannablu at libero.it (Faber) Date: Sun, 28 May 2006 18:43:14 GMT Subject: html 2 plain text References: <1148840205.741356.209310@i40g2000cwc.googlegroups.com> Message-ID: <6bmeg.15876$jP5.394845@twister1.libero.it> robin wrote: > i remember seeing this simple python function which would take raw html > and output the content (body?) of the page as plain text (no <..> tags > etc) > i have been looking at htmllib and htmlparser but this all seems to > complicated for what i'm looking for. i just need the main text in the > body of some arbitrary webbpage to then do some natural-language > processing with it... > thanks for pointing me to some helpful resources! Have a look at the Beautiful Soup library: http://www.crummy.com/software/BeautifulSoup/ Regards -- Faber http://faberbox.com/ http://smarking.com/ A teacher must always teach to doubt his teaching. -- Jos? Ortega y Gasset From sspivey at gmail.com Mon May 1 16:33:13 2006 From: sspivey at gmail.com (pythonhelpneeded) Date: 1 May 2006 13:33:13 -0700 Subject: Could not find platform independent libraries Message-ID: <1146515593.911374.261910@g10g2000cwb.googlegroups.com> While building Python 2.4.3 on SCO OpenServer 5.0.5, I'm getting the error below. The modules mentioned seem to be available in the Lib subdirectory. I've tried setting PYTHONHOME to the build directory (/tmp/Python-2.4.3), it didn't help. Any help would be appreciated. # make case $MAKEFLAGS in \ *-s*) CC='cc' LDSHARED='cc -Wl,-G,-Bexport' OPT='-DNDEBUG -O' ./python -E ./setup.py -q build;; \ *) CC='cc' LDSHARED='cc -Wl,-G,-Bexport' OPT='-DNDEBUG -O' ./python -E ./setup.py build;; \ esac Could not find platform independent libraries <prefix> Could not find platform dependent libraries <exec_prefix> Consider setting $PYTHONHOME to <prefix>[:<exec_prefix>] 'import site' failed; use -v for traceback Traceback (most recent call last): File "./setup.py", line 6, in ? import sys, os, getopt, imp, re ImportError: No module named os *** Error code 1 (bu21) UX:make: ERROR: fatal error. From ramen at lackingtalent.com Fri May 12 12:16:36 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Fri, 12 May 2006 11:16:36 -0500 Subject: Time to bundle PythonWin In-Reply-To: <1hf737g.1oyxbs31plch4nN%aleax@mac.com> References: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> <1hf737g.1oyxbs31plch4nN%aleax@mac.com> Message-ID: <Pine.LNX.4.63.0605121114270.7260@lackingtalent.com> On Thu, 11 May 2006, Alex Martelli wrote: > Dave Benjamin <ramen at lackingtalent.com> wrote: > ... >> It's time to bundle PythonWin. > > No: the Python Standard Distribution, in 2.5, includes instead ctypes, > which is lower-level than PythonWin but more general (exists for other > platforms, lets you call other DLLs on Windows and not just those > wrapped for you by the author). I didn't realize you could do COM with ctypes. Thanks for the tip! Are there any caveats to this approach? Dave From rpdooling at gmail.com Wed May 3 23:08:07 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 3 May 2006 20:08:07 -0700 Subject: Gettings subdirectories In-Reply-To: <Ncc6g.5297$DT5.1781@newsread3.news.pas.earthlink.net> References: <e3au5u$drm$1@news.in.tum.de> <Ncc6g.5297$DT5.1781@newsread3.news.pas.earthlink.net> Message-ID: <1146712086.983463.226990@g10g2000cwb.googlegroups.com> Thank you all for the great info and education. rick From bdesth.quelquechose at free.quelquepart.fr Mon May 15 19:50:26 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 May 2006 01:50:26 +0200 Subject: common practice for creating utility functions? In-Reply-To: <Az4ag.2098$No6.46267@news.tufts.edu> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <Uq4ag.2096$No6.46172@news.tufts.edu> <Az4ag.2098$No6.46267@news.tufts.edu> Message-ID: <4468e4b5$0$7716$626a54ce@news.free.fr> John Salerno a ?crit : > John Salerno wrote: > >> John Salerno wrote: >> >>> Just a quickie for today >> >> >> Another quick one I'll combine in this thread: How can I create two >> separate conditions in a for loop? >> >> Such as this, which doesn't seem to work beyond string.punctuation: >> >> for char in string.punctuation or string.whitespace: > > > I tried this: > > punc_space = string.punctuation + string.whitespace > for char in punc_space: Or if you want to save memory (which is not a problem in this example) : import itertools for char in itertools.chain(string.punctuation, string.whitespace): ... From yasmeen_alkadi at yahoo.com Sat May 20 03:13:43 2006 From: yasmeen_alkadi at yahoo.com (Yasmeen Alkadi) Date: Sat, 20 May 2006 00:13:43 -0700 (PDT) Subject: Help Needed plz :) Message-ID: <20060520071343.32463.qmail@web51413.mail.yahoo.com> Hello . . I am trying to control an NIDS (network intustion detection system) that uses Snort via mobile phones, but I need urgent help please in the following topics below: 1. How to send a text file from a PC running windows to a nokia mobile phone series 60, for example nokia 6680 via bluetoooth 2. How python that is installed on the mobile phone reads the accepted bluetooth message that was recived just a while ago in number 1. Thank you so much for your help, I really appricate it :) --------------------------------- Be a chatter box. Enjoy free PC-to-PC calls with Yahoo! Messenger with Voice. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060520/961e7184/attachment.html> From aleax at mac.com Wed May 10 21:16:24 2006 From: aleax at mac.com (Alex Martelli) Date: Wed, 10 May 2006 18:16:24 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1147194791.809735.251500@g10g2000cwb.googlegroups.com> <1hf33s3.1bdn2e4juoow0N%aleax@mac.com> <1147280693.450683.95790@j73g2000cwa.googlegroups.com> Message-ID: <1hf4uwk.1eup3h31rzwpyyN%aleax@mac.com> Joe Marshall <eval.apply at gmail.com> wrote: > Alex Martelli wrote: > > Joe Marshall <eval.apply at gmail.com> wrote: > > ... > > > The problem is that a `name' is a mapping from a symbolic identifier to > > > an object and that this mapping must either be global (with the > > > attendant name collision issues) or within a context (with the > > > attendant question of `in which context'). > > > > Why is that a problem? Even for so-called "global" names, Python > > supports a structured, hierarchical namespace, so there can never be any > > collision betwen the "globals" of distinct modules (including modules > > which happen to have the same name but live in distinct packages or > > subpackages) -- I did mention that names could usefully be displayed in > > some strcutured form such as apackage.somemodule.thefunction but perhaps > > I was too tangential about it;-). > > Can you refer to inner functions from the global context? Suppose I > have this Python code: > > def make_adder(x): > def adder_func(y): > sum = x + y > return sum > return adder_func > > Can I refer to the inner adder_func in any meaningful way? You can refer to one instance/closure (which make_adder returns), of course -- you can't refer to the def statement itself (but that's a statement, ready to create a function/closure each time it executes, not a function, thus, not an object) except through introspection. Maybe I don't understand what you mean by this question... > > If I used continuations (I assume you mean in the call/cc sense rather > > than some in which I'm not familiar?) I might feel the same way, or not, > > but I don't (alas), so I can't really argue the point either way for > > lack of real-world experience. > > I meant continuations as in the receiver function in > continuation-passing-style. If you have a function that has to act > differently in response to certain conditions, and you want to > parameterize the behavior, then one possibility is to pass one or more > thunks to the function in addition to the normal arguments. The Ah, OK, I would refer to this as "callbacks", since no call-with-continuation is involved, just ordinary function calls; your use case, while pretty alien to Python's typical style, isn't all that different from other uses of callbacks which _are_ very popular in Python (cfr the key= argument to the sort methods of list for a typical example). I would guess that callbacks of all kinds (with absolutely trivial functions) is the one use case which swayed Guido to keep lambda (strictly limited to just one expression -- anything more is presumably worth naming), as well as to add an if/else ternary-operator. I still disagree deeply, as you guessed I would -- if I had to work with a framework using callbacks in your style, I'd name my callbacks, and I wish Python's functools module provided for the elementary cases, such as: def constant(k): def ignore_args(*a): return k return ignore_args def identity(v): return v and so on -- I find, for example, that to translate your > (define (option3 key table default-value) > (lookup key table > (lambda (value) value) > (lambda () default-value))) I prefer to use: def option3(key, table, default_value): return lookup(key, table, identity, constant(default_value)) as being more readable than: def option3(key, table, default_value): return lookup(key, table, lambda v: v, lambda: default_value) After all, if I have in >1 place in my code the construct "lambda v: v" (and if I'm using a framework that requires a lot of function passing I'm likely to be!), the "Don't Repeat Yourself" (DRY) principle suggests expressing the construct *ONCE*, naming it, and using the name. By providing unnamed functions, the language aids and abets violations of DRY, while having the library provide named elementary functions (in the already-existing appropriate module) DRY is reinforced and strongly supported, which, IMHO, is a very good thing. Alex From jjl at pobox.com Fri May 5 15:27:02 2006 From: jjl at pobox.com (John J Lee) Date: Fri, 5 May 2006 19:27:02 +0000 (UTC) Subject: unittest.main-workalike that runs doctests too? In-Reply-To: <445BA5EB.2090506@benjiyork.com> References: <uvesklpyi.fsf@pobox.com> <445BA5EB.2090506@benjiyork.com> Message-ID: <Pine.LNX.4.64.0605051925460.8449@localhost> On Fri, 5 May 2006, Benji York wrote: > John J. Lee wrote: >> ...I wrote something to do this once, but didn't do as good a job as I >> might have done and wondered if anybody else has done it properly. > > The Zope 3 project has zope.testing which has a very nice test runner (and > isn't Zope-specific at all). You can get the code (via Subversion) at > svn://svn.zope.org/repos/main/zope.testing/trunk and browse the code > (including docs) at http://svn.zope.org/zope.testing/trunk/. Ah, thanks. I actually looked for zope.testing, but couldn't find it in the repository! (I was looking under Zope3.) Is there a page that describes the Zope SVN layout? John From ced at blv-sam-01.ca.boeing.com Wed May 17 00:45:24 2006 From: ced at blv-sam-01.ca.boeing.com (Charles DeRykus) Date: Wed, 17 May 2006 04:45:24 GMT Subject: python vs perl lines of code In-Reply-To: <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <Xns97C5D08D18788castleamber@130.133.1.4> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> Message-ID: <IzE7vM.8A4@news.boeing.com> Edward Elliott wrote: > John Bokma wrote: > >> Edward Elliott <nobody at 127.0.0.1> wrote: >> >>> This is just anecdotal, but I still find it interesting. Take it for >>> what it's worth. I'm interested in hearing others' perspectives, just >>> please don't turn this into a pissing contest. >> Without seeing the actual code this is quite meaningless. > > Evaluating my experiences yes, relating your own no. > But why would anecdotal accounts be of interest... unless there's an agenda :) Differing skill levels and problem scenarios would tangle the results so much no one could ever unravel the skein or pry out any meaningful conclusions. I'm not sure what's to be gained ...even if you're just evaluating your own experiences. And, as you suspect, it almost certainly would devolve into a pissing contest. This subject thread may be of great interest but I think an language advocacy mailing list would be a better forum. -- Charles DeRykus From invalidemail at aerojockey.com Tue May 9 14:41:13 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 9 May 2006 11:41:13 -0700 Subject: Multi-line lambda proposal. In-Reply-To: <mMidnUCvoJmRSP3ZnZ2dnUVZ_vOdnZ2d@comcast.com> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <mMidnUCvoJmRSP3ZnZ2dnUVZ_vOdnZ2d@comcast.com> Message-ID: <1147200073.494334.181660@y43g2000cwc.googlegroups.com> DH wrote: > Kaz Kylheku wrote: > > I've been reading the recent cross-posted flamewar, and read Guido's > > article where he posits that embedding multi-line lambdas in > > expressions is an unsolvable puzzle. > > To say that multi-line lambda is an unsolvable problem is completely > absurd. Note that the "solution" is understood to entail the BDFL stamp of approval. Furthermore it has already been solved. > http://wiki.python.org/moin/AlternateLambdaSyntax#head-c81743c0b461ab6812564785c7bc7ba581dec6fa Meh. I think the syntax you linked to would result in gobs of ugly and unreadable code. I like how the examples are always part of relatively simple statements ("Look, it's readable!"). Try citing examples of these statements at work in if conditions, generator expressions, as default arguments to functions, multiple times in the same statement. Try showing what they look like nested. The "readable" example would turn into ASCII vomit. Probably the day it makes it into Python is the day Python jumps the shark. Carl Banks From pac at fernside.com Thu May 18 22:33:56 2006 From: pac at fernside.com (pac) Date: 18 May 2006 19:33:56 -0700 Subject: number of different lines in a file In-Reply-To: <iY7bg.3778$x4.261@newsread3.news.pas.earthlink.net> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <mailman.5913.1147991572.27775.python-list@python.org> <iY7bg.3778$x4.261@newsread3.news.pas.earthlink.net> Message-ID: <1148006036.868374.307880@u72g2000cwu.googlegroups.com> A generator expression can "share" the parenthesis of a function call. The syntax is explained in PEP 289, which is also in "What's new" in the Python 2.4 docs. Nice line of code! From matteo.rattotti at gmail.com Mon May 22 06:59:15 2006 From: matteo.rattotti at gmail.com (Matteo Rattotti) Date: 22 May 2006 03:59:15 -0700 Subject: string.count issue (i'm stupid?) Message-ID: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> Hi all, i've noticed a strange beaviour of string.count: in my mind this code must work in this way: str = "a_a_a_a_" howmuch = str.count("_a_") print howmuch -> 3 but the count return only 2 Ok this can be fine, but why? The doc string tell that count will return the number of substring in the master string, if we spoke about substring i count 3 substring... Can someone explain me this? And in which way i can count all the occurrence of a substring in a master string? (yes all occurrence reusing already counter character if needed) Thanks a lot Matteo Rattotti www.rknet.it Powered by: - MacOsX - Gnu / Linux Debian Sarge - Amiga Os 3.9 - Milk From grante at visi.com Tue May 9 15:49:59 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 09 May 2006 19:49:59 -0000 Subject: python rounding problem. References: <mailman.5443.1146987087.27775.python-list@python.org> <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> <fPednfg-wOsvDcLZRVn-vQ@telcove.net> <125v9g8q00o1d52@corp.supernews.com> <gp6dnXfkodcrLcLZRVn-sg@telcove.net> <125vedc9n2q3m55@corp.supernews.com> <1147203401.653076.109230@i39g2000cwa.googlegroups.com> Message-ID: <1261sj7q7lsli24@corp.supernews.com> On 2006-05-09, Dan Bishop <danb_83 at yahoo.com> wrote: > Grant Edwards wrote: > ... >> Did they actually have 60 unique number symbols and use >> place-weighting in a manner similar to the arabic/indian system >> we use? > > The Bablyonians did use a place-value system, but they only had two > basic numerals: a Y-like symbol for 1 and a <-like symbol for ten. > These were combined to make base-60 digits. For example, 59 was > represented by > > < YYY > < < YYY >< < YYY > > Zero (used as a placeholder, but not as a number in itself) was > represented by a space. And they also (acording to the web pages I found) used base-60 floating point notation, but without an actual symbol to represent the sexagesimal point. Which seems really ambiguous -- even to somebody who does know how to use a slide rule. -- Grant Edwards grante Yow! I'm totally at DESPONDENT over the LIBYAN visi.com situation and the price of CHICKEN... From http Fri May 26 05:54:56 2006 From: http (Paul Rubin) Date: 26 May 2006 02:54:56 -0700 Subject: genexp surprise (wart?) References: <7xpsi14drb.fsf@ruckus.brouhaha.com> <1148622671.835989.217780@i39g2000cwa.googlegroups.com> Message-ID: <7xac95jekv.fsf@ruckus.brouhaha.com> "Paul Du Bois" <paul.dubois at gmail.com> writes: > The second is that you don't like the late-binding behavior of > generator expressions. PEP 289 has this to say: > > > After much discussion, it was decided that the first (outermost) > > for-expression should be evaluated immediately and that the remaining > > expressions be evaluated when the generator is executed. Thanks. That PEP is informative. It shows that I stumbled into something that other people found confusing too, and that alternatives were considered that turned out not to be better. From kay.schluehr at gmx.net Wed May 10 02:30:41 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 9 May 2006 23:30:41 -0700 Subject: New tail recursion decorator Message-ID: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 From ptmcg at austin.rr._bogus_.com Fri May 19 12:26:20 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 16:26:20 GMT Subject: how could I get all email address in a html page? References: <1148013399.715307.326120@j55g2000cwa.googlegroups.com> Message-ID: <Mkmbg.46826$CH2.20610@tornado.texas.rr.com> "dongdong" <dongdonglove8 at hotmail.com> wrote in message news:1148013399.715307.326120 at j55g2000cwa.googlegroups.com... > how could I get all email address in a html page? Have any modle can do > this? > like the htmldata.urlextract . > ...a spammer is born... From __peter__ at web.de Tue May 2 08:46:12 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 02 May 2006 14:46:12 +0200 Subject: string.find first before location References: <87hd49m0xc.fsf@localhost.localdomain> <e370ro$415$02$2@news.t-online.com> <87zmi0emhd.fsf@localhost.localdomain> <e37ff0$km9$00$1@news.t-online.com> <1146571862.234132.8670@u72g2000cwu.googlegroups.com> Message-ID: <e37k7j$f8f$02$1@news.t-online.com> Serge Orlov wrote: > Peter Otten wrote: >> Gary Wessle wrote: >> >> >> These days str methods are preferred over the string module's >> >> functions. >> >> >> >> >>> text = "abc abc and Here and there" >> >> >>> here_pos = text.find("Here") >> >> >>> text.rfind("abc", 0, here_pos) >> >> 4 >> >> >> >> Peter >> > >> > and what about when python 3.0 is released and those depreciated >> > functions like find and rfind are not supported. is there another >> > solution which is more permanent? >> >> I think the functions may go away, the methods will stay; so I'm >> confident the above will continue to work. > > find and rfind methods are in danger too. AFAIR they are to be replaced > by partion and rpartition methods. People who are worried about future > can continue to use index and rindex I really should read those PEPs before posting. And just as I was starting to complain I noted that my original reply to Gary is buggy -- excluding the last letter in the string from the rfind() search if "Here" is not found is probably never the desired behaviour. So r/index() is indeed superior here. Peter From durumdara at gmail.com Mon May 29 11:40:40 2006 From: durumdara at gmail.com (DurumDara) Date: Mon, 29 May 2006 17:40:40 +0200 Subject: How to calc easier the "long" filesize from nFileSizeLow and nFileSizeHigh Message-ID: <447B15F8.7010009@gmail.com> Hi ! I get the file datas with FindFilesW. I want to calc the filesize from nFileSizeLow and nFileSizeHigh with easiest as possible, without again calling os.getsize(). How to I do it ? I need good result ! Thanx for help: dd From bedouglas at earthlink.net Mon May 8 18:48:02 2006 From: bedouglas at earthlink.net (bruce) Date: Mon, 8 May 2006 15:48:02 -0700 Subject: group for pure startups... Message-ID: <2ceb01c672f1$77e61510$0301a8c0@Mesa.com> hi... can someone tell me if there's a group where people who are interested in starting/contributing to embryoninc startup concepts can get together/meet, exchange ideas, etc... i'm not referring to meetings where you do VC/Funding presentations, I'm basically talking about meetings where you could form your team, join a team, etc... i'm in the west coast, bay area. thanks -bruce bedouglas at earthlink.net From cdwest1 at tva.gov Thu May 18 17:43:06 2006 From: cdwest1 at tva.gov (Cary West) Date: Thu, 18 May 2006 16:43:06 -0500 Subject: Python trig precision problem Message-ID: <newscache$13fhzi$5xd$1@lyris.knx.tva.gov> Hello all, having a small problem with a trig routine using python math module. This code is designed to convert geodetic coordinates to lambert conformal conic coordinates. It implements the formulas found at http://mathworld.wolfram.com/LambertConformalConicProjection.html . The problem is that, at least on my machine, the precision is off to the tune of around 1 km, which is unacceptable. (using the calculator found at http://www.deh.gov.au/erin/tools/geo2lam-gda.html ) Anyone have any ideas? here is the offending code. from math import * def lambert(lat,lon,ref_lat,ref_lon,st_parallel_1,st_parallel_2): earth_radius= 6371.9986 lon*=pi/180.0 lat *=pi/180.0 ref_lon*=pi/180.0 ref_lat *=pi/180.0 st_parallel_1 *=pi/180.0 st_parallel_2 *=pi/180.0 def sec(theta): return 1.0/cos(theta) def cot(theta): return 1.0/tan(theta) n = log( cos( st_parallel_1 ) * sec( st_parallel_2 ) ) / ( log( tan ( pi / 4.0 + st_parallel_2 / 2.0 ) * cot( pi / 4.0 + st_parallel_1 / 2.0 ) ) ) F = ( cos( st_parallel_1 ) * tan ( pi / 4.0 + st_parallel_1 / 2.0 ) ** n ) / n rho = F * ( cot ( pi / 4.0 + lat / 2.0 ) ** n ) ref_rho = F * ( cot ( pi / 4.0 + ref_lat / 2.0 ) ** n ) x = rho * sin( n * ( lon-ref_lon ) ) y = ref_rho - ( rho * cos( n * ( lon-ref_lon ) ) ) return earth_radius*x,earth_radius*y ####################################### lat,lon=35,-90 print lambert(lat,lon,40,-97,33,45) From stefan.behnel-n05pAM at web.de Fri May 19 10:19:46 2006 From: stefan.behnel-n05pAM at web.de (Stefan Behnel) Date: Fri, 19 May 2006 16:19:46 +0200 Subject: the tostring and XML methods in ElementTree In-Reply-To: <1147853382.250160.270530@i39g2000cwa.googlegroups.com> References: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> <mailman.5467.1147077842.27775.python-list@python.org> <1147853382.250160.270530@i39g2000cwa.googlegroups.com> Message-ID: <446dd405$0$4512$9b4e6d93@newsread2.arcor-online.net> George Sakkis wrote: > Fredrik Lundh wrote: > >> mirandacascade at yahoo.com wrote: >> >>> I wanted to see what would happen if one used the results of a tostring >>> method as input into the XML method. What I observed is this: >>> a) beforeCtag.text is of type <type 'str'> >>> b) beforeCtag.text when printed displays: I'm confused >>> c) afterCtag.text is of type <type 'unicode'> >>> d) afterCtag.text when printed displays: I?m confused >> the XML file format isn't a Python string serialization format, it's an XML infoset >> serialization format. >> >> as stated in the documentation, ET always uses Unicode strings for text that >> contain non-ASCII characters. for text that *only* contains ASCII, it may use >> either Unicode strings or 8-bit strings, depending on the implementation. >> >> the behaviour if you're passing in non-ASCII text as 8-bit strings is undefined >> (which means that you shouldn't do that; it's not portable). > > I was about to post a similar question when I found this thread. > Fredrik, can you explain why this is not portable ? Because there is no such things as a default encoding for 8-bit strings. > I'm currently using > (a variation of) the workaround below instead of ET.tostring and it > works fine for me: > > def tostring(element, encoding=None): > text = element.text > if text: > if not isinstance(text, basestring): > text2 = str(text) > elif isinstance(text, str) and encoding: > text2 = text.decode(encoding) > element.text = text2 > s = ET.tostring(element, encoding) > element.text = text > return s > > > Why isn't this the standard behaviour ? Because it wouldn't work. What if you wanted to serialize a different encoding than that of the strings you put into the .text fields? How is ET supposed to know what encoding your strings have? And how should it know that you didn't happily mix various different byte encodings in your strings? Use unicode, that works *and* is portable. Stefan From af.dingo at gmail.com Wed May 3 14:56:34 2006 From: af.dingo at gmail.com (af.dingo at gmail.com) Date: 3 May 2006 11:56:34 -0700 Subject: symbolic links, aliases, cls clear In-Reply-To: <87r7430x2t.fld@apaflo.com> References: <1143672131.167324.36920@i39g2000cwa.googlegroups.com> <1144844223.094969.82870@t31g2000cwb.googlegroups.com> <87r7430x2t.fld@apaflo.com> Message-ID: <1146682594.341905.187600@u72g2000cwu.googlegroups.com> it would be nice if python provided a termcap or terminfo library, wouldn't it? From petite.abeille at gmail.com Fri May 19 09:56:56 2006 From: petite.abeille at gmail.com (PA) Date: Fri, 19 May 2006 15:56:56 +0200 Subject: noob import question In-Reply-To: <4d5vqaF18i4l1U1@uni-berlin.de> References: <mailman.5945.1148045097.27775.python-list@python.org> <4d5vqaF18i4l1U1@uni-berlin.de> Message-ID: <16532b502ad5283d1e53f8782898aaf8@gmail.com> On May 19, 2006, at 15:33, Diez B. Roggisch wrote: > And it seems as if you have some JAVA-background, putting one class in > one > file called the same as the class. Don't do that, it's a stupid > restriction > in JAVA and should be avoided in PYTHON. Restrictive or not, what's so fundamentally devious in putting a class declaration in a separate file whose name is that of the declared class (class Queue -> Queue.py)? Sounds like a handy way of organizing your code, no? Cheers -- PA, Onnay Equitursay http://alt.textdrive.com/ From bdesth.quelquechose at free.quelquepart.fr Wed May 17 08:29:45 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 May 2006 14:29:45 +0200 Subject: calling upper() on a string, not working? In-Reply-To: <h2rag.2111$No6.46279@news.tufts.edu> References: <Ayqag.2108$No6.45797@news.tufts.edu> <446a3b52$0$11000$626a54ce@news.free.fr> <h2rag.2111$No6.46279@news.tufts.edu> Message-ID: <446ae81f$0$7021$636a55ce@news.free.fr> John Salerno a ?crit : > Bruno Desthuilliers wrote: > >>> def encrypt_quote(original): >> >> # Since it's here that we define that the new letters >> # will be uppercase only, it's our responsability >> # to handle any related conditions and problems >> # The other functions shouldn't have to even know this. >> original = original.upper() > > >>> def filter_letters(original): >> >> # here, we *dont* have to do anything else than filtering >> # upper/lower case is *not* our problem. >> >>> return ''.join(set(original) - PUNCT_SPACE_SET) > > > Thanks, I was wondering if it only needed to be done in a single place > like that. It's always better to do something in a single place - you may here of this as the DRY (Dont Repeat Yourself) or SPOT (Single Point Of Transformation) rule. The way you wrote it, part of encrypt_quote's responsability and knowldege was leaking into filter_letters. This is a Bad Thing(tm), and should be avoided by any mean. From bignose+hates-spam at benfinney.id.au Thu May 18 21:30:04 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 May 2006 11:30:04 +1000 Subject: Opensource vs Microsoft, Wat do you think about opensource? References: <1147996793.841733.109020@j33g2000cwa.googlegroups.com> Message-ID: <87ac9els2r.fsf@benfinney.id.au> "cracker" <thakur.dheeraj at gmail.com> writes: > So wat do u think about opensource software? and what is your view > about Microsoft share your views with us! > and let us know what do you think about opensource software. > > http://www.desi-tek.com/forum/index.php?showtopic=394&st= Please don't spam here to ask for discussion on another forum, on a tangentially related topic. -- \ "I believe in making the world safe for our children, but not | `\ our children's children, because I don't think children should | _o__) be having sex." -- Jack Handey | Ben Finney From tjreedy at udel.edu Wed May 31 19:34:52 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 31 May 2006 19:34:52 -0400 Subject: OT: Search for python in Norway References: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> <1149114551.858491.231890@i40g2000cwc.googlegroups.com> Message-ID: <e5l96s$bhb$1@sea.gmane.org> <ippisl at gmail.com> wrote in message news:1149114551.858491.231890 at i40g2000cwc.googlegroups.com... > your search for python refers for python=snake. It combines both, but spikes are definately snakey. > you should look for "python programming". I tried that, and Google missed the Nokia article it found with python alone. Also, South Africa and India are hottest countries with their normalization. http://www.google.com/trends?q=python+programming&ctab=1&geo=all&date=all tjr From nobody at 127.0.0.1 Sat May 6 21:18:57 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 07 May 2006 01:18:57 GMT Subject: Counterproductive goals (was Re: code vetting) References: <yvT5g.132$yh.117@trnddc04> <mailman.5299.1146719004.27775.python-list@python.org> <_%w6g.44217$C63.42016@trnddc06> <cBz6g.67490$F_3.12273@newssvr29.news.prodigy.net> <TGV6g.112$W83.13@trnddc07> <mailman.5415.1146898161.27775.python-list@python.org> <ri67g.22464$4L1.12703@newssvr11.news.prodigy.com> <mailman.5433.1146957542.27775.python-list@python.org> Message-ID: <5Wb7g.73593$H71.60663@newssvr13.news.prodigy.com> Apologies to the group for getting so OT here. Thanks for your indulgence. Ben Finney wrote: >> I think both your goal and his (spreading free software at the >> expense of non-free) are counterproductive. > > Huh? A goal is counterproductive? By what do you measure > "counterproductive", if not the goal? I'm measuring against the implicit goal of producing useful software from a functional perspective. I assumed all projects followed that goal, but I suppose Hurd is a counterexample to that. Regardless, I should have said "can be counterproductive". Both goals can coexist. But I would argue that focusing on the functional goal does more in the end to gain and help users than many of the more direct attempts to spread free software. In that sense, the tactics undertaken to explicitly further a goal can actually hurt achievement of the goal itself. >> Often it's a combination. A successful project should focus on >> discovering and meeting its users' needs. > > Again, success is measured by the goal. My goal is to increase the > freedom of software users. That's fine. But if we're talking about the software world at large, or even the open source world at large, many do not share that goal. The closest we can get to a universal goal, and hence the most representative way to measure success, is with a functional approach. You are free to measure things differently, but it's not a conversation a lot people would care about. >> Spreading open source for its own sake helps no one. > > Increasing the freedom of software users helps all software users, > except those who want that freedom restricted. I repeat: spreading open source for its own sake helps no one. Open source != freedom. You can access Sun's Java source and even Microsoft's Windows source under certain conditions. Access to the source gives you nothing. To borrow from Agent Smith: What good is a phone call if you're unable to speak? Now maybe you're thinking of open source as an OSI-approved license. That's a different statement which jives more with your contention that increasing freedom helps all software users. I'd say it depends how you define freedom and helps. Regardless, I'll relax my statement that it helps no one and agree that some people benefit in some situations. Maybe it's a lot, maybe it's a little; I don't want to quibble over quantifying it. I'm not disagreeing with your basic philosophy. Free software brings a number of benefits. Both the BSD and the GNU camps have laudable goals and do some fantastic work. Where I part company is in thinking those approaches are inherently superior or should/will become widespread. To each his own. In the current discussion about universal benefits of transparency, the fact that different groups have different goals is highly relevant. From aylwyn at cantab.net Tue May 16 18:02:19 2006 From: aylwyn at cantab.net (achates) Date: 16 May 2006 15:02:19 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> Message-ID: <1147816939.467976.202120@j73g2000cwa.googlegroups.com> Duncan Booth wrote: >However the important thing is that a tab does >not map to a single indentation level in Python: it can map to any number >of indents, and unless I know the convention you are using to display the >tabs I cannot know how many indents are equivalent to a tabstop. Sorry but this is just wrong. Python works out the indentation level for a source file dynamically: see http://docs.python.org/ref/indentation.html. The particular algorithm it uses is designed to accommodate people who mix tabs and spaces (which is unfortunate, and should probably be changed). Nevertheless, using tabs only, one tab does indeed map to exactly one indentation level. One tabstop == one indent, on your editor and on mine. You do not need to know my display convention to run my code. All I can suggest is that you try it out: create a short source file indented with tabs only, and play around with your editor's tabstop setting (and make sure it is writing tab characters, not spaces, to the source file). I promise you the Python interpreter will neither know nor care what your editor display settings were when you last wrote the file. I realise that a lot of code out there uses spaces only. That's unfortunate, but it doesn't mean we should stop explaining to people why tab-indenting is a better standard. This is about freedom: indenting with spaces lets you control over how other people view your code; indenting with tabs give them that control. From ogahejini at yahoo.com Tue May 23 06:03:43 2006 From: ogahejini at yahoo.com (gen_tricomi) Date: 23 May 2006 03:03:43 -0700 Subject: problem with reload(sys) (doing reload on the sys module) In-Reply-To: <sgjmzdxbue1.fsf@alphaville.zko.hp.com> References: <1146676364.470772.232350@y43g2000cwc.googlegroups.com> <sgjmzdxbue1.fsf@alphaville.zko.hp.com> Message-ID: <1148378623.587526.174570@j33g2000cwa.googlegroups.com> hi nick, have you found any solutions to this problem. maybe sys module does not need to be reloaded. may Tim peters and the rest can help us on this From mariano.difelice at gmail.com Fri May 26 12:40:56 2006 From: mariano.difelice at gmail.com (mardif) Date: 26 May 2006 09:40:56 -0700 Subject: PIL problem with biprocessor hardware Message-ID: <1148661656.407762.147020@j73g2000cwa.googlegroups.com> Hi guys, I've a problem, but very big! So, i have a python/PIL application that manipulate images ( rotate, crop, save, etc etc ). If this application work on a PC mono-processor, I don't have any problems. If this application work instead on a PC bi-processor, the process elaborates an image "corrupted": I mean "corrupted" because: If I open this image with any image-viewer, it will show the image with background color on top blue, and on bottom green. Sometimes it can happen that somethings inside was wrong designed. If i open this image instead with GIMP, this message will shown: Corrupt JPEG data: 36 ( this value is not ever equal ) extraneous bytes before marker 0xd9 EXIF data will be ignored. This error don't has a procedure that will produce it. It's random. I've executed this application in a PC mono-processor, and it seems all ok ( 100% ), instead on a PC bi-processor sometimes don't work ( 90% ? ). Thx very much From iddw at hotmail.com Wed May 10 10:57:42 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 10 May 2006 09:57:42 -0500 Subject: multiline strings and proper indentation/alignment References: <Ms48g.2070$No6.45827@news.tufts.edu> <mailman.5527.1147204632.27775.python-list@python.org> <44613e5d$0$9438$c3e8da3@news.astraweb.com> <4461c445$0$14031$626a54ce@news.free.fr> <Eim8g.2075$No6.45677@news.tufts.edu> Message-ID: <5iv3629eodhhq7g8hp42n5eclusli2r5qo@4ax.com> On Wed, 10 May 2006 13:56:52 GMT in comp.lang.python, John Salerno <johnjsal at NOSPAMgmail.com> wrote: >bruno at modulix wrote: > >> Why not trying by yourself ?-) > >Doh! I always forget I can do this! :) > > >> Mmm. Not good. Let's try again: >>>>> print textwrap.dedent(s).strip() >> this is a multiline >> triple-quted string with >> indentation for nicer code formatting >> >> Well, seems like we're done. About 2'30'' to solve the problem. > >Actually, I'm still wondering if it's possible to remove the newlines at >the end of the first and second lines (after 'multiline' and 'with'), so Well, it's too long for my news reader to display the result on a single line, but: >>> print textwrap.dedent(s).strip().replace('\n',' ') this is a multiline triple-quted string with indentation for nicer code formatting >>> >that the string is one line. But it's already been shown that textwrap >alone doesn't do this, so I'd rather not mess with all the extra stuff >to do it, when I can just put the string in parentheses. If that's the way you want the sting in the first place, that'd be my recommendation. Regards, -=Dave -- Change is inevitable, progress is not. From stanc at al.com.au Sun May 14 07:56:03 2006 From: stanc at al.com.au (Astan Chee) Date: Sun, 14 May 2006 21:56:03 +1000 Subject: send an email with picture/rich text format in the body In-Reply-To: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> Message-ID: <44671AD3.5040207@al.com.au> what about sending the mail as html instead of normal plain/text ? anya wrote: >Hey, >I have a certain problem and till now I didnt find an answer on the >web. > >I want to send an email message with picture in it. I dont want to put >it as >attachment but make it in the body of the mail, so every one who open >the email will see the picture.. (it is possible that the solution will >be in any other format that will be opened i.e pdf, doc and I will put >this in the body ) > >Neither in MimeWriter nor using the definition of MymeTypes I was able >to do it .. > >Does anyone have a solution? > >Thanks > > > From vinogri at mcmaster.ca Fri May 5 18:00:59 2006 From: vinogri at mcmaster.ca (Ivan Vinogradov) Date: Fri, 5 May 2006 18:00:59 -0400 Subject: NaN handling In-Reply-To: <125neus2mkbgp51@corp.supernews.com> References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> Message-ID: <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> > <snip> > There are those of us that need NaNs in production code, so it > would have to be something that could be configured. I find > that in my programs the places where I need to do something > "exceptional" with a NaN are very limited. The vast majority > of the time, I need them to propagate quietly. Our programming expectations may differ, but an option to catch NaNs as an exception is a great idea. Regards, Ivan. From http Fri May 26 01:44:05 2006 From: http (Paul Rubin) Date: 25 May 2006 22:44:05 -0700 Subject: genexp surprise (wart?) References: <7xpsi14drb.fsf@ruckus.brouhaha.com> <1148620982.393630.250970@i40g2000cwc.googlegroups.com> Message-ID: <7xfyixe3x6.fsf@ruckus.brouhaha.com> "Ben Cartwright" <bencvt at gmail.com> writes: > You do realize that you're creating a new level of generator nesting > with each iteration of the while loop, right? You will quickly hit the > maximum recursion limit. Try generating the first 1000 primes. Yes, I know about the generator nesting, that was the point. The Sieve of Eraswhatsisname takes linear space by definition. It's usually done with an array but this version uses nested generators instead. I didn't bother to test whether they counted against the recursion limit, so it's informative to know that they do. > I don't see how it's a wart. p is accessed (i.e., not set) by the > genexp. Consistent with the function scoping rules in... > http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python > ...Python treats p in the genexp as a non-local variable. Yeah, it's just counterintuitive is all. I guess the natural way to express this would have been with tail recursion instead of a while loop. From tfb at conquest.OCF.Berkeley.EDU Mon May 8 15:53:09 2006 From: tfb at conquest.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 08 May 2006 12:53:09 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> Message-ID: <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> Ken Tilton <kentilton at gmail.com> writes: > No, you do not want on-change handlers propagating data to other > slots, though that is a sound albeit primitive way of improving > self-consistency of data in big apps. The productivity win with > VisiCalc was that one simply writes rules that use other cells, and > the system keeps track of what to update as any cell changes for > you. You have that exactly backwards: every slot has to know what > other slots to update. Ick. No no, that's fine and the way it should be: when you change a slot, it should know who to update. And that's also the way it works in Cells. The trick is that Cells takes care of that part for you: all the *programmer* has to care about is what values a slot depends on -- Cells takes care of inverting that for you, which is important because that's a job that a computer is much better at than a human. From george.sakkis at gmail.com Sun May 28 22:56:44 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 28 May 2006 19:56:44 -0700 Subject: Array? Please help. References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> <4drlreF1ba60oU1@uni-berlin.de> <1148762266.844574.210900@y43g2000cwc.googlegroups.com> <4duh3tF1cbk1bU1@uni-berlin.de> Message-ID: <1148871404.385691.20750@38g2000cwa.googlegroups.com> Diez B. Roggisch wrote: > George Sakkis schrieb: > > Diez B. Roggisch wrote: > >> Dr. Pastor schrieb: > >>> I need a row of 127 bytes that I will use as a > >>> circular buffer. Into the bytes (at unspecified times) > >>> a mark (0<mark<128) will be written, one after the other. > >>> After some time the "buffer" will contain the last 127 marks. > >>> (A pointer will point to the next byte to write to.) > >>> What would be the Pythonic way to do the above? > >>> Thanks for any guidance. > >> Use a list, use append and slicing on it: > >> > >> > >> max_size = 10 > >> buffer = [] > >> > >> for i in xrange(100): > >> buffer.append(i) > >> buffer[:] = buffer[-max_size:] > >> print buffer > >> > >> > >> Diez > > > > You're not serious about this, are you ? > > Tell me why I shouldn't. I presumed he's after a ringbuffer. Ok, the > above lacks a way to determine the amount of bytes added since the last > read. Add a counter if you want. And proper synchronization in case of a > multithreaded environment. But as the OP was sketchy about what he > actually needs, I thought that would at least give him a start. > > Maybe I grossly misunderstood his request. But I didn't see your better > implementation so far. So - enlighten me. Strange; there are two threads on this and my reply was sent to the first one: http://tinyurl.com/lm2ho. In short, adding a new mark should be a simple O(1) operation, not an O(buf_size). This is textbook material, that's why I wasn't sure if you meant it. George From scott.daniels at acm.org Wed May 31 00:47:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 30 May 2006 21:47:50 -0700 Subject: shuffling elements of a list In-Reply-To: <1149048606.100581.119980@y43g2000cwc.googlegroups.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <mailman.6344.1149046001.27775.python-list@python.org> <1149048606.100581.119980@y43g2000cwc.googlegroups.com> Message-ID: <447d1b9a$1@nntp0.pdx.net> greenflame wrote: > Zhang Fan wrote: >> ... The random module has a `shuffle' method. It "Shuffle the sequence x >> in place". It may be help for you > > I am sorry but this does not help much. In my version of python (2.3) > this method does not seem to exist. Also from the documentation, it > seems that this method would give a random number. Using Python 2.3.4 on Windows 2000, I get: import random lst = range(52) random.shuffle(lst) print lst [8, 26, 9, 10, 22, 39, 36, 48, 29, 5, 50, 16, 15, 2, 40, 33, 3, 7, 37, 43, 11, 0, 30, 49, 32, 44, 24, 47, 42, 27, 23, 28, 12, 18, 13, 35, 1, 34, 25, 45, 21, 20, 46, 38, 17, 31, 6, 4, 14, 41, 51, 19] Don't be so sure the advice you get is wrong. --Scott David Daniels scott.daniels at acm.org From johnjsal at NOSPAMgmail.com Mon May 8 16:41:45 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 20:41:45 GMT Subject: i don't understand this RE example from the documentation In-Reply-To: <oZN7g.2061$No6.45493@news.tufts.edu> References: <oZN7g.2061$No6.45493@news.tufts.edu> Message-ID: <d2O7g.2063$No6.45493@news.tufts.edu> John Salerno wrote: > Ok, I've been staring at this and figuring it out for a while. I'm close > to getting it, but I'm confused by the examples: > > (?(id/name)yes-pattern|no-pattern) > Will try to match with yes-pattern if the group with given id or name > exists, and with no-pattern if it doesn't. |no-pattern is optional and > can be omitted. > > For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>) is a poor email matching > pattern, which will match with '<user at host.com>' as well as > 'user at host.com', but not with '<user at host.com'. New in version 2.4. > > group(1) is the email address pattern, right? So why does the above RE > match 'user at host.com'. If the email address exists, does the last part > of the RE: (?(1)>) mean that it has to end with a '>'? I think I got it. The group(1) is referring to the opening '<', not the email address. I had seen an earlier example that used group(0), so I thought maybe the groups were 0-based. From jjl at pobox.com Sun May 28 13:35:16 2006 From: jjl at pobox.com (John J. Lee) Date: Sun, 28 May 2006 17:35:16 GMT Subject: Finding a lost PYTHONPATH with find Message-ID: <87zmh2oxwr.fsf@pobox.com> OK, this is really a reminder to myself next time I forget where I set my PYTHONPATH and forget exactly how to invoke the GNU "find" command ;-) Hope somebody else finds it useful too find / -maxdepth 3 -size -100k -type f -exec grep -sli pythonpath '{}' \; The minus in '-100k' (meaning "less than 100k") seems to be undocumented, at least on my system. I suppose the -maxdepth is redundant since I think find searches breadth-first by default. The file I was looking for turned out to be in /etc/profile.d/, whose existence I completely forgot about... John From http Tue May 9 16:03:59 2006 From: http (Paul Rubin) Date: 09 May 2006 13:03:59 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> Message-ID: <7xmzdrdky8.fsf@ruckus.brouhaha.com> aleax at mac.com (Alex Martelli) writes: > I think it's reasonable to make a name a part of functions, classes and > modules because they may often be involved in tracebacks (in case of > uncaught errors): to me, it makes sense to let an error-diagnosing > tracebacks display packages, modules, classes and functions/methods > involved in the chain of calls leading to the point of error _by name_. But it would be even nicer if the traceback could point back to the exact location in the source code where the function definition occurred, and that wouldn't need any name for the function. From johnjsal at NOSPAMgmail.com Fri May 19 15:11:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 19:11:57 GMT Subject: altering an object as you iterate over it? Message-ID: <1Mobg.2139$No6.46432@news.tufts.edu> What is the best way of altering something (in my case, a file) while you are iterating over it? I've tried this before by accident and got an error, naturally. I'm trying to read the lines of a file and remove all the blank ones. One solution I tried is to open the file and use readlines(), then copy that list into another variable, but this doesn't seem very efficient to have two variables representing the file. Perhaps there's also some better to do it than this, including using readlines(), but I'm most interested in just how you edit something as you are iterating with it. Thanks. From r.s at ZZmindspring.com Thu May 18 17:51:30 2006 From: r.s at ZZmindspring.com (r.e.s.) Date: Thu, 18 May 2006 21:51:30 GMT Subject: number of different lines in a file Message-ID: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> I have a million-line text file with 100 characters per line, and simply need to determine how many of the lines are distinct. On my PC, this little program just goes to never-never land: def number_distinct(fn): f = file(fn) x = f.readline().strip() L = [] while x<>'': if x not in L: L = L + [x] x = f.readline().strip() return len(L) Would anyone care to point out improvements? Is there a better algorithm for doing this? From jes at nl.demon.net Fri May 26 08:00:37 2006 From: jes at nl.demon.net (Jim Segrave) Date: Fri, 26 May 2006 12:00:37 -0000 Subject: hi,everyone. a problem with shelve Module References: <1148628096.075581.113290@i40g2000cwc.googlegroups.com> <17526.52542.775526.203864@montanaro.dyndns.org> <mailman.6225.1148636669.27775.python-list@python.org> <1148643170.068802.264320@u72g2000cwu.googlegroups.com> Message-ID: <127drf5ip12b94a@corp.supernews.com> In article <1148643170.068802.264320 at u72g2000cwu.googlegroups.com>, softwindow <softwindow at gmail.com> wrote: [some context restored] >> Sometimes you add records but the size of the database does not >> change... :-) >really > >in which case? whenever the database is big enough to add them without it's having to grow :) -- Jim Segrave (jes at jes-2.demon.nl) From blair.bethwaite at gmail.com Sun May 7 22:56:53 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 7 May 2006 19:56:53 -0700 Subject: utility functions within a class? References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> Message-ID: <1147057013.476199.26910@j33g2000cwa.googlegroups.com> > You do *NOT* want to put double-underscores before and after a method > name. That does not indicate a private method, it indicates a "magic > method" WHOOPS!! Sorry, I haven't touched python for a few months and just started working on a script this morning so was going to post my own question when I got sidetracked answering this thread. I guess that might be a good reason not to use underscores as significant syntax. Cheers, -B From me+python at modelnine.org Fri May 19 18:35:02 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sat, 20 May 2006 00:35:02 +0200 Subject: Complex evaluation bug In-Reply-To: <v%lbg.46822$CH2.40151@tornado.texas.rr.com> References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> <446d8209$0$7139$626a54ce@news.free.fr> <v%lbg.46822$CH2.40151@tornado.texas.rr.com> Message-ID: <200605200035.03025.me+python@modelnine.org> Am Freitag 19 Mai 2006 18:03 schrieb Paul McGuire: > An eval-less approach - the problem is the enclosing parens. > <snip> I've just submitted two patches to the Python bugtracker at: http://sourceforge.net/tracker/index.php?func=detail&aid=1491866&group_id=5470&atid=305470 which either change the repr() format (removing the parentheses), which I find doubtful, because it's not backwards-compatible, or alter the constructor to accept the repr() format for complex numbers (a bracketed number). Feel free to comment. --- Heiko. From onurb at xiludom.gro Wed May 10 08:01:29 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 10 May 2006 14:01:29 +0200 Subject: interactive shell -- reload definitions? In-Reply-To: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> References: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> Message-ID: <4461d67a$0$3551$626a54ce@news.free.fr> Metalone wrote: > I have a question about the interactive Python shell. Is it possible > to reload a file and get the new definitions. > > For example, if I do > import xyz > > Then I find a bug in some function in xyz. > So, I edit xyz.py > > I would like to reload the definitions in xyz.py without leaving my > current shell session. > Is this possible? you want reload(). > > Also, is there any way to save definitions created in the interactive > shell to a file? > Sometimes I write a simple function in the shell, and this wish I had > that function in an external file. AFAIK, Idle and IPython might do this. I personnaly uses emacs + python-mode, and it's quite powerful (let you eval a whole buffer or part of it in an running embedded python shell, and of course copy/paste from the shell to a buffer). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From rpdooling at gmail.com Sat May 13 07:49:25 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 13 May 2006 04:49:25 -0700 Subject: where do you run database scripts/where are DBs 'located'? References: <jz09g.2091$No6.46071@news.tufts.edu> <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> <1147490582.719840.51200@i39g2000cwa.googlegroups.com> <44655f44$0$9414$c3e8da3@news.astraweb.com> Message-ID: <1147520965.186376.185570@j33g2000cwa.googlegroups.com> John, Yep, different module. I'll watch the thread. Perhaps once you get connected, we should make a mini-HOWTO for XP users while it's fresh in your mind, because this question seems to come up a lot, and beginners would probably appreciate a short howto that would perhaps detail how to set up either mysqldb, mxodbc, or both on XP and get Python talking to MySQL. I think no matter which you choose, you will benefit from downloading the mysql connector and adding your mysql db to datasources on XP. Then you can access the db just by using the name you gave it in the datasources panel, e.g. driv="bbdatabank" rick From bdesth.quelquechose at free.quelquepart.fr Tue May 23 21:34:37 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 May 2006 03:34:37 +0200 Subject: dict literals vs dict(**kwds) In-Reply-To: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> Message-ID: <447388e7$0$12284$626a54ce@news.free.fr> George Sakkis a ?crit : > Although I consider dict(**kwds) as one of the few unfortunate design > choices in python since it prevents the future addition of useful > keyword arguments (e.g a default value or an orderby function), I've > been finding myself lately using it sometimes instead of dict literals, > for no particular reason. Is there any coding style consensus on when > should dict literals be preferred over dict(**kwds) and vice versa ? using dict literals means that you'll always have a builtin dict - you cannot dynamically select another dict-like class. OTHO, you can only use valid python identifiers as keys with dict(**kw). From tdelaney at avaya.com Sun May 14 18:37:21 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 15 May 2006 08:37:21 +1000 Subject: count items in generator Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6EB@au3010avexu1.global.avaya.com> George Sakkis wrote: > Paul Rubin wrote: > >> claird at lairds.us (Cameron Laird) writes: >>> For that matter, would it be an advantage for len() to operate >>> on iterables? >> >> print len(itertools.count()) >> >> Ouch!! > > How is this worse than list(itertools.count()) ? list(itertools.count()) will eventually fail with a MemoryError. Actually len(itertools.count()) would as well - when a couple of long instances used up everything available - but it would take a *lot* longer. Tim Delaney From tjreedy at udel.edu Mon May 15 13:28:58 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Mon, 15 May 2006 13:28:58 -0400 Subject: do/while structure needed References: <4466bddd$0$18984$c3e8da3@news.astraweb.com><1147585422.693953.292480@u72g2000cwu.googlegroups.com> <4467786c$0$1956$c3e8da3@news.astraweb.com> Message-ID: <e4adoq$bs5$1@sea.gmane.org> "John Salerno" <johnjsal at NOSPAMgmail.com> wrote in message news:4467786c$0$1956$c3e8da3 at news.astraweb.com... > Thanks, that looks pretty good. Although I have to say, a do/while > structure is the much more obvious way. I wonder why it hasn't been > added to the language. Been suggested many times, been considered, and rejected. Easily similated with while True: ... if exit_condition: break which also solves 'loop and a half' problem, which is more common. Requires new keyword for little gain. Etc. tjr From sturlamolden at yahoo.no Fri May 26 09:35:54 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 26 May 2006 06:35:54 -0700 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <mailman.6052.1148256588.27775.python-list@python.org> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <mailman.6052.1148256588.27775.python-list@python.org> Message-ID: <1148650554.256471.141510@j55g2000cwa.googlegroups.com> Gonzalo Monz?n wrote: > I use Python 2.4.3 (msvcrt71) and I succesfully installed the last > version of binutils, pyrex and MinGW, some weeks ago, using Julien Fiore > step-by-step guide, so "my" MinGW is linking with msvcrt71.dll, with the > default configuration. A successful build (compile and linkage) does not imply that you are linking with the same crt as Python. It just means that there are no syntax errors (successful compile) or unresolved external symbols (successful linkage) in your code. > I don't understand why do you say MinGW links with msvcrt.dll... perhaps > you've got an older version than the ones Julien posted? Because it does not! What happens is that MinGW links with the import library for msvcrt.dll. The compiler does not complain bacause there are no syntax errors. The linker does not complain bacuase there are no unresolved external symbols (after all, msvcrt is a standard crt). When you run your program, Windows search the search path for msvcrt.dll, finds the dll in c:\windows\system32, and loads it into your process image. This produces no errors either. So intitially everything seems to be ok. But... The process image for your Pyrex extension is shared with the Python interpreter. Previously, msvcrt71.dll was loaded into into the porcess image when Python started. Now both crts reside in the process, and Python and your Pyrex extension starts to call their respective crts. The crts interfere with each other and you get very unpredictable results. This is not just a Python problem. Microsoft created this problem when they started to publish multiple versions of their crt. Whenever a process has imported different crts, there will inevitably be run-time conflicts. Windows is a "component" based operating system. If you are e.g. using in proc COM objects (also known as "ActiveX Components"), you can only pray to God that the author did not use a different crt than you. If you are loading a precompiled DLLs, you can only pray to God that the author did not use a different crt than you. Previously this was not an issue, as Windows had exactly one shared crt. Now this is all messed up. Why did Microsoft decide to create "C runtime DLL Hell"? I have no idea. From nogradi at gmail.com Thu May 18 04:27:06 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Thu, 18 May 2006 10:27:06 +0200 Subject: How to tell if function was passed a list or a string? In-Reply-To: <87wtckmdnv.fsf@benfinney.id.au> References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> <1147907798.819913.146580@i40g2000cwc.googlegroups.com> <87wtckmdnv.fsf@benfinney.id.au> Message-ID: <5f56302b0605180127m65ddf6afgeb68e6c269722214@mail.gmail.com> > > >>> import types > > >>> type("") is types.ListType > > False > > >>> type("") is types.StringType > > True > > >>> type([]) is types.StringType > > False > > >>> type([]) is types.ListType > > True > > This is even worse than an 'isinstance' check; it refuses even > subclasses of the types you accept, breaking polymorphism *and* > inheritance. And also note the following comment in the types module of the standard library that was imported above: # StringTypes is already outdated. Instead of writing "type(x) in # types.StringTypes", you should use "isinstance(x, basestring)". But # we keep around for compatibility with Python 2.2. From sybrenUSE at YOURthirdtower.com.imagination Fri May 19 19:16:41 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sat, 20 May 2006 01:16:41 +0200 Subject: FAQ for XML with Python References: <3esbg.19024$Lm5.1740@newssvr12.news.prodigy.com> Message-ID: <slrne6skeo.o93.sybrenUSE@schuimige.stuvel.eu> Dave Kuhlman enlightened us with: > For those who are beginners to using Python to process XML, I've > recently updated my Python XML FAQ (PyXMLFaq). It has a number of > code samples that may help you get started. You might want to include a list of things you assume the reader already knows, including links to pages where the reader can learn about them if it's not the case. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From scott.daniels at acm.org Wed May 31 17:11:29 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 31 May 2006 14:11:29 -0700 Subject: Save data to a file thru a http connection In-Reply-To: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> Message-ID: <447e0221$1@nntp0.pdx.net> yinglcs at gmail.com wrote: > I am new to python. I read an example here about how to fetch data thru > a HTTP connection: > http://diveintopython.org/http_web_services/review.html, > > My question is how can i save the data to a file after reading it from > a http connection. Do the tutorial and this and many other things will become clear. Instead of just "print sometext", do something like: ... f = open('filename', 'w') ... print >>f, sometext ... (possibly more prints like the above). f.close() --Scott David Daniels scott.daniels at acm.org From larry.bates at websafe.com Sat May 20 18:34:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 20 May 2006 17:34:46 -0500 Subject: buffers readlines and general popen2 confusion... In-Reply-To: <1148162219.463249.155680@j33g2000cwa.googlegroups.com> References: <1148162219.463249.155680@j33g2000cwa.googlegroups.com> Message-ID: <446F9986.5010706@websafe.com> aristotelian at onet.eu wrote: > I'm interested in taking the output of a daemonized shell script that > greps for patterns which would act as an argument to a script. Is it > better to write this stuff to file and visit the file every few seconds > or can this be done a better way. I'm hoping for a more elegant > solution. So far I've seen some troubling info about buffer overflows > with popen2 but it looks like the low-hanging fruit. I'm not a unixpro > so I want to make sure anything I tackle is best practice. Suggestions > welcomed. > > -Aris > Sounds like you should take a look at logdog. It uses fifo files to send the output of /var/log/messages and greps them for patterns. As the daemon just looks at the fifo file for any input, it is quite efficient. I could be way off base about what you are trying to do, but it still might we worth a look. http://caspian.dotconf.net/menu/Software/LogDog/v1.0-old/ -Larry Bates From tbrkic at yahoo.com Wed May 17 17:24:46 2006 From: tbrkic at yahoo.com (glomde) Date: 17 May 2006 14:24:46 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. Message-ID: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> i I would like to extend python so that you could create hiercical tree structures (XML, HTML etc) easier and that resulting code would be more readable than how you write today with packages like elementtree and xist. I dont want to replace the packages but the packages could be used with the new operators and the resulting IMHO is much more readable. The syntax i would like is something like the below: # Example creating html tree '*!*' is an operator that creates an new node, '*=*' is an operator that sets an attribute. So if you take an example to build a smalle web page and compare with how it looks with in element tree now and how it would look like when the abover operators would exist. With element tree package. # build a tree structure root = ET.Element("html") head = ET.SubElement(root, "head") title = ET.SubElement(head, "title") title.text = "Page Title" body = ET.SubElement(root, "body") body.set("bgcolor", "#ffffff") body.text = "Hello, World!" With syntactical sugar: # build a tree structure root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): *=*text = "Page Title" *!*body("body"): *=*bgcolor = "#ffffff" *=*text = "Hello, World!" I think that with the added syntax you get better view of the html page. Repeating things dissapears and you get indentation that corresponds to the tree. I think it is very pythonic IMHO. It could be done quite generic. If the variable, object after '*!*' must support append method and if you use '*=*' it must support __setitem__ Any comments? From nicolasp at aaton.com Wed May 17 02:31:20 2006 From: nicolasp at aaton.com (NicolasP) Date: Wed, 17 May 2006 08:31:20 +0200 Subject: cross-compile PIL Message-ID: <446ac1e6$0$4868$626a54ce@news.free.fr> Hello, I need to compile PIL (python imaging library) package for an ARM based linux system. Does anyone can tell me how to do this ? Thanks Nicolas From onurb at xiludom.gro Fri May 12 12:25:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 18:25:44 +0200 Subject: listener program in Python In-Reply-To: <1147448608.316757.228500@v46g2000cwv.googlegroups.com> References: <1147445594.747005.61620@y43g2000cwc.googlegroups.com> <1147448608.316757.228500@v46g2000cwv.googlegroups.com> Message-ID: <4464b76b$0$6828$636a55ce@news.free.fr> simon.hibbs at gmail.com wrote: > diffuser78 at gmail.com wrote: > > >>I basically want to remotely shut down windows from linux and write >>such a program in python. > FWIW, s/from linux/from another machine/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tismer at stackless.com Mon May 15 11:35:34 2006 From: tismer at stackless.com (Christian Tismer) Date: Mon, 15 May 2006 17:35:34 +0200 Subject: Iterating generator from C In-Reply-To: <op.s9ljg1ddplgmb3@localhost> References: <op.s9ic3nhpplgmb3@localhost> <446887C8.4070705@stackless.com> <op.s9ljg1ddplgmb3@localhost> Message-ID: <44689FC6.6000603@stackless.com> Sven Suursoho wrote: >>> Is there any way to rewrite following program to handle returned >>> generator without hitting this bug? The only way I can think of getting around this is to make sure that there is always a running python frame. This would be possible if you can control how the extension is called. > Unfortunately, this is not an option because I can't control used > environment: I'm trying to improve PostgreSQL's stored procedure > language PL/Python and this software can be used everywhere. Then there is no other way than to report the bug, get the fix back-ported and nagging the PL/Python maintainers to update things after the fix. Also a test should be added which is probably missing since a while. I'd put a warning somewhere that generators are broken in debug mode, file an issue as well, but avoid trying to hack around this. It would make the bug even more resistent :-) ciao - chris -- Christian Tismer :^) <mailto:tismer at stackless.com> tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From oliphant.travis at ieee.org Wed May 10 18:29:06 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 10 May 2006 16:29:06 -0600 Subject: segmentation fault in scipy? In-Reply-To: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> Message-ID: <e3tpfi$sse$1@sea.gmane.org> conor.robinson at gmail.com wrote: > I'm running operations large arrays of floats, approx 25,000 x 80. > Python (scipy) does not seem to come close to using 4GB of wired mem, > but segments at around a gig. Everything works fine on smaller batches > of data around 10,000 x 80 and uses a max of ~600mb of mem. Any Ideas? > Is this just too much data for scipy? > > Thanks Conor > > Traceback (most recent call last): > File "C:\Temp\CR_2\run.py", line 68, in ? > net.rProp(1.2, .5, .000001, 50.0, input, output, 1) > File "/Users/conorrob/Desktop/CR_2/Network.py", line 230, in rProp > print scipy.trace(error*scipy.transpose(error)) > File "D:\Python24\Lib\site-packages\numpy\core\defmatrix.py", line > 149, in > __mul__ > return N.dot(self, other) > MemoryError You should ask this question on the numpy-discussion list for better feedback. Does it actually segfault or give you this Memory Error? Temporary arrays that need to be created could be the source of the extra memory. Generally, you should be able to use all the memory on your system (unless you are on a 64-bit system and are not using Python 2.5). -Travis From benkasminbullock at gmail.com Wed May 24 23:35:40 2006 From: benkasminbullock at gmail.com (Ben Bullock) Date: Thu, 25 May 2006 12:35:40 +0900 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> Message-ID: <e538mb$av1$1@ml.accsnet.ne.jp> "Ken Tilton" <kentilton at gmail.com> wrote in message news:R_Zcg.248$LO3.40 at fe11.lga... > > > Ben Bullock wrote: >> "Xah Lee" <xah at xahlee.org> wrote in message >> news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... >> >>> If you believe this lobbying to my webhosting provider is unjust, >>> please write to my web hosting provider abuse at dreamhost.com >> >> >> Why don't you just change your provider? It would take less time than >> this. > > Are you joking. "Just change your provider?" Do you have a little button > on your computer that says "Change provider"? Cool! :) No, but if you go any look at the website of Xah Lee, he seems to have spent enough time and energy complaining that it would be overwhelmingly greater than the time it would take him to apply for a new provider. From ask at me Tue May 23 23:17:03 2006 From: ask at me (AndyL) Date: Tue, 23 May 2006 23:17:03 -0400 Subject: Web framework comparison video In-Reply-To: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> References: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> Message-ID: <_7qdnQSQu6PZQ-7ZnZ2dnUVZ_tWdnZ2d@comcast.com> Iain King wrote: > http://compoundthinking.com/blog/index.php/2006/03/10/framework-comparison-video/ > > Thought this might be interesting to y'all. (I can't watch it 'cos I'm > at work, so any comments about it would be appreciated :) Indeed it was. The headache factor is 1, for some reason my Mandrake 2006 media players mute the sound. Had to boot to M$ :-(. A. From skip at pobox.com Thu May 4 21:24:10 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 4 May 2006 20:24:10 -0500 Subject: whois info from Python? Message-ID: <17498.43322.289413.807689@montanaro.dyndns.org> I'm looking to get whois information for a given domain from Python. I'm mostly interested in record update and creation dates at the moment, but eventually might want more. I stumbled upon a couple modules/programs: rwhois.py and whois.py but neither seems to work. I can clearly issue a whois command directly, but I'm hoping there's some module out there that will do the domain-to-whoisserver mapping and all the output parsing for me. Any candidates other than the two I've found so far? Thx, Skip From robert.kern at gmail.com Fri May 5 21:55:50 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 05 May 2006 20:55:50 -0500 Subject: NaN handling In-Reply-To: <DE87348C-5BE0-4D55-B041-516FB72E7B04@mcmaster.ca> References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> <mailman.5402.1146867973.27775.python-list@python.org> <125nlbgm8l1fi17@corp.supernews.com> <DE87348C-5BE0-4D55-B041-516FB72E7B04@mcmaster.ca> Message-ID: <e3gvn8$vsv$1@sea.gmane.org> Ivan Vinogradov wrote: > It doesn't seem to be here under OSX either (universal Python install). It's not enabled by default. In the source distribution, it is Modules/fpectlmodule.c . > Since numpy seems to be working on a variety of platforms/hardware, > how hard would it be to extract this functionality from it to add to > Python proper? Harder than just enabling fpectl. -- 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 softwindow at gmail.com Fri May 19 01:05:19 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 22:05:19 -0700 Subject: Script to make Windows XP-readable ZIP file In-Reply-To: <1148014650.844340.212540@38g2000cwa.googlegroups.com> References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> <Xns97C7E851F9CC2castleamber@130.133.1.4> <1148011001.613000.294750@g10g2000cwb.googlegroups.com> <Xns97C7ED9E857DEcastleamber@130.133.1.4> <1148014650.844340.212540@38g2000cwa.googlegroups.com> Message-ID: <1148015119.818301.167740@i39g2000cwa.googlegroups.com> import os import zipfile z = zipfile.ZipFile(r"c:\text.zip",mode="w",compression=zipfile.ZIP_DEFLATED) cwd = os.getcwd() try: for dirpath,dirs,files in os.walk(cwd): for file in files: z_path = os.path.join(dirpath,file) start = cwd.rfind(os.sep)+1 z.write(z_path,z_path[start:]) z.close() finally: if z: z.close() ********************* can work From johnjsal at NOSPAMgmail.com Sat May 20 00:34:10 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 20 May 2006 00:34:10 -0400 Subject: DO NOT USE file() (was Re: altering an object as you iterate over it?) In-Reply-To: <mailman.5995.1148099603.27775.python-list@python.org> References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <e4la8j$od9$1@daisy.noc.ucla.edu> <e4m0jg$o3t$1@panix3.panix.com> <446e8a54$0$5326$c3e8da3@news.astraweb.com> <mailman.5995.1148099603.27775.python-list@python.org> Message-ID: <446e9d65$0$5048$c3e8da3@news.astraweb.com> Tim Peters wrote: > [John Salerno, on the difference between `open` and `file`] >> Interesting. What is the difference between them now? > > In 2.5 `file` is unchanged but `open` becomes a function: > >>>> file > <type 'file'> >>>> open > <built-in function open> So they are still used in the same way though? From a.schmolck at gmail.com Fri May 12 19:44:26 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 13 May 2006 00:44:26 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> <m38xp7p7el.fsf@rigel.goldenthreadtech.com> <yfs3bffuqj7.fsf@oc.ex.ac.uk> <r559g.16$Id.14@fe10.lga> <yfsk68rt3cq.fsf@oc.ex.ac.uk> <m3vesaon4l.fsf@rigel.goldenthreadtech.com> Message-ID: <yfszmhmst9h.fsf@oc.ex.ac.uk> jayessay <nospam at foo.com> writes: > > Great -- so can I see some code? Can't be that difficult, it takes about 10-15 > > lines in python (and less in scheme). > > Do you actually need the code to understand this relatively simple concept??? Yes. I'd be genuinely curious to see how an implementation in Java, Pascal, C, (or any other language that has little more than dictionaries) compares to python and CL. In my limited understanding I have trouble seeing how you'd do without either unwind-protect/try-finally or reliable finalizers for starters. 'as From cvanarsdall at mvista.com Tue May 9 16:22:59 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 09 May 2006 13:22:59 -0700 Subject: Shadow Detection? In-Reply-To: <HGEOKIAPAMCIFPPBDALKMEINCAAA.m.yanowitz@kearfott.com> References: <HGEOKIAPAMCIFPPBDALKMEINCAAA.m.yanowitz@kearfott.com> Message-ID: <4460FA23.1070904@mvista.com> Michael Yanowitz wrote: > Hello: > > Many times, people are warning things like > "Don't use 'str' as a variable name as it will shadow the > built in str function." > Is there some way to determine if a string is already > defined in some higher scope? > Maybe something like > <code> > > if isdefined ('str'): > print 'str is already defined, please choose another name' > > You might check out globals() which returns a dictionary of everything: Python 2.2 (#1, Mar 26 2002, 15:46:04) [GCC 2.95.3 20010315 (SuSE)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> globals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None} >>> blah = None >>> globals() {'__builtins__': <module '__builtin__' (built-in)>, '__name__': '__main__', '__doc__': None, 'blah': None} #Taking this a step further, this is a dictionary so you can use the has_key method or try to access the dict and catch an exception should the key not exist >>> if globals().has_key('blah'): ... print "I have blah" ... I have blah -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From john at castleamber.com Thu May 25 23:03:38 2006 From: john at castleamber.com (John Bokma) Date: 26 May 2006 03:03:38 GMT Subject: OT: Navarth (was Re: John Bokma harassment) References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> <Xns97CE807F1ADC6castleamber@130.133.1.4> <Zpmdg.2874$%Z2.298786@news20.bellglobal.com> <Xns97CE8E1B64A6Bcastleamber@130.133.1.4> <Sstdg.3023$%Z2.324494@news20.bellglobal.com> Message-ID: <Xns97CEE068E3432castleamber@130.133.1.4> "Geoffrey Summerhayes" <sumrnot at NhOoStPmAaMil.com> wrote: > > "John Bokma" <john at castleamber.com> wrote in message > news:Xns97CE8E1B64A6Bcastleamber at 130.133.1.4... >> "Geoffrey Summerhayes" <sRuEmMrOnVoEt at hotmail.com> wrote: >> >>> After you kill Navarth, will it be nothing but gruff and deedle >>> with a little wobbly to fill in the chinks? >> >> Comparing Navarth with Xah is a huge insult to Jack Vance. You should >> be ashamed of yourself for even thinking about it, let alone write it >> down. > > Mr. Vance is too intelligent to be insulted by this. OTOH he changed Wankh to Wannek. [1] > OTOH, Mad Navarth is free to be as insulted as much > as his fictional soul will allow. :) One can only wonder what he would say, but if it comes out in print, I will buy it and read it and probably enjoy it. [1] http://starling.us/wankh_vs_wannek.html -- 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 george.sakkis at gmail.com Sat May 20 20:45:21 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 20 May 2006 17:45:21 -0700 Subject: python vs perl lines of code In-Reply-To: <Xns97C9B5C01B657castleamber@130.133.1.4> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> <Xns97C9ADA375FCCcastleamber@130.133.1.4> <lFMbg.19879$Lm5.7431@newssvr12.news.prodigy.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> <Xns97C9B5C01B657castleamber@130.133.1.4> Message-ID: <1148172321.824018.207540@j33g2000cwa.googlegroups.com> John Bokma wrote: > "George Sakkis" <george.sakkis at gmail.com> wrote: > > > Not trying to be as ass, but can you take this offline or at least in > > a perl newsgroup ? Arguing on a particular fact or speculation about > > the perl community is rather unproductive and offtopic for a python > > newsgroup. > > Use a real Usenet client, and you can make it skip a thread. That's funny, coming from the same guy that's been harassing Xah for OT posts. Oh, the irony. George From simon at renderIHATESPAMmania.com Tue May 16 19:02:07 2006 From: simon at renderIHATESPAMmania.com (Simon Bunker) Date: Wed, 17 May 2006 00:02:07 +0100 Subject: Python and GLSL Message-ID: <446a59ee_2@mk-nntp-2.news.uk.tiscali.com> Hi I was wondering if there is a Python module for running GLSL (OpenGL shader language) in OpenGL through Python. I think that Cg is available through PyCg - most likely using PyGame for the OpenGL. Has anyone done this with GLSL shaders? thanks Simon From NOatkinwSPAM at rpi.edu Sat May 6 21:02:03 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 21:02:03 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> Message-ID: <8764kive9g.fsf@rpi.edu> aleaxit at yahoo.com (Alex Martelli) writes: > Ken Tilton <kentilton at gmail.com> wrote: > ... >> True but circular, because my very point is that () was a great design >> choice in that it made macros possible and they made CL almost >> infinitely extensible, while indentation-sensitivity was a mistaken >> design choice because it makes for very clean code (I agree >> wholeheartedly) but placed a ceiling on its expressiveness. > > Having to give functions a name places no "ceiling on expressiveness", > any more than, say, having to give _macros_ a name. > > >> As for: >> >> > At a syntax-sugar >> > level, for example, Lisp's choice to use parentheses as delimiter means >> > it's undesirable, even unfeasible, to use the single character '(' as an >> > ordinary identifier in a future release of the language. >> >> (defun |(| (aside) (format nil "Parenthetically speaking...~a." aside)) >> => |(| >> (|(| "your Lisp /is/ rusty.") >> => "Parenthetically speaking...your Lisp /is/ rusty.." >> >> :) No, seriously, is that all you can come up with? > > Interestingly, the SECOND lisper to prove himself unable to read the > very text he's quoting. Reread carefully, *USE THE ***SINGLE*** > CHARACTER* ... *AS AN ORDINARY IDENTIFIER*. What makes you read a > ``PART OF'' that I had never written? You've shown how to use the > characters as *PART* of an identifier [[and I believe it couldn't be the > very start]], and you appear to believe that this somehow refutes my > assertion? Now I see what the problem is here - you just don't know what you're talking about. The identifier in Ken's and my samples *is* a single character identifier. The vertical bars tell the Lisp reader that what's between them is exempt from other reading rules. (symbol-name '|(| ) => "(" (length (symbol-name '|(| )) => 1 > Are you ready to admit you were utterly wrong, and (while it is indeed > true that my Lisp is rusty) there is nothing in this exchange to show > it, as opposed to showing rustiness in your ability to understand > English? Or shall we move from polite although total dissent right on > to flamewars and namecalling? Believe it or not, _you_ got it wrong. > The point is, OF COURSE any design choice places limitations on future > design choices; but some limitations are even DESIRABLE (a language > where *every* single isolated character could mean anything whatsoever > would not be "expressive", but rather totally unreadable) or at least > utterly trivial (syntax-sugar level issues most typically are). Wilfully > distorting some such limitation as meaning that one language "can scale" > (when EVERY language inevitably has SOME such limitations) is not even > funny, and clearly characterizes a polemist who is intent on proving a > preconceived thesis, as opposed to an investigator with any real > interest in ascertaining the truth of the matter. Having to name a variable "paren" instead of "(" is not a serious restriction. I can't think of a single situation where being able to do so would be useful. That said, raw, out-of-the-box Common Lisp can accomodate you if you both a) need variables named "(" and b) are unwilling to use the bar syntax. Simply redefine the parenthesis characters in the readtable (a matter of four function calls) and get this abomination: {let {{( 3}} {+ ( 5}} Lisp places no restrictions on you, even when your goal is as silly as this one. >> > Oh, is that the same Graham who writes: >> >> So we are going to skip the point I was making about Common Lisp being >> so insanely extensible? By /application/ programmers? Hell, for all we >> know CL does have a BDFL, we just do not need their cooperation. > > Yes, we are, because the debate about why it's better for Python (as a > language used in real-world production systems, *SCALABLE* to extremely > large-scale ones) to *NOT* be insanely extensible and mutable is a > separate one -- Python's uniformity of style allows SCALABILITY of > teams, and teams-of-teams, which is as crucial in the real world as > obviously not understood by you (the law you misquoted was about adding > personnel to a LATE project making it later -- nothing to do with how > desirable it can be to add personnel to a large and growing collection > of projects, scaling and growing in an agile, iterative way to meet > equally growing needs and market opportunities). Buh? The project doesn't have to be late for Brooks's law to hold; adding programmers, so goes Brooks reasoning, will always increase the time required to complete the project because of various communication issues. > This specific debate grew from your misuse of "scalable" to mean or > imply "a bazillion feechurz can [[and, implicitly, should]] be added to > a language, and therefore anything that stands in the way of feechuritis > is somehow holding the language back". That's bad enough, even though > in its contextual misuse of "scalable" it breaks new ground, and I don't > want to waste even more time re-treading *old* ground as to whether the > "*insane* extensibility" afforded by macros is a good or a bad thing in > a language to be used for real-world software production (as opposed to > prototyping and research). > > >> > """ >> > A friend of mine who knows nearly all the widely used languages uses >> > Python for most of his projects. He says the main reason is that he >> > likes the way source code looks. >> >> No argument. The little Python I wrote while porting Cells to Python was >> strikingly attractive. But it was a deal with the devil, unless Python >> is content to be just a scripting language. (And it should be.) > > It's hard to attribute feelings to a programming language, but, if you > really must, I'd say Pyton aspires to be *useful* -- if all you need is > "just a scripting language", it will be content to be one for you, and > if your need SCALE, well then, PYTHON IS SCALABLE, and will remain a > *SIMPLE, CLEAN, LITTLE AND POWERFUL LANGUAGE* (letting nobody do > anything INSANE to it;-) while scaling up to whatever size of project(s) > you need (including systems so large that they redefine the very concept > of "large scale" -- believe me, once in a while at a conference I make > the mistake of going to some talk about "large scale" this or that, and > invariably stagger out once again with the realization that what's > "large scale" to the world tends to be a neat toy-sized throwaway little > experiment to my current employer). You haven't given much justification for the claim that Python is a particularly "scalable" language. Sure, Google uses it, Graham gave it some props somewhere in the middle of his notoriously pro-Lisp writings, and even Norvig has said good things about it. Fair enough. But what does Python offer above any garbage-collected language that makes it so scalable? > >> OK, I propose a duel. We'll co-mentor this: >> >> http://www.lispnyc.org/wiki.clp?page=PyCells >> >> In the end Python will have a Silver Bullet, and only the syntax will >> differ, because Python has a weak lambda, statements do not always >> return values, it does not have macros, and I do not know if it has >> special variables. >> >> Then we can just eyeball the code and see if the difference is >> interesting. These abstract discussions do tend to loop. > > As a SummerOfCode mentor, I'm spoken for, and can't undertake to mentor > other projects. I do agree that these discussions can be sterile, and > I'll be glad to see what comes of your "pycells" project, but until then > there's little we can do except agree to disagree (save that I'd like > you to acknowledge my point above, regarding what exactly I had said and > the fact that your alleged counterexample doesn't address at all what I > had said -- but, I'll live even without such an acknowledgment). > > > Alex -- This is a song that took me ten years to live and two years to write. - Bob Dylan From bborcic at gmail.com Mon May 29 08:12:46 2006 From: bborcic at gmail.com (Boris Borcic) Date: Mon, 29 May 2006 14:12:46 +0200 Subject: John Bokma harassment In-Reply-To: <1148463588.566212.36300@i39g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> Message-ID: <447ae549$1_5@news.bluewin.ch> ilitzroth at gmail.com wrote: > We seem to have strayed a long way from Voltaire's > "I do not agree with what you say, but I will defend to the death your > right to say it.", > but that was of course the age of enlightenment. Obviously this wisdom is getting stale and should be updated to something like "There is so much noise we can't hear each other, but I will defend to the death a chance to get heard for whatever you might have to say that's intelligent (while not necessarily from your own mouth)". Besides, it is not clear that Voltaire really said that. Cheers, BB -- python >>> filter(lambda W : W not in 'ILLITERATE','BULLSHIT') From diffuser78 at gmail.com Thu May 4 12:57:15 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 4 May 2006 09:57:15 -0700 Subject: cross platform libraries Message-ID: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> I am using python on a linux terminal. I want to shutdown a remote windows box. I found a script which does something like this. My question is can we use windows libraries in linux as follows .... import win32api import win32con import win32netcon import win32security import win32wnet def shutdown(parameters): OTHER CODE HERE Every help is appreciated. From wegwerp at gmail.com Thu May 25 08:39:27 2006 From: wegwerp at gmail.com (Bas) Date: 25 May 2006 05:39:27 -0700 Subject: a good explanation References: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> Message-ID: <1148560767.356002.230590@i39g2000cwa.googlegroups.com> I guess that your version is faster, although the difference would be negligible in this small example. The for loop is probably optimized for speed under the hood (it is written in C), while the 'while' loop is performed in python, which is much slower. Much more important than the speed difference is the clarity: your version is the accepted practice in the python world, so people will understand it immediately. It also saves two lines of code. And most of all, it prevents you from making mistakes: your friend, for example, has forgotten to increase cnt, so he created an infinite loop! Bas From sjmachin at lexicon.net Sun May 21 17:43:57 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 22 May 2006 07:43:57 +1000 Subject: Python update trouble (2.3 to 2.4): x<<y In-Reply-To: <mailman.6038.1148239366.27775.python-list@python.org> References: <cef393a0512232219w6fab1b09tfb10debd31fd12b7@mail.gmail.com> <mailman.6016.1148188117.27775.python-list@python.org> <1148197232.312628.255650@i39g2000cwa.googlegroups.com> <mailman.6025.1148204320.27775.python-list@python.org> <1148209690.978989.65430@j55g2000cwa.googlegroups.com> <mailman.6038.1148239366.27775.python-list@python.org> Message-ID: <4470DF1D.4040109@lexicon.net> On 22/05/2006 5:22 AM, Gonzalo Monz?n wrote: > Thank you for all the suggestions! :-) > > The C routine is almost -changing data type long for word- a copy of the > function given by a hardware manufacturer, the same code used in their > firmware to calc the checksum of every piece of data sent or received, > and that data is somewhat special: it does not contain only plain ascii > character data (only 0x01 - 0x09 as delimiters) and every data set ends > with a 0x00 null byte so its fine to calculating checksum until "\x00" > is reached. And I must get the same crc calculations. That C routine > (and a very similar PHP one too) are tested for months and work smoothly. > > And of course I should use integer not long!!... we aren't anymore in > the 8 bit computer era... ;-) original code from hardware manufacturer > use words by the way. And now really don't know why I used long. I > thought I did that way 'cause see pyrex C generated glue code always > using PyInt_FromLong so thought would use the same type. Perhaps we need some amplification of "of course I should use integer not long" :-) Is the transmitted checksum (which your routine must create and/or verify) 2 bytes long or 4 bytes long??? This is the most important thing; once that is established, then you choose the C and/or Python types and the mask (0xFFFF or 0xFFFFFFFF) as/if necessary. In that original specification from the manufacturer, how wide was a "word"? Note that in most/many C compilers at the moment, "int" and "long" *both* mean 32 bits, to get 64 bits you need "long long" [or "_int64" or whatever in realms under the sway of the dark tower], and "short" may get you 16 bits if you are lucky. In a typical Python environment at the moment, "int" uses the C "long", and thus typically will be 32 bits. Python "long" is a variable-length data type. Also note that even if the "checksum" is 32 bits wide, the high-order 16 bits are not verifiably useful, so you could use a [faster] 16-bit version when receiving. > > I changed the C function to use integer, and it is performing a little > bit slowly than using longs (best with long: 0.614us, best with int: > 0.629us), that is maybe as I said due pyrex glueing always the return > values with PyObject* PyInt_FromLong for all kind of short int to long > data types? Anyway both results are fine, and the timming gap is > insignificant (int: 1580403 loops -> 0.973 secs, long: 1601902 loops -> > 1.01 secs) as i usually never have to call more than 100,000 times when > loading a full file data backup. I'm somewhat puzzled: Do you have the facility to cross-compile C to run on the Pocket PC? If NO, why do you continue to mention fast versions coded in C and glued with Pyrex? If YES, why did you include a Python version in your initial question? Cheers, John From spam4bsimons at yahoo.ca Wed May 17 07:49:22 2006 From: spam4bsimons at yahoo.ca (Brendan) Date: 17 May 2006 04:49:22 -0700 Subject: Using python for a CAD program In-Reply-To: <e4en51$mv4$1@news.al.sw.ericsson.se> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <xqxpsietsrf.fsf@cola3.ca.boeing.com> <1147807050.375537.297430@j73g2000cwa.googlegroups.com> <e4en51$mv4$1@news.al.sw.ericsson.se> Message-ID: <1147866562.867008.88490@j55g2000cwa.googlegroups.com> On 17-May-06, at 6:33 AM, comp.lang.python group wrote: >>I'd like my program >>to *look* slick, like it belongs in a movie or something. I think that >>means starting from scratch, since I've not seen any CAD program >>take >>any artistic/human/psychological approach to its design. >That *is* true - the problem with CAD programs are that they need the >*exact* details to be entered at design time so one cannot easily >schetch in them and fix the design errors later. Not universally true, and here's a niche for you Andreas: Most 2D cad requires that you enter ALL design information as you go. You can't, for instance, draw a line at 30degrees to another line and then change the second without having to redraw the first. "Sketchers" from 3D cad programs (like Solidworks, Inventor, Solid Edge, Pro/Engineer) are more like geometry solvers - by putting in a dimension, you say "line a is always 30 degrees to line b". Now when you change the angle of line b, line a changes too! In this way, you can sketch out the SHAPE of your drawing, and worry about the DIMENSIONS later. You can't imagine how useful this is. Now that I've switched to Solidworks, my drafting speed has doubled. I haven't seen anyone make a 2D cad package with this behaviour. I'm sure there's a market for one if you go that route. -Brendan From aleax at mac.com Mon May 8 01:57:19 2006 From: aleax at mac.com (Alex Martelli) Date: Sun, 7 May 2006 22:57:19 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> Message-ID: <1heznxs.1m1eqceeowwsrN%aleax@mac.com> Patrick May <pjm at spe.com> wrote: ...an alleged reply to me, which in fact quotes (and responds to) only to statements by Brian, without mentioning Brian... Mr May, it seems that you're badly confused regarding Usenet's quoting conventions. You may want to repeat your answer addressing specifically the poster you ARE apparently answering. Nevertheless, I'll share my opinions: > Using lambda in an expression communicates the fact that it will > be used only in the scope of that expression. Another benefit is that > declaration at the point of use means that all necessary context is > available without having to look elsewhere. Those are two pragmatic > benefits. You still need to look a little bit upwards to the "point of use", almost invariably, to see what's bound to which names -- so, you DO "have to look elsewhere", nullifying this alleged benefit -- looking at the def statement, immediately before the "point of use", is really no pragmatic cost when you have to go further up to get the context for all other names used (are they arguments of this function, variables from a lexically-containing outer function, assigned somewhere...), which is almost always. And if you think it's an important pragmatic advantage to limit "potential scope" drastically, nothing stops you from wrapping functions just for that purpose around your intended scope -- me, I find that as long as functions are always kept small (as they should be for a host of other excellent reasons anyway), the "ambiguity" of scope being between the def and the end of the containing function is nil (literally nil when the statement right after the def, using the named function, is a return, as is often the case -- pragmatically equivalent to nil when the statements following the def are >1 but sufficiently few). Your "pragmatic benefits", if such they were, would also apply to the issue of "magic numbers", which was discussed in another subthread of this unending thread; are you therefore arguing, contrary to widespread opinion [also concurred in by an apparently-Lisp-oriented discussant], that it's BETTER to have magic unexplained numbers appear as numeric constants "out of nowhere" smack in the middle of expressions, rather than get NAMED separately and then have the names be used? If you really believe in the importance of the "pragmatic benefits" you claim, then to be consistent you should be arguing that...: return total_amount * 1.19 is vastly superior to the alternative which most everybody would deem preferable, VAT_MULTIPLIER = 1.19 return total_amount * VAT_MULTIPLIER because the alternative with the magic number splattered inexplicably smack in the middle of code "communicated the fact" that it's used only within that expression, and makes all context available without having to look "elsewhere" (just one statement up of course, but then this would be identically so if the "one statement up" was a def, and we were discussing named vs unnamed functions vs "magic numbers"). > >> 3. It adds another construction to the language. > > That's a very minimal cost relative to the benefits. To my view of thinking, offering multiple semantically equivalent ways (or, perhaps worse, "nearly equivalent but with subtle differences" ones) to perform identical tasks is a *HUGE* conceptual cost: I like languages that are and stay SMALL and SIMPLE. Having "only one obvious way to do it" is just an ideal, but that's no reason to simply abrogate it when it can so conveniently be reached (my only serious beef with Python it has it *HAS* abdicated the pursuit of that perfect design principle by recent decisions to keep lambda, and to keep the syntax [<genexp>] as an identical equivalent to list(<genexp>), in the future release 3.0, which was supposed to simplify and remove redundant stuff accreted over the years: suddenly, due to those decisions, I don't really look forward to Python 3.0 as I used to - though, as I've already mentioned, being a greedy fellow I'll no doubt stick with Python until all my Google options have vested). > You haven't made your case for named functions being preferable. I think it's made at least as well as the case for using constant-names rather than "magic numbers" numeric constants strewn throughout the code, and THAT case is accepted by a wide consensus of people who care about programming style and clarity, so I'm pretty happy with that. Alex From john at castleamber.com Thu May 18 20:19:03 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 00:19:03 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <Xns97C7BC8549BA0castleamber@130.133.1.4> <1147996910.404673.120340@j33g2000cwa.googlegroups.com> Message-ID: <Xns97C7C4821C189castleamber@130.133.1.4> "Michael Tobis" <mtobis at gmail.com> wrote: >> According to your silly rule the shortest book on a subject would be >> the best. Now why is that false? > > No, according to the rule, the shorter of two books **containing the > same information** would be best. What is "the same information"? > In fact, that's what makes the comparison interesting. I had always > thought that Pythonistas type more than Perlists, though I prefer > Python anyway. The presumption was based on the fact that Perl (as > language and culture) takes delight in saving keystrokes at the > expense of clarity ($_ and all that) Then you're very mistaken about the Perl culture, or you consider a small group *the* Perl culture, which is also a mistake IMNSHO. I have never see someone recommend unclear Perl code over clear code, except in golf. But we're not talking about golf here. > while Python makes no special effort in > that direction. Nor does Perl. That one can do something doesn't mean one has to do it. > If real world Python code is substantially more terse *despite* this > cultural difference, it is a fact worthy of some note. Maybe you got the Perl culture wrong. I think you do. > Let me add my voice to those clamoring for Edward to release his code > while I'm here, though. Yup, I agree on that. Since I am learning Python (well, I read Dive into Python, and the Python documentation), and have quite some Perl experience, I am curious. Yes, I might comment on the Perl code, but isn't the goal to learn? -- 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 harlinseritt at yahoo.com Fri May 19 07:59:45 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 19 May 2006 04:59:45 -0700 Subject: How to append to a dictionary Message-ID: <1148039985.232831.56040@i40g2000cwc.googlegroups.com> I have some code here: groups = {'IRISH' : 'green', 'AMERICAN' : 'blue'} I want to add another key: 'ITALIAN' : 'orange' How do I append this to 'groups'? Thanks, Harlin Seritt From aleaxit at yahoo.com Sun May 7 14:57:59 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sun, 7 May 2006 11:57:59 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> Message-ID: <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <brian at sweetapp.com> wrote: > Patrick May wrote: > > aleaxit at yahoo.com (Alex Martelli) writes: > >> In my opinion (and that of several others), the best way for Python to > >> grow in this regard would be to _lose_ lambda altogether, since named > >> functions are preferable > > > > Why? I find the ability to create unnamed functions on the fly > > to be a significant benefit when coding in Common Lisp. > > 1. They don't add anything new to the language semantically i.e. you > can always used a named function to accomplish the same task > as an unnamed one. > 2. Giving a function a name acts as documentation (and a named > function is more likely to be explicitly documented than an unnamed > one). This argument is pragmatic rather than theoretical. > 3. It adds another construction to the language. Creating *FUNCTIONS* on the fly is a very significant benefit, nobody on the thread is disputing this, and nobody ever wanted to take that feature away from Python -- it's the obsessive focus on the functions needing to be *unnamed* ones, that's basically all the debate. I wonder whether all debaters on the "unnamed is a MUST" side fully realize that a Python's def statement creates a function on the fly, just as much as a lambda form does. Or maybe the debate is really about the distinction between statement and expression: Python does choose to draw that distinction, and while one could certainly argue that a language might be better without it, the distinction is deep enough that nothing really interesting (IMHO) is to be gleaned by the debate, except perhaps as pointers for designers of future languages (and there are enough programming languages that I personally see designing yet more of them as one of the least important tasks facing the programming community;-). Alex From deets at nospam.web.de Tue May 9 17:21:27 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 May 2006 23:21:27 +0200 Subject: Can Python installation be as clean as PHP? In-Reply-To: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> Message-ID: <4ccfejF15g5taU1@uni-berlin.de> > With Python, things are really messy. I have to run the installer > to install dozens of directories and hundreds of files, and I don't > really know if all of them are necessary. Plus, lots of libraries > are in .py, which is of course not as efficient/clean as having all > of the core functions built-in in the C/C++ core, like in PHP. > > Then again, I do like the Python language. It would be great if > Python (or a variation of Python) can be made the PHP way, one > executable file, and you get everything. You have a somewhat distorted view of things. I've been cursing PHP quite a few times exactly for that monolitic nature. If you need e.g. oracle support, you have to recompile the whole lot, not just a module as it has no no C-module concept - so you can't add functionality besides using PHP-includes. So much for efficiency. Diez From mumia.w.18.spam+nospam.usenet at earthlink.net Tue May 30 06:22:41 2006 From: mumia.w.18.spam+nospam.usenet at earthlink.net (Mumia W.) Date: Tue, 30 May 2006 10:22:41 GMT Subject: John Bokma harassment In-Reply-To: <e5h28o$kq5$1@news.ox.ac.uk> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> <Xns97D294C4D81FCcastleamber@130.133.1.4> <447bff02$0$38691$edfadb0f@dread12.news.tele.dk> <e5h28o$kq5$1@news.ox.ac.uk> Message-ID: <R1Veg.25$gx3.11@newsread3.news.pas.earthlink.net> David Squire wrote: > Max M wrote: >> John Bokma wrote: >>> ilitzroth at gmail.com wrote: >> >>> Your first question should be: Is it alright that Xah harasses 5 >>> newsgroups? Or maybe work on your spelling, harass is with one r, but >>> maybe you didn't read the subject, which wouldn't amaze me, since you >>> sound like you should be spending time on MySpace OMG!. >> >> >> I assume that the single l in alright is the courteous misspelling >> that should allways be in a posting, when correcting other peoples >> speling? > > Nope. Oxford English Dictionary has: > > alright > > a frequent spelling of all right. > > And Merriam-Webster has: > > alright > Pronunciation: (")ol-'rIt, 'ol-" > Function: adverb or adjective > : ALL RIGHT > usage The one-word spelling alright appeared some 75 years after all > right itself had reappeared from a 400-year-long absence. Since the > early 20th century some critics have insisted alright is wrong, but it > has its defenders and its users. It is less frequent than all right but > remains in common use especially in journalistic and business > publications. It is quite common in fictional dialogue, and is used > occasionally in other writing <the first two years of medical school > were alright -- Gertrude Stein>. > > DS American Heritage Dictionary: Usage Note: [...] one who uses alright, especially in formal writing, runs the risk that readers may view it as an error or as the willing breaking of convention. That's sounds kinda like what Xah does, and that's why I flag it as hypocrisy. From eligottlieb at gmail.com Wed May 24 12:02:36 2006 From: eligottlieb at gmail.com (Eli Gottlieb) Date: Wed, 24 May 2006 16:02:36 GMT Subject: John Bokma harassment In-Reply-To: <1148484776.213699.34610@i39g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> <1148484776.213699.34610@i39g2000cwa.googlegroups.com> Message-ID: <ws%cg.7001$8G3.3811@twister.nyroc.rr.com> olsongt at verizon.net wrote: > John Bokma wrote: > >>"Ant" <antroy at gmail.com> wrote: >> >> >>>I have no particular affinity for Xah's views, but what does get up my >>>nose is usenet Nazism. >> >>That's because you're clueless. >> >>-- >>John MexIT: http://johnbokma.com/mexit/ >> personal page: http://johnbokma.com/ >> Experienced programmer available: http://castleamber.com/ >> Happy Customers: http://castleamber.com/testimonials.html > > > Time for a game! > > Both johnbokma.com and castleamber.com are hosted by seagull.net. Here > is a link to their TOS: > > http://www.seagull.net/tos.html > > Who can come up with the most violations that John is committing on > this thread? I count 4. > Let's not drop to his level. -- The science of economics is the cleverest proof of free will yet constructed. From me+python at modelnine.org Fri May 12 09:14:04 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Fri, 12 May 2006 15:14:04 +0200 Subject: Python memory deallocate In-Reply-To: <1147363639.855800.87930@j33g2000cwa.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <mailman.5587.1147355642.27775.python-list@python.org> <1147363639.855800.87930@j33g2000cwa.googlegroups.com> Message-ID: <200605121514.04250.me+python@modelnine.org> Am Donnerstag 11 Mai 2006 18:07 schrieb Michele Petrazzo: > Heiko Wundram wrote: > > As was said before: as long as you keep a reference to an object, the > > object's storage _will not be_ reused by Python for any other objects > > (which is sensible, or would you like your object to be overwritten by > > other objects before you're done with them?). Besides, even if Python did > > free the memory that was used, the operating system wouldn't pick it up > > (in the general case) anyway (because of fragmentation issues), so Python > > keeping the memory in an internal free-list for new objects is a sensible > > choice the Python developers took here. > > This isn't true. Just tried with python 2.5a2 and: > > d:\python25\python.exe > > >>> a = range(1000 * 100 *100) # 173 MB > >>> del a # 122MB > > So now, like you saied, if I try to allocate another memory chunk, > > python'll re-use it... But this isn't true: > >>> b = range(100 * 100 * 100) # 126 MB > >>> del b # 122MB > >>> exit() # :) > > d:\python25\python.exe > > >>> b = range(100 * 100 * 100) # 19 MB > > Do why python don't reuse the freed memory and re-allocate 4 MB (126 - > 122)? What the OS reports as the memory usage isn't actually what's allocated by Python objects. As Tim Peters pointed out in another post, this number just specifies the amount of memory the OS has given to libc, which in turn has given it to Python. Basically, what you're seeing is exactly the reuse of memory that Python internally does. Why it allocates 4 more megabytes I wouldn't know, but as you can see, the range b is actually 19 megabytes in size (a little smaller, but >10MB), whereas it only takes up 4 megabytes when you construct it after you deleted the old list. That's a major difference. I just tried the following: modelnine at phoenix ~ $ python Python 2.4.3 (#1, May 4 2006, 23:51:29) [GCC 3.4.6 (Gentoo 3.4.6-r1, ssp-3.4.5-1.0, pie-8.7.9)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> 1000 7836 0.0 0.3 15816 3540 pts/1 S+ 15:09 0:00 python >>> x = range(1000000) 1000 7836 0.2 3.8 47656 35388 pts/1 S+ 15:09 0:00 python >>> del x 1000 7836 0.2 2.9 39840 27572 pts/1 S+ 15:09 0:00 python >>> x = range(1000000) 1000 7836 0.2 3.8 48720 35460 pts/1 S+ 15:09 0:00 python >>> del x 1000 7836 0.2 2.9 40904 27644 pts/1 S+ 15:09 0:00 python >>> x = range(1000000) 1000 7836 0.2 3.8 48720 35460 pts/1 S+ 15:09 0:00 python >>> del x 1000 7836 0.2 2.9 40904 27644 pts/1 S+ 15:09 0:00 python ... Ad infinitum (see the pattern?) Convinced now that Python reuses memory? (see the sixth column for actual memory usage, the fifth is mapped memory, which contains shared libraries, etc.) The list is about 32MB in size (see the initial jump from 3MB to 35MB), but only adds about 8MB in each iteration, which are freed in each run. --- Heiko. From tdelaney at avaya.com Tue May 9 18:50:56 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 10 May 2006 08:50:56 +1000 Subject: hyperthreading locks up sleeping threads Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6D7@au3010avexu1.global.avaya.com> OlafMeding at gmail.com wrote: > Thanks for trying and reporting the results. Both of you and Tim and > Dave have run the .py program now (all on hyper-threaded CPUs) and > none of you were able to reproduce the problem. > > So that indicates that there is something special about our PC. We > are planing to re-install Windows XP (and nothing else) and try again. Hmm - you say you've got multiple identical machines that it hangs on - were they all built by putting the same disc image on them? Or from a customised XP install? If so, that might indicate that there's something specific to the XP install. Otherwise it may well be specific to the hardware ... :( Tim Delaney From deets at nospam.web.de Mon May 22 10:33:20 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 May 2006 16:33:20 +0200 Subject: Testing for file type References: <1273iims70cu3e6@corp.supernews.com> Message-ID: <4de0ejF19o62dU1@uni-berlin.de> Andrew Robert wrote: > Hi Everyone, > > Is there a way to test if a file is binary or ascii within Python? try: open(filname).read().decode("ascii") ascii = True except UnicodeError: ascii = False Diez From daniel.huangfei at gmail.com Tue May 16 11:36:21 2006 From: daniel.huangfei at gmail.com (daniel) Date: 16 May 2006 08:36:21 -0700 Subject: what is the difference between tuple and list? In-Reply-To: <mailman.5753.1147791882.27775.python-list@python.org> References: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> <mailman.5753.1147791882.27775.python-list@python.org> Message-ID: <1147793781.665306.201910@i39g2000cwa.googlegroups.com> thank you all for replying, I'm new to python, and just reading the python tutorial now. I did not expect the FAQ to contain any relevant topics, so thanks Simon... your comments did make sense, I should have read the tutorial more thoroughly, It's not a good question, I admit. ;-) English is not my mother language, so sorry if there is any mistakes or improper expression. From steve at holdenweb.com Tue May 30 06:48:59 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 30 May 2006 11:48:59 +0100 Subject: os.time() In-Reply-To: <4e2helF1cvdleU1@uni-berlin.de> References: <mailman.6327.1148977040.27775.python-list@python.org> <4e2helF1cvdleU1@uni-berlin.de> Message-ID: <447C231B.3070108@holdenweb.com> Diez B. Roggisch wrote: > Anthony wrote: > > >>i have a problem with the os.times() command, on different Python >>versions, i get different printout: > > <snip/> > >>and on the 3 servers, the linux command: $date >>returns the same value..... >> >>any suggestions??? >>what is the command that gives me the actual time? > > > time.time(), not os.times(). The latter is for process-times. No idea why it > can become _negative, though. > > Diez WANTED: reliable benchmarks to improve Python speed/performance estimation. REWARD: the thanks of the whole community. I spent some time at the recent Need For Speed sprint addressing benchmarking questions, and discovered that we need more benchmark tests for speed and perfomance. Sean Reifenshneider seems to be on the trail of one addition, but the, more the merrier. It's not easy to write good benchmarks ... regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From bignose+hates-spam at benfinney.id.au Thu May 18 17:46:34 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 May 2006 07:46:34 +1000 Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: <87psibknut.fsf@benfinney.id.au> "akameswaran at gmail.com" <akameswaran at gmail.com> writes: > The UFO comparison is silly, UFO sightings being based on time and > space coordinates are inherently unreviewable. Ed's code and his > analysis methods can be repeated (didn't say they were repeated, > just they can be). Until we get the code to examine independently, all we have is an anecdote. Thus the comparison to UFO sightings. -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From michele.petrazzo at TOGLIunipex.it Sat May 6 04:56:20 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Sat, 06 May 2006 08:56:20 GMT Subject: python 2.5a2, gcc 4.1 and memory problems Message-ID: <UwZ6g.111186$A83.2617718@twister1.libero.it> Hi list, I'm doing some tests on my debian testing and I see a very strange memory problem with py 2.5a2 (just downloaded) and compiled with gcc 4.1.0, but not with the gcc 3.3.5: My test are: #--test.py import sys if sys.version.startswith("2.3"): from sets import Set as set b=set(range(5000000)) a=set(range(100000)) c = b-a for i in 3 4 5; do echo "python 2.$i" && time python2.$i test.py; done My configure args for compile py 2.5a2 are: michele:~/Python-2.5a2$ export CC=gcc-4.1 michele:~/Python-2.5a2$ export CXX=g++-4.1 michele:~/Python-2.5a2$ ./configure --prefix=/usr --enable-shared michele:~/Python-2.5a2$ make michele:~/Python-2.5a2$ make install michele:~/Python-2.5a2$ export CC=gcc-3.3 michele:~/Python-2.5a2$ export CXX=g++-3.3 michele:~/Python-2.5a2$ ./configure --prefix=/usr --enable-shared michele:~/Python-2.5a2$ make michele:~/Python-2.5a2$ make install Then I execute my test. The memory usage of 2.5a2 and gcc 3.3 that I see with "top", is the same (about VIRT: 260 MB and RES: 250MB ) that with the py 2.3 and 2.4, but then I recompile with 4.1 and execute the same test, my system "stop to work"... with "top" I can see that it use VIRT: 2440 MB and RES: 640MB RAM (I think all that I have into my pc) I haven't tried to recompile py 2.4 myself with gcc 4.1 because it is already compiled with it (4.0.3), so I think (only think) that is a py 2.5 problem. I'm right? or I have to compile it with something other switches? Thanks, Michele From http Sun May 14 16:29:59 2006 From: http (Paul Rubin) Date: 14 May 2006 13:29:59 -0700 Subject: Question regarding checksuming of a file References: <126d1u4ke4itg7f@corp.supernews.com> <roy-1E8950.21485413052006@reader1.panix.com> <126d3g8tkfovs19@corp.supernews.com> <1147593420.907522.325920@i40g2000cwc.googlegroups.com> <7xhd3tav56.fsf@ruckus.brouhaha.com> <126ev127h04e2bb@corp.supernews.com> Message-ID: <7xiro8qri0.fsf@ruckus.brouhaha.com> Andrew Robert <andrew.arobert at gmail.com> writes: > When I run the script, I get an error that the file object does not have > the attribute getblocks. Woops, yes, you have to call getblocks(f). Also, Heiko says you can't use "return" to break out of the generator; I thought you could but maybe I got confused. From nospam at nospam.nospam Mon May 15 08:23:32 2006 From: nospam at nospam.nospam (Nic) Date: Mon, 15 May 2006 14:23:32 +0200 Subject: List and order References: <446842f7$0$14785$4fafbaef@reader4.news.tin.it> <1147691967.998184.285120@u72g2000cwu.googlegroups.com> Message-ID: <446872cb$0$18288$4fafbaef@reader1.news.tin.it> Hello Miki, Many thanks for the support. I tried to insert and execute the code, but the following error happens: Traceback (most recent call last): File "grafodna.py", line 10, in ? edges.sort(key = lambda u, v: (ddeg(u), ddeg(v))) TypeError: <lambda>() takes exactly 2 arguments (1 given) Do you know how is it possible to delete it? Thanks. Nic "Miki" <miki.tebeka at gmail.com> ha scritto nel messaggio news:1147691967.998184.285120 at u72g2000cwu.googlegroups.com... > Hello Nic, > > Python lists has a very powerfull buid-in "sort". > > edges = list(G.edges()) > edges.sort(key = lambda u, v: (ddeg(u), ddeg(v))) > for u, v in edges: > print u,v, # Note the training comma to avoid newline > print > > HTH, > Miki > http://pythonwise.blogspot.com > From tschaef at sbcglobal.net Tue May 16 09:48:43 2006 From: tschaef at sbcglobal.net (numeromancer) Date: 16 May 2006 06:48:43 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147787323.424608.311000@j73g2000cwa.googlegroups.com> An old debate. My $0.02 : http://numeromancer.dyndns.org/~timothy/tab-width-independence/description.html The idea can be extended to other programming languages. TS From onurb at xiludom.gro Wed May 24 08:53:49 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 24 May 2006 14:53:49 +0200 Subject: Python Programming Books? In-Reply-To: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> Message-ID: <447457ca$0$24922$626a54ce@news.free.fr> herraotic at googlemail.com wrote: (snip) > So now i'm hear to use all of your collective expertise for the ideal > book for a beginning programming who want's to start with python. 'ideal' greatly depends on the reader !-) But FWIW, this is a FAQ (well : 2): http://www.python.org/doc/faq/general/#i-ve-never-programmed-before-is-there-a-python-tutorial http://www.python.org/doc/faq/general/#are-there-any-books-on-python And you may get good answers here: http://wiki.python.org/moin/BeginnersGuide/NonProgrammers and by googling this ng (someone asked the same question yesterday...). HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From 1usa at llenroc.ude.invalid Thu May 25 17:28:41 2006 From: 1usa at llenroc.ude.invalid (A. Sinan Unur) Date: Thu, 25 May 2006 21:28:41 GMT Subject: Go "help" the perl list instead Fredrik Lundh References: <mailman.6205.1148585963.27775.python-list@python.org> <jbednXMRKL1RgOvZRVn-qQ@comcast.com> Message-ID: <Xns97CEB1D6156A2asu1cornelledu@127.0.0.1> D H <no at spam.please> wrote in news:jbednXMRKL1RgOvZRVn-qQ at comcast.com: > You obviously ignored that and invented some argument that he > posted with malicious intentions. That better describes most of > your thousands of annoying posts. I don't know what describes what you did. What is the point of bringing clpmisc into this argument. Anyway, *PLONK* Sinan -- A. Sinan Unur <1usa at llenroc.ude.invalid> (remove .invalid and reverse each component for email address) From robert.kern at gmail.com Wed May 10 19:48:33 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 10 May 2006 18:48:33 -0500 Subject: segmentation fault in scipy? In-Reply-To: <1147303366.635169.305300@q12g2000cwa.googlegroups.com> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <mailman.5571.1147301063.27775.python-list@python.org> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> Message-ID: <e3tu4i$9ip$1@sea.gmane.org> conor.robinson at gmail.com wrote: > Good point. Finding the SSE using an absolute error matrix of (25000 x > 1) is insane. I pulled out the error function (for now) and I'm back > in business. Thanks for all the great advise. Could you go back for a second and describe your problem a little bit more. It sounds like you were doing the wrong operation. By SSE, you mean "Sum of Squared Errors" of the 25000 length-80 vectors, right? In that case, using matrix multiplication won't give you that. That will, in essence calculate the dot-product of each of the 25000 length-80 vectors with *each* of the other 25000 length-80 vectors in addition to themselves. It seems to me like you want something like this: SSE = sum(error * error, axis=-1) Then SSE.shape == (25000,). -- 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 tbrkic at yahoo.com Thu May 18 13:14:05 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 10:14:05 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147947048.303912.109150@38g2000cwa.googlegroups.com> <446c5a80$0$7024$636a55ce@news.free.fr> <mailman.5873.1147952119.27775.python-list@python.org> <1147958226.200557.264850@j33g2000cwa.googlegroups.com> <446c7b51$0$7040$636a55ce@news.free.fr> Message-ID: <1147972445.573698.54080@i40g2000cwc.googlegroups.com> I'm answering two of you posts here... > Sweet Lord, have mercy ! > > > Which should create myList = [[0..9], {0:0, ... 9:9}] > > myList = [ > range(10), > dict((i, i) for i in range(10)) > ] > Let's talk about readability.... My code was just to show that the proposal is not only for HTML generation but could be used whenever you want to create COMPLEX hierarcical datastructures. In the above example I would of course use what you wrote. Do I need to show you a example where you cant use the style you showed? > Strange enough, working with trees is nothing new, and it seems that > almost anyone managed to get by without cryptic 'operators' stuff. Strange enough once almost anyone managed to get by without Python... :-) > > I used HTML as example since it is a good > > example and > > most people would understand the intention. > >Sorry for being dumb. It not your fault :-) > > But could you elaborate on your comment that it is unusable. > > Ask all the coders that switched from Perl to Python why they did so... You seem to really have a thing for Perl... >From what you written I assume you mean that it is no good because you find the syntax cryptic. For me cryptic is for example how you in Perl create list of lists, ie it takes a while to understand and when you havent done in a while youyou have to relearn it. Python has a few of those aswell... but you really only need them when doing something cryptic... IMO what I propose isnt cryptic, because of * I think after it has been explained it is no problem to understand how it works. * It doesnt have strange sideeffects * Doesnt break any old code. * You dont have to relearn if you havent done it a while. Also if you never would have seen such code before, I think you would understand what is meant and even be able to modify it. From kentilton at gmail.com Sun May 7 10:05:12 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sun, 07 May 2006 10:05:12 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1146982654.897283.293390@y43g2000cwc.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> Message-ID: <r8n7g.10$Q17.3@fe08.lga> Serge Orlov wrote: > Ken Tilton wrote: > >>It is vastly more disappointing that an alleged tech genius would sniff >>at the chance to take undeserved credit for PyCells, something probably >>better than a similar project on which Adobe (your superiors at >>software, right?) has bet the ranch. This is the Grail, dude, Brooks's >>long lost Silver Bullet. And you want to pass????? >> >>C'mon, Alex, I just want you as co-mentor for your star quality. Of >>course you won't have to do a thing, just identify for me a True Python >>Geek and she and I will take it from there. >> >>Here's the link in case you lost it: >> >> http://www.lispnyc.org/wiki.clp?page=PyCells >> >>:) >> >>peace, kenny >> >>ps. flaming aside, PyCells really would be amazingly good for Python. >>And so Google. (Now your job is on the line. <g>) k > > > Perhaps I'm missing something... yes, but do not feel bad, everyone gets confused by the /analogy/ to spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief period I swore off the analogy because it was so invariably misunderstood. Even Graham misunderstood it. But it is such a great analogy! <sigh> > but what's the big deal about PyCells? > Here is 22-lines barebones implementation of spreadsheet in Python, > later I create 2 cells "a" and "b", "b" depends on a and evaluate all > the cells. The output is > > a = negate(sin(pi/2)+one) = -2.0 > b = negate(a)*10 = 20.0 Very roughly speaking, that is supposed to be the code, not the output. So you would start with (just guessing at the Python, it has been years since I did half a port to Python): v1 = one a = determined_by(negate(sin(pi/2)+v1) b = determined_by(negate(a)*10) print(a) -> -2.0 ;; this and the next are easy print(b) -> 20 v1 = two ;; fun part starts here print(b) -> 40 ;; of course a got updated, too The other thing we want is (really inventing syntax here): on_change(a,new,old,old-bound?) print(list(new, old, old-bound?) Then the print statements Just Happen. ie, It is not as if we are just hiding computed variables behind syntax and computations get kicked off when a value is read. Instead, an underlying engine propagates any assignment throughout the dependency graph before the assignment returns. My Cells hack does the above, not with global variables, but with slots (data members?) of instances in the CL object system. I have thought about doing it with global variables such as a and b above, but never really seen much of need, maybe because I like OO and can always think of a class to create of which the value should be just one attribute. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From mirandacascade at yahoo.com Sun May 7 16:55:07 2006 From: mirandacascade at yahoo.com (mirandacascade at yahoo.com) Date: 7 May 2006 13:55:07 -0700 Subject: the tostring and XML methods in ElementTree Message-ID: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> O/S: Windows XP Home Vsn of Python: 2.4 Copy/paste of interactive window is immediately below; the text/questions toward the bottom of this post will refer to the content of the copy/paste >>> from elementtree import ElementTree >>> beforeRoot = ElementTree.Element('beforeRoot') >>> beforeCtag = ElementTree.SubElement(beforeRoot, 'C') >>> beforeCtag.text = 'I\x92m confused' >>> type(beforeCtag.text) <type 'str'> >>> print beforeCtag.text I'm confused >>> resultToStr = ElementTree.tostring(beforeRoot) >>> resultToStr '<beforeRoot><C>I’m confused</C></beforeRoot>' >>> afterRoot = ElementTree.XML(resultToStr) >>> afterCtag = afterRoot[0] >>> type(afterCtag.text) <type 'unicode'> >>> print afterCtag.text I?m confused >>> I wanted to see what would happen if one used the results of a tostring method as input into the XML method. What I observed is this: a) beforeCtag.text is of type <type 'str'> b) beforeCtag.text when printed displays: I'm confused c) afterCtag.text is of type <type 'unicode'> d) afterCtag.text when printed displays: I?m confused Question 1: assuming the following: a) beforeCtag.text gets assigned a value of 'I\x92m confused' b) afterRoot is built using the XML() method where the input to the XML() method is the results of a tostring() method from beforeRoot Are there any settings/arguments that could have been modified that would have resulted in afterCtag.text being of type <type 'str'> and afterCtag.text when printed displays: I'm confused ? Another snippet from interactive window >>> resultToStr2 = ElementTree.tostring(beforeRoot, encoding="utf-8") >>> resultToStr2 '<beforeRoot><C>I’m confused</C></beforeRoot>' >>> if resultToStr == resultToStr2: ... print 'equal' ... equal >>> If I'm reading the signature of the tostring method in ElementTree.py correctly, it looks like encoding gets assigned a value of None if the tostring method gets called without a 2nd argument. In the specific examples above, the result of the tostring method was the same when an encoding of utf-8 was specified as it was when no encoding was specified. Question 2: Does the fact that resultToStr is equal to resultToStr2 mean that an encoding of utf-8 is the defacto default when no encoding is passed as an argument to the tostring method, or does it only mean that in this particular example, they happened to be the same? Another snippet >>> fileHandle = open('c:/output1.text', 'w') >>> fileHandle.write(beforeCtag.text) >>> fileHandle.write(afterCtag.text) Traceback (most recent call last): File "<interactive input>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\x92' in position 1: ordinal not in range(128) >>> encodedCtagtext = afterCtag.text.encode("utf-8") >>> type(encodedCtagtext) <type 'str'> >>> encodedCtagtext 'I\xc2\x92m confused' >>> print encodedCtagtext I?'m confused >>> fileHandle.write(encodedCtagtext) >>> ord(encodedCtagtext[1]) 194 >>> In this snippet, I am trying to discern what can be written to a file without raising an exception. The variable beforeCtag.text can be written, but an exception is raised when an attempt is made to write the unicode variable afterCtag.text to the file. The statement encodedCtagtext = afterCtag.text.encode("utf-8") was a shot-in-the-dark attempt to transform afterCtag.text to something that can be written to a file without raising an exception. What I observed is that: a) encodedCtagtext can be written to a file without raising an exception b) the second character in encodedCtagtext has an ordinal value of 194 Questions 3 and 4: 3) would it be possible to construct a statement of the form newResult = afterCtag.text.encode(?? some argument ??) where newResult was the same as beforeCtag.text? If so, what should the argument be to the encode method? 4) what is the second character in encodedCtagtext (the character with an ordinal value of 194)? From tomerfiliba at gmail.com Sun May 7 17:13:32 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 7 May 2006 14:13:32 -0700 Subject: released: RPyC 2.55 Message-ID: <1147036412.383008.179810@e56g2000cwe.googlegroups.com> Remote Python Call (RPyC) - transparent and symmetrical python RPC and distributed computing library download and info: http://rpyc.wikispaces.com full changelog: http://rpyc.wikispaces.com/changelog release notes: http://rpyc.wikispaces.com/release+notes major changes: * added isinstance and issubclass for remote objects * moved to tlslite for authentication and encryption * added server discovery (using UDP broadcasts) * refactoring -tomer From ronnyma at math.uio.no Mon May 1 12:17:34 2006 From: ronnyma at math.uio.no (RonnyM) Date: 1 May 2006 09:17:34 -0700 Subject: Numeric, vectorization Message-ID: <1146500254.216411.166700@u72g2000cwu.googlegroups.com> Hello. I want to vectorize this operation, which below is implemented as a for-loop: def smoothing_loop( y ): #y is an array with noisy values ybar = [] ybar.append( y[0] ) #Smoothing with a loop length = size( y ) for i in range( 1, length -1 ): ybar.append( .5 * ( y[ i-1 ] + y[ i + 1 ] ) ) e.g. y = [ 1, 2, 3, 4, 5, 6 ,7 ,8, 9 ] ybar = [ 1, (1 + 3)*.5,(2 + 4)*.5,(3 + 5)*.5,..., (n-1 + n+1)*.5 ], n = 1,...len(y) -1 How do I make a vectorized version of this, I will prefer not to utilize Map or similar functions, but numeric instead. Regards, Ronny Mandal From fredrik at pythonware.com Fri May 5 05:12:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 5 May 2006 11:12:14 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com><4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com><mailman.5248.1146637412.27775.python-list@python.org> <445880e8$0$27057$626a54ce@news.free.fr><mailman.5305.1146727852.27775.python-list@python.org> <4459c1e5$0$2617$636a55ce@news.free.fr> Message-ID: <e3f4te$4pm$1@sea.gmane.org> Christophe wrote: > I think you've made a mistake in your example. >>> constant A = [] >>> def foo(var): ... var.append('1') ... print var ... >>> b = A >>> foo(b) >>> foo(b) > > and this ? > > > > >>> constant A = [] > > >>> print A is A > > Obviously, False. why obviously ? why shouldn't a constant be constant ? </F> From rdh at new.rr.com Tue May 30 10:12:36 2006 From: rdh at new.rr.com (DataSmash) Date: 30 May 2006 07:12:36 -0700 Subject: Linking onClick event to other controls on the Frame References: <1148669541.274757.136760@i40g2000cwc.googlegroups.com> <1148813268.210808.102600@i39g2000cwa.googlegroups.com> Message-ID: <1148998355.931946.169730@38g2000cwa.googlegroups.com> Hi Miki, I appreciate you taking the time to figure out what I was trying to do. This is exactly what I was looking for. I plan on studing this code and looking at the wxpython demo as you mentioned. Thanks again! R.D. Harles From python-url at phaseit.net Mon May 15 13:51:02 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 15 May 2006 17:51:02 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 15) Message-ID: <e4af26$o2m$1@lairds.us> QOTW: "It seems if you lurk here [on comp.lang.python] long enough you eventually get all you[r] questions answered without even asking!" - Ted Landis "We're going to learn from Python. JavaScript is pretty close to Python" - Brendan Eich Scott David Daniels shows how to find all occurrences of a string in another string without using regular expressions. http://groups.google.com/group/comp.lang.python/msg/f19cdf6de899c755 Learn more about Python string formating by watching James Tauber as he develops a simple templating system in twelve steps. http://jtauber.com/2006/05/templates.html Steven Bethard extends optparse's OptionParser to check for positional arguments. http://groups.google.com/group/comp.lang.python/msg/9c363a089d70fcbb Miki Tebeka and Cameron Laid use the CherryPy web framework and Cheetah template engine to build a small addressbook application. http://www.unixreview.com/documents/s=10075/ur0604h/ Alex Martelli calculates the "length" of a generator. Whether it would be a good idea to incorporate the approach into the built-in len() function is discussed in the same thread. http://groups.google.com/group/comp.lang.python/msg/3ec6fd2119192bd0 Pythonthreads has an interview with Titus Brown, developer of twill, a tool for automated web crawling and scraping. http://www.pythonthreads.com/articles/interviews/python-community-is-extremely-active-in-building-agile-testing-tools..html Brendan Eich, the creator of JavaScript, draws inspiration from Python for the evolution of his language. http://www.pcwelt.de/news/englishnews/137850/index.html ======================================================================== Everything Python-related you want is probably one or two clicks away in these pages: Python.org's Python Language Website is the traditional center of Pythonia http://www.python.org Notice especially the master FAQ http://www.python.org/doc/FAQ.html PythonWare complements the digest you're reading with the marvelous daily python url http://www.pythonware.com/daily Mygale is a news-gathering webcrawler that specializes in (new) World-Wide Web articles related to Python. http://www.awaretek.com/nowak/mygale.html While cosmetically similar, Mygale and the Daily Python-URL are utterly different in their technologies and generally in their results. 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, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python 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 <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From johnjsal at NOSPAMgmail.com Tue May 9 21:10:42 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 21:10:42 -0400 Subject: multiline strings and proper indentation/alignment In-Reply-To: <mailman.5527.1147204632.27775.python-list@python.org> References: <Ms48g.2070$No6.45827@news.tufts.edu> <mailman.5527.1147204632.27775.python-list@python.org> Message-ID: <44613e5d$0$9438$c3e8da3@news.astraweb.com> Gary Herron wrote: > Gary John Salerno wrote: > >> How do you make a single string span multiple lines, but also allow >> yourself to indent the second (third, etc.) lines so that it lines up >> where you want it, without causing the newlines and tabs or spaces to be >> added to the string as well? >> >> Example (pretend this is all on one line): >> >> self.DTD = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML >> 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n\n' >> >> I want it to read: >> >> self.DTD = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n >> "http://www.w3.org/TR/html4/strict.dtd">\n\n''' >> >> Or anything like that, but I don't want the extra newline or tabs to be >> a part of the string when it's printed. >> >> Thanks. >> >> > The textwrap module has a function to do just the thing you want. > > *dedent*( text) > > Remove any whitespace that can be uniformly removed from the left of > every line in text. > > This is typically used to make triple-quoted strings > line up with the left edge of screen/whatever, while still > presenting it in the source code in indented form. > > Gary Herron > > But does this do anything to the newline character that gets added to the end of the first line? From anyab5 at gmail.com Sun May 14 07:24:09 2006 From: anyab5 at gmail.com (anya) Date: 14 May 2006 04:24:09 -0700 Subject: send an email with picture/rich text format in the body Message-ID: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> Hey, I have a certain problem and till now I didnt find an answer on the web. I want to send an email message with picture in it. I dont want to put it as attachment but make it in the body of the mail, so every one who open the email will see the picture.. (it is possible that the solution will be in any other format that will be opened i.e pdf, doc and I will put this in the body ) Neither in MimeWriter nor using the definition of MymeTypes I was able to do it .. Does anyone have a solution? Thanks From cvanarsdall at mvista.com Wed May 24 12:00:07 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 24 May 2006 09:00:07 -0700 Subject: Best way to handle exceptions with try/finally In-Reply-To: <1148481073.976420.316970@j55g2000cwa.googlegroups.com> References: <mailman.6122.1148413632.27775.python-list@python.org> <pan.2006.05.24.11.59.47.24496@thomas-guettler.de> <1148481073.976420.316970@j55g2000cwa.googlegroups.com> Message-ID: <44748307.2040308@mvista.com> Zameer wrote: > That's it. But the return statement should not be a part of finally if > you want exceptions to propagate out of the function containing > try/finally. As mentioned multiple times in the thread. > Ah, great, that was it. Thanks to everyone for their help, I got a lot of really useful information from your replies. I tend to put "return" statements at the end of functions to make an attempt at being clean. I realize that a lot of the time functions will just return but I was hoping by explicitly stating my function returns that another person reading my code would more easily see any exit points in my code. Turns out that it came to bite me later. Again, thanks to all your help and comments on my coding style. .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From ullrich at math.okstate.edu Mon May 8 17:06:49 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Mon, 08 May 2006 16:06:49 -0500 Subject: A critic of Guido's blog on Python's lambda References: <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> Message-ID: <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> On 08 May 2006 12:53:09 -0700, tfb at conquest.OCF.Berkeley.EDU (Thomas F. Burdick) wrote: >Ken Tilton <kentilton at gmail.com> writes: > >> No, you do not want on-change handlers propagating data to other >> slots, though that is a sound albeit primitive way of improving >> self-consistency of data in big apps. The productivity win with >> VisiCalc was that one simply writes rules that use other cells, and >> the system keeps track of what to update as any cell changes for >> you. You have that exactly backwards: every slot has to know what >> other slots to update. Ick. > >No no, that's fine and the way it should be: when you change a slot, >it should know who to update. And that's also the way it works in >Cells. The trick is that Cells takes care of that part for you: I'm glad you said that - this may be what he meant, but it seems more plausible than what he actually said. > all >the *programmer* has to care about is what values a slot depends on -- >Cells takes care of inverting that for you, which is important because >that's a job that a computer is much better at than a human. Fine. I suppose that is better; if b is going to return a + 1 the fact that this is what b returns should belong to b, not to a. So a has an update list including b, so when a's value is set a tells b it needs to update itself. If we're allowed to pass (at some point, to some constructor or other) something like (b, a + 1, [a]), which sets up a cell b that shall return a + 1, and where the [a] is used in the constructor to tell a to add b to a's update list then this seems like no big deal. And doing that doesn't seem so bad - now when the programmer is writing b he has to decide that it should return a + 1 and also explicitly state that b shall depend on a; this is all nice and localized, it's still _b_ telling _a_ to add b to a's update list, and the programmer only has to figure out what _b_ depends on when he's writing _b_. Doesn't seem so bad. But of course it would be better to be able to pass just something morally equivalent to (b, a + 1) to whatever constructor and have the system figure out automatically that since b returns a + 1 it has to add a to b's update list. There must be some simple trick to accomplish that (using Python, without parsing code). (I begin to see the point to the comment about how the callbacks should fire when things are constucted.) Exactly what the trick is I don't see immediately. In Cells do we just pass a rule using other cells to determine this cell's value, or do we also include an explicit list of cells that this cell depends on? ************************ David C. Ullrich From redefined.horizons at gmail.com Tue May 16 11:52:41 2006 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 16 May 2006 08:52:41 -0700 Subject: Help System For Python Applications Message-ID: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> I did some searching for this topic, but couldn't find anything. A search of this list only turned up an old post from 2002. I'd like to add a comprehesive help system to my Python Application. By "comprehensive" I mean regular "read-like-a-book" help and context sensitive help that can be launched from the application. Is there an existing system in Python that would support this, or would I need to start from scratch? On a related note, is there a way to fire up Adobe's Acorbat Reader or and Web Browser from Python and have the external application open a specified PDF or HTML file? (For example, I want to open the file "myhelp.pdf" in reader from Python code.) Could you give me an example of the code that would do this? Thanks for all the help on my help. :] Scott Huey From fredrik at pythonware.com Tue May 9 10:50:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 May 2006 16:50:26 +0200 Subject: lines of code per functional point References: <e3q96g$uk9$1@sea.gmane.org> Message-ID: <e3qa7f$2qs$1@sea.gmane.org> Bryan wrote: > in document, which is titled, "Java and programmer productivity", there is a > table on page 4 which shows LOC/FP for several languages. unfortunately, python > is the only language "dashed out" and has no value. i'm unable to google and > find a source that shows this value for python if you google for "python loc/fp" in google groups, you'll find a couple of threads that discusses this (including this one). from what I can tell, the consensus is that Perl and Python has a very similar LOC/FP value (15-25, depending on who you ask), but that people are more productive in Python anyway... </F> From pydecker at gmail.com Mon May 15 12:48:13 2006 From: pydecker at gmail.com (Peter Decker) Date: Mon, 15 May 2006 12:48:13 -0400 Subject: Tabs versus Spaces in Source Code In-Reply-To: <f35bcf140605142141n373a6d27xb19abd095a62ddf8@mail.gmail.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <f35bcf140605142141n373a6d27xb19abd095a62ddf8@mail.gmail.com> Message-ID: <ca55a9900605150948p2318b2b5vd607da18ab8c43a3@mail.gmail.com> On 5/15/06, Chris Klaiber <cklaiber at gmail.com> wrote: > The problem comes when the author prefers a smaller tab width than what my > editor is set to. Sure, I could change it for that file, but what if I'm > reading a whole directory? Sure, I could change the default setting in my > editor, but what if I'm browsing multiple projects in the same day? Sure, I > could find a way to set the tab width based on the directory I'm currently > in, but by now I'm annoyed and simply replacing tabs with spaces is a far > simpler solution that requires zero configuration on my part. Funny, I was going to say that the problem is when the author prefers a font with a differntly-sized space. Some of us got rid of editing in fixed-width fonts when we left Fortran. -- # p.d. From ptmcg at austin.rr._bogus_.com Wed May 17 19:15:59 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 17 May 2006 23:15:59 GMT Subject: Pyparsing: Specify grammar at run time References: <mailman.5845.1147902428.27775.python-list@python.org> Message-ID: <P8Oag.41872$CH2.13029@tornado.texas.rr.com> "Khoa Nguyen" <khoa.coffee at gmail.com> wrote in message news:mailman.5845.1147902428.27775.python-list at python.org... I run into another issue with my grammar: My input record contains a common part and an extended part. Based on the value of the common part, the extended part will be different. So, I am thinking of parsing the common part first and check the common's value and then parse again for the rest of the record. How do I tell pyparsing to start the 2nd parse at the exact location where the 1st parse left off? ###################################### from pyparsing import * common = Word('aA').setResultsName('value') extend1 = Word('b') extend2 = Word('c') result = common.parseString(record) if result.value == 'a': result1 = extend1.parseString(???) else: result2 = extend2.parseString(???) ###################################### Thanks, Khoa Any reason you can't construct a grammar that looks like: allData = "a" From micklee74 at hotmail.com Mon May 8 04:11:30 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 8 May 2006 01:11:30 -0700 Subject: printing out elements in list In-Reply-To: <pan.2006.05.08.08.05.26.437021@gmail.com> References: <1147074279.391832.158350@y43g2000cwc.googlegroups.com> <pan.2006.05.08.08.05.26.437021@gmail.com> Message-ID: <1147075890.042861.250650@i40g2000cwc.googlegroups.com> thanks for all your replies...I will go test them out.. I was wondering what does this mean alist[1::2]? thanks From Bulkan at gmail.com Fri May 12 03:41:49 2006 From: Bulkan at gmail.com (placid) Date: 12 May 2006 00:41:49 -0700 Subject: Threads In-Reply-To: <slrne68ddu.qon.sybrenUSE@schuimige.stuvel.eu> References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <jq8862dcirmmj5atp7tdv2q7t032ansquh@4ax.com> <1147417744.770080.11490@q12g2000cwa.googlegroups.com> <slrne68ddu.qon.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1147419709.500563.120190@i39g2000cwa.googlegroups.com> Sybren Stuvel wrote: > placid enlightened us with: > >> Did you read the documentation for Queue methods? > > > > there is no need to be patronizing about this dude, im just learning > > Python in my spare time, as im a Intern Software Engineer > > There is nothing patronizing about the question, it's merely an > enquiry to a possible fact. If you're going to be a techie, you should true enough > learn stuff like that. its always said that (in programming) that the easiest solution to a problem is hard to find, well for me posting my question here was the hardest, when the easier solution was for me to go look at the Python documentation! > > Sybren > -- > The problem with the world is stupidity. Not saying there should be a > capital punishment for stupidity, but why don't we just take the > safety labels off of everything and let the problem solve itself? > Frank Zappa From michele.simionato at gmail.com Fri May 12 08:40:56 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 May 2006 05:40:56 -0700 Subject: New tail recursion decorator In-Reply-To: <1147436852.364490.99440@u72g2000cwu.googlegroups.com> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <Xns97BF8E839A8D1duncanbooth@127.0.0.1> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> Message-ID: <1147437656.779139.54840@d71g2000cwd.googlegroups.com> Tim N. van der Leeuw wrote: > > I don't know why it wouldn't work this way, or why it isn't > tail-recursion? >From the google page do "define: tail recursion" > I tried the tail_recursion decorator from the cookbook-recipe with both > definitions of factorial, and I tried both definitions of the factorial > function with and without tail_recursion decorator. > In all four cases I get the same results, so it does work with both > definitions of factorial(), even if (according to you) the second > definition is not proper tail-recursion. For me factorial(1001) with the second definition does not work, I get the recursion limit (which is what I expect). I suppose the recursion limit is higher on your system, but definitely you should reach it at some point with the non tail-recursive version of factorial. > Using the tail-recursion decorator (the version that does not inspect > the stackframes) I get a small performance-increase over using the > factorial-function undecorated. > However, calculating factorial(1000) with the factorial-function as > defined in the cookbook-recipe is much much faster than calculating the > same factorial(1000) with the factorial-function you gave! > I cannot yet explain why the first function has so much better > performance than the second function - about a factor 10 difference, > in both python2.4.3 and python 2.5a2 It is because the decorator is doing is job (converting a long recursion in a loop) only with the first function, which is properly tail recursive. Just as Duncan said. Michele Simionato From grflanagan at yahoo.co.uk Mon May 22 04:36:57 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 22 May 2006 01:36:57 -0700 Subject: Generating Cutter numbers References: <1148114166.590393.176250@u72g2000cwu.googlegroups.com> <1148146441.412605.163750@j55g2000cwa.googlegroups.com> <mailman.6012.1148149024.27775.python-list@python.org> Message-ID: <1148287017.043341.267150@y43g2000cwc.googlegroups.com> Terry Reedy wrote: > "Gerard Flanagan" <grflanagan at yahoo.co.uk> wrote in message > news:1148146441.412605.163750 at j55g2000cwa.googlegroups.com... > > I'm cataloging a small library and want to generate a unique id (called > > a 'call number') for each book. This id is composed of: > > > > * Dewey 3-digit Subject Classification Number > > * Dewey Decimal (always 0 for the minute) > > * Cutter Number > > * Copy number (multiple copies or volumes) > > > > (That Celestial Emporium again...) > > > > I haven't researched it much but it seems the Cutter number is used to > > distinguish between authors with the same name, and between different > > books written by the same author - so you need last name, first name > > and title. But it may be as much art as science. > > I seems you are mixing pieces of two cataloging systems. The link you gave > was for creating Cutter numbers to represent subtopics of Library of > Congress classes. For instance, 'algorithms' is .A43. I think 'Cuttering' is a general term for identifying any given book within a subject area. Whether you use Dewey or Library of Congress system of subject classification you still need to have a way of identifying particuar books. >From the link below: <quote> [Examples of] LC (Library of Congress) call numbers: LB 1631.S686 1994 QA 76.76.H94 C36 1997 The first part of those call numbers, i.e. before the final decimal point, are the "filing numbers" as they are often called. They indicate the general subject area and are of no interest to us at this point for they are shared by all other books in this class. All libraries using the system will all use the same "pre-decimal" filing number. But ... there could still be a whole wallfull of books sharing those numbers so we still have a problem. The part of the call number that really made Cutter's system famous -- and a winner -- was the stuff after the (final) decimal point. Those are the cutter numbers -- and those are the numbers that guarantee not only every book's uniqueness, but also lead us straight to its location once we are in the right general area of the library. Cutter numbers are in a sense "relative". They are not assigned in some kind of absolute way, as are the filing numbers that precede the decimal point. Thus if a book is "about science" then its filing number will begin with a Q in a more absolute or determinate sense because Q is the Library of Congress Classification for books on science. All books using the LC system will end up giving each book the same filing number, but they are unlikely to end up giving it exactly the same cutter because every library is different and will have different books on its shelf. Cutters depend, relatively, on what other books are located in the general area in which a given book is to be placed in that particular library. So when a book has to be cuttered, then the table that Cutter provided for allocating numbers is used. However, the resulting numbers must fit into the order established by already existing books in the library. That's to say, it is the librarian's responsibility to check to be sure that no other book in this class has the same cutter number. </quote> http://mailman.code404.com/pipermail/nord-modular/2002-December/003910.html (Before clicking on the link give yourself 10 geek-points if you can complete the following sentence: <quote> The first real library -- i.e. the first one known to have systematically tried to solve the problems of maintaining a collection by imposing a "logical order" on its objects was the Great Library of Alexandria. The Great Library's first librarian was... </quote> ) Gerard From NOatkinwSPAM at rpi.edu Sat May 6 22:41:56 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 22:41:56 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1hexigt.h7vk5s1i5fkn3N%aleaxit@yahoo.com> Message-ID: <87bquay2rv.fsf@rpi.edu> aleaxit at yahoo.com (Alex Martelli) writes: > Bill Atkins <NOatkinwSPAM at rpi.edu> wrote: > ... >> Believe it or not, _you_ got it wrong. > > Acknowledged: Common Lisp is even MORE insane (note that the quote > "INSANELY extensible" is from Tilton) than I believed -- I'm pretty sure > that the Lisp dialects I used in 1979-1981 didn't go to such crazy > extremes, and neither did Scheme. > >> Buh? The project doesn't have to be late for Brooks's law to hold; >> adding programmers, so goes Brooks reasoning, will always increase the >> time required to complete the project because of various communication >> issues. > > And here is where we check if you're as gracious about admitting your > errors, as I am about mine. Brooks' law is: > > """Adding manpower to a late software project makes it later.""" > > These are Brooks' words, literally. OK so far? You are correct. I posted too hastily. Here is what my paragraph ought to have said: Buh? The project doesn't have to be late for Brooks's law to hold; adding programmers *in the middle of a project*, so goes Brooks reasoning, will always increase the time required to complete the project because of various communication issues. Agree? > Your claim, that adding programmers will ALWAYS increase the time, is > not just wrong, but utterly ridiculous. I can't put it better than the > wikipedia: > """ > Misconceptions > > A commonly understood implication of Brooks' law is that it will be more > productive to employ a smaller number of very talented (and highly paid) > programmers on a project than to employ a larger number of less talented > programmers, since individual programmer productivity can vary greatly > between highly talented and efficient programmers and less talented > programmers. However, Brooks' law does not mean that starving a project > of resources by employing fewer programmers beyond a certain point will > get it done faster. > """ > > Moreover, check out the research on Pair Programming: it scientifically, > empirically confirms that "two heads are better than one", which should > surprise nobody. Does this mean that there aren't "various > communication issues"? Of course there are, but there's no implied > weighting of these factors wrt the _advantages_ of having that second > person on the team (check the Pair Programming literature for long lists > of those advantages). > > Only empirical research can tell us where the boundary is -- when > productivity is decreased by going from N to N+1. A lot depends on > imponderable issues such as personality meshes or clashes, leadership > abilities at hands, methodology used, etc. All of this is pretty > obvious, making your assertion that Brooks held otherwise actionable (as > libel, by Brooks) in many legislations. Hahaha. > As it happens, I also have examples in which adding (a few carefully > selected) people to a software project that WAS (slightly) late put that > project back on track and made it deliver successfully on schedule. > Definitely not the "pointy-haired boss" management style of "throwing > warm bodies at the problem" that Brooks was fighting against, but, > consider: the project's velocity has suffered because [a] the tech lead > has his personal (usually phenomenal) productivity hampered by a painful > condition requiring elective surgery to abate, and [b] nobody on the > team is really super-experienced in the intricacies of cryptography, yes > some very subtle cryptographic work turns out to be necessary. One day, > the tech lead calls in -- the pain has gotten just too bad, he's going > for surgery, and will be out of the fray for at least one week. > > I still remember with admiration how my Director reacted to the > emergency: he suspended two other projects, deciding that, if THEIR > deadlines were broken, that would be a lesser damage to the company than > if this one slipped any further; and cherrypicked exactly two people -- > one incredibly flexible "jack of all trades" was tasked with getting up > to speed on the project and becoming the acting TL for it, and an > excellent cryptography specialist was tasked to dig deep into the > project's cryptography needs and solve them pronto. > > So, We Broke Brooks' Law -- the cryptographer did his magic, and > meanwhile the JOAT ramped up instantly and took the lead (kudos to the > Jack's skills, to the clarity and transparency of the previous TL's > work, to the agile methodologies employed throughout, AND to the > uniformity of style of one language which will stay unnamed here)... and > the project delivered on time and within budget. We had one extra > person (two "replacements" for one TL's absence), yet it didn't make the > late software project even later -- it brought it back on track > perfectly well. > > I have many other experiences where _I_ was that JOAT (and slightly > fewer ones where I was the specialist -- broadly speaking, I'm more of a > generalist, but, as needs drive, sometimes I do of necessity become the > specialist in some obscure yet necessary technology... must have > happened a dozen times over the 30 years of my careers, counting > graduate school...). > > This set of experiences in no way tarnishes the value of Brooks' Law, > but it does *put it into perspective*: done JUST RIGHT, by sufficiently > brilliant management, adding A FEW people with exactly the right mix of > skills and personality to a late software project CAN save the bacon, > > >> Fair enough. But what does Python offer above any garbage-collected >> language that makes it so scalable? > > Uniformity of style, facilitating egoless programming; a strong cultural > bias for simplicity and clarity, and against cleverness and obscurity; > "just the right constraints" (well, mostly;-), such as immutability at > more or less the right spots (FP languages, with _everything_ immutable, > have an edge there IN THEORY... but in practice, using them most > effectively requires a rare mindset/skillset, making it hard to "scale > up" teams due to the extra difficulty of finding the right people). > > > Alex -- This is a song that took me ten years to live and two years to write. - Bob Dylan From gregory.petrosyan at gmail.com Fri May 26 11:16:06 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 26 May 2006 08:16:06 -0700 Subject: Speed up this code? In-Reply-To: <1148649951.816182.134210@g10g2000cwb.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <4476d3ac_2@newspeer2.tds.net> <1148647447.804097.228580@j33g2000cwa.googlegroups.com> <1148649951.816182.134210@g10g2000cwb.googlegroups.com> Message-ID: <1148656566.089446.159470@y43g2000cwc.googlegroups.com> # Paul Rubin's version gregory at home:~$ python -mtimeit "import test2" "test2.primes(1000)" 100 loops, best of 3: 14.3 msec per loop # version from the Cookbook gregory at home:~$ python -mtimeit "import test1" "test1.primes(1000)" 1000 loops, best of 3: 528 usec per loop From sam at nuevageorgia.com Thu May 18 10:09:15 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 18 May 2006 07:09:15 -0700 Subject: Python - Web Display Technology In-Reply-To: <mailman.5872.1147945818.27775.python-list@python.org> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5872.1147945818.27775.python-list@python.org> Message-ID: <1147961355.652526.230610@i39g2000cwa.googlegroups.com> I guess there isn't much to understand. If you are satisfied with a text based, static image web, that is light on artistic possabilities, all that HTML stuff is acceptable. Perhaps the HTML/JS group will even get off their rear ends and bring some decent cross platform graphics capabilities to the web one decade? Perhaps even bring some 90's style graphics to the browser one decade? WC3 at Work - Beware Falling Luddites From ian at excess.org Mon May 1 19:54:17 2006 From: ian at excess.org (Ian Ward) Date: Mon, 01 May 2006 19:54:17 -0400 Subject: ANN: Urwid 0.9.4 - Console UI Library Message-ID: <44569FA9.1050603@excess.org> Announcing Urwid 0.9.4 ---------------------- Urwid home page: http://excess.org/urwid/ Tarball: http://excess.org/urwid/urwid-0.9.4.tar.gz About this release: =================== This release adds mouse event handling to the standard widgets and example programs. Also, the files used to generate the reference and tutorial documentation are now included in the tarball. New in this release: ==================== - Enabled mouse handling across the Urwid library. Added a new mouse_event(..) method to the Widget interface definition and to the following widgets: Edit, CheckBox, RadioButton, Button, GridFlow, Padding, Filler, Overlay, Frame, Pile, Columns, BoxAdapter and ListBox. Updated example programs browse.py, calc.py, dialog.py, edit.py and tour.py to support mouse input. - Released the files used to generate the reference and tutorial documentation: docgen_reference.py, docgen_tutorial.py and tmpl_tutorial.html. The "docgen" scripts write the documentation to stdout. docgen_tutorial.py requires the Templayer HTML templating library to run. - Improved Widget and List Walker interface documentation. - Fixed a bug in the handling of invalid UTF-8 data. All invalid characters are now replaced with '?' characters when displayed. About Urwid =========== Urwid is a console UI library for Python. It features fluid interface resizing, UTF-8 support, multiple text layouts, simple attribute markup, powerful scrolling list boxes and flexible interface design. Urwid is released under the GNU LGPL. From pain.and.cookies at gmail.com Wed May 3 21:24:20 2006 From: pain.and.cookies at gmail.com (klauts) Date: 3 May 2006 18:24:20 -0700 Subject: Packet finding and clicking... In-Reply-To: <1146526807.262200.247870@u72g2000cwu.googlegroups.com> References: <1146526807.262200.247870@u72g2000cwu.googlegroups.com> Message-ID: <1146705860.347800.219720@y43g2000cwc.googlegroups.com> anyone have any help on this subjecT? From julien.arnoux at ext.cri74.org Fri May 19 08:47:10 2006 From: julien.arnoux at ext.cri74.org (Julien ARNOUX) Date: Fri, 19 May 2006 14:47:10 +0200 Subject: Python sqlite and regex. Message-ID: <1148042830.29145.5.camel@localhost.localdomain> Hi, I'd like to use regular expressions in sqlite query, I using apsw module but it doesn't work...Can you help me ? My script: import apsw import re path = 'db/db.db3' #regexp function (extract from python-list discusion) def regexp(expr, item): reg = re.compile(expr) return reg.match(item) is not None con = apsw.Connection(path) #create function con.createscalarfunction("REGEXP", regexp) cur = con.cursor() #exampl cur.execute("select foo from test where foo regex 'aa.[0-9])") and the error is: cur.execute('select foo from test where foo regex tata') apsw.SQLError: SQLError: near "regex": syntax error Thanks From http Fri May 26 14:50:42 2006 From: http (Paul Rubin) Date: 26 May 2006 11:50:42 -0700 Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> <1148650269.190130.209840@i39g2000cwa.googlegroups.com> <Xns97CF9CDFFB09Cduncanbooth@127.0.0.1> <1148655313.422226.297700@i40g2000cwc.googlegroups.com> <Xns97CFC5A7DE754duncanbooth@127.0.0.1> Message-ID: <7xr72gy60t.fsf@ruckus.brouhaha.com> Duncan Booth <duncan.booth at invalid.invalid> writes: > > d = dict(default=0) > > d['x'] += 3 > > > > more elegant than > > > > d = {} > > d.withdefault(0) > > d['x'] += 3 > > > Well you could have: > > d = dict.withdefault(0) > > but then you may have to start with an empty dictionary. What happens if > you need to change default for different uses? It might be nice to have something like: d = {} ... d.withdefault(0)['x'] += 3 d.withdefault would have to construct some special object whose __iadd__ did the right thing to make this happen. This would also let you do stuff like: d = {} d0 = d.withdefault(0) # can similarly make d1, d2, etc. ... d0['x'] += 3 From robert.kern at gmail.com Wed May 3 13:08:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 May 2006 12:08:08 -0500 Subject: NaN handling In-Reply-To: <18277502.1146675628355.JavaMail.root@elwamui-karabash.atl.sa.earthlink.net> References: <18277502.1146675628355.JavaMail.root@elwamui-karabash.atl.sa.earthlink.net> Message-ID: <e3ao1n$dea$1@sea.gmane.org> Andy McDonagh wrote: > Dear python experts, > > I am new to python and this site, so I apologize if this is off topic (i.e. is it a SciPy question?). I will try to demonstrate my problem below: > -------------------------------------------------------- > #!/usr/local/bin/python > > from scipy import * > from scipy.stats import * > a=norm(loc=0,scale=1) > a_data = a.rvs(10) > > problem = zeros(10) > print problem > > h_x1_x2 = -sum(problem * log2(a_data)) > > print h_x1_x2 > #NaN > ---------------------------------------------------------- > > I need a way of handling NaNs for example R has the 'na.omit' option. Does anybody know if this exists? How do you want to handle them? But you will be better off asking on the numpy or scipy lists: http://scipy.org/Mailing_Lists -- 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 pmartin at snakecard.com Fri May 5 10:19:08 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 09:19:08 -0500 Subject: Is this a legal / acceptable statement ? References: <2AI6g.10201$9c6.5375@dukeread11> <1146837825.644979.313120@j33g2000cwa.googlegroups.com> Message-ID: <x9J6g.10202$9c6.7241@dukeread11> I'm sorry (typo): l_init = False if True == l_init and 1234 == l_value: print 'l_value is initialized' Note that 1234 == l_value does not get evaluated. Philippe vbgunz wrote: > you don't have to say: > > if True == l_init > > it is suggested you simply say: > > if l_init: > > Remember the and operator requires expressions on both sides to be true > to continue. If you notice, your expression on the right side of the > 'and' is an assignment and so this is forbidden (SyntaxError). > assignments only work on lines by themselves and no where else. > > if you meant == rather than = remember this, l_value doesn't exist and > would pull up a NameError *but* because the first expression evaluates > as false the second expression is never evaluated. > > refactor your code ASAP. good luck! From sandro at e-den.it Wed May 3 16:21:48 2006 From: sandro at e-den.it (Sandro Dentella) Date: Wed, 03 May 2006 20:21:48 GMT Subject: __init__.py, __path__ and packaging Message-ID: <slrne5i46s.3hc.sandro@bluff.diade.it> Hi everybody, I'm trying to fix the packaging of a very simple package, but some problem show me that I have not well understood the whole mechanism The structure of my package (some debug functions) is as follows: python/ `-- dbg/ |-- __init__.py `-- lib |-- __init__.py |-- debug.py `-- gtk_dbg.py my sys.path includes 'python' and I wanted that the content of debug.py was simply included by: 'import dbg', so I wrote dbg/__init__.py as follows: import os Dir = os.path.dirname(__file__) __path__ = [os.path.join(Dir, 'lib')] from debug import * It seems to work: python$ python -c 'import dbg; print dir(dbg)' ['DBG', 'Dir', '__builtins__', '__doc__', '__file__', '__name__', \ '__path__', 'caller', 'debug', 'dshow', 'os', 're', 'show_caller', \ 'sql_debug', 'sys'] BUT, if I set some variables they are not correctly seen: import dbg dbg.DBG = 1 function test included in debug.py raises NameError: def test(): print DBG NameError: global name 'DBG' is not defined` What's happening? DBG seems to be set, as shown by dir(dbg)... any hints? I'd also accept a hint for a different approch, if it's the case, but I'd really would also understant this issue Thanks in advance sandro *:-) -- Sandro Dentella *:-) http://www.tksql.org TkSQL Home page - My GPL work From onurb at xiludom.gro Wed May 3 06:48:57 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 12:48:57 +0200 Subject: Binary File Reading : Metastock In-Reply-To: <1146615474.410864.52950@g10g2000cwb.googlegroups.com> References: <1146615474.410864.52950@g10g2000cwb.googlegroups.com> Message-ID: <44588af4$0$12445$626a54ce@news.free.fr> Jack wrote: > Hi > > I am having a little trouble trying to read a binary file, I would like > to write an ascii to Metastock converter in python but am not having a > lot of success. > > The file formats are > > http://sf.gds.tuwien.ac.at/00-pdf/m/mstockfl/MetaStock.pdf > > > If any one can point me in the right direction it would be much > appreciated. Not sure, but this may help you: http://pyconstruct.wikispaces.com/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From tim.peters at gmail.com Sat May 20 00:52:23 2006 From: tim.peters at gmail.com (Tim Peters) Date: Sat, 20 May 2006 00:52:23 -0400 Subject: DO NOT USE file() (was Re: altering an object as you iterate over it?) In-Reply-To: <7x3bf58fz1.fsf@ruckus.brouhaha.com> References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <e4la8j$od9$1@daisy.noc.ucla.edu> <e4m0jg$o3t$1@panix3.panix.com> <446e8a54$0$5326$c3e8da3@news.astraweb.com> <mailman.5995.1148099603.27775.python-list@python.org> <7x3bf58fz1.fsf@ruckus.brouhaha.com> Message-ID: <1f7befae0605192152s73e04e24p41bbf26ad096501d@mail.gmail.com> [Tim Peters] >> In 2.5 `file` is unchanged but `open` becomes a function: >> >> >>> file >> <type 'file'> >> >>> open >> <built-in function open> [Paul Rubin] > So which one are we supposed to use? Use for what? If you're trying to check an object's type, use the type; if you're trying to open a file, use the function. >>> type(open('a.file', 'wb')) is file True From nkanthikiran at gmail.com Sun May 28 23:00:52 2006 From: nkanthikiran at gmail.com (k.i.n.g.) Date: 28 May 2006 20:00:52 -0700 Subject: generating random passwords ... for a csv file with user details In-Reply-To: <slrne7iubc.413.sybrenUSE@schuimige.stuvel.eu> References: <1148802192.793574.209720@i40g2000cwc.googlegroups.com> <slrne7iubc.413.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1148871652.481927.235200@j55g2000cwa.googlegroups.com> Hi ALL, I am sorry for not mentioning that I am new to python and scripting. How can I add the above script to handle csv file. I want the script to generate passwords in the passwords column/row in a csv file. userid,realname,dateofB,passwd The script should read the userid and genrate the password for each user id (there are thousands of userids) Kanthi From martin at v.loewis.de Mon May 22 18:39:07 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Tue, 23 May 2006 00:39:07 +0200 Subject: system(...) and unicode In-Reply-To: <1148335865.001493.13320@38g2000cwa.googlegroups.com> References: <1148331460.400964.158420@u72g2000cwu.googlegroups.com> <1148335865.001493.13320@38g2000cwa.googlegroups.com> Message-ID: <44723D8B.8030304@v.loewis.de> andrew at acooke.org wrote: > Hmmm. After reading > http://kofoto.rosdahl.net/trac/wiki/UnicodeInPython I tried: > > system(cmd.encode(getfilesystemencoding())) > > which works (nothing else changed). But that seems odd - is this a bug > (the asymmetry - I read files with os.listdir with no explicit unicode > handling, but need to do something explicitly on output - seems wrong), > or am I going to be bitten by other errors later? Whether or not listdir returns a Unicode string depends on whether you pass a Unicode string as the directory name. So if you change the directory name to be a byte string, the file name should be a byte string, too. And yes, it would be desirable to enhance system() to support Unicode strings; contributions in that direction are welcome (although one should then also support exec*(), spawn*(), popen*(), and the subprocess module). Regards, Martin From kevin at netkev.com Mon May 22 19:02:47 2006 From: kevin at netkev.com (NetKev) Date: 22 May 2006 16:02:47 -0700 Subject: global name not defined Message-ID: <1148336530.868187.60290@j55g2000cwa.googlegroups.com> I added a function 'warn_Admin' and defined it just before another function 'process_log'. 'process_log' calls this warn_Admin' function. However, when it gets called i get the following error every time: --- Traceback (most recent call last): File "/usr/bin/denyhosts.py", line 202, in ? first_time, noemail, daemon) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 86, in __init__ last_offset) File "/usr/lib/python2.3/site-packages/DenyHosts/daemon.py", line 74, in createDaemon apply(func, args) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 137, in runDaemon purge_time, purge_sleep_ratio) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 178, in daemonLoop last_offset = self.process_log(logfile, last_offset) File "/usr/lib/python2.3/site-packages/DenyHosts/deny_hosts.py", line 380, in process_log [warn_Admin(ip) for ip in new_denied_hosts] NameError: global name 'warn_Admin' is not defined -- If I take the two functions out of their current environment and store them in test file and run it, it doesn't complain. I'm new to python so I'm guessing there is some weird scope rule I am missing. I did try 'self.warn_Admin(ip)' just to be safe but then I got a 'too many arguments' error? I'm lost :) -kevin From nobody at 127.0.0.1 Tue May 16 21:47:02 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 01:47:02 GMT Subject: any plans to make pprint() a builtin? References: <44669e46$0$5337$c3e8da3@news.astraweb.com> <Xns97C3667B2DA19duncanbooth@127.0.0.1> <446735ea$1_1@newspeer2.tds.net> <1147680829.246867.161640@i40g2000cwc.googlegroups.com> Message-ID: <qgvag.28305$4L1.12491@newssvr11.news.prodigy.com> Ant wrote: > Longer, messy, and what's the actual point? Wouldn't: > > import pprint as pp > pp.pprint(x) > > be better, standard *and* shorter? why not just: from pprint import pprint pprint (x) No need to modify the interpreter when you can pollute the global namespace yourself just as easily. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From david.murmann at rwth-aachen.de Tue May 2 21:55:48 2006 From: david.murmann at rwth-aachen.de (David Murmann) Date: Wed, 03 May 2006 03:55:48 +0200 Subject: Anaglyph 3D Stereo Imaging with PIL and numpy Message-ID: <4bqgraF121v26U1@news.dfncis.de> Hi all! i just found some colored glass and experimented a bit with these red/green 3d images, so i thought i'd share this simple script i wrote to generate such images with anyone whos interested. i also wouldn't mind some comments on the code. see ya, David. *** anaglyph.py *** # uses PIL from http://www.pythonware.com/ # and numpy from http://www.scipy.org/ from PIL import Image import numpy _magic = [0.299, 0.587, 0.114] _zero = [0, 0, 0] _ident = [[1, 0, 0], [0, 1, 0], [0, 0, 1]] # anaglyph methods from here: # http://mitglied.lycos.de/stereo3d/anaglyphcomparison.htm true_anaglyph = ([_magic, _zero, _zero], [_zero, _zero, _magic]) gray_anaglyph = ([_magic, _zero, _zero], [_zero, _magic, _magic]) color_anaglyph = ([_ident[0], _zero, _zero], [_zero, _ident[1], _ident[2]]) half_color_anaglyph = ([_magic, _zero, _zero], [_zero, _ident[1], _ident[2]]) optimized_anaglyph = ([[0, 0.7, 0.3], _zero, _zero], [_zero, _ident[1], _ident[2]]) methods = [true_anaglyph, gray_anaglyph, color_anaglyph, half_color_anaglyph, optimized_anaglyph] def anaglyph(image1, image2, method=true_anaglyph): m1, m2 = [numpy.array(m).transpose() for m in method] im1, im2 = image_to_array(image1), image_to_array(image2) composite = numpy.matrixmultiply(im1, m1) + numpy.matrixmultiply(im2, m2) result = array_to_image(image1.mode, image1.size, composite) return result def image_to_array(im): s = im.tostring() dim = len(im.getbands()) return numpy.fromstring(s, numpy.UnsignedInt8).reshape(len(s)/dim, dim) def array_to_image(mode, size, a): return Image.fromstring(mode, size, a.reshape(len(a)*len(mode), 1).astype(numpy.UnsignedInt8).tostring()) if __name__=='__main__': im1, im2 = Image.open("left-eye.jpg"), Image.open("right-eye.jpg") anaglyph(im1, im2, half_color_anaglyph).save('output.jpg', quality=98) From compromise at gmail.com Mon May 8 22:24:08 2006 From: compromise at gmail.com (compromise at gmail.com) Date: 8 May 2006 19:24:08 -0700 Subject: Memory leak in Python In-Reply-To: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> Message-ID: <1147141448.837348.115470@y43g2000cwc.googlegroups.com> Can you paste an example of the code you're using? From iainking at gmail.com Tue May 16 05:39:04 2006 From: iainking at gmail.com (Iain King) Date: 16 May 2006 02:39:04 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147772344.649771.301610@i40g2000cwc.googlegroups.com> Oh God, I agree with Xah Lee. Someone take me out behind the chemical sheds... Iain Xah Lee wrote: > Tabs versus Spaces in Source Code > > Xah Lee, 2006-05-13 > > In coding a computer program, there's often the choices of tabs or > spaces for code indentation. There is a large amount of confusion about > which is better. It has become what's known as ?religious war? ? > a heated fight over trivia. In this essay, i like to explain what is > the situation behind it, and which is proper. > > Simply put, tabs is proper, and spaces are improper. Why? This may seem > ridiculously simple given the de facto ball of confusion: the semantics > of tabs is what indenting is about, while, using spaces to align code > is a hack. > > Now, tech geekers may object this simple conclusion because they itch > to drivel about different editors and so on. The alleged problem > created by tabs as seen by the industry coders are caused by two > things: (1) tech geeker's sloppiness and lack of critical thinking > which lead them to not understanding the semantic purposes of tab and > space characters. (2) Due to the first reason, they have created and > propagated a massive none-understanding and mis-use, to the degree that > many tools (e.g. vi) does not deal with tabs well and using spaces to > align code has become widely practiced, so that in the end spaces seem > to be actually better by popularity and seeming simplicity. > > In short, this is a phenomenon of misunderstanding begetting a snowball > of misunderstanding, such that it created a cultural milieu to embrace > this malpractice and kick what is true or proper. Situations like this > happens a lot in unix. For one non-unix example, is the file name's > suffix known as ?extension?, where the code of file's type became > part of the file name. (e.g. ?.txt?, ?.html?, ?.jpg?). > Another well-known example is HTML practices in the industry, where > badly designed tags from corporation's competitive greed, and stupid > coding and misunderstanding by coders and their tools are so > wide-spread such that they force the correct way to the side by the > eventual standardization caused by sheer quantity of inproper but set > practice. > > Now, tech geekers may still object, that using tabs requires the > editors to set their positions, and plain files don't carry that > information. This is a good question, and the solution is to advance > the sciences such that your source code in some way embed such > information. This would be progress. However, this is never thought of > because the ?unix philosophies? already conditioned people to hack > and be shallow. In this case, many will simply use the character > intended to separate words for the purpose of indentation or alignment, > and spread the practice with militant drivels. > > Now, given the already messed up situation of the tabs vs spaces by the > unixers and unix brain-washing of the coders in the industry... Which > should we use today? I do not have a good proposition, other than just > use whichever that works for you but put more critical thinking into > things to prevent mishaps like this. > > Tabs vs Spaces can be thought of as parameters vs hard-coded values, or > HTML vs ascii format, or XML/CSS vs HTML 4, or structural vs visual, or > semantic vs format. In these, it is always easy to convert from the > former to the latter, but near impossible from the latter to the > former. And, that is because the former encodes information that is > lost in the latter. If we look at the issue of tabs vs spaces, indeed, > it is easy to convert tabs to spaces in a source code, but more > difficult to convert from spaces to tabs. Because, tabs as indentation > actually contains the semantic information about indentation. With > spaces, this critical information is lost in space. > > This issue is intimately related to another issue in source code: > soft-wrapped lines versus physical, hard-wrapped lines by EOL (end of > line character). This issue has far more consequences than tabs vs > spaces, and the unixer's unthinking has made far-reaching damages in > the computing industry. Due to unix's EOL ways of thinking, it has > created languages based on EOL (just about ALL languages except the > Lisp family and Mathematica) and tools based on EOL (cvs, diff, grep, > and basically every tool in unix), thoughts based on EOL (software > value estimation by counting EOL, hard-coded email quoting system by > ?>? prefix, and silent line-truncations in many unix tools), such > that any progress or development towards a ?algorithmic code unit? > concept or language syntaxes are suppressed. I have not written a full > account on this issue, but i've touched it in this essay: ?The Harm > of hard-wrapping Lines?, at > http://xahlee.org/UnixResource_dir/writ/hard-wrap.html > ---- > This post is archived at: > http://xahlee.org/UnixResource_dir/writ/tabs_vs_spaces.html > > Xah > xah at xahlee.org > ? http://xahlee.org/ From johnjsal at NOSPAMgmail.com Fri May 19 13:44:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 17:44:52 GMT Subject: WTF? Printing unicode strings In-Reply-To: <mailman.5969.1148060491.27775.python-list@python.org> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <RFkbg.2124$No6.46433@news.tufts.edu> <e4kruq$19o$1@sea.gmane.org> <mailman.5967.1148058991.27775.python-list@python.org> <Ufnbg.2131$No6.46463@news.tufts.edu> <mailman.5969.1148060491.27775.python-list@python.org> Message-ID: <ounbg.2133$No6.46491@news.tufts.edu> skip at pobox.com wrote: > John> Hmm, not that this helps me any :) > > >>>> import sys > >>>> sys.stdout.encoding > John> 'cp1252' > > Sure it does. You can print Unicode objects which map to cp1252. I assume > that means you're on Windows or that for some perverse reason you have your > Mac's Terminal window set to cp1252. (Does it go there? I'm at work right > now so I can't check). > > Skip You're right, I'm on XP. I just couldn't make sense of the lookup call, although some of the names looked like .NET classes. From kevin at netkev.com Tue May 23 23:34:00 2006 From: kevin at netkev.com (NetKev) Date: 23 May 2006 20:34:00 -0700 Subject: global name not defined In-Reply-To: <4472c4dc$0$25675$626a54ce@news.free.fr> References: <1148336761.776348.260450@j33g2000cwa.googlegroups.com> <4472c4dc$0$25675$626a54ce@news.free.fr> Message-ID: <1148441640.537692.181890@j73g2000cwa.googlegroups.com> good point From ahaas at airmail.net Fri May 19 14:56:14 2006 From: ahaas at airmail.net (Art Haas) Date: Fri, 19 May 2006 13:56:14 -0500 Subject: [ANNOUNCE] Thirty-first release of PythonCAD now available Message-ID: <20060519185614.GI2124@artsapartment.org> Hi. I'm pleased to announce the thirty-first development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The latest release features improvements to the entity splitting code and a new split operation, automatic entity splitting. The splitting code has been rewritten which fixed several bugs while making the code simpler and clearer to understand. The new autosplitting code is a feature that, when activated, will make the program split existing entities in a drawing when a newly added point lands on the entity. Various code cleanups are also present in this release, including the ability to set and later change the default style values for the different entities used within PythonCAD. Finally, a number of bug fixes and other code improvements are present in this release. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From fredrik at pythonware.com Thu May 18 09:43:11 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 15:43:11 +0200 Subject: Question about exausted iterators In-Reply-To: <446c7346$0$7147$626a54ce@news.free.fr> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> Message-ID: <e4htle$522$2@sea.gmane.org> Christophe wrote: > Because I'm still waiting for a valid answer to my question. The answer > "Because it has been coded like that" or is not a valid one. it's been coded like that because that's what the specification says: http://www.python.org/dev/peps/pep-0234/ </F> From bdesth.quelquechose at free.quelquepart.fr Sat May 27 19:48:34 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 May 2006 01:48:34 +0200 Subject: Software Needs Philosophers In-Reply-To: <WOadnW-sRKmdoe7Z4p2dnA@speakeasy.net> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <Xns97CC91CC89166BaldHeadedJohn@216.196.109.145> <WOadnW-sRKmdoe7Z4p2dnA@speakeasy.net> Message-ID: <4478b5f1$0$1599$636a55ce@news.free.fr> John A. Bailo a ?crit : > John D Salt wrote: > >> <corff at zedat.fu-berlin.de> wrote in news:4dbartF19cb9rU1 at uni-berlin.de: >> >> [Snips] >> >>> Wrong. We live in a paradise of ideas and possibilities well beyond the >>> wildest dreams of only 20 years ago. >> >> >> >> What exciting new ideas exist in software that are both important and >> cannot be traced back to 1986 or earlier? > > > What exciting new ideas exist in software that are both important and > cannot be traced back to Doug Engbart's 1968 presentation at Xerox Parc? > Those that can be traced back to 1958 when someone invented Lisp ?-) From yairchu at gmail.com Thu May 11 03:48:16 2006 From: yairchu at gmail.com (yairchu at gmail.com) Date: 11 May 2006 00:48:16 -0700 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <slrne63ahp.dac.apardon@rcpc42.vub.ac.be> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> Message-ID: <1147333696.789718.189050@v46g2000cwv.googlegroups.com> this is how I think it should be done with multi-line lambdas: def arg_range(inf, sup, f): return lambda(arg): if inf <= arg <= sup: return f(arg) else: raise ValueError and instead of @arg_range(5, 17) def f(arg): return arg*2 you do: f = arg_range(5, 17, lambda(arg)): return arg*2 From sjmachin at lexicon.net Wed May 24 18:49:01 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 May 2006 08:49:01 +1000 Subject: Finding Upper-case characters in regexps, unicode friendly. In-Reply-To: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> References: <1148499811.676868.196900@j55g2000cwa.googlegroups.com> Message-ID: <4474E2DD.2010805@lexicon.net> On 25/05/2006 5:43 AM, possibilitybox at gmail.com wrote: > I'm trying to make a unicode friendly regexp to grab sentences > reasonably reliably for as many unicode languages as possible, focusing > on european languages first, hence it'd be useful to be able to refer > to any uppercase unicode character instead of just the typical [A-Z], > which doesn't include, for example ?. Is there a way to do this, or > do I have to stick with using the isupper method of the string class? > You have set yourself a rather daunting task. :-) je suis ici a vous dire grandpere que maintenant nous ecrivons sans accents sans majuscules sans ponctuation sans tout vive le sms vive la revolution les professeurs a la lanterne ah m**** pas des lanternes (-: I would have thought that a full-on NLP parser might be required, even for more-or-less-conventionally-expressed utterances. How will you handle "It's not elementary, Dr. Watson."? However if you persist: there appears to be no way of specifying "an uppercase character" in Python's re module. You are stuck with isupper(). Light entertainment for the speed-freaks: >>> ucucase = set(unichr(i) for i in range(65536) if unichr(i).isupper()) >>> len(ucucase) 704 Is foo in ucucase faster than foo.isupper()? Cheers, John From workbee at gmail.com Wed May 24 19:25:10 2006 From: workbee at gmail.com (Enigma Curry) Date: 24 May 2006 16:25:10 -0700 Subject: Best way to handle exceptions with try/finally In-Reply-To: <1148511177.319796.228280@g10g2000cwb.googlegroups.com> References: <mailman.6122.1148413632.27775.python-list@python.org> <pan.2006.05.24.11.59.47.24496@thomas-guettler.de> <1148481073.976420.316970@j55g2000cwa.googlegroups.com> <mailman.6152.1148486485.27775.python-list@python.org> <1148511177.319796.228280@g10g2000cwb.googlegroups.com> Message-ID: <1148513110.914528.121280@i40g2000cwc.googlegroups.com> We used to have a try..except..finally syntax in Python. It was taken out a while ago for reasons unknown to me. The good news is that it is back in Python 2.5. I haven't tested it, but Guido said so himself: http://video.google.com/videoplay?docid=60331183357868340 From aylwyn at cantab.net Wed May 17 13:01:34 2006 From: aylwyn at cantab.net (achates) Date: 17 May 2006 10:01:34 -0700 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> Message-ID: <1147885294.044080.132570@38g2000cwa.googlegroups.com> Andy Sy: >Code with anything other than 8-space tabs will *NEVER* display >properly using everyday unix utilities such as less and cat. less -x<tabstop> does what you want. From hancock at anansispaceworks.com Wed May 17 19:28:20 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 17 May 2006 23:28:20 +0000 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <oYLag.18303$Lm5.11202@newssvr12.news.prodigy.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <slrne6mkt5.hoa.sybrenUSE@schuimige.stuvel.eu> <_2Jag.88816$dW3.57801@newssvr21.news.prodigy.com> <kurm62ph2d18bcal7jkm08q0dohmlg6nll@4ax.com> <oYLag.18303$Lm5.11202@newssvr12.news.prodigy.com> Message-ID: <446BB194.9090309@anansispaceworks.com> Edward Elliott wrote: >Dave Hansen wrote: > > >I fail to see why less 'will work' but cat 'doesn't always work'. > The distinction is not in the choice of program, but in the way it is being used... >The net >effect of both is the same. Unless you're in some weird place that pipes >aren't allowed, these should be equivalent: > >cat file |sed 's/\t/ /g' |less >less -x4 file > > Nope. To demonstrate, I will use "T" to represent tab characters and "S" to represent spaces (I think this will be a lot easier to read): In a properly formatting program, with tabstops at intervals of 4: A= """ SSTSTdefSspam(self,Sfoo): STTSSSSbarS=S1/foo TTSTreturnSbar """ and B = """ TTdefSspam(self,Sfoo): SSSSSSSSSSSSbarS=S1/foo TTTreturnSbar """ should render exactly the same (i.e. like the following): A=B= """ def spam(self, foo): bar = 1/foo return bar """ However, if we have tabstop set to 8 (the usual default), then they will render differently: A= """ def spam(self, foo): bar = 1/foo return bar """ B= """ def spam(self, foo): bar = 1/foo return bar """ (both are syntax errors, of course). Presumeably, the "x" option to less will correctly handle tabs (I didn't know about that -- thanks, BTW), but your sed substitution doesn't "jump to the next tabstop" when it hits a tab, it always adds a fixed number of spaces. So it mangles the code too: A= """ def spam(self, foo): bar = 1/foo return bar """ B= """ def spam(self, foo): bar = 1/foo return bar """ >Now if you're talking about the conversion altering the data's semantics, >that's a separate issue that has nothing to do with unix utilities and >everything to do with the file formatting. In that case, I'll simply refer >you to the rest of this thread for discussion. > > Now, of course, the data I provide is nasty, mean, poorly-formatted data, abhorable by space-zealots and tab-libertines alike (;-)), but the point is, unless you have set up your editor to syntax color spaces and tabs differently, you won't see the difference in the original editor. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From raghavan.viswanathan at wipro.com Thu May 18 03:33:53 2006 From: raghavan.viswanathan at wipro.com (raghu) Date: 18 May 2006 00:33:53 -0700 Subject: Reference Counts References: <1147933695.752344.195350@u72g2000cwu.googlegroups.com> <mailman.5866.1147934567.27775.python-list@python.org> Message-ID: <1147937632.918370.300350@j55g2000cwa.googlegroups.com> Heiko, Thanks for the explanation. I understood the idea of 1 being interned. Also I understood the globals vars having a reference in the internal dict. I ran the "leaky" version of the program and yes...it showed a progressively increasing totalrefcount as below. Before 0 : 16579 After 0 : 16581 Before 1 : 16581 After 1 : 16583 Before 2 : 16583 After 2 : 16585 Before 3 : 16585 After 3 : 16587 Before 4 : 16587 After 4 : 16589 Before 5 : 16589 After 5 : 16591 Before 6 : 16591 After 6 : 16593 Before 7 : 16593 After 7 : 16595 Before 8 : 16595 After 8 : 16597 Before 9 : 16597 After 9 : 16599 Before 10 : 16599 After 10 : 16601 Before 11 : 16601 After 11 : 16603 Before 12 : 16603 After 12 : 16605 Before 13 : 16605 After 13 : 16607 Before 14 : 16607 After 14 : 16609 Before 15 : 16609 However, the 'non-leaky' one showed a funny trend ...it kept increasing the totalrefcount for five iterations (see 1 thru 5) and then dropped down by 5 ( See Before 5 : 16584 After 5 : 16580 ) suddenly and again increase as shown below. However, at the time when the script finsished execution, we were not too far from the starting totalrefcount (16584 from 16579), Before 0 : 16579 After 0 : 16580 Before 1 : 16580 After 1 : 16581 Before 2 : 16581 After 2 : 16582 Before 3 : 16582 After 3 : 16583 Before 4 : 16583 After 4 : 16584 Before 5 : 16584 After 5 : 16580 Before 6 : 16580 After 6 : 16581 Before 7 : 16581 After 7 : 16582 Before 8 : 16582 After 8 : 16583 Before 9 : 16583 After 9 : 16584 Before 10 : 16584 After 10 : 16580 Before 11 : 16580 After 11 : 16581 Before 12 : 16581 After 12 : 16582 Before 13 : 16582 After 13 : 16583 Before 14 : 16583 After 14 : 16584 Before 15 : 16584 What is the Mystery behind the increase and the subsequent drop ? Thanks. Raghavan V From ziga.seilnacht at gmail.com Mon May 1 19:24:04 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 1 May 2006 16:24:04 -0700 Subject: list*list References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> Message-ID: <1146525844.275261.266620@e56g2000cwe.googlegroups.com> BBands wrote: > There must be a better way to multiply the elements of one list by > another: [snipped] > Perhaps a list comprehension or is this better addressed by NumPy? If you have a large amount of numerical code, it is definetly better to use numpy, since it is intended just for that purpose: >>> import numpy >>> a = numpy.array([1, 2, 3]) >>> b = numpy.array([1, 2, 3]) >>> c = a * b >>> c array([1, 4, 9]) Otherwise, you can use the builtin function map and functions in the operator module: >>> import operator >>> a = [1, 2, 3] >>> b = [1, 2, 3] >>> c = map(operator.mul, a, b) >>> c [1, 4, 9] >>> d = map(operator.add, a, b) >>> d [2, 4, 6] > Thanks, > > jab Ziga From edeveaud at pasteur.fr Wed May 3 11:19:26 2006 From: edeveaud at pasteur.fr (Eric Deveaud) Date: Wed, 3 May 2006 15:19:26 +0000 (UTC) Subject: Sorting a list of dictionaries by dictionary key References: <mailman.5260.1146660794.27775.python-list@python.org> <slrne5hano.qf7.edeveaud@localhost.localdomain> <4458b992$0$19954$626a54ce@news.free.fr> Message-ID: <slrne5hi49.shf.edeveaud@localhost.localdomain> bruno at modulix wrote: > Eric Deveaud wrote: > (snip) > > > > sort can take a comparaison function. > > The problem with it is that it may slow down things a lot... point taken. I have to purge my mind from the other programing languages I practice. ;-) Eric From xivulon at gmail.com Wed May 24 10:27:24 2006 From: xivulon at gmail.com (ago) Date: 24 May 2006 07:27:24 -0700 Subject: Scipy: vectorized function does not take scalars as arguments Message-ID: <1148480844.817338.69230@u72g2000cwu.googlegroups.com> Once I vectorize a function it does not acccept scalars anymore. Es def f(x): return x*2 vf = vectorize(f) print vf(2) AttributeError: 'int' object has no attribute 'astype' Is this the intended behaviour? From johnjsal at NOSPAMgmail.com Mon May 8 16:38:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 20:38:46 GMT Subject: utility functions within a class? In-Reply-To: <445fa2c1$1@nntp0.pdx.net> References: <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <USH7g.2052$No6.45672@news.tufts.edu> <SdI7g.2055$No6.45780@news.tufts.edu> <98uu52hiic72dtt9ibu0e7anfgndv6o8qb@4ax.com> <uQM7g.2060$No6.45697@news.tufts.edu> <445fa2c1$1@nntp0.pdx.net> Message-ID: <q%N7g.2062$No6.45493@news.tufts.edu> Scott David Daniels wrote: > John Salerno wrote: >> Dennis Lee Bieber wrote: >>> ... Single underscores are a convention/signal to the programmer that >>> "this method/attribute" is considered "private" and should only be used >>> by other methods within the class that defined it. The language does no >>> enforcement of usage.... >> >> I see. But isn't there something about a single leading underscore >> that doesn't import when you use from X import *? Or am I thinking of >> something else? Is that also the double underscore? > > That has to do with module contents, and is a completely separate issue. > If you define a module with a variable name '__all__' which is a list > (or tuple) of strings, only module elements with those names will be > imported with a "from module import *". If you fail to define the > '__all__' element, all names which do not start with an underscore will > be imported. > > --Scott David Daniels > scott.daniels at acm.org Thanks, that's what I was thinking of. So it doesn't apply to the contents within a class, just top-level contents? From duncan.booth at invalid.invalid Tue May 16 09:03:05 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 13:03:05 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> <mailman.5711.1147697881.27775.python-list@python.org> <1147781797.407160.54740@u72g2000cwu.googlegroups.com> Message-ID: <Xns97C58EED2F83Dduncanbooth@127.0.0.1> jantod at gmail.com wrote: > BTW why are python dicts implemented as hash tables and not judy > arrays? > Probably because: Python predates judy arrays. Nobody has proposed replacing the current dict implementation. Nobody has demonstrated that it would actually be an advantage to replace the current implementation. Or maybe Python dicts are just more flexible? You choose. A quick scan of the Judy IV Shop Manual reveals: > Judy is a dessert topping and a floor wax, but it?s not intended for > use as a house paint. ... > Judy is a programming library that provides a relatively simple > interface (API) for array-like storage of word or string indexes with > optional mapping of indexes to single-word values. It doesn't sound to me as though they match the flexibility of Python dictionaries. Without reading further through the documentation, the implication is that keys are restricted to simple word or string values. Remember, all that Python requires of a dict key is that it has a hash value and can be compared for equal/not equal with other keys. It doesn't require the key to be expressible as a sequence of bits which is what the Judy manual seems to imply: > You can think of digital trees as peeling (decoding) leading bits off > a key until only one bit is left, but in the case of an unbounded > variable-size key there is no definite ?bottom? (that is, a definite > last bit or maximum length for every key). However, there are always > unpopulated subexpanses, except with a fixed-size key where every > possible key value is stored in the data structure. When decoding keys > top-down in this way, each (sub)expanse is defined by the bits already > decoded and the number of bits remaining (if finite). From gry at ll.mit.edu Tue May 23 14:20:09 2006 From: gry at ll.mit.edu (gry at ll.mit.edu) Date: 23 May 2006 11:20:09 -0700 Subject: "Thinking like CS" problem I can't solve In-Reply-To: <1148402620.032735.60000@g10g2000cwb.googlegroups.com> References: <1148402620.032735.60000@g10g2000cwb.googlegroups.com> Message-ID: <1148408409.286419.240920@g10g2000cwb.googlegroups.com> Alex Pavluck wrote: > Hello. On page 124 of "Thinking like a Computer Scientist". There is > an exercise to take the following code and with the use of TRY: / > EXCEPT: handle the error. Can somone help me out? Here is the code: > > def inputNumber(n): > if n == 17: > raise 'BadNumberError: ', '17 is off limits.' > else: > print n, 'is a nice number' > return n > > inputNumber(17) Yikes! It's a very bad idea to use string literals as exceptions. Use one of the classes from the 'exceptions' module, or derive your own from one of them. E.g.: class BadNum(ValueError): pass def inputNumber(n): if n == 17: raise BadNum('17 is off limits') else: print n, 'is a nice number' try: inputNumber(17) except BadNum, x: print 'Uh Oh!', x Uh Oh! 17 is off limits See: http://docs.python.org/ref/try.html#try especially the following bit: ...the clause matches the exception if the resulting object is ``compatible'' with the exception. An object is compatible with an exception if it is either the object that identifies the exception, or (for exceptions that are classes) it is a base class of the exception,... Note that the object identities must match, i.e. it must be the same object, not just an object with the same value. Identity of string literals is a *very* slippery thing. Don't depend on it. Anyway, python 2.5 gives a deprecation warning if a string literal is used as an exception. From sybrenUSE at YOURthirdtower.com.imagination Fri May 12 02:22:28 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 12 May 2006 08:22:28 +0200 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <445fe772$1@nntp0.pdx.net> <1147248164.805219.295970@y43g2000cwc.googlegroups.com> <slrne63ahp.dac.apardon@rcpc42.vub.ac.be> <1147283519.066005.134470@i40g2000cwc.googlegroups.com> <1147333696.789718.189050@v46g2000cwv.googlegroups.com> <slrne662c4.9qk.sybrenUSE@schuimige.stuvel.eu> <1147367127.569933.213710@i39g2000cwa.googlegroups.com> Message-ID: <slrne68ad4.phi.sybrenUSE@schuimige.stuvel.eu> Kaz Kylheku enlightened us with: > Which proposed lambda syntax is closest in this sense? I was talking about different ways (your multi-line lambda vs. the currently implemented one) of doing function decorators. > Is it unusual to have a tougher time explaining X than Y to people > who are learning a language, where X and Y are different features? See above: same feature, function decorators. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From luis at geodynamics.org Fri May 26 10:16:45 2006 From: luis at geodynamics.org (Luis Armendariz) Date: Fri, 26 May 2006 07:16:45 -0700 Subject: hide python window In-Reply-To: <2387F0EED10A4545A840B231BBAAC7226083B5@slcimail1.slcgov.com> References: <2387F0EED10A4545A840B231BBAAC7226083B5@slcimail1.slcgov.com> Message-ID: <44770DCD.9080005@geodynamics.org> Bell, Kevin wrote: > When I run a script, how can I make it run in the background? I don't > want to see the command window because it runs all day. I'm on > windows... > > Hi Kevin, Rename your kevin_script.py to kevin_script.pyw (so that it runs with pythonw.exe instead of python.exe). -Luis From kentilton at gmail.com Fri May 5 22:50:53 2006 From: kentilton at gmail.com (Ken Tilton) Date: Fri, 05 May 2006 22:50:53 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <0RT6g.83274$tc.10279@fe2.news.blueyonder.co.uk> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <0RT6g.83274$tc.10279@fe2.news.blueyonder.co.uk> Message-ID: <haU6g.89$Ey5.85@fe12.lga> David Hopwood wrote: > Ken Tilton wrote: > >>[...] The upshot of what [Guido] wrote is that it would be really hard to make >>semantically meaningful indentation work with lambda. > > > Haskell manages it. > To be honest, I was having a hard time imagining precisely how indentation broke down because of lambda. does text just sail out to the right too fast? kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From tbrkic at yahoo.com Wed May 17 17:01:41 2006 From: tbrkic at yahoo.com (glomde) Date: 17 May 2006 14:01:41 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1147899701.004246.294580@g10g2000cwb.googlegroups.com> > But generally, I don't do layout like that. I'd do: > > --->cursor.execute( > --->--->--->'select id, item, amount, field4, <etc> > --->--->--->'from table1 where amount>100' > --->) > >Which keeps looking fine, no matter what tab size, and without mixing >tabs and spaces. > Which only works fine only if you are the one only editing the file. But If you work in a team it is kind of hard to make sure that everybody use tabs and not spaces. And it is not very easy to spot either. The same is valid if somebody use your code or you want to import somebody elses code. From bedouglas at earthlink.net Wed May 3 03:36:07 2006 From: bedouglas at earthlink.net (bruce) Date: Wed, 3 May 2006 00:36:07 -0700 Subject: Zope Guru... Message-ID: <226901c66e84$3d9f8240$0301a8c0@Mesa.com> Hi.. In doing some research into Workflow apps regarding document management, I came across Zope. Given that it's Python Based, I figured I'd shout to the group here... Are there any Zope gurus that I can talk to regarding Zope, and what it does/how it works? In particular, I'm looking for an app that I could use to manage a pretty simple workflow for a bunch of scripts that are going to be developed. I envision having a number of people on the team, each developing/testing various scripts. I then need to somehow manage the process of the scripts going from development to testing to production, which is the workflow. At the same time, I have to implement/enforce some form of Access control for the users, so they don't screw up with files that they shouldn't touch... If there's anyone on this list that I could talk to, I'd appreciate it.. Thanks -bruce From scott.daniels at acm.org Wed May 24 12:02:32 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 24 May 2006 09:02:32 -0700 Subject: Running script in __main__ shows no output in IDLE In-Reply-To: <1148367832.691286.320790@j33g2000cwa.googlegroups.com> References: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> <44724be3$1@nntp0.pdx.net> <1148367832.691286.320790@j33g2000cwa.googlegroups.com> Message-ID: <44747f6b$1@nntp0.pdx.net> heidi.hunter at fantasy-interactive.com wrote: > Thanks for your help! Shouldn't Idle have shown an error when trying to > read the string constant if it's not interpretable as a normal string, > then? I suspect it should. The error probably got lost in the start-script handling somewhere. --Scott David Daniels scott.daniels at acm.org From mariano.difelice at gmail.com Thu May 11 09:15:48 2006 From: mariano.difelice at gmail.com (mariano.difelice at gmail.com) Date: 11 May 2006 06:15:48 -0700 Subject: Python memory deallocate In-Reply-To: <1147347601.597292.15220@j73g2000cwa.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <1147347601.597292.15220@j73g2000cwa.googlegroups.com> Message-ID: <1147353348.028544.143470@u72g2000cwu.googlegroups.com> Well, it's right about range diff xrange, ok, but this was a simple example... I repeat that my program don't work with range or xrange... I MUST find a system which deallocate memory... Otherwise, my application crashes not hardly it's arrived to break-point system From None at none.none Mon May 22 21:20:14 2006 From: None at none.none (WIdgeteye) Date: Mon, 22 May 2006 20:20:14 -0500 Subject: No math module?? Message-ID: <pan.2006.05.23.01.20.13.781679@none.none> I have been trying to run a python program and I get the following error: Traceback (most recent call last): File "<string>", line 39, in ? File "/home/Larry/.blender/scripts/bzflag/__init__.py", line 22, in ? import BZfileRead File "/home/Larry/.blender/scripts/bzflag/BZfileRead.py", line 24, in ? import BZsceneWriter File "/home/Larry/.blender/scripts/bzflag/BZsceneWriter.py", line 25, in ? import BZcommon File "/home/Larry/.blender/scripts/bzflag/BZcommon.py", line 24, in ? import math ImportError: No module named math So just to check and make sure I tried to import the math module and sure enough there isn't one. This whole program has calls to the "math" module all the way through it. I have been using python on my computer since it first came out and this is the first time I have runinto this. I have Python 2.3.2 installed on Slackware Linux. I installed it from source download from the Python.org web site. I have looked all over for a math module but can't find one. Maybe not looking in the right place??? So what's up?? :) thanks From johnjsal at NOSPAMgmail.com Fri May 19 16:12:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 20:12:48 GMT Subject: altering an object as you iterate over it? In-Reply-To: <446e1def$0$6919$626a54ce@news.free.fr> References: <1Mobg.2139$No6.46432@news.tufts.edu> <446e1def$0$6919$626a54ce@news.free.fr> Message-ID: <4Fpbg.2141$No6.46535@news.tufts.edu> bruno at modulix wrote: > Now if what you want to do is just to rewrite the file without the blank > files, you need to use a second file: > > fin = open(path, 'r') > fout = open(temp, 'w') > for line in fin: > if line.strip(): > fout.write(line) > fin.close() > fout.close() > > then delete path and rename temp, and you're done. And yes, this is > actually the canonical way to do this !-) Thanks, that's what I want. Seems a little strange, but at least you showed me that line.strip() is far better than line == '\n' From gmc at serveisw3.net Sun May 21 01:21:52 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Sun, 21 May 2006 07:21:52 +0200 Subject: Python update trouble (2.3 to 2.4): x<<y Message-ID: <446FF8F0.5070004@serveisw3.net> I reply again attaching a file as I see the editor wrecked the tab indentation. Gonzalo Monz?n escribi?: > Hi all! > > I have been translating some Python custom C extension code into > Python, as I need these modules to be portable and run on a PocketPC > without the need of compile (for the purpose its a must 2.4 as it is > the last PythonCE release with great improvements). > > But I've been stuck with a script wich does not work as expected once > translated to python, 2.4 > > In the meantime, I thought I could test it with an old 2.3 version I > have installed too on my computer, and found it run as expected, but > see the FutureWarning, so googled a bit and found PEP 237 and long > integer integration issue, but then can't find any workaround to fix > the code for Python 2.4 > > Hope somebody could point some suggestion, or perhaps, the solution is > pretty simple, but I missed it. > > As I said, the code works fine on 2.3. I attach the code below. > > The trouble is on the CalcCRC16 function, as you can see on the > FutureWarning message. > > InitCRC16 function does some bitwise xor's too, but I checked it and > works as expected. Thought because only happen to be with small values > there. > > Thanks in advance for any help, > Gonzalo > > ############################## > Python 2.3.2: > > pytest1.py:90: FutureWarning: x<<y losing bits or changing sign will > return a long in Python 2.4 and up > crc = gCRC16Table[((crc >> 8) & 255)] ^ (crc << 8) ^ ord(str[x]) > 67560050 > > ############################## > Python 2.4.2: > > 22002496167782427386022437441624938050682666541682 > > > *Expected result is 67560050* > > > # ############################# > # pytest1.py > > gCRC16Table = [] > > def InitCRC16(): > global gCRC16Table > > for i in xrange(0,256): > crc = i << 8 > for j in xrange(0,8): > if (crc & 0x8000) != 0: > tmp = 0x1021 > else: > tmp = 0 > crc = (crc << 1) ^ tmp > gCRC16Table.append(crc) > def CalcCRC16(str): > global gCRC16Table > > crc = 0xFFFF for x in xrange(0,len(str)): > crc = gCRC16Table[((crc >> 8) & 255)] ^ (crc << 8) ^ ord(str[x]) > return crc > > test = "123456asdfg12345123" > InitCRC16() > print CalcCRC16(test) > > -------------- next part -------------- A non-text attachment was scrubbed... Name: pytest1.py Type: text/x-python Size: 623 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060521/82b16672/attachment.py> From vbgunz at gmail.com Thu May 25 13:04:12 2006 From: vbgunz at gmail.com (vbgunz) Date: 25 May 2006 10:04:12 -0700 Subject: script vs inneractive In-Reply-To: <1148574517.158866.157280@38g2000cwa.googlegroups.com> References: <1148574517.158866.157280@38g2000cwa.googlegroups.com> Message-ID: <1148576652.846741.96560@i39g2000cwa.googlegroups.com> the interactive shell will immediatly show the result of an expression without you having to explicitly print the result. In all text editor, you will have to print the result if you wish to see it. From peace.is.our.profession at gmx.de Mon May 8 08:31:02 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Mon, 08 May 2006 14:31:02 +0200 Subject: Python's regular expression? In-Reply-To: <1147085552.824265.128220@i39g2000cwa.googlegroups.com> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> Message-ID: <e3ndsm$rfa$1@mlucom4.urz.uni-halle.de> Hi Davy > > More similar than Perl ;-) But C has { }'s everywhere, so has Perl ;-) > > And what's 'integrated' mean (must include some library)? Yes. In Python, regular expressions are just another function library - you use them like in Java or C. In Perl, it's part of the core language, you use the awk-style (eg: /.../) regular expressions everywhere you want. If you used regexp in C/C++ before, you can use them in almost the same way in Python - which may give you an easy start. BTW. Python has some fine extensions to the perl(5)-Regexes, e.g. 'named backreferences'. But you won't see much regular expressions in Python code posted to this group, maybe because it looks clunky - which is unpythonic ;-) Lets see - a really simple find/match would look like this in Python: import re t = 'blue socks and red shoes' p = re.compile('(blue|white|red)') if p.match(t): print t which prints the text 't' because of the positive pattern match. In Perl, you write: use Acme::Pythonic; $t = 'blue socks and red shoes' if ($t =~ /(blue|white|red)/): print $t which is one line shorter (no need to compile the regular expression in advance). > > I like C++ file I/O, is it 'low' or 'high'? C++ has afaik actually three levels of I/O: (1) - (from C, very low) operating system level, included by <io.h> which provides direct access to operating system services (read(), write(), lseek() etc.) (2) - C-Standard-Library buffered IO, included by <stdio.h>, provides structured 'mid-level' access like (block-) fread()/ fwrite(), line read (fgets()) and formatted I/O (fprintf()/ fscanf()) (3) - C++/streams library (high level, <fstream>, <iostream>, <sstream>), which abstracts out the i/o devices, provides the same set of functionality for any abstract input or output. Perl provides all three levels of I/O, the 'abstracting' is introduced by modules which tie 'handle variables' to anything that may receive or send data. Python also does a good job on all three levels, but provides the (low level) operating system I/O by external modules (afaik). I didn't do much I/O in Python, so I can't say much here. Regards Mirco From enleverlesX.XmcX at XmclaveauX.com Wed May 24 00:54:04 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Wed, 24 May 2006 06:54:04 +0200 Subject: documentation for win32com? References: <hQHcg.2153$No6.46370@news.tufts.edu> Message-ID: <4473e770$0$19689$8fcfb975@news.wanadoo.fr> Hi! MS-Office-2007 beta2, can downloaded here : http://www.microsoft.com/office/preview/beta/getthebeta.mspx (with a passport account). Doc, for COM access, are include in the help-system. @-salutations MCI From durumdara at gmail.com Mon May 15 08:01:58 2006 From: durumdara at gmail.com (DurumDara) Date: Mon, 15 May 2006 14:01:58 +0200 Subject: Unicode to DOS filenames (to call FSUM.exe) In-Reply-To: <1147691744.880789.296320@y43g2000cwc.googlegroups.com> References: <mailman.5697.1147679156.27775.python-list@python.org> <1147691744.880789.296320@y43g2000cwc.googlegroups.com> Message-ID: <44686DB6.7020909@gmail.com> John Machin ?rta: > Looks like you need a GetShortPathNameW() but it's not implemented. > Raise it as an issue on the pywin32 sourceforge bug register. Tell Mark > I sent you :-) > Another thought: try using ctypes. > Hi ! It seems to be I found a solution. A little tricky, but it is working: ##################################################################### import sys,os from sys import argv as sysargv UFN=u'%s\\xA\xff'%os.getcwd() if os.path.exists(UFN): os.remove(UFN) f=open(UFN,'w') f.write('%s\n'%('='*80)) f.close() from ctypes import windll, create_unicode_buffer, sizeof, WinError buf=create_unicode_buffer(512) if windll.kernel32.GetShortPathNameW(UFN,buf,sizeof(buf)): fname=buf.value #import win32api #dfn=win32api.GetShortPathName(name) #print dfn else: raise shortpath,filename=os.path.split(fname) import win32file filedatas=win32file.FindFilesW(fname) fd=filedatas[0] shortfilename=fd[9] or fd[8] shortfilepath=os.path.join(shortpath,shortfilename) print [UFN] print shortfilepath f=open(shortfilepath,'r') print f.read() sys.exit() But I don't understand: why the shortpathw not convert the filename too (like dir) ? Thanx for help: dd From NOatkinwSPAM at rpi.edu Sat May 6 04:14:28 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 04:14:28 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1146900379.023190.164640@u72g2000cwu.googlegroups.com> Message-ID: <87hd43bme3.fsf@rpi.edu> "Kay Schluehr" <kay.schluehr at gmx.net> writes: > And then the 12th vanished Lisper returns and Lispers are not > suppressed anymore and won't be loosers forever. The world will be The mark of a true loser is the inability to spell 'loser.' Zing! > them as zealots, equipped with the character of suicide bombers. No, A very reasonable comparison. Yes, the more I think about it, we Lisp programmers are a lot like suicide bombers. Doofus. -- This is a song that took me ten years to live and two years to write. - Bob Dylan From Elric02 at rogers.com Tue May 16 14:19:54 2006 From: Elric02 at rogers.com (Elric02 at rogers.com) Date: 16 May 2006 11:19:54 -0700 Subject: Unable to extract Python source code using Windows In-Reply-To: <446a0229$1@nntp0.pdx.net> References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> <446a0229$1@nntp0.pdx.net> Message-ID: <1147803594.844448.271640@i39g2000cwa.googlegroups.com> Scott , I tried downloading for different archives, (different versions of Python) I can't believe they are all garbled. But they all don't work with WinZip. From fredrik at pythonware.com Sat May 20 02:37:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 May 2006 08:37:19 +0200 Subject: performance problem of streaming data over TCP In-Reply-To: <e4luqj$d0h$1@news.ks.uiuc.edu> References: <e4luqj$d0h$1@news.ks.uiuc.edu> Message-ID: <e4mdeu$7ng$1@sea.gmane.org> Changhao wrote: > I am implementing a protocol on top of 'asyncore.dispatcher' to > send streaming multimedia data over TCP socket. However, I found that > the throughput of my current implementation is surprisingly low. I'm not sure what you think you're doing in your code, but I'm quite sure that using a home-brewed blocking loop inside an event handler in a high-performance asynchronous framework isn't exactly the best way to get good performance. Have you tried using asyncore for asynchronous communication ? </F> From birchb at ozemail.com.au Wed May 3 00:01:42 2006 From: birchb at ozemail.com.au (birchb at ozemail.com.au) Date: 2 May 2006 21:01:42 -0700 Subject: Types-SIG Archives. Message-ID: <1146628902.010352.293660@j73g2000cwa.googlegroups.com> Hi, I'm researching the history of proposals to add types to Python, partly to improve my own code, and secondly to be able to make an informed PEP one day. The Types-SIG archives link (http://mail.python.org/pipermail/types-sig/) gives a 404 error. Does anyone know how to get the archive back? Paul Prescod was listed as the sig owner, are you still around Paul? Bill From cfbolz at gmx.de Wed May 3 17:56:21 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Wed, 03 May 2006 23:56:21 +0200 Subject: This coding style bad practise? In-Reply-To: <44591be3$0$2626$636a55ce@news.free.fr> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> <44591be3$0$2626$636a55ce@news.free.fr> Message-ID: <e3b8ss$a7g$2@sea.gmane.org> Bruno Desthuilliers wrote: > Martin P. Hellwig a ?crit : >>I created a class which creates a relative unique id string, now my >>program just works fine and as expected but somehow I get the feeling >>that I misused the __repr__ since I guess people expect to 'execute' a >>function in an instance instead of using it's representation string of >>the instance itself, could you elaborate whether you find this bad >>practice and if yes what would have been a better way to do it? > > Why not just use the call operator instead ? ie: > > >>> id = IDGenerator(...) > >>> id() > 01_20060424_151903_1 > >>> id() > 01_20060424_151905_2 because that shadows a builtin? sorry, could not resist :-) Cheers, Carl Friedrch Bolz From belred at gmail.com Tue May 23 01:38:35 2006 From: belred at gmail.com (Bryan) Date: Mon, 22 May 2006 22:38:35 -0700 Subject: groupby In-Reply-To: <1148356503.165982.247800@y43g2000cwc.googlegroups.com> References: <mailman.6096.1148354906.27775.python-list@python.org> <1148356503.165982.247800@y43g2000cwc.googlegroups.com> Message-ID: <e4u74q$7gl$1@sea.gmane.org> George Sakkis wrote: > Bryan wrote: > >> can some explain why in the 2nd example, m doesn't print the list [1, 1, 1] >> which i had expected? >> >> >> >>> for k, g in groupby([1, 1, 1, 2, 2, 3]): >> ... print k, list(g) >> ... >> 1 [1, 1, 1] >> 2 [2, 2] >> 3 [3] >> >> >> >>> m = list(groupby([1, 1, 1, 2, 2, 3])) >> >>> m >> [(1, <itertools._grouper object at 0x00AAC600>), (2, <itertools._grouper object >> at 0x00AAC5A0>), (3, <itertools._grouper object at 0x00AAC5B0>)] >> >>> list(m[0][1]) >> [] >> >>> >> >> >> thanks, >> >> bryan > > I've tripped on this more than once, but it's in the docs > (http://docs.python.org/lib/itertools-functions.html): > > "The returned group is itself an iterator that shares the underlying > iterable with groupby(). Because the source is shared, when the groupby > object is advanced, the previous group is no longer visible. So, if > that data is needed later, it should be stored as a list" > > George > i read that description in the docs so many times before i posted here. now that i read it about 10 more times, i finally get it. there's just something about the wording that kept tripping me up, but i can't explain why :) thanks, bryan From andy at neotitans.com Wed May 17 14:40:27 2006 From: andy at neotitans.com (Andy Sy) Date: Thu, 18 May 2006 02:40:27 +0800 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <446B6AD1.4080104@mvista.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> Message-ID: <e4fqga$ep3$1@sea.gmane.org> Carl J. Van Arsdall wrote: >> Next major objection then, how can one practically use 'tabs as >> semantic indentation' without screwing up formatting of code like >> the below?? >> >> >> def sqlcall(): >> cursor.execute('select id, item, amount, field4, field5, field6'+ >> 'from table1 where amount>100') >> >> > Why couldn't you tab your third line over as close as possible to the > start of the quote then use a couple spaces? Then the tabs would work > just fine and you could still have your pretty line. This will break if someone tries to view my code using different tab settings from the one I'm using. -- It's called DOM+XHR and it's *NOT* a detergent! From __peter__ at web.de Mon May 15 02:14:33 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 May 2006 08:14:33 +0200 Subject: comparing values in two sets References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> <7xslncdsvk.fsf@ruckus.brouhaha.com> Message-ID: <e4964g$r7f$00$1@news.t-online.com> Paul Rubin wrote: > You could even get cutesy and say something like (untested): > > from?itertools?import?izip > def?test_sets(original_set,?trans_letters): > return?not?sum(a==b?for?a,b?in?izip(original_set,?trans_letters)) > > but that can be slower since it always scans both lists in entirety, > even if a matching pair of elements is found right away. Here's a variant that does performs only the necessary tests: >>> from itertools import izip >>> True not in (a == b for a, b in izip(range(3), range(3))) False A "noisy" equality test to demonstrate short-circuiting behaviour: >>> def print_eq(a, b): ... print "%r == %r --> %r" % (a, b, a == b) ... return a == b ... >>> True not in (print_eq(a, b) for a, b in izip(range(3), range(3))) 0 == 0 --> True False >>> True not in (print_eq(a, b) for a, b in izip(["x", 1, 2], range(3))) 'x' == 0 --> False 1 == 1 --> True False >>> True not in (print_eq(a, b) for a, b in izip(["x", "x", "x"], range(3))) 'x' == 0 --> False 'x' == 1 --> False 'x' == 2 --> False True Peter From kay.schluehr at gmx.net Sun May 7 03:29:57 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 7 May 2006 00:29:57 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> Message-ID: <1146986997.937204.265920@y43g2000cwc.googlegroups.com> Tomasz Zielonka wrote: > On the other hand, what do you get by allowing ( as an indentifier? > > Significant whitespace is a good thing, but the way it is designed in > Python it has some costs. Can't you simply acknowledge that? One can admit this but what is it worth or how should those costs be evaluated? This problem is unsolvable because we cannot agree on a common standard of the value of PL design. All we can do is making the decisions more visible. Obviously Lispers want the boundary between application-level and interpreter-level programming as low as possible. It is still present but making it invisible and expressing language semantics through the language is regarded of high value. This makes application level meta-programming as simple as it could be. Others tend to separate the concerns/boundaries more strictly and standardize the language while implementing all features regarded necessary for application-level programming in a huge opaque runtime and a vast amount of libraries. Application level metaprogramming is restricted to runtime-reflection, metaclass-protocols, annotations etc. From this point of view a programming language is basically an interface to a virtual machine that is much like an operating system i.e. it supports basic functions and hides complexity. This is the way Java and Python have gone. The benefit of the latter approach lies not so much in creating new language capabilities but considering the language as just another application where requirement engineering and carefull design can be done without sprawling in every possible direction ( see Forth as an example for this tendency ). This way standard libraries ( "batteries included" ) become almost equal important and "language-designer" is a job that is not once be done. This is roughly my interpretation of GvRs "design view" on PLs that Xah Lee obviously doesn't get - Xah is not important here, because he never gets anything right but here are enough Lispers with quite some working brain cells who seem to think that the best thing to do is giving a programmer unlimited programming power. Concluding remark: I'm not sure I want to defend one point of view all the way long. Although not being a Lisper myself I can clearly see that the DSL topic is hot these days and the pendulum oscillates into the direction of more liberty. I have mixed feelings about this but I have my own strong opinion of how those *can* fit into the CPython design space and a working model that is to be published soon. As with the dialectic double negation there is no return to a former position. From tfb at conquest.OCF.Berkeley.EDU Sun May 7 06:55:50 2006 From: tfb at conquest.OCF.Berkeley.EDU (Thomas F. Burdick) Date: 07 May 2006 03:55:50 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> Message-ID: <xcvfyjmdryh.fsf@conquest.OCF.Berkeley.EDU> Ken Tilton <kentilton at gmail.com> writes: > As for: > > > At a syntax-sugar > > level, for example, Lisp's choice to use parentheses as delimiter means > > it's undesirable, even unfeasible, to use the single character '(' as an > > ordinary identifier in a future release of the language. > > (defun |(| (aside) (format nil "Parenthetically speaking...~a." aside)) > => |(| > (|(| "your Lisp /is/ rusty.") > => "Parenthetically speaking...your Lisp /is/ rusty.." > > :) No, seriously, is that all you can come up with? Well, you have to quote your (s-as-identifiers. I tried a goofy hack of a reader macro for ( to make this parse: (let (( ( 10))) ( )) [The spaces are just for readability, not necessary] Alas, short of cps-transforming the whole reader, I can't see a reasonable way to get that to parse as a single sexp that, when evaluated, returns 10. What my reader macro gave me was five sexps: \(, LET, \(, ((10)), NIL I'll follow up with the Lisp code (on c.l.l only), in case I'm missing something simple. > OK, I propose a duel. We'll co-mentor this: > > http://www.lispnyc.org/wiki.clp?page=PyCells > > In the end Python will have a Silver Bullet, and only the syntax will > differ, because Python has a weak lambda, statements do not always > return values, it does not have macros, and I do not know if it has > special variables. I have no idea what the big problem with a multi-line lambda is in Python, but I wonder if Cells wouldn't run against the same thing. I often pass around anonymous formulas that eventually get installed in a slot. Seems annoying to have to name every formula with a labels-like mechanism. From sybrenUSE at YOURthirdtower.com.imagination Fri May 19 08:09:24 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 19 May 2006 14:09:24 +0200 Subject: Newbie append() question References: <mailman.5922.1148004495.27775.python-list@python.org> <slrne6r0pp.m6t.sybrenUSE@schuimige.stuvel.eu> <mailman.5937.1148037151.27775.python-list@python.org> Message-ID: <slrne6rdbj.mnv.sybrenUSE@schuimige.stuvel.eu> Brian Blazer enlightened us with: > I'm still not sure why it was grabbing the prompt string though. Me neither. Try it in a standalone script instead of an interactive session. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From kent at kentsjohnson.com Tue May 9 14:19:24 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 09 May 2006 14:19:24 -0400 Subject: Global utility module/package In-Reply-To: <mailman.5488.1147125939.27775.python-list@python.org> References: <mailman.5488.1147125939.27775.python-list@python.org> Message-ID: <4460dcaa$1_2@newspeer2.tds.net> Christoph Haas wrote: > Evening, > > I'm currently working on a larger Python project that consists of multiple > programs and packages. As I need a few utility functions time and again I > moved them all into a Utility package and created a class there. ... > As I know that importing packages from multiple modules always keeps it a > singleton I thought of something like this: > > Util.py: > ~~~~~~~~ > debugFlag = False > vibranceLevel = 'good' > > def function1(): > global debugFlag > print debugFlag > > main.py: > ~~~~~~~~ > import Util > Util.debugFlag = True > Util.function1(whatever) > > def doThis(): > Util.function1(42) > > Here I don't use classes any longer. Good. But to access the "package > variables" I probably need to use "global" again which just moved the > ugliness to another position. This is fine. You don't need 'global' statements to read global variables, function1() can be simply def function1(): print debugFlag Kent From stijndesaeger at gmail.com Fri May 5 06:22:57 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 03:22:57 -0700 Subject: Tuple assignment and generators? In-Reply-To: <mailman.5361.1146822663.27775.python-list@python.org> References: <mailman.5334.1146755400.27775.python-list@python.org> <1146821724.732068.268960@g10g2000cwb.googlegroups.com> <mailman.5361.1146822663.27775.python-list@python.org> Message-ID: <1146824577.242547.315600@y43g2000cwc.googlegroups.com> > language reference, objects: "Even the importance of object identity is affected in some sense: for immutable types, operations that compute new values may actually return a reference to any existing object with the same type and value, while for mutable objects this is not allowed. E.g., after "a = 1; b = 1", a and b may or may not refer to the same object with the value one, depending on the implementation, but after "c = []; d = []", c and d are guaranteed to refer to two different, unique, newly created empty lists. (note the use of "may or may not" and "depending on the implementation") </F> That, I knew. What I did not know, nor get from this explanation, is that this behaviour "may" differ not only within the same implementation, but with instances of the same class or type (in this case, 'int'). Is this really a case of me being too dumb or too lazy, or could it just be that this behaviour is not all that consistent ? v. v. From chris at foote.com.au Thu May 18 02:06:02 2006 From: chris at foote.com.au (Chris Foote) Date: Thu, 18 May 2006 15:36:02 +0930 Subject: Large Dictionaries In-Reply-To: <e4ftjn$bp7$1@newsreader3.netcologne.de> References: <1147699064.107490@teuthos> <e49va0$m72$1@newsreader3.netcologne.de> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> <e4ftjn$bp7$1@newsreader3.netcologne.de> Message-ID: <1147934447.138732@teuthos> Claudio Grondi wrote: > Chris Foote wrote: >> Klaas wrote: >> >>>> 22.2s 20m25s[3] >>> >>> 20m to insert 1m keys? You are doing something wrong. >> >> I've put together some simplified test code, but the bsddb >> module gives 11m for 1M keys: >> > I have run your code for the bsddb on my P4 2.8 GHz and have got: > Number generator test for 1000000 number ranges > with a maximum of 3 wildcard digits. > Wed May 17 16:34:06 2006 dictionary population started > Wed May 17 16:34:14 2006 dictionary population stopped, duration 8.4s > Wed May 17 16:34:14 2006 StorageBerkeleyDB population started > Wed May 17 16:35:59 2006 StorageBerkeleyDB population stopped, duration > 104.3s > > Surprising here, that the dictionary population gives the same time, but > the BerkeleyDB inserts the records 6 times faster on my computer than on > yours. I am running Python 2.4.2 on Windows XP SP2, and you? Fedora core 5 with ext3 filesystem. The difference will be due to the way that Windows buffers writes for the filesystem you're using (it sounds like you're using a FAT-based file system). >> Number generator test for 1000000 number ranges >> with a maximum of 3 wildcard digits. >> Wed May 17 22:18:17 2006 dictionary population started >> Wed May 17 22:18:26 2006 dictionary population stopped, duration 8.6s >> Wed May 17 22:18:27 2006 StorageBerkeleyDB population started >> Wed May 17 22:29:32 2006 StorageBerkeleyDB population stopped, >> duration 665.6s >> Wed May 17 22:29:33 2006 StorageSQLite population started >> Wed May 17 22:30:38 2006 StorageSQLite population stopped, duration 65.5s > As I don't have SQLite installed, it is interesting to see if the factor > 10 in the speed difference between BerkeleyDB and SQLite can be > confirmed by someone else. > Why is SQLite faster here? I suppose, that SQLite first adds all the > records and builds the index afterwards with all the records there (with > db.commit()). SQLite is way faster because BerkeleyDB always uses a disk file, and SQLite is in RAM only. Cheers, Chris From johnjsal at NOSPAMgmail.com Wed May 24 10:45:55 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 24 May 2006 14:45:55 GMT Subject: how to change sys.path? In-Reply-To: <e2n772hhn9rhqi0arkc6qdns0aql6nrvfc@4ax.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <5aGcg.2150$No6.46806@news.tufts.edu> <e4vn3u$brc$1@atlantis.news.tpi.pl> <W8Kcg.2156$No6.46787@news.tufts.edu> <e2n772hhn9rhqi0arkc6qdns0aql6nrvfc@4ax.com> Message-ID: <Dk_cg.2161$No6.46749@news.tufts.edu> Dennis Lee Bieber wrote: > On Tue, 23 May 2006 20:21:10 GMT, John Salerno > <johnjsal at NOSPAMgmail.com> declaimed the following in comp.lang.python: > >> I meant actually adding the PYTHONPATH variable to the environment >> variables list. > > You're looking at editing the Windows registry for that... I just right-clicked on My Computer --> Properties --> Advanced --> Environment Variables, and added a new one called PYTHONPATH. I don't know if that edits the registry, but you don't *manually* have to edit the registry if you do it that way...unless of course you aren't supposed to be doing it that way! But it worked anyway. :) From chris at kateandchris.net Sun May 7 10:06:59 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Sun, 7 May 2006 10:06:59 -0400 Subject: How to doctest if __name__ already used? In-Reply-To: <4c226cF13sh8vU1@individual.net> References: <4c226cF13sh8vU1@individual.net> Message-ID: <20060507140659.GB20209@kateandchris.net> On Fri, May 05, 2006 at 10:33:48PM +0000, Leo Breebaart wrote: > Trigger doctest.testmod() via a "--test" command-line option, is > what I'm thinking. But is that really the best way? That is what I would have suggested. -Chris From bignose+hates-spam at benfinney.id.au Thu May 18 18:19:26 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 19 May 2006 08:19:26 +1000 Subject: number of different lines in a file References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> Message-ID: <87iro3kmc1.fsf@benfinney.id.au> "r.e.s." <r.s at ZZmindspring.com> writes: > I have a million-line text file with 100 characters per line, > and simply need to determine how many of the lines are distinct. I'd generalise it by allowing the caller to pass any iterable set of items. A file handle can be iterated this way, but so can any sequence or iterable. def count_distinct(seq): """ Count the number of distinct items """ counts = dict() for item in seq: if not item in counts: counts[item] = 0 counts[item] += 1 return len(counts) >>> infile = file('foo.txt') >>> for line in file('foo.txt'): ... print line, ... abc def ghi abc ghi def xyz abc abc def >>> infile = file('foo.txt') >>> print count_distinct(infile) 5 -- \ "A man may be a fool and not know it -- but not if he is | `\ married." -- Henry L. Mencken | _o__) | Ben Finney From a.schmolck at gmail.com Sun May 7 16:32:48 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 07 May 2006 21:32:48 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> <yfshd41yeaj.fsf@oc.ex.ac.uk> <87mzdt4ri5.fsf@rpi.edu> Message-ID: <yfsbqu9y3rj.fsf@oc.ex.ac.uk> Bill Atkins <NOatkinwSPAM at rpi.edu> writes: > Here's how one of the cells examples might look in corrupted Python > (this is definitely not executable): > > class FallingRock: > def __init__(self, pos): > define_slot( 'velocity', lambda: self.accel * self.elapsed ) > define_slot( 'pos', lambda: self.accel * (self.elapsed ** 2) / 2, > initial_position = cell_initial_value( 100 ) ) > self.accel = -9.8 > > rock = FallingRock(100) > print rock.accel, rock.velocity, rock.pos > # -9.8, 0, 100 > > rock.elapsed = 1 > print rock.accel, rock.velocity, rock.pos > # -9.8, -9.8, -9.8 > > rock.elapsed = 8 > print rock.accel, rock.velocity, rock.pos > # -9.8, -78.4, -627.2 > > Make sense? No, not at all. Why do you pass a ``pos`` parameter to the constructor you never use? Did you mean to write ``cell_initial_value(pos)``? Why is elapsed never initialized? Is the dependency computation only meant to start once elapsed is bound? But where does the value '0' for velocity come from then? Why would it make sense to have ``pos`` initially be completely independent of everything else but then suddenly reset to something which is in accordance with the other parameters? What happens if I add ``rock.pos = -1; print rock.pos ``? Will I get an error? Will I get -1? Will I get -627.2? To make this more concrete, here is how I might implement a falling rock: class FallingRock(object): velocity = property(lambda self:self.accel * self.elapsed) pos = property(lambda self: 0.5*self.accel * self.elapsed**2) def __init__(self, elapsed=0): self.elapsed = elapsed self.accel = -9.8 rock = FallingRock() print rock.accel, rock.velocity, rock.pos # => -9.8 -0.0 -0.0 rock.elapsed = 1 print rock.accel, rock.velocity, rock.pos # => -9.8 -9.8 -4.9 rock.elapsed = 9 print rock.accel, rock.velocity, rock.pos # => -9.8 -88.2 -396.9 How would you like the behaviour to be different from that (and why)? > The idea is to declare what a slot's value represents > (with code) and then to stop worrying about keeping different things > synchronized. That's what properties (in python) and accessors (in lisp) are for -- if you compute the slot-values on-demand (i.e. each time a slot is accessed) then you don't need to worry about stuff getting out of synch. So far I haven't understood what cells (in its essence) is meant to offer over properties/accessors apart from a straightforward efficiency hack (instead of recomputing the slot-values on each slot-access, you recompute them only when needed, i.e. when one of the other slots on which a slot-value depends has changed). So what am I missing? > Here's another of the examples, also translated into my horrific > rendition of Python (forgive me): > > class Menu: > def __init__(self): > define_slot( 'enabled', > lambda: focused_object( self ).__class__ == TextEntry and > OK, now you've lost me completely. How would you like this to be different in behaviour from: class Menu(object): enabled = property(lambda self: isinstance(focused_object(self),TextEntry) \ and focused_object(self).selection) ??? > Now whenever the enabled slot is accessed, it will be calculated based > on what object has the focus. Again, it frees the programmer from > having to keep these different dependencies updated. Again how's that different from the standard property/accessor solution as above? 'as From JShrager at gmail.com Sun May 7 16:35:20 2006 From: JShrager at gmail.com (JShrager at gmail.com) Date: 7 May 2006 13:35:20 -0700 Subject: (non)compositionality In-Reply-To: <1heyw5k.1997033mne3xrN%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <1vspxcmldcqa5.t1b4abyraqom.dlg@40tude.net> <1heytyi.lope5l1p029gfN%aleaxit@yahoo.com> <19qhkvgj0bdmg.1ex2haasqrgrj.dlg@40tude.net> <1heyw5k.1997033mne3xrN%aleaxit@yahoo.com> Message-ID: <1147034120.609908.184570@i39g2000cwa.googlegroups.com> > There are *NO* semantic advantages for named vs unnamed functions in Python. I feel that this conversation has glanced off the point. Let me try a new approach: There is the Pythonic way (whatever that is), and then The Lisp Way. I don't know what the former is, but it has something to do with indentation, and the (meaningless to me*) phrase "It fits your mind." The Lisp way is quite specific: Pure Compositionality. Compositionality encompasses and defines all aspects of Lisp, from the parens to functional style to fundamental recursion to lambda, and even the language itself is classically composed from the bottom up, and compositionality enables us to create new complete languages nearly trivially. How this concept plays into the current conversation is not subtle: LAMBDA forms server to directly modify the forms in which they appear. SORT is the example that comes to mind for me. If one says: (sort ... #'(lambda (a b) ...)) [I realize that the #' is optional, I use it here for emphasis that there is a function being formed.] the lambda form composes, with sort, a new type of sort -- a sort of type <whatever the lambda function does>. Thus, the semantics of this form are localized to the sort expression, and do not leave it -- they are, indeed, conceptually a part of the sort expression, and to require it/them to be moved outside and given a name breaks the conceptual compositionality -- that is, the compositional locality of the form. Similarly, parens and the functional fact that every form returns a value provide compositional locality and, perhaps more importantly in practice, compositional *mobility* -- so that, pretty much anywhere in Lisp where you need an argument, you can pick up a form and drop it in. [Macros often break this principle, I'll get to those in a moment.] This is something that no other language (except some dead ones, like APL) were able to do, and these provide incredible conceptual flexibility -- again, I'll use the term "mobility" -- one can, in most cases, literally move code as though it were a closed concept to anywhere that that concept is needed. Macros, as I have said, bear a complex relationship to this concept of composition mobility and flexibility. The iteration macro, demonstrated elsewhere in this thread, is an excellent example. But macros are more subtly related to compositionality, and to the present specific question, because, as you yourself said: All you need to do is make up a name that isn't used....But how is one to find a name that isn't used if one has macros? [Actually, in Lisp, even if we didn't have lambda we could do this by code walking, but I'll leave that aside, because Python can't do that, nor can it do macros.] I do not hesitate to predict that Python will someday sooner than later recognize the value of compositional flexibility and mobility, and that it will struggle against parentheses and lambdas, but that in the end it will become Lisp again. They all do, or die. === [*] BA - Biographical Annotation: Yeah, I've programmed all those things too for years and years and years. I also have a PhD in cognitive psychology from CMU, where I worked on how people learn complex skills, and specifically programming. When I say that "fits your brain" is meaningless to me, I mean that in a technical sense: If it had any meaning, I, of all people, would know what it means; meaning that I know that it doesn't mean anything at all. From joesb.coe9 at gmail.com Tue May 9 05:13:09 2006 From: joesb.coe9 at gmail.com (Pisin Bootvong) Date: 9 May 2006 02:13:09 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <slrne60jsm.dac.apardon@rcpc42.vub.ac.be> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> <slrne60jsm.dac.apardon@rcpc42.vub.ac.be> Message-ID: <1147165989.106261.164090@j33g2000cwa.googlegroups.com> Antoon Pardon wrote: > Op 2006-05-09, Pisin Bootvong schreef <joesb.coe9 at gmail.com>: > > Is this a Slippery Slope fallacious argument? > > (http://c2.com/cgi/wiki?SlipperySlope) > > No it is not. > > [...] > > So the question I have is: Why is requiring me to give this function > a name considered a good thing, when it leads to a situation that > is considered bad practice in case of a number. > > -- Slippery Slope:: "Argumentation that A is bad, because A might lead to B, and B to C, and we all know C is very bad." > Why is requiring me to give this function > a name considered a good thing, when it leads to a situation that > is considered bad practice in case of a number. A === "requiring me to give function a name" no B C === "requiring me to give number a name" "Argumentation that requiring one to give function a name is bad, because that might lead to requiring one to give number a name, and we all know that that is very bad." Now you tell me which part of that is not Slippery slope argument. -- Or are you trying to make a sarcastic joke? I'm sorry if I didn't get it. -- From charleshixsn at earthlink.net Sun May 21 15:43:33 2006 From: charleshixsn at earthlink.net (Charles D Hixson) Date: Sun, 21 May 2006 12:43:33 -0700 Subject: Iterators: Would "rewind" be a good idea? Message-ID: <4470C2E5.1020004@earthlink.net> I was reading through old messages in the list and came up against an idea that I thought might be of some value: "Wouldn't it be a good idea if one could "rewind" an iterator?" Not stated in precisely those terms, perhaps, but that's the way I read it. I appreciate that one could use a sequence rather than an iterator, and that I don't understand the implementation issues. (They don't look large, but what to I know?) But would it be a good idea to have a rewind method for iterators? I tend to think of them as mag tapes, and I was always wanting to rewind those. Or skip to file n. (Well, that probably doesn't have any relevance to the usage of iterators.) OTOH, if this is a bother, it's almost always quite easy to create a new iterator, it just feels less efficient. Still, I would use this much more often that I would use reversed (which I've never wanted to use). From fredrik at pythonware.com Mon May 1 13:07:13 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 1 May 2006 19:07:13 +0200 Subject: list*list References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com><4bmotsF126gicU1@uni-berlin.de> <m%q5g.11251$Un3.9202@trnddc05> Message-ID: <e35f83$u77$1@sea.gmane.org> David Isaac wrote: > > it's considered bad style to use range if all you want is a > > enumeration of indices, as it will actually create a list of the size you > > specified. Use xrange in such cases. > > I'm pretty sure this distinction goes away in 2.5. 3.0. and for short sequences, it doesn't really matter much in the 2.X series. it's definitely not "bad style" to use range instead of xrange for a ten to, say, 1000 item loop. (it's not always the most efficient thing to do, though, but that's another story). </F> From ptmcg at austin.rr._bogus_.com Fri May 19 12:24:21 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 16:24:21 GMT Subject: Getting URL's References: <1148019975.277742.253400@y43g2000cwc.googlegroups.com> <7Hdbg.41202$Qq.40549@tornado.texas.rr.com> <1148026352.141338.89290@j73g2000cwa.googlegroups.com> Message-ID: <Vimbg.46825$CH2.20669@tornado.texas.rr.com> "softwindow" <softwindow at gmail.com> wrote in message news:1148026352.141338.89290 at j73g2000cwa.googlegroups.com... > it is difficult to get all URL's in a page <snip> Is this really so hard?: ----------------- from pyparsing import Literal,Suppress,CharsNotIn,CaselessLiteral,\ Word,dblQuotedString,alphanums,SkipTo,makeHTMLTags import urllib # extract all <a> anchor tags - makeHTMLTags defines a # fairly robust pair of match patterns, not just "<tag>","</tag>" linkOpenTag,linkCloseTag = makeHTMLTags("a") link = linkOpenTag + \ SkipTo(linkCloseTag).setResultsName("body") + \ linkCloseTag.suppress() # read the HTML source from some random URL serverListPage = urllib.urlopen( "http://www.google.com" ) htmlText = serverListPage.read() serverListPage.close() # use the link grammar to scan the HTML source for toks,strt,end in link.scanString(htmlText): print toks.startA.href,"->",toks.body ----------------- Prints: /url?sa=p&pref=ig&pval=2&q=http://www.google.com/ig%3Fhl%3Den -> Personalized Home https://www.google.com/accounts/Login?continue=http://www.google.com/&hl=en -> Sign in /imghp?hl=en&tab=wi&ie=UTF-8 -> Images http://groups.google.com/grphp?hl=en&tab=wg&ie=UTF-8 -> Groups http://news.google.com/nwshp?hl=en&tab=wn&ie=UTF-8 -> News http://froogle.google.com/frghp?hl=en&tab=wf&ie=UTF-8 -> Froogle /maphp?hl=en&tab=wl&ie=UTF-8 -> Maps /intl/en/options/ -> more » /advanced_search?hl=en -> Advanced Search /preferences?hl=en -> Preferences /language_tools?hl=en -> Language Tools /intl/en/ads/ -> Advertising Programs /services/ -> Business Solutions /intl/en/about.html -> About Google -- Paul From bencvt at gmail.com Thu May 25 20:12:28 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 25 May 2006 17:12:28 -0700 Subject: list comprehensions put non-names into namespaces! In-Reply-To: <mailman.6206.1148586159.27775.python-list@python.org> References: <1148577813.000229.225330@y43g2000cwc.googlegroups.com> <mailman.6206.1148586159.27775.python-list@python.org> Message-ID: <1148602348.917853.107210@g10g2000cwb.googlegroups.com> skip at pobox.com wrote: > Lonnie> List comprehensions appear to store their temporary result in a > Lonnie> variable named "_[1]" (or presumably "_[2]", "_[3]" etc for > Lonnie> nested comprehensions) > > Known issue. Fixed in generator comprehensions. Dunno about plans to fix > it in list comprehensions. I believe at some point in the future they may > just go away or become syntactic sugar for a gen comp wrapped in a list() > call. The latter, starting in Python 3.0. It won't be fixed before Python 3.0 because it has the potential to break existing 2.x code. From PEP 289: """List comprehensions also "leak" their loop variable into the surrounding scope. This will also change in Python 3.0, so that the semantic definition of a list comprehension in Python 3.0 will be equivalent to list(<generator expression>). Python 2.4 and beyond should issue a deprecation warning if a list comprehension's loop variable has the same name as a variable used in the immediately surrounding scope.""" Source: http://www.python.org/dev/peps/pep-0289/ Also mentioned in PEP 3100. Doesn't look like the deprecation warning was ever implemented for 2.4, though. On my 2.4.3: >>> def f(): [x for x in range(10)] print x >>> f() 9 >>> # no warning yet.. 2.5 is in alpha now, hopefully the warning will be added. --Ben From bignose+hates-spam at benfinney.id.au Mon May 22 18:37:11 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 23 May 2006 08:37:11 +1000 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <bhv172hbu1i37nqi3kp1rhnuaujj1qo208@4ax.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> Message-ID: <87odxp3cvc.fsf@benfinney.id.au> "SamFeltus" <sam at nuevageorgia.com> writes: > I do find it interesting that Flash folks readily will acknowledge > that Flash has shortcomings, yet anti-Flash folks seem to have great > difficulty acknowledging Flash's positive features over HTML. Such > situations always make me suspicious Ludditism is at work. I find it tiresome that Flash apologists believe technical advantages can overcome a need for open, community-driven, vendor-independent standards. -- \ "If trees could scream, would we be so cavalier about cutting | `\ them down? We might, if they screamed all the time, for no good | _o__) reason." -- Jack Handey | Ben Finney From michele.simionato at gmail.com Mon May 15 03:44:37 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 May 2006 00:44:37 -0700 Subject: New tail recursion decorator In-Reply-To: <Xns97BF8E839A8D1duncanbooth@127.0.0.1> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <Xns97BF8E839A8D1duncanbooth@127.0.0.1> Message-ID: <1147679077.003621.211890@g10g2000cwb.googlegroups.com> Duncan Booth wrote: > My other problem with this is that the decorator is very fragile although > this may be fixable This version should be more robust against exceptions: class tail_recursive(object): """ tail_recursive decorator based on Kay Schluehr's recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 """ CONTINUE = object() # sentinel def __init__(self, func): self.func = func self.firstcall = True def __call__(self, *args, **kwd): try: if self.firstcall: # start looping self.firstcall = False while True: result = self.func(*args, **kwd) if result is self.CONTINUE: # update arguments args, kwd = self.argskwd else: # last call break else: # return the arguments of the tail call self.argskwd = args, kwd return self.CONTINUE except: # reset and re-raise self.firstcall = True raise else: # reset and exit self.firstcall = True return result From Michael.J.Fromberger at Clothing.Dartmouth.EDU Mon May 15 12:14:13 2006 From: Michael.J.Fromberger at Clothing.Dartmouth.EDU (Michael J. Fromberger) Date: Mon, 15 May 2006 12:14:13 -0400 Subject: Finding yesterday's date with datetime References: <1147709343.491705.276360@v46g2000cwv.googlegroups.com> Message-ID: <Michael.J.Fromberger-0AB331.12141315052006@localhost> In article <1147709343.491705.276360 at v46g2000cwv.googlegroups.com>, "Thierry Lam" <lamthierry at gmail.com> wrote: > Is there an easy way to determine the yesterday's date(year-month-day) > from the python datetime library if I know today's date? from datetime import datetime, timedelta today = datetime.today() yesterday = today - timedelta(1) # See the .month, .day, and .year fields of yesterday Cheers, -M -- Michael J. Fromberger | Lecturer, Dept. of Computer Science http://www.dartmouth.edu/~sting/ | Dartmouth College, Hanover, NH, USA From paul at boddie.org.uk Tue May 16 12:32:54 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 16 May 2006 09:32:54 -0700 Subject: Help System For Python Applications References: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> <4469fcc4$0$7745$626a54ce@news.free.fr> Message-ID: <1147797174.410449.170480@v46g2000cwv.googlegroups.com> bruno at modulix wrote: > redefined.horizons at gmail.com wrote: > > > On a related note, is there a way to fire up Adobe's Acorbat Reader or > > and Web Browser from Python and have the external application open a > > specified PDF or HTML file? (For example, I want to open the file > > "myhelp.pdf" in reader from Python code.) > > os.system() may be a good start. Take a look at the desktop module for a partial solution: http://www.python.org/pypi/desktop An example: import desktop desktop.open("itools-0.9.0.pdf") Apparently, os.startfile will expose (or already exposes) other parameters which may specify that the file be printed, amongst other things. I may well add such functionality to the desktop module, since various non-Windows systems have supported such things for a while. Paul From rainbow.cougar at gmail.com Fri May 26 09:53:59 2006 From: rainbow.cougar at gmail.com (rainbow.cougar at gmail.com) Date: 26 May 2006 06:53:59 -0700 Subject: a good explanation In-Reply-To: <slrne7bhrs.rhj.nick@irishsea.home.craig-wood.com> References: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> <4dlmsqF1abojeU1@uni-berlin.de> <1148561036.982387.316920@j33g2000cwa.googlegroups.com> <slrne7bhrs.rhj.nick@irishsea.home.craig-wood.com> Message-ID: <1148651639.899363.83240@y43g2000cwc.googlegroups.com> Nick Craig-Wood wrote: > mik3 <mik3l3374 at hotmail.com> wrote: > > So he has written his first program in python and i have roughly toook > > a glance at it and saw what he did.. i pointed out his "mistakes" but > > couldn't convince him otherwise. Anyway , i am going to show him your > > replies.. > > You might want to show him this too...if you happen to need cnt in the > loop, this is what you write > > files = [a,b,c,d] > for cnt, fi in enumerate(files): > do_something(cnt, fi) > > -- > Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick Like many things in Python, measurement is the key, Being an old C coder. I quite often write: i=0 while i<end_condition: something=stuff[i] i++ and try to be a good pythonesita translate it to: for something in stuff: #stuff code A few weeks ago I found myself manipulating a list of lists that I wanted to use as columns and discovered that in: def resort(list,d2list): newlist=[] """ while (i < d2len): newlist.append(list[d2list[i][1]]) i+=1 """ for row in d2list: newlist.append(list[row[1]]) return newlist ran as fast with the while as the for. However, for 'elegance', and to stick to python style, I kept the for. Something that is being missed is the idea of changing conditions. A for loop assumes known boundaries. def condition_test(): # check socket status # return true if socket good, false otherwise while condition_test(): # do stuff allows the loopiing code to react to changing conditions. Which of couse is why we like to keep while loops around ;-0 Curtis From NOatkinwSPAM at rpi.edu Wed May 24 11:15:35 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Wed, 24 May 2006 11:15:35 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> Message-ID: <873bezwj1k.fsf@rpi.edu> Ken Tilton <kentilton at gmail.com> writes: > C'mon, John Bokma (and everyone else dumb enough to crosspost their > shushing to every group on the crosspost list -- why do they do that? > So Xah will hear them six times? No, they want everyone to see how > witty they are when they tell Xah off. Now /that/ is spam) is the > problem. +12 ! -- You fool! You fell victim to one of the classic blunders! The most famous is, "Never get involved in a land war in Asia", but only slightly less well-known is this: "Never go in against a Sicilian when death is on the line"! From tjreedy at udel.edu Thu May 18 18:42:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Thu, 18 May 2006 18:42:57 -0400 Subject: Question about exausted iterators References: <446b48e2$0$5293$626a54ce@news.free.fr><mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> Message-ID: <e4it9g$utf$1@sea.gmane.org> "Christophe" <chris.cavalaria at free.fr> wrote in message news:446c2dea$0$5306$626a54ce at news.free.fr... >Instead of saying that all works as intended could you be a little >helpful and tell me why it was intended in such an obviously broken way >instead ? I answered both your explicit and implied questions in good faith. But you seem to be too attached to your pre-judgment to have benefited much, so I won't waste my time and yours saying more. Instead I suggest that you try this: 1. Write a specification for your an alternate, more complicated, iterator protocol. 2. Write a simple class with .next method that implements your specification. 3. Test your class with your example. 4. Consider how you would persuade people to add the extra machinery needed. 5. Consider what you would do when people don't. If you want, post a report on your experiment, and I will read it if I see it. Terry Jan Reedy From robin.meier at gmail.com Thu May 25 08:13:06 2006 From: robin.meier at gmail.com (robin) Date: 25 May 2006 05:13:06 -0700 Subject: webbrowser module bug on os x? Message-ID: <1148559186.196535.224720@j73g2000cwa.googlegroups.com> hi it seems to me like the webbrowser command webbrowser.open('http://www...', new=0) does not work as advertised: all the urls open in seperate windows regardless of the default browser (safari, firefox, mozilla). i do not have this problem on windows... can anyone help? thank you in advance. robin From maric at aristote.info Tue May 16 02:20:38 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 May 2006 08:20:38 +0200 Subject: Large Dictionaries In-Reply-To: <4cs1qgF17ee24U1@uni-berlin.de> References: <1147699064.107490@teuthos> <mailman.5727.1147715121.27775.python-list@python.org> <4cs1qgF17ee24U1@uni-berlin.de> Message-ID: <200605160820.39791.maric@aristote.info> Le Lundi 15 Mai 2006 21:07, Diez B. Roggisch a ?crit?: > > d={}.fromkeys(xrange(5*10**6)) ? > > That is a totally different beast. You don't want to insert arbitrary > keys, you want the internal hash-array to be of the right size. But you can replace the xrange part by any generator function you want. def get_mykeys(..) ... yield key I just the wonder if the time consuming part is the memory allocation of hash table (key by key) or the hash operation itself. I don't see a use case where a python programmer should need a dictionnary "that will be probably big" but can't predict what keys will be in. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From bignose+hates-spam at benfinney.id.au Wed May 17 02:05:49 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 16:05:49 +1000 Subject: assignment in a for loop References: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> <mailman.5781.1147842350.27775.python-list@python.org> <1147843606.982432.269470@38g2000cwa.googlegroups.com> Message-ID: <87ves5nq2q.fsf@benfinney.id.au> "MackS" <mackstevenson at hotmail.com> writes: > Thank you for your reply. A pleasure to help. > > What's preventing the use of list comprehensions? > > > > new_list = [x+1 for x in old_list] > > Suppose I want to do anything as trivial as modify the values of the > list members _and_ print their new values. List comprehensions must > not contain statements, I think. You're correct, but that's because you're creating a new list, not modifying the existing one. The list comprehension can do anything you like to generate each element, so long as it's an expression:: >>> foo = [3, 5, 8] >>> print [x+1 for x in foo] [4, 6, 9] >>> print [x**2 for x in foo] [9, 25, 64] >>> print [str(x**2) for x in foo] ['9', '25', '64'] >>> print [len(str(x**2)) for x in foo] [1, 2, 2] If it's too complex to be readable in a single expression, make it a function which returns a value, since calling a function is itself an expression:: >>> def get_result_of_complex_stuff(n): ... quad = n**4 ... if len(str(quad)) % 2: ... word = "spam" ... else: ... word = "eggs" ... result = word.strip("s").title() ... return result ... >>> foo = [3, 5, 8] >>> print [get_result_of_complex_stuff(x) for x in foo] ['Egg', 'Pam', 'Egg'] Once you have your new list being created by a list comprehension, do what you like with it. If you want it to be stored, assigned back to the original name, each value printed, or whatever you like, then do so:: >>> bar = [get_result_of_complex_stuff(x) for x in foo] >>> foo = bar >>> for x in foo: ... print x, ... Egg Pam Egg -- \ "One time a cop pulled me over for running a stop sign. He | `\ said, 'Didn't you see the stop sign?' I said, 'Yeah, but I | _o__) don't believe everything I read.'" -- Steven Wright | Ben Finney From johnjsal at NOSPAMgmail.com Wed May 17 15:23:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 19:23:08 GMT Subject: creating a new database with mysqldb In-Reply-To: <1147893204.503850.225770@j73g2000cwa.googlegroups.com> References: <gcKag.2113$No6.46302@news.tufts.edu> <1147893204.503850.225770@j73g2000cwa.googlegroups.com> Message-ID: <wKKag.2114$No6.46328@news.tufts.edu> BartlebyScrivener wrote: > Type: > > create a new database with mysql > > into google and see what happens > > rd > Well, the thing about it is that all the guides I find online seem to begin with using a command prompt or a unix shell, neither of which will work in my case. I'm trying to find a way to access my database server using just a python script. Perhaps that isn't even possible for me to do without shell access. I might just have to use the msqladministrator in my server control panel, instead of using python. From frank at chagford.com Fri May 26 09:25:51 2006 From: frank at chagford.com (Frank Millman) Date: 26 May 2006 06:25:51 -0700 Subject: Speed up this code? In-Reply-To: <1148647447.804097.228580@j33g2000cwa.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <4476d3ac_2@newspeer2.tds.net> <1148647447.804097.228580@j33g2000cwa.googlegroups.com> Message-ID: <1148649951.816182.134210@g10g2000cwb.googlegroups.com> bearophileHUGS at lycos.com wrote: > If you are interested in such programs, you can take a look at this one > too: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178 > > It requires more memory, but it's quite fast. > > Bye, > bearophile I compared the speed of this one (A) with the speed of Paul Rubin's above (B). Primes from 1 to 100 - A - 0.000118 B - 0.000007 Primes from 1 to 200 - A - 0.000224 B - 0.000008 Primes from 1 to 300 - A - 0.000278 B - 0.000008 Nice one, Paul. Frank Millman From grante at visi.com Tue May 2 15:28:16 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 02 May 2006 19:28:16 -0000 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <I9O5g.2039$No6.43918@news.tufts.edu> Message-ID: <125fcmg5j8u8q32@corp.supernews.com> On 2006-05-02, John Salerno <johnjsal at NOSPAMgmail.com> wrote: >> Python knows how to count. :) >> >> def countFalse(seq): >> return len([v for v in seq if not v]) >> >> def countTrue(seq): >> return len([v for v in seq if v]) >> >> def truth_test(seq): >> return countTrue(seq) == 1 > > Gosh, so much to learn! Of course, I already know all about list > comprehensions, but now I just need to learn to *use* them! :) That's the part that takes a while... -- Grant Edwards grante Yow! Is this "BOOZE"? at visi.com From kak at purdue.edu Mon May 8 11:13:06 2006 From: kak at purdue.edu (Avi Kak) Date: 8 May 2006 08:13:06 -0700 Subject: Retrieving event descriptors in Tkinter In-Reply-To: <mailman.5479.1147099497.27775.python-list@python.org> References: <1147098160.527716.100700@y43g2000cwc.googlegroups.com> <mailman.5479.1147099497.27775.python-list@python.org> Message-ID: <1147101186.340430.20860@y43g2000cwc.googlegroups.com> Thanks very much. That's exactly what I was looking for. --- Avi From bignose+hates-spam at benfinney.id.au Tue May 16 18:41:29 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 08:41:29 +1000 Subject: taking qoutes in arguments References: <98063b170605150748h3d0fffddibd6f8de28fff3d4f@mail.gmail.com> <87k68mrisa.fsf@benfinney.id.au> <98063b170605160623h2eca5a04xf106264d7909ef8f@mail.gmail.com> Message-ID: <8764k5r3s6.fsf@benfinney.id.au> "Lee Caine" <kano.priv at gmail.com> writes: > yea thanks alot for your help, gonna read up on 'Konsole' :) Be advised that 'Konsole' is not a command shell, it's a GUI program for running a command shell. On POSIX systems, find out what your current command shell is with this command: echo $SHELL -- \ "Working out the social politics of who you can trust and why | `\ is, quite literally, what a very large part of our brain has | _o__) evolved to do." -- Douglas Adams | Ben Finney From sybrenUSE at YOURthirdtower.com.imagination Mon May 8 09:26:00 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 8 May 2006 15:26:00 +0200 Subject: Web framework comparison video References: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> <slrne5uh9v.3lr.sybrenUSE@schuimige.stuvel.eu> Message-ID: <slrne5uhn8.3sj.sybrenUSE@schuimige.stuvel.eu> Sybren Stuvel enlightened us with: > Perhaps I'll look into Plone for my site in the future ;-) I take that back. The Plone webserver is hosted by XS4ALL, the best ISP in The Netherlands, which resides in Amsterdam. I happen to live in Amsterdam too, so you'd expect the site to be fast. Well, it took 5 to 15 seconds to get a page from their FAQ[1], which is just way too slow. As a comparison, the XS4ALL website[2] took only 0.4 seconds. I tested it using "time lynx -dump $URL >/dev/null". [1] http://plone.org/documentation/faq/products-for-plone [2] http://www.xs4all.nl/ > For now, I'm very happy with my own framework > (http://www.unrealtower.org/engine) Looks like I'll be happy a while longer! Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From mensanator at aol.com Sat May 13 13:54:10 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 13 May 2006 10:54:10 -0700 Subject: Slovenian Python User Group In-Reply-To: <mailman.5654.1147506625.27775.python-list@python.org> References: <mailman.5654.1147506625.27775.python-list@python.org> Message-ID: <1147542850.468492.316380@j73g2000cwa.googlegroups.com> Sebastjan Trepca wrote: > Hi! > > just wanted to send a notice about a new portal/group for Slovenian > Python fans here :) > > http://soup.zen.si (btw, it's in slovene lang) But why is SOUP (Slovenski Ortodoksni Uporabniki Pythona) used as an acronym? Or is SOUP a word in Slovene also? > > Sebastjan From trebucket at gmail.com Thu May 25 17:08:45 2006 From: trebucket at gmail.com (trebucket at gmail.com) Date: 25 May 2006 14:08:45 -0700 Subject: Problem with itertools.groupby. Message-ID: <1148591325.875006.246120@j55g2000cwa.googlegroups.com> What am I doing wrong here? >>> import operator >>> import itertools >>> vals = [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), ... (1, 16), (2, 17), (3, 18), (4, 19), (5, 20)] >>> for k, g in itertools.groupby(iter(vals), operator.itemgetter(0)): ... print k, [i for i in g] ... 1 [(1, 11)] 2 [(2, 12)] 3 [(3, 13)] 4 [(4, 14)] 5 [(5, 15)] 1 [(1, 16)] 2 [(2, 17)] 3 [(3, 18)] 4 [(4, 19)] 5 [(5, 20)] What I want is tuples starting with identical numbers to be grouped. I cannot figure out why this is not working. If anyone has any insights, I would appreciate it. - Alex Ross From WSobczuk at gmail.com Thu May 18 10:23:27 2006 From: WSobczuk at gmail.com (WSobczuk at gmail.com) Date: 18 May 2006 07:23:27 -0700 Subject: Strange error Message-ID: <1147962206.900840.19130@38g2000cwa.googlegroups.com> I have encountered a very strange error and I'm hoping that some Python hackers here could give me insight on this. searchview.py file contains two functions: def mysearch(indexname, request, c, page = 0, searchdburl = INDEX_URL, query_add = {}, queries = [], form = True, limit = DEFAULT_LIMIT, tags = {}, order = ''): and def search(findquery, path = None, page=0, tags = {}, order='', limit = DEFAULT_LIMIT, queries=[], searchdburl = INDEX_URL): I import and call both from various places. Now recently I discovered that when I call: mysearch('pubcomm', request, vars, page = page, query_add = query_add) from one place, then inside mysearch() (I test it at the start of the function) the tags argument *has* a value leftover from apparently from a previous call. When investigating I have also found that it sometimes has the value of the search() function's tags parameter from, apparently, some previous call. After I changed the call to this: mysearch('pubcomm', request, vars, page = page, query_add = query_add, tags = {}) the error stopped occurring, so it seems that what I'm suspecting is right. The searchview.py file does not contain any global 'tags' variable, but the search() function does process it's own tags argument like so: tags = dict([(k, listify(v)) for k, v in tags.iteritems()]) The whole thing is happening on Python 2.4.2 on Linux (I tried it on Fedora and Gentoo). It's under a heavy load (the whole thing happens inside a Flup based FCGI backend), but I'm not using threads so there is no concurrency involved - only sequential processing of requests. I haven't isolated a test case yet, hoping that someone could give me a hint on this. Maybe I'm making some stupid mistake or maybe it's some namespace bug (or 'feature'). Any ideas? Thanks, Wojtek From deets at nospam.web.de Mon May 8 11:24:13 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 08 May 2006 17:24:13 +0200 Subject: connect file object to standard output? References: <1147101408.320069.12780@g10g2000cwb.googlegroups.com> Message-ID: <4c964tF14si09U1@uni-berlin.de> beliavsky at aol.com wrote: > I want to write a function that writes to an output file if specified > and otherwise to standard output. How can I connect a file object to > standard output in the code below? I could use an if statement to > choose between print and print>>fp throughout the function, but this > seems awkward. I think there is a way to connect standard output to a > file, but I'd prefer not to do that, since I want to use plain print > statements to warn about errors in the function and have their output > appear on the screen. Thanks. > > def write_data(data,out_file=""): > if (out_file != ""): > fp = open(out_file,"w") > else fp = sys.stdout > print>>fp,data > # more print>>fp statements follow sys.stdout _is_ a file... DIez From andy47 at gmail.com Wed May 10 06:35:58 2006 From: andy47 at gmail.com (andy47 at gmail.com) Date: 10 May 2006 03:35:58 -0700 Subject: Is PythonCard dead? In-Reply-To: <1147238793.364423.3800@g10g2000cwb.googlegroups.com> References: <1147228229.133910.118410@g10g2000cwb.googlegroups.com> <1147238793.364423.3800@g10g2000cwb.googlegroups.com> Message-ID: <1147257358.435733.44240@i39g2000cwa.googlegroups.com> Luis M. Gonz?lez wrote: > 18 months? Wow!.. time flies... > Anyway, PythonCard is a fine product, and it's very good just the way > it is. > It would be great if a new release comes up though... The mailing list is quite active : http://news.gmane.org/gmane.comp.python.pythoncard And there is work on the next release, it'll be here any day/week/month now; http://article.gmane.org/gmane.comp.python.pythoncard/1955 Regards, Andy From invalidemail at aerojockey.com Sat May 13 15:46:55 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 13 May 2006 12:46:55 -0700 Subject: distributing a app frozen by cx_freeze In-Reply-To: <1147536825.158172.73480@i40g2000cwc.googlegroups.com> References: <1147482467.404798.187530@y43g2000cwc.googlegroups.com> <1147501391.800070.265860@g10g2000cwb.googlegroups.com> <1147536825.158172.73480@i40g2000cwc.googlegroups.com> Message-ID: <1147549615.716786.240560@d71g2000cwd.googlegroups.com> Flavio wrote: > Well I managed to get rid of the undefined symbol message by copying > all qt libs to the freeze directory, the problem is that now the > package is huge (83MB)! > > So my question is: is there a way to find out exactly which lib is > missing ? You know, if you're doing this on Linux, it's not all that unreasonable to require QT to be installed on the target system. Any reasonable distribution has it nicely packaged. But, if you must, "ldd qt.so" will list library dependencies of qt.so. Carl Banks From michele.simionato at gmail.com Mon May 15 04:46:33 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 15 May 2006 01:46:33 -0700 Subject: Decorator In-Reply-To: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> Message-ID: <1147682793.621176.181170@g10g2000cwb.googlegroups.com> I will shamelessly plug in my own decorator module: http://www.phyast.pitt.edu/~micheles/python/decorator.zip and http://www.phyast.pitt.edu/~micheles/python/documentation.html From webraviteja at gmail.com Fri May 26 01:21:27 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 25 May 2006 22:21:27 -0700 Subject: IronPython 1.0 Beta 7 Released In-Reply-To: <1148564746.724535.259140@38g2000cwa.googlegroups.com> References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> <1148518396.856710.173810@g10g2000cwb.googlegroups.com> <1148532003.624344.88030@38g2000cwa.googlegroups.com> <1148564746.724535.259140@38g2000cwa.googlegroups.com> Message-ID: <1148620887.444701.272180@y43g2000cwc.googlegroups.com> > Can you recommend a book or a link for a person learning Python on > Windows who does not yet know C# or .NET? Since Python is cross-platform, any Python book will do. If you need to do MS Windows specific programming (COM and OLE automation, Windows Services etc), you can use Mark Hammond's "Python Programming On Win32". From andy at neotitans.com Sat May 20 08:31:23 2006 From: andy at neotitans.com (Andy Sy) Date: Sat, 20 May 2006 20:31:23 +0800 Subject: The ONE TRUE WAY to use tabs (Re: Tabs versus Spaces in Source Code) In-Reply-To: <1147907634.532463.63730@u72g2000cwu.googlegroups.com> References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <mailman.5846.1147904183.27775.python-list@python.org> <1147907634.532463.63730@u72g2000cwu.googlegroups.com> Message-ID: <e4n1vr$pk8$1@sea.gmane.org> achates wrote: > Yeah - we've got to the repeating ourselves stage. Actually a couple of the responses on this newsgroup have settled the question for me. I did learn something new by engaging in this holy war. Tabs need not be evil, but ONLY if they are used in one particular way: If you really must use tabs, use them *ONLY* for 'semantic' indentation and use pure spaces when you need arbitrary indentation (e.g. arbitrary spacing). PHP Example =========== function xyz() { ->print "This is a really really really long line that I'd ". -> "like to extend to the one down below while preserving ". -> "ease of readability by aligning the start of the string". -> "lines. I use tabs to reflect syntactical (e.g. semantic) ". -> "indentation, but use spaces for arbitrary indentation.\n\n".; ->while (10) { ->->print "This code will align properly no matter what tabsize setting ". ->-> "the reader uses, and is the only real benefit of using tab ". ->-> "characters instead of pure spaces.\n\n"; } I did some basic tests, and it looks like this style should also work for Python code. THIS IS THE *SINGLE* CORRECT WAY TO USE TABS IN CODE! ANYTHING ELSE WILL BE A PAIN FOR PEOPLE WITH TABSIZE SETTINGS DIFFERENT FROM YOURS!! > But that's the problem with this issue: it's really hard to get the > space-indenters to actually think about it and to address what is being > said. Every time it comes up, there's always a few people trying to > explain why tabs give are a good idea, facing a whole raft of others > spouting stuff like: Most of the tab-indenters have the same attitude. But I did get ALL of my points against tabs addressed this time. And thank you to those people including you for the 'less -x<tabstop>' tip. > But unfortunately the situation is worse than that: tab indentation > needs to be actively defended. A world where everyone uses pure spaces would be far far far better than the current situation where tab users can't even decide what the universal tabsize should be and whose code alignment breaks on different tabsize settings. However, a world where EVERYONE who uses tabs strictly practice the ONE TRUE TAB WAY would be a *slightly* better place than one where everyone used pure spaces. And remember, the ONE TRUE TAB WAY does not come for free and involves a certain amount of tedium and attention. It will be impractical on most simple text editors. For most people, I frankly don't think the minor benefits are worth it. > Unlikely perhaps. I hope so. It's a cruel irony that Python's creator > didn't appreciate the benefits that tab indentation would bring to his > own language - the only major language in which indentation levels > actually have semantic significance. You might want to run those benefit/s/ by me again, because the SINGLE benefit I can still see to using tabs is so that people who have different indentation width preferences can view code according to the way they want. And remember, this benefit will ONLY occur IF people stick to using the ONE TRUE TAB WAY outlined above. Any other method of tabbing would just be worse than a pure-spaces world. -- It's called DOM+XHR and it's *NOT* a detergent! From kentilton at gmail.com Sat May 6 11:09:18 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 11:09:18 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1146900379.023190.164640@u72g2000cwu.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1146900379.023190.164640@u72g2000cwu.googlegroups.com> Message-ID: <y_27g.17$pv7.8@fe08.lga> Kay Schluehr wrote: > Ken Tilton wrote: > > >>Oh, my, you are preaching to the herd (?!) of lemmings?! Please tell me >>you are aware that lemmings do not have ears. You should just do Lisp >>all day and add to the open source libraries to speed Lisp's ascendance. >>The lemmings will be liberated the day Wired puts John McCarthy on the >>cover, and not a day sooner anyway. > > > And then the 12th vanished Lisper returns and Lispers are not > suppressed anymore and won't be loosers forever. The world will be > united in the name of Lisp and Lispers will be leaders and honorables. > People stop worrying about Lispers as psychpaths and do not consider > them as zealots, equipped with the character of suicide bombers. No, > Lisp means peace and paradise. > "The Twelfth Vanished Lisper"? I love it. Must start a secret society.... :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From johnjsal at NOSPAMgmail.com Wed May 24 13:24:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 24 May 2006 17:24:08 GMT Subject: how to change sys.path? In-Reply-To: <532972pkqut50suspvi4qhmkkeporlcopv@4ax.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <5aGcg.2150$No6.46806@news.tufts.edu> <e4vn3u$brc$1@atlantis.news.tpi.pl> <W8Kcg.2156$No6.46787@news.tufts.edu> <e2n772hhn9rhqi0arkc6qdns0aql6nrvfc@4ax.com> <Dk_cg.2161$No6.46749@news.tufts.edu> <532972pkqut50suspvi4qhmkkeporlcopv@4ax.com> Message-ID: <YE0dg.2171$No6.46883@news.tufts.edu> Dennis Lee Bieber wrote: > I may have gotten slightly confused That's my job. :) From go at away.com Sun May 28 20:29:56 2006 From: go at away.com (3rdshiftcoder) Date: Mon, 29 May 2006 00:29:56 GMT Subject: pyswt SWT.NULL References: <O6reg.2716$HV1.383@trndny01> Message-ID: <8greg.680$Oa3.561@trndny09> I got it. it is SWT.None thanks, jim "3rdshiftcoder" <go at away.com> wrote in message news:O6reg.2716$HV1.383 at trndny01... > hi- > > i am trying to make a pyswt gui and when it gets to this line: > colType = Combo(self.shell, SWT.NULL) > > i get: > colType = Combo(self.shell, SWT.NULL) > AttributeError: NULL > > when using swt with java i had to have lots of imports at the beginning of > a swt file. > are they not needed when using pyswt? > > thanks for any help, > jim > From tomerfiliba at gmail.com Fri May 19 15:00:18 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 19 May 2006 12:00:18 -0700 Subject: combining a C# GUI with Python code? In-Reply-To: <3Dnbg.2135$No6.46516@news.tufts.edu> References: <3Dnbg.2135$No6.46516@news.tufts.edu> Message-ID: <1148065218.059284.124370@j33g2000cwa.googlegroups.com> see http://interpython.sourceforge.net From Serge.Orlov at gmail.com Wed May 3 17:11:11 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 3 May 2006 14:11:11 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <1146689930.600243.65340@v46g2000cwv.googlegroups.com> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> Message-ID: <1146690671.421084.56450@i40g2000cwc.googlegroups.com> OlafMeding at gmail.com wrote: > > What do you mean "stop responding"? > > Both threads print their thread numbers (either 1 or 2) approximately > every 10 seconds. However, after a while (minutes to hours) both > programs (see above) hang! > > Pressing ctrl-c (after the printing stops) causes the threads to "wake > up" from their sleep statement. And since the sleep took more than 1 > seconds the thread number and the duration of the sleep is printed to > the screen. > > Do you have a hyper-threading/dual/multi core CPU? Did you try this? I don't have such CPU but I run the first program anyway. It printed C:\py>th.py thread 1 started sleep time: 0.01 3.63174649292e-006 8.43682646817e-005 0.000164825417756 thread 2 started sleep time: 0.003 0.000675225482568 0.000753447714724 0.00082943502596 1 1 1 2 1 1 1 2 1 1 1 2 1 1 1 1 2 1 1 1 2 1 I got bored and tried to stop it with ctrl-c but it didn't respond and kept running and printing the numbers. I had to kill it from task manager. From Dorit.Gross at fao.org Mon May 15 09:29:13 2006 From: Dorit.Gross at fao.org (Gross, Dorit (SDRN)) Date: Mon, 15 May 2006 15:29:13 +0200 Subject: How to pass variables between scripts? Message-ID: <5290E77B1FE2FE40B82AA54158825F0602EF50F9@hqosex01.fao.org> > > > > #! /usr/local/bin/python > > # test_exec.py > > > > import os, sys, glob > > > > fileList = glob.glob('/data/*.ZIP') > > > > for f in fileList: > > try: > > globvars = {'infile' : f} > > locvars = {} > > execfile('/scripts/second.py', globvars(), locvars) > > except IOError: > > exit(0) > > print locvars > > > > > > You are calling the dictionary globvars as a function then the error. > The fixed line is: > > execfile('/scripts/second.py', globvars, locvars) > > > > What you want is the function globals(). > Try putting this line in second.py: > > print globals()['infile'] > > Using the dictionary returned by globals() you can make second.py to > read the contents of testexec.py's globvars dictionary. > locvars is populated with the local variables of second.py > and that is > what you want. > Marcelo, thank you! Passing the variables with dictonaries and function globals() works fine if no other functions are defined in 'second.py'. Now 'second.py' contains further functions and a "if __name__ = __main__" statement and in this case it seems that 'second.py' is not fully executed from 'test_exec.py'. For the sole purpose of testing, 'second.py' looks like this at the moment: #! /usr/local/bin/python # second.py import os, sys global zipfile print 'Read from globals: ' + globals()['infile'] zipfile = globals()['infile'] print 'Read from zipfile: ' + zipfile if __name__ == '__main__': print 'Hello' print globals()['infile'] print zipfile Calling test_exec.py results into this output: ./test_exec.py Read from globals: /data/S0012230_0010.ZIP Read from zipfile: /data/S0012230_0010.ZIP It seems that the commands within the main are not executed when calling test_exec.py!?! Is there a way to make it running? Regards and thank you again, Dorit From seberino at spawar.navy.mil Wed May 3 21:52:49 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 3 May 2006 18:52:49 -0700 Subject: Any useful benefit to a tiny OS written in Python? Message-ID: <1146707569.227486.278750@j73g2000cwa.googlegroups.com> I was curious if there was any benefit to having an OS written in Python. The only benefit I can think of is that maybe Python is easier to audit for security bugs than C is. Any other benefits? Chris From steve at hastings.org Tue May 2 15:35:16 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 02 May 2006 12:35:16 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <I9O5g.2039$No6.43918@news.tufts.edu> Message-ID: <pan.2006.05.02.19.35.15.219815@hastings.org> On Tue, 02 May 2006 19:11:36 +0000, John Salerno wrote: > Grant Edwards wrote: > >> Python knows how to count. :) >> >> def countFalse(seq): >> return len([v for v in seq if not v]) >> >> def countTrue(seq): >> return len([v for v in seq if v]) >> >> def truth_test(seq): >> return countTrue(seq) == 1 > > Gosh, so much to learn! Of course, I already know all about list > comprehensions, but now I just need to learn to *use* them! :) Play around with them. They are fun. :-) We could also use "generator expressions", available only in Python 2.4 and newer. A list comprehension always builds a list. A generator expression can return values one at a time. [v for v in seq if v] # builds a list and returns it (v for v in seq if v) # returns a generator object len([v for v in seq if v]) # builds a list, then feeds it to len() len(v for v in seq if v) # gen obj feeds values to len one at a time The generator expression saves Python from having to build a list and then destroy the list. It's useful when you only care about the *values* and you don't want to save the list. For a short list, the savings are small; but for a really large list, a generator expression can save a lot of wasted effort in building the new list and destroying it. Python 2.5 will be introducing two new functions, "all()" and "any()", which are intended for use mostly with generator expressions: any(v for v in seq if v) # true if any v evaluates true all(v for v in seq if v) # true if *all* v evalute true Or a better example: any(is_green(x) for x in lst) # true if any value in list is green -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From a.schmolck at gmail.com Mon May 22 07:25:47 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 22 May 2006 12:25:47 +0100 Subject: string.count issue (i'm stupid?) References: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> <1148296237.506185.41860@y43g2000cwc.googlegroups.com> Message-ID: <yfszmhal2ro.fsf@oc.ex.ac.uk> "Dirk Hagemann" <DirkHagemann at gmail.com> writes: > I think I can tell you WHY this happens, but I don't know a work-around > at the moment. len(re.findall('_(?=a_)', '_a_a_a_a_')) # untested def countWithOverlaps(s, pat): return len(re.findall("%s(?=%s)" % (re.escape(pat[0]), re.escape(pat[1:])),s)) 'as From michele.petrazzo at TOGLIunipex.it Sat May 6 05:13:55 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Sat, 06 May 2006 09:13:55 GMT Subject: Best IDE for Python? In-Reply-To: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> Message-ID: <nNZ6g.111127$PR2.1722281@twister2.libero.it> Saurabh Sardeshpande wrote: > Pardon if this is already discussed extensively. But what is the best > IDE for Python for a newbie? I have experience in C++ and Java and this > is the first time I am learning a scripting language. > Thanks in advance > Try all the you find! However on linux I find eric3(4) very useful. Bye, Michele From mike at hobbshouse.org Mon May 8 11:02:32 2006 From: mike at hobbshouse.org (Michael Hobbs) Date: Mon, 08 May 2006 10:02:32 -0500 Subject: ANN: iTorrent alpha-2 Message-ID: <445F5D88.7040603@hobbshouse.org> Announcing the second alpha release of iTorrent. iTorrent allows you to download BitTorrent podcasts from iTunes. It transforms BitTorrent podcasts so that you can update them just like any other podcast in iTunes. Details can be found at http://www.itorrent.cc. iTorrent is written in Python and is released under the GPL. With its second alpha release, iTorrent still isn't pretty, but it is much easier to install and run. Technical Details: iTorrent runs as an RSS proxy on your local machine and will fetch enclosures from a BitTorrent network on behalf of iTunes. The BitTorrent content will then be fed to iTunes via a standard HTTP loopback connection. It uses the official BitTorrent 4.4.0 code to perform the actual downloads from a BitTorrent network. (http://www.bittorrent.com) Regards, - Michael Hobbs <mike at hobbshouse.org> From sjmachin at lexicon.net Thu May 25 17:11:17 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 May 2006 07:11:17 +1000 Subject: regex/lambda black magic In-Reply-To: <127bu3vklr0g56e@corp.supernews.com> References: <127be5or10v59e9@corp.supernews.com> <mailman.6197.1148570049.27775.python-list@python.org> <127bnkqc8pdoef5@corp.supernews.com> <mailman.6201.1148576793.27775.python-list@python.org> <127bu3vklr0g56e@corp.supernews.com> Message-ID: <44761D75.8060605@lexicon.net> On 26/05/2006 4:33 AM, Andrew Robert wrote: > Hi Everyone, > > > Thanks for all of your patience on this. > > I finally got it to work. > > > Here is the completed test code showing what is going on. Consider doing what you should have done at the start: state what you are trying to achieve. Not very many people have the patience that Max showing ploughing through code that was both fugly and broken in order to determine what it should have been doing. What is the motivation for encoding characters like ,./<>;':"`~!@#$^&*()-+=[]\{}| > > Not cleaned up yet but it works for proof-of-concept purposes. > > > > #!/usr/bin/python > > import re,base64 > > # Evaluate captured character as hex > def ret_hex(value): > return '%'+base64.b16encode(value) This is IMHO rather pointless and obfuscatory, calling a function in a module when it can be done by a standard language feature. Why did you change it from the original "%%%2X" % value (which would have been better IMHO done as "%%%02X" % value)? > > # Evaluate the value of whatever was matched > def enc_hex_match(match): > return ret_hex(match.group(0)) Why a second level of function call? > > def ret_ascii(value): > return base64.b16decode(value) See above. > > # Evaluate the value of whatever was matched > def enc_ascii_match(match): > > arg=match.group() > > #remove the artifically inserted % sign Don't bother, just ignore it. return int(match()[1:], 16) > arg=arg[1:] > > # decode the result > return ret_ascii(arg) > > def file_encoder(): > # Read each line, pass any matches on line to function for > # line in file.readlines(): > output=open(r'e:\pycode\sigh.new','wb') > for line in open(r'e:\pycode\sigh.txt','rb'): > output.write( (re.sub('[^\w\s]',enc_hex_match, line)) ) > output.close() Why are you opening the file with "rb" but then reading it a line at a time? For a binary file, the whole file may be one "line"; it would be safer to read() blocks of say 8Kb. For a text file, the only point of the binary mode might be to avoid any sort of problem caused by OS-dependant definitions of "newline" i.e. CRLF vs LF. I note that as \r and \n are whitespace, you are not encoding them as %0D and %0A; is this deliberate? > > def file_decoder(): > # Read each line, pass any matches on line to function for > # line in file.readlines(): > > output=open(r'e:\pycode\sigh.new2','wb') > for line in open(r'e:\pycode\sigh.new','rb'): > output.write(re.sub('%[0-9A-F][0-9A-F]',enc_ascii_match, line)) > output.close() > > > > > file_encoder() > > file_decoder() From eurleif at ecritters.biz Wed May 3 18:58:04 2006 From: eurleif at ecritters.biz (Leif K-Brooks) Date: Wed, 03 May 2006 18:58:04 -0400 Subject: scope of variables In-Reply-To: <87zmhyagqq.fsf@localhost.localdomain> References: <874q06bz4c.fsf@localhost.localdomain> <pan.2006.05.03.21.37.01.804277@hastings.org> <87zmhyagqq.fsf@localhost.localdomain> Message-ID: <445934ef$0$3703$4d3efbfe@news.sover.net> Gary Wessle wrote: > the example was an in-accuretlly representation of a the problem I am > having. my apologies. > > a = [] > def prnt(): > print len(a) > >>>> prnt > <function prnt at 0xb7dc21b4> > > I expect to get 0 "the length of list a" Python requires parenthesis to call a function. >>> a = [] >>> def prnt(): ... print len(a) ... >>> prnt <function prnt at 0xb7dcad84> >>> prnt() 0 From python.list at tim.thechases.com Fri May 12 09:09:31 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 12 May 2006 08:09:31 -0500 Subject: NEWBIE: Tokenize command output In-Reply-To: <446478eb$0$287$626a54ce@news.free.fr> References: <lorenzo-58D5E4.10282511052006@hedley.thethurmans.com> <mailman.5590.1147362357.27775.python-list@python.org> <446478eb$0$287$626a54ce@news.free.fr> Message-ID: <4464890B.6020109@tim.thechases.com> >>starLines = [line for line in p.readlines() if line.startswith("*")] > > files are iterators, so no need to use readlines() (unless it's an old > Python version of course): > > starLines = [line for line in p if line.startswith("*")] Having started with some old Python, it's one of those things I "know", but my coding fingers haven't yet put into regular practice. :) >>or you may optionally want to prune of the "\n" characters in the process: >> >>starLines = [line[:-1] for line in p.readlines() if line.startswith("*")] > > *please* use str.rstrip() for this: > starLines = [line.rstrip() for line in p if line.startswith("*")] They can yield different things, no? >>> s = "abc \n" >>> s[:-1] 'abc ' >>> s.rstrip() 'abc' >>> s.[:-1] == s.rstrip() False If trailing space matters, you don't want to throw it away with rstrip(). Otherwise, just to be informed, what advantage does rstrip() have over [:-1] (if the two cases are considered uneventfully the same)? Thanks, -tkc From gshepherd281281 at yahoo.com Wed May 3 01:37:04 2006 From: gshepherd281281 at yahoo.com (ProvoWallis) Date: 2 May 2006 22:37:04 -0700 Subject: NewB question on text manipulation Message-ID: <1146634624.622224.323010@u72g2000cwu.googlegroups.com> I'm totally stumped by this problem so I'm hoping someone can give me a little advice or point me in the right direction. I have a file that looks like this: <SC>APPEAL<XC>40-24; 40-46; 42-46; 42-48; 42-62; 42-63 <SC>PROC GUIDE<XC>92<LT>1(b)(1) (i.e., <<SC>[chapter name]<XC>[multiple or single book page ranges]<SC>[chapter name]<XC>[multiple or single book page ranges]<LT>[code] but I want to change it so that it looks like this <1><SC>APPEAL<XC>40-24<LT>1(b)(1) <1><SC>APPEAL<XC>40-46<LT>1(b)(1) <1><SC>APPEAL<XC>42-46<LT>1(b)(1) <1><SC>APPEAL<XC>42-48<LT>1(b)(1) <1><SC>APPEAL<XC>42-62<LT>1(b)(1) <1><SC>APPEAL<XC>42-63<LT>1(b)(1) <1><SC>PROC GUIDE<XC>92<LT>1(b)(1) but I'm not at all sure how to do it. I've come up with a simlple function that will change the order of the text but I'm not sure how to break out def Switch(m): return '%s<LT>%s' % (m.group(2), m.group(1)) data = re.sub(r'''<1>(.*?)<LT>(.*?)\n''', Switch, data) But I'm still a long way from what I need. Any pointers would be greatly appreciated. Thanks, Greg From python.list at tim.thechases.com Fri May 19 08:05:27 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 19 May 2006 07:05:27 -0500 Subject: How to append to a dictionary In-Reply-To: <1148039985.232831.56040@i40g2000cwc.googlegroups.com> References: <1148039985.232831.56040@i40g2000cwc.googlegroups.com> Message-ID: <446DB487.1080609@tim.thechases.com> > groups = {'IRISH' : 'green', 'AMERICAN' : 'blue'} > > I want to add another key: 'ITALIAN' : 'orange' > > How do I append this to 'groups'? groups['ITALIAN'] = 'orange' as described at http://docs.python.org/tut/node7.html#SECTION007500000000000000000 -tkc From tomasz.zielonka at gmail.com Sun May 7 02:17:14 2006 From: tomasz.zielonka at gmail.com (Tomasz Zielonka) Date: Sun, 7 May 2006 06:17:14 +0000 (UTC) Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <slrne5qu42.9lp.tomasz.zielonka@tomekz.gem.lan> <1hextts.o0uihlttzk47N%aleaxit@yahoo.com> Message-ID: <slrne5r41j.9tu.tomasz.zielonka@tomekz.gem.lan> Alex Martelli wrote: > Tomasz Zielonka <tomasz.zielonka at gmail.com> wrote: > >> Alex Martelli wrote: >> > Having to give functions a name places no "ceiling on expressiveness", >> > any more than, say, having to give _macros_ a name. >> >> And what about having to give numbers a name? > > Excellent style, in most cases; I believe most sensible coding guides > recommend it for most numbers -- cfr ><http://en.wikipedia.org/wiki/Magic_number_(programming)> , section > "magic numbers in code". I was a bit unclear. I didn't mean constants (I agree with you on magic numbers), but results of computations, for example (x * 2) + (y * 3) Here (x * 2), (y * 3) and (x * 2) + 3 are anonymous numbers ;-) Would you like if you were forced to write it this way: a = x * 2 b = y * 3 c = a * b ? Thanks for your answers to my questions. Best regards Tomasz From larswarholm at gmail.com Thu May 4 06:50:13 2006 From: larswarholm at gmail.com (Lars) Date: 4 May 2006 03:50:13 -0700 Subject: Problem building extension under Cygwin (ImportError: Bad address) Message-ID: <1146739813.157265.238320@i39g2000cwa.googlegroups.com> Hi, I have problems building a simple handcoded C-extension (hello.c) with Cygwin and gcc3.4.4. I hope somebody has encountered the same problem before, and has some advice. The extension works just fine with Linux: gcc -c hello.c -I/usr/local/include/python2.4/ ld -shared hello.o -o hello.so -L /usr/local/lib/ -lpython2.4 -lc python -c'import hello;q = hello.message("Lars");print q' Hello, Lars But doing a similar compile under Cygwin doesn't work so well: (same options, but the output is called hello.dll and the directories are a bit different) $ python -c"import hello" Traceback (most recent call last): File "<string>", line 1, in ? ImportError: Bad address btw: hello.c is from "Programming Python 2nd ed." by Mark Lutz. It's published by O'Reilly. The code can be downloaded from: http://examples.oreilly.com/python2/Examples.zip . hello.c is in the directory PP2E\Integrate\Extend\Hello. -Lars From zhaoyuanjiang at gmail.com Tue May 23 02:50:55 2006 From: zhaoyuanjiang at gmail.com (Minlar Ginger) Date: 22 May 2006 23:50:55 -0700 Subject: New beginner to python for advice Message-ID: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> HIi all: I am a new beginner to python, would you like give me some advice on studying it? Welcome to list some book on python for me. Thanks a lot. From lard at tardis.ed.ac.molar.uk Wed May 24 07:13:33 2006 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Wed, 24 May 2006 12:13:33 +0100 Subject: John Bokma harassment In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <44743fdd$0$650$5a6aecb4@news.aaisp.net.uk> Xah Lee wrote: > I'm sorry to trouble everyone. But as you might know, due to my > controversial writings and style, recently John Bokma lobbied people to > complaint to my web hosting provider. After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. > > I'm not sure I will be able to keep using their service, but I do hope > so. > I do not like to post off-topic messages, You don't? Then who has been forcing you to post off-topic essays? A man with a gun? > but this is newsgroup > incidence is getting out of hand, and I wish people to know about it. Nothing out of hand here. You are abusing usenet, and for once an ISP is doing something prompt about it. More power them. From kentilton at gmail.com Sat May 6 21:11:38 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 21:11:38 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> Message-ID: <ePb7g.334$pv7.229@fe08.lga> Alex Martelli wrote: > Ken Tilton <kentilton at gmail.com> wrote: > ... > >>True but circular, because my very point is that () was a great design >>choice in that it made macros possible and they made CL almost >>infinitely extensible, while indentation-sensitivity was a mistaken >>design choice because it makes for very clean code (I agree >>wholeheartedly) but placed a ceiling on its expressiveness. > > > Having to give functions a name places no "ceiling on expressiveness", > any more than, say, having to give _macros_ a name. > > > >>As for: >> >> >>> At a syntax-sugar >>>level, for example, Lisp's choice to use parentheses as delimiter means >>>it's undesirable, even unfeasible, to use the single character '(' as an >>>ordinary identifier in a future release of the language. >> >>(defun |(| (aside) (format nil "Parenthetically speaking...~a." aside)) >>=> |(| >>(|(| "your Lisp /is/ rusty.") >>=> "Parenthetically speaking...your Lisp /is/ rusty.." >> >>:) No, seriously, is that all you can come up with? > > > Interestingly, the SECOND lisper to prove himself unable to read the > very text he's quoting. Reread carefully, *USE THE ***SINGLE*** > CHARACTER* ... *AS AN ORDINARY IDENTIFIER*. What makes you read a > ``PART OF'' that I had never written? You've shown how to use the > characters as *PART* of an identifier [[and I believe it couldn't be the > very start]], and you appear to believe that this somehow refutes my > assertion? The function name here: (|(| "Boy, your Lisp is rusty") -> Boy, your Lisp is rusty. ...is exactly one (1) character long. (length (symbol-name'|(|) -> 1 Why? (symbol-name '|(|) -> "(" (No, the "s are not part of the name!) If you want to argue about that, I will have to bring up the Lisp readtable. Or did you forget that, too? :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From 3dbernard at gmail.com Fri May 26 11:22:58 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Fri, 26 May 2006 11:22:58 -0400 Subject: Running Python scripts under a different user Message-ID: <61d0e2b40605260822r22d55856s1d132f560951c726@mail.gmail.com> Hello, I would like to know if there is a way to run a Python file under a different user account than the one logged in. Allow me to explain. There are a bunch of people here, they are "basic user", with limited permissions. Basically there are locations on the network where they can only read and execute files, but no way to write. Now, if these users want to write or modify files and directories, they would have to use my tools, which would control the permissions and allow the operations under parameters that I have defined. Currently I see two ways of accomplishing this: 1- the script changes the permissions of the locations the user is writing to, allowing the "basic user" to write to this location, and then restore the original permissions. What I don't like about this one, is that if the script stops, the locations may retain the writing permissions for the basic user. 2- the script itself runs under a account with writing privileges (the power user), and network location permissions are not changed. If the script crashes, well, nothing to worry about as far as I can see. I could find in the Python library a way to do #1 easily (the os module), but failed to find anything for #2. Thanks in advance Bernard From grante at visi.com Sat May 27 09:12:38 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 13:12:38 -0000 Subject: access serial port in python References: <1148678743.109181.259710@i40g2000cwc.googlegroups.com> <0audnaDolMWd4erZRVn-jg@comcast.com> <1148711269.318723.77150@i39g2000cwa.googlegroups.com> Message-ID: <127gk26tbs29pee@corp.supernews.com> On 2006-05-27, vipulagarwal.in at gmail.com <vipulagarwal.in at gmail.com> wrote: > i can use the polling method to check for data on the serial port using > pyserial...but i need to use the interrupt driven method .....am workin > on a windows platform .... I don't think there is any way to so interrupt driven I/O under Windows. You can do asynchronous I/O under Windows using the normal Win32 FileIO API. -- Grant Edwards grante Yow! Is it 1974? What's at for SUPPER? Can I spend my visi.com COLLEGE FUND in one wild afternoon?? From yuna77 at spankthedonkey.com Sat May 13 13:03:18 2006 From: yuna77 at spankthedonkey.com (yuna77 at spankthedonkey.com) Date: 13 May 2006 10:03:18 -0700 Subject: Factory pressed dvd movies, ps2, psp & xbox backups for sale !!! Message-ID: <1147539798.315983.307280@i39g2000cwa.googlegroups.com> We're offering all the latest factory pressed high quality dvd movies, ps2, psp and xbox silvers with factory printed colour inserts at fantastic prices, whether for personal use or reselling. We're shipping worldwide with various shipping methods. For resellers, please contact us for bulk discounts. For a complete list and prices, please email us at movieworld at time.net.my (Please state the type of list that you want and tell us your location as the prices varies for different locations. If you're reseller, please state the quantity you wish to order per shipment and we'll quote you a wholesale price depending on the quantity ordered.) * If you need references, we can provide them to you. From federico.pelloni at gmail.com Wed May 3 11:53:08 2006 From: federico.pelloni at gmail.com (Fredp) Date: 3 May 2006 08:53:08 -0700 Subject: __getattr__ on non-instantiated class Message-ID: <1146671588.529743.249570@v46g2000cwv.googlegroups.com> Hi I was wondering if it is possible to have the various magic methods, mainly __getattr__ and __setattr__, and @property attributes called when accessing the attribute of a non-intantiated class. Imagin something like this: ##### class MyClass: @property def prop(self): print "Accessed" return "ABCD" print MyClass.prop ##### having it printing: ##### Accessed ABCD ##### Thanks very much From george.sakkis at gmail.com Fri May 26 14:56:17 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 26 May 2006 11:56:17 -0700 Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> <1148650269.190130.209840@i39g2000cwa.googlegroups.com> <Xns97CF9CDFFB09Cduncanbooth@127.0.0.1> <1148655313.422226.297700@i40g2000cwc.googlegroups.com> <Xns97CFC5A7DE754duncanbooth@127.0.0.1> Message-ID: <1148669777.689284.165080@j73g2000cwa.googlegroups.com> Duncan Booth wrote: > George Sakkis wrote: > > > Duncan Booth wrote: > > > >> George Sakkis wrote: > >> > >> > 2) restricting in a more serious sense: the future addition of > >> > optional keyword arguments that affect the dict's behaviour. Google > >> > for "default dict" or "dictionary accumulator". > >> > >> There is nothing to stop dictionaries being created using factory > >> functions (e.g. see dict.fromkeys). So one possible way to implement > >> defaults would be to extend the dict class with a new classmethod > >> 'withdefault' which takes a default value as an argument. > >> > >> However, given that the default argument isn't actually needed during > >> construction, it doesn't seem to me that it fits either as a > >> constructor parameter nor a factory method. I don't see why it > >> shouldn't just be set on an existing dictionary (or dictionary > >> subclass) when you need it. > > > > Because I would find > > > > d = dict(default=0) > > d['x'] += 3 > > > > more elegant than > > > > d = {} > > d.withdefault(0) > > d['x'] += 3 > > > Well you could have: > > d = dict.withdefault(0) > > but then you may have to start with an empty dictionary. What happens if > you need to change default for different uses? > > Wouldn't wrapping the dictionary in an adaptor be a simpler solution? In > many cases the place where you are going to know what default is > appropriate will be separated from the place where you create the > dictionary. You should be able to write a function which takes a dictionary > as parameter and accumulates values into it. I bet that usually when you create a dictionary, you either populate it right away or at least you know what kind of items are going to be added, e.g. "word -> count" or "word -> list of indexes it appears". In such cases you typically know the default value as well, e.g. 0 or []. Do you have many use cases where you make a dict without knowing what is it going to store or where the default might change during the dict's lifetime ? I can't think of any. George From timr at probo.com Tue May 9 02:09:42 2006 From: timr at probo.com (Tim Roberts) Date: Tue, 09 May 2006 06:09:42 GMT Subject: the print statement References: <1146950481.610645.39710@j33g2000cwa.googlegroups.com> <n1eq52tv6r6uarag1394j8ejil2e4pom44@4ax.com> <vflq52hllh4211ih9ov2453313bahd56da@4ax.com> Message-ID: <kfc062t038okqed76faelsvv9ueimhtrqf@4ax.com> Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: >On Sun, 07 May 2006 00:09:06 GMT, Tim Roberts <timr at probo.com> declaimed >the following in comp.lang.python: > >> mirandacascade at yahoo.com wrote: >> >> >6) Would it be correct to infer that the print statement is aware of >> >characters beyond the 128 characters in the ascii character set? >> >> Certainly. It knows about whatever the current character set is. > > I'd argue that the print statement actually doesn't care... All it >does is send the bytes making up a string to whatever display driver is >active, and it is the driver that converts those bytes into a visible >display. Yes, I agree. I was too glib in my response. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From gene.tani at gmail.com Fri May 19 08:17:55 2006 From: gene.tani at gmail.com (gene tani) Date: 19 May 2006 05:17:55 -0700 Subject: who can give me the detailed introduction of re modle? In-Reply-To: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: <1148041075.790511.154740@i40g2000cwc.googlegroups.com> softwindow wrote: > the re module is too large and difficult to study it's powerful, takes a little time to work with. Make yourself aware of the VERBOSE switch, RE debuggers in komodo and Wing, string functions/methods and when you need a full parser, also http://www.awaretek.com/tutorials.html#regular http://en.wikibooks.org/wiki/Programming:Python_Strings http://www.regexlib.com/Default.aspx http://www.regular-expressions.info/python.html http://www.unixreview.com/documents/s=2472/uni1037388368795/ http://diveintopython.org/regular_expressions/index.html#re.intro > i need a detaild introduction. You have everything you need From pmartin at snakecard.com Wed May 17 15:30:21 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Wed, 17 May 2006 14:30:21 -0500 Subject: creating a new database with mysqldb References: <gcKag.2113$No6.46302@news.tufts.edu> Message-ID: <jRKag.10579$B42.3063@dukeread05> John Salerno wrote: > Since the connect method of mysqldb requires a database name, it seems > like you can't use it without having a database already created. So is > there a way to connect to your mysql server (without a specified > database) in order to create a new database (i.e., the CREATE DATABASE > query)? > > Thanks. I'm no expert but: can't you spawn mysql with a script/scheme ? Philippe From rpdooling at gmail.com Mon May 22 12:15:30 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 22 May 2006 09:15:30 -0700 Subject: string.count issue (i'm stupid?) References: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> Message-ID: <1148314530.085960.73790@u72g2000cwu.googlegroups.com> We were doing something like this last week thestring = "a_a_a_a_" >>> for x in range(len(thestring)): ... try: ... thestring.count("_a_", x, x + 3) ... except ValueError: ... pass From nobody at 127.0.0.1 Mon May 1 17:46:05 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 01 May 2006 21:46:05 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> Message-ID: <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> Holger wrote: > oops, that was kinda embarrassing. It's really not. You got a completely unhelpful error message saying you passed 2 args when you only passed one explicitly. The fact the b is also an argument to b.addfile(f) is totally nonobvious until you know that 1) b is an object not a module*, and 2) objects pass references to themselves as the first argument to their methods. The syntax "b." is completely different from the syntax of any other type of parameter. The mismatch between the number of parameters declared in the method signature and the number of arguments actually passed is nonobvious, unintuitive, and would trip up anybody who didn't already know what was going on. It's ugly and confusing. It's definitely a wart on the langauge. Making people pass 'self' explicitly is stupid because it always has to be the first argument, leading to these kinds of mistakes. The compiler should handle it for you - and no, explicit is not *always* better than implicit, just often and perhaps usually. While it's easy to recognize once you know what's going on, that doesn't make it any less of a wart. * technically modules may be objects also, but in practice you don't declare self as a parameter to module functions From pjb at informatimago.com Thu May 18 07:10:13 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Thu, 18 May 2006 13:10:13 +0200 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> <1147796116.826750@elch.in-berlin.de> <1147905290_7@news-east.n> Message-ID: <87ves3wpuy.fsf@thalassa.informatimago.com> Edmond Dantes <edmond at le-comte-de-monte-cristo.biz> writes: > It all depends on your editor of choice. Emacs editing of Lisp (and a few > other languages, such as Python) makes the issue more or less moot. I > personally would recommend choosing one editor to use with all your > projects, and Emacs is wonderful in that it has been ported to just about > every platform imaginable. > > The real issue is, of course, that ASCII is showing its age and we should > probably supplant it with something better. But I know that will never fly, > given the torrents of code, configuration files, and everything else in > ASCII. Even Unicode couldn't put a dent in it, despite the obvious growing > global development efforts. Not sure how many compilers would be able to > handle Unicode source anyway. I suspect the large majority of them would > would choke big time. All right unicode support is not 100% perfect already, but my main compilers support it perfectly well, only 1/5 don't support it, and 1/5 support it partially: ------(unicode-script.lisp)--------------------------------------------- (defun clisp (file) (ext:run-program "/usr/local/bin/clisp" :arguments (list "-ansi" "-norc" "-on-error" "exit" "-E" "utf-8" "-i" file "-x" "(ext:quit)") :input nil :output :terminal :wait t)) (defun gcl (file) (ext:run-program "/usr/local/bin/gcl" :arguments (list "-batch" "-load" file "-eval" "(lisp:quit)") :input nil :output :terminal :wait t)) (defun ecl (file) (ext:run-program "/usr/local/bin/ecl" :arguments (list "-norc" "-load" file "-eval" "(si:quit)") :input nil :output :terminal :wait t)) (defun sbcl (file) (ext:run-program "/usr/local/bin/sbcl" :arguments (list "--userinit" "/dev/null" "--load" file "--eval" "(sb-ext:quit)") :input nil :output :terminal :wait t)) (defun cmucl (file) (ext:run-program "/usr/local/bin/cmucl" :arguments (list "-noinit" "-load" file "-eval" "(extensions:quit)") :input nil :output :terminal :wait t)) (dolist (implementation '(clisp gcl ecl sbcl cmucl)) (sleep 3) (terpri) (print implementation) (terpri) (funcall implementation "unicode-source.lisp")) ------(unicode-source.lisp)--------------------------------------------- ;; -*- coding: utf-8 -*- (eval-when (:compile-toplevel :load-toplevel :execute) (format t "~2%~A ~A~2%" (lisp-implementation-type) (lisp-implementation-version)) (finish-output)) (defun ???? (&key (????? 10) (?? 1) (???? 0)) (loop :for i :from ???? :to ????? :by ?? :collect i)) (defun test () (format t "~%Calling ~S --> ~A~%" '(???? :????? 10 :?? 2 :???? 2) (???? :????? 10 :?? 2 :???? 2))) (test) ------------------------------------------------------------------------ (load"unicode-script.lisp") ;; Loading file unicode-script.lisp ... CLISP i i i i i i i ooooo o ooooooo ooooo ooooo I I I I I I I 8 8 8 8 8 o 8 8 I \ `+' / I 8 8 8 8 8 8 \ `-+-' / 8 8 8 ooooo 8oooo `-__|__-' 8 8 8 8 8 | 8 o 8 8 o 8 8 ------+------ ooooo 8oooooo ooo8ooo ooooo 8 Copyright (c) Bruno Haible, Michael Stoll 1992, 1993 Copyright (c) Bruno Haible, Marcus Daniels 1994-1997 Copyright (c) Bruno Haible, Pierpaolo Bernardi, Sam Steingold 1998 Copyright (c) Bruno Haible, Sam Steingold 1999-2000 Copyright (c) Sam Steingold, Bruno Haible 2001-2006 ;; Loading file unicode-source.lisp ... CLISP 2.38 (2006-01-24) (built 3347193361) (memory 3347193794) Calling (???? :????? 10 :?? 2 :???? 2) --> (2 4 6 8 10) ;; Loaded file unicode-source.lisp Bye. GCL GNU Common Lisp (GCL) GCL 2.6.7 Calling (???? :????? 10 :?? 2 :???? 2) --> (2 4 6 8 10) ECL ;;; Loading "unicode-source.lisp" ECL 0.9g Calling (???? :????? 10 :?? 2 :???? 2) --> (2 4 6 8 10) SBCL This is SBCL 0.9.12, an implementation of ANSI Common Lisp. More information about SBCL is available at <http://www.sbcl.org/>. SBCL is free software, provided as is, with absolutely no warranty. It is mostly in the public domain; some portions are provided under BSD-style licenses. See the CREDITS and COPYING files in the distribution for more information. SBCL 0.9.12 Calling (|????| :|?????| 10 :|??????| 2 :|????| 2) --> (2 4 6 8 10) CMUCL ; Loading #P"/local/users/pjb/src/lisp/encours/unicode-source.lisp". CMU Common Lisp 19c (19C) Reader error at 214 on #<Stream for file "/local/users/pjb/src/lisp/encours/unicode-source.lisp">: Undefined read-macro character #\?? [Condition of type READER-ERROR] Restarts: 0: [CONTINUE] Return NIL from load of "unicode-source.lisp". 1: [ABORT ] Skip remaining initializations. Debug (type H for help) (LISP::%READER-ERROR #<Stream for file "/local/users/pjb/src/lisp/encours/unicode-source.lisp"> "Undefined read-macro character ~S" #\??) Source: Error finding source: Error in function DEBUG::GET-FILE-TOP-LEVEL-FORM: Source file no longer exists: target:code/reader.lisp. 0] abort * Received EOF on *standard-input*, switching to *terminal-io*. * (extensions:quit) ;; Loaded file unicode-script.lisp T [4]> -- __Pascal Bourguignon__ http://www.informatimago.com/ Grace personified, I leap into the window. I meant to do that. From eval.apply at gmail.com Tue May 9 12:49:03 2006 From: eval.apply at gmail.com (Joe Marshall) Date: 9 May 2006 09:49:03 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147148036.512676.288190@i39g2000cwa.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> Message-ID: <1147193343.140552.51470@i40g2000cwc.googlegroups.com> Pisin Bootvong wrote: > Is this a Slippery Slope fallacious argument? > (http://c2.com/cgi/wiki?SlipperySlope) > > "if python required you to name every function then soon it will > require you to name every number, every string, every immediate result, > etc. And we know that is bad. Therefore requiring you to name your > function is bad!!!! So Python is bad!!!!" No, it is a question about consistency. Why are functions singled out? Or is this an attempt to apply an Argumentum ad Logicam fallacy? From belred at gmail.com Wed May 24 10:24:53 2006 From: belred at gmail.com (Bryan) Date: Wed, 24 May 2006 07:24:53 -0700 Subject: graphs and charts In-Reply-To: <4473F4A6.1000805@anansispaceworks.com> References: <4473444E.4060102@telus.net> <4473F4A6.1000805@anansispaceworks.com> Message-ID: <44746CB5.6040706@gmail.com> Terry Hancock wrote: > Yaron Butterfield wrote: >> What's the best way to on-the-fly graphs and charts using Python? Or >> is Python not really the best way to do this? > > I quite enjoyed using Biggles for this: > > http://biggles.sf.net > > There are many different choices, though. > > Cheers, > Terry > Terry Hancock wrote: > Yaron Butterfield wrote: >> What's the best way to on-the-fly graphs and charts using Python? Or >> is Python not really the best way to do this? > > I quite enjoyed using Biggles for this: > > http://biggles.sf.net > > There are many different choices, though. > > Cheers, > Terry > hi terry, this is the first time i've heard of biggles. it looks really nice and simple to use? and i especially like your use of gradients in example 9. does biggles integrate well wxPython? if so, do you have an example of how to add it to a wxPython panel? thanks, bryan From bignose+hates-spam at benfinney.id.au Wed May 31 07:15:57 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 31 May 2006 21:15:57 +1000 Subject: [OT] whitespace References: <44778C05.9020701@grads.ece.mcmaster.ca> <4477A74C.6080605@lexicon.net> <slrne7p8p8.2t1.grahn+nntp@frailea.sa.invalid> <447cdc3d@news.eftel.com> <6uA*vT1hr@news.chiark.greenend.org.uk> Message-ID: <87wtc2zbpu.fsf@benfinney.id.au> Sion Arrowsmith <siona at chiark.greenend.org.uk> writes: > And if we didn't say "whitespace", how would we distinguish between > "space characters" meaning " " and "whitespace characters" > meaning " \t\r\n\v"? (OK, has anyone met a "\v" in the wild?) Not me. But I routinely use a whitespace character you omitted: '\f' (ASCII FF, '\x0C') to separate sections of source code within a file. -- \ "I don't like country music, but I don't mean to denigrate | `\ those who do. And for the people who like country music, | _o__) denigrate means 'put down'." -- Bob Newhart | Ben Finney From bignose+hates-spam at benfinney.id.au Wed May 31 07:29:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 31 May 2006 21:29:12 +1000 Subject: create a text file References: <Xns97D3657BA981Emaxericksongmailcom@80.91.229.5> <e5htg5$89d$1@sea.gmane.org> <mailman.6336.1149023697.27775.python-list@python.org> <1149062005.973225.181740@y43g2000cwc.googlegroups.com> Message-ID: <87odxezb3r.fsf@benfinney.id.au> "per9000" <per9000 at gmail.com> writes: > appendix = '.txt' # or '.csv' or whatever > > # some code > > c += 1 > filetitle = 'result_' + zeropadding(c) + str(c) > myfile = open(filetitle+appendix,'w') Resist the urge to construct strings by concatenation, when Python's built-in string formatting operations will do the job more elegantly. >>> filesuffix = ".txt" >>> count = 123 >>> filename = "result_%05d%s" % (count, filesuffix) >>> print filename result_00123.txt -- \ "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 fredrik at pythonware.com Tue May 30 12:56:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 30 May 2006 18:56:39 +0200 Subject: create a text file In-Reply-To: <Xns97D3657BA981Emaxericksongmailcom@80.91.229.5> References: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> <1148983561.469393.262430@j73g2000cwa.googlegroups.com> <Xns97D3657BA981Emaxericksongmailcom@80.91.229.5> Message-ID: <e5htg5$89d$1@sea.gmane.org> Max Erickson wrote: >> # w is for writing >> myfile = open('theoutfile',w) > > That won't work, the second argument to open needs to be a string: w = 'w' </F> From bignose+hates-spam at benfinney.id.au Mon May 29 17:48:28 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 30 May 2006 07:48:28 +1000 Subject: send an email with picture/rich text format in the body References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <iAJ9g.76667$H71.54770@newssvr13.news.prodigy.com> <1148797671.937857.151250@y43g2000cwc.googlegroups.com> <mailman.6297.1148858516.27775.python-list@python.org> <447acc88$0$38659$edfadb0f@dread12.news.tele.dk> Message-ID: <878xok1p03.fsf@benfinney.id.au> Max M <maxm at mxm.dk> writes: > Ben Finney wrote: > > "anya" <anyab5 at gmail.com> writes: > > > > > >>Acctualy there is a solution: > >>see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 > > > > > > Again, sending anything but plain text as the message body ensures > > that your message is unreadable to a large number of people using a > > variety of software. It's your choice whether to restrict your > > audience in this way, but know that that's what you're doing. > > > 90% of users are non-technical users who use standard email readers, > that can easily read html messages. Even if your figure of 90% were correct, 10% of readers is still a large number for most purposes. It's also unknown exactly *which* 10% of your readers that covers. > In my experience the kind of user that receives emails with html and > pictures often prefer it that way. What of those who prefer it not to be that way? What of those who are *incapable* of reading a message that way? > So why bother with the lecture? I cannot remember when I have last > received a relevant email that I could not read in text mode. Nice for you. Fortunately, standard message formats allow the internet to be used by those other than the enabled majority. Let's keep it that way. -- \ "People come up to me and say, 'Emo, do people really come up | `\ to you?'" -- Emo Philips | _o__) | Ben Finney From cfbolz at gmx.de Sun May 7 05:51:14 2006 From: cfbolz at gmx.de (Carl Friedrich Bolz) Date: Sun, 07 May 2006 11:51:14 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <87mzducj27.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <87mzducj27.fsf@rpi.edu> Message-ID: <445DC312.6080000@gmx.de> Bill Atkins wrote: [snip] > > Unfortunately, it's *nothing* like a full PyCell implementation. I > explained what Cells is above. It is not merely a spreadsheet - it is > an extension that allows the programmer to specify how the value of > some slot (Lisp lingo for "member variable") can be computed. It > frees the programmer from having to recompute slot values since Cells > can transparently update them. It has to do with extending the object > system, not with merely setting tables in a hash and then retrieving > them. I have not looked at Cells at all, but what you are saying here sounds amazingly like Python's properties to me. You specify a function that calculates the value of an attribute (Python lingo for something like a "member variable"). Something like this: >>> class Temperature(object): ... def __init__(self, temperature_in_celsius): ... self.celsius = temperature_in_celsius ... def _get_fahrenheit(self): ... return self.celsius * 9.0 / 5.0 + 32 ... fahrenheit = property(_get_fahrenheit) ... >>> t = Temperature(0) >>> t.fahrenheit 32.0 >>> t.celsius = -32 >>> t.fahrenheit -25.600000000000001 >>> t = Temperature(100) >>> t.fahrenheit 212.0 no metaclass hacking necessary. Works also if you want to allow setting the property. Cheers, Carl Friedrich Bolz From rory.brandybuck at gmail.com Mon May 15 08:08:33 2006 From: rory.brandybuck at gmail.com (rory.brandybuck at gmail.com) Date: 15 May 2006 05:08:33 -0700 Subject: please help me is sms with python References: <mailman.5701.1147690409.27775.python-list@python.org> <4cr6deF17i9mpU1@uni-berlin.de> Message-ID: <1147694913.198080.183750@i39g2000cwa.googlegroups.com> Yet another option: Use web-service provided by your mobile operator (by means of cookielib, urllib2, etc). From sjmachin at lexicon.net Mon May 8 08:58:59 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 08 May 2006 22:58:59 +1000 Subject: Python's regular expression? In-Reply-To: <e3ndsm$rfa$1@mlucom4.urz.uni-halle.de> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> <e3ndsm$rfa$1@mlucom4.urz.uni-halle.de> Message-ID: <445F4093.4070505@lexicon.net> On 8/05/2006 10:31 PM, Mirco Wahab wrote: [snip] > > Lets see - a really simple find/match > would look like this in Python: > > import re > > t = 'blue socks and red shoes' > p = re.compile('(blue|white|red)') > if p.match(t): What do you expect when t == "green socks and red shoes"? Is it possible that you mean to use search() rather than match()? > print t > > which prints the text 't' because of > the positive pattern match. > > In Perl, you write: > > use Acme::Pythonic; > > $t = 'blue socks and red shoes' > if ($t =~ /(blue|white|red)/): > print $t > > which is one line shorter (no need > to compile the regular expression > in advance). There is no need to compile the regex in advance in Python, either. Please consider the module-level function search() ... if re.search(r"blue|white|red", t): # also, no need for () in the regex. From mwilson-to at sympatico.ca Fri May 26 07:04:34 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 26 May 2006 07:04:34 -0400 Subject: list comprehensions put non-names into namespaces! In-Reply-To: <mailman.6206.1148586159.27775.python-list@python.org> References: <1148577813.000229.225330@y43g2000cwc.googlegroups.com> <mailman.6206.1148586159.27775.python-list@python.org> Message-ID: <7hBdg.2071$ho5.166428@news20.bellglobal.com> skip at pobox.com wrote: > Lonnie> List comprehensions appear to store their temporary result in a > Lonnie> variable named "_[1]" (or presumably "_[2]", "_[3]" etc for > Lonnie> nested comprehensions) > > Known issue. Fixed in generator comprehensions. Dunno about plans to fix > it in list comprehensions. I believe at some point in the future they may > just go away or become syntactic sugar for a gen comp wrapped in a list() > call. Point of information, would this be the interpreter putting the result of its last calculation in _ ? Python 2.4.2 (#1, Jan 23 2006, 21:24:54) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> [2*x for x in range(5)] [0, 2, 4, 6, 8] >>> _[4] 8 Mel. From tim.peters at gmail.com Mon May 22 23:19:06 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 23 May 2006 03:19:06 +0000 Subject: module confict? gmpy and operator In-Reply-To: <1148346626.184199.125740@38g2000cwa.googlegroups.com> References: <1148346626.184199.125740@38g2000cwa.googlegroups.com> Message-ID: <1f7befae0605222019o42c29e75p8a20cc3e24bbe3f5@mail.gmail.com> [mensanator at aol.com] > ## Holy Mother of Pearl! > ## > ## >>> for i in range(10): > ## for j in range(10): > ## print '%4d' % (gmpy.mpz(i)*gmpy.mpz(j)), > ## print > ## > ## > ## 0 0 0 0 0 0 0 0 0 0 > ## 0 1 2 3 1 5 6 7 2 9 > ## 0 2 4 6 2 10 12 14 4 18 > ## 0 3 6 9 3 15 18 21 6 27 > ## 0 1 2 3 1 5 6 7 2 9 > ## 0 5 10 15 5 25 30 35 10 45 > ## 0 6 12 18 6 30 36 42 12 54 > ## 0 7 14 21 7 35 42 49 14 63 > ## 0 2 4 6 2 10 12 14 4 18 > ## 0 9 18 27 9 45 54 63 18 81 > > No wonder I couldn't figure out why my program wasn't working, > gmpy mutiplication seems to have stopped working. > > My guess is that when I did > > import gmpy > import random > import operator > > I somehow messed up gmpy's mutilpication. I brought in operator > because I needed to do > > NN = sum(map(operator.__mul__,X,C)) > > which seemed to work ok. It was later when I got > > 8 * 3 = 6 (the 3 was an mpz) > > that I got in trouble. So I got rid of operator and did > > def product(a,b): return a*b > > NN = sum(map(product,X,C)) > > which seems to work ok. Please try to give a complete program that illustrates the problem. For example, this program shows no problem on my box (Windows Python 2.4.3): """ import gmpy import random import operator NN = sum(map(operator.__mul__, [1, 2, 3], [4, 5, 6])) for i in range(10): for j in range(10): print '%4d' % (gmpy.mpz(i)*gmpy.mpz(j)), print """ The output was: 0 0 0 0 0 0 0 0 0 0 0 1 2 3 4 5 6 7 8 9 0 2 4 6 8 10 12 14 16 18 0 3 6 9 12 15 18 21 24 27 0 4 8 12 16 20 24 28 32 36 0 5 10 15 20 25 30 35 40 45 0 6 12 18 24 30 36 42 48 54 0 7 14 21 28 35 42 49 56 63 0 8 16 24 32 40 48 56 64 72 0 9 18 27 36 45 54 63 72 81 > Am I correct that there is a conflict with > > import gmpy > import operator I don't see a problem of any kind, and there's no way to guess from the above what you did that mattered. It's hard to believe that merely importing any module (operator or otherwise) has any effect on gmpy. > Would reversing the import order help or should I just avoid > mixing them? Both are dubious. From rupole at hotmail.com Wed May 17 00:23:26 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 17 May 2006 00:23:26 -0400 Subject: pythoncom and IDispatch References: <44688c2a$0$7047$636a55ce@news.free.fr> Message-ID: <1147839560_3465@sp6iad.superfeed.net> "fraca7" <fraca7 at free.fr> wrote in message news:44688c2a$0$7047$636a55ce at news.free.fr... > Hello. I got a little problem while using pythoncom to automate IE; for some reason, changing the 'selectedIndex' on an > instance of IHTMLSelectElement doesn't fire the 'onchange' event (I guess this is a bug in mshtml). As I understand it, this was done as a security measure to foil script exploits. > So, I tried to get the 'onchange' event handler and call it myself. According to the docs, this is a simple IDispatch > implementation and calling Invoke() should do the trick; I actually have a working example of this in Delphi. > > But I can't manage to get it work in Python; the following code > > > idisp = pythoncom.WrapObject(elt.onchange) > idisp.Invoke(pythoncom.DISPID_VALUE, > 0x400, # LOCALE_USER_DEFAULT > pythoncom.DISPATCH_METHOD, > False) > > fails with an AttributeError: > You can access the underlying IDispatch using the _oleobj_ property, ie elt.onchange._oleobj_.Invoke(......) Alternately, you can also use FireEvent, which would look something like this (untested): elt.FireEvent('onchange',elt.onchange) 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 K.Wong at lboro.ac.uk Wed May 3 06:50:43 2006 From: K.Wong at lboro.ac.uk (K.S.Wong) Date: Wed, 3 May 2006 11:50:43 +0100 Subject: how to install multiple pythons on window Message-ID: <e3a1u4$4mj$1@sun-cc204.lut.ac.uk> Hi, I have python 2.2 that is embedded in an application and I need to work with other sofware/modules that require higher python version. I have current installed 2.4. I can only use environment variables to allow one of the two versions to work at one time (e.g. setting pythonhome for one version at one time!). Would someone let me know how could I allow both to work at the same time? Appreciate your time! best regards Casey Wong From tim.peters at gmail.com Wed May 3 17:13:33 2006 From: tim.peters at gmail.com (Tim Peters) Date: Wed, 3 May 2006 17:13:33 -0400 Subject: Because of multithreading semantics, this is not reliable. In-Reply-To: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> Message-ID: <1f7befae0605031413q3cce808du980257285d8f57d1@mail.gmail.com> [OlafMeding at gmail.com] > Because of multithreading semantics, this is not reliable. This > sentence is found in the Python documentation for "7.8.1 Queue > Objects". > > This scares me! Why would Queue.qsize(), Queue.empty( ), and a > Queue.full() not be reliable? Because they may not be telling the truth at the instant the _caller_ tries to use the result. I'm not sure why, but people write code like if q.empty(): return in a thread, and then complain that "it's a bug" if some other thread of theirs happens to sneak in and add another item to the queue _between_ the time q.empty() correctly determined that q was empty, and the time the code generated for "if q.empty()" tests the result. There's no mutex to stop other threads from running between those times. The docs could be clearer about this, and "not reliable" had a stronger meaning in earlier versions of Python. > Looking at the source code of Queue.py, all 3 calls use a mutex (based > on thread.allocate_lock()). Does this mean that the > thread.allocate_lock() mechanism is not reliable (scary indeed) No. > or does this have to do with other implementation details? It just has to do with the way threads work, and with trying to disabuse newbies of faulty common beliefs. It's good to scare threading newbies away from these methods, because they _don't_ do what newbies typically assume they do. That puts them in the "attractive nuisance" category for many people. From Serge.Orlov at gmail.com Fri May 19 09:02:14 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 May 2006 06:02:14 -0700 Subject: Encode exception for chinese text References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> <1148039929.462581.51770@i40g2000cwc.googlegroups.com> <1148042230.341700.151410@y43g2000cwc.googlegroups.com> Message-ID: <1148043734.554660.152120@j55g2000cwa.googlegroups.com> Vinayakc wrote: > Yes serge, I have removed the first character but it is still giving > encoding exception. Then I guess this character was used as a poor man indentation tool at least in the beginning of your text. It's up to you to decide what to do with that character, you have several choices: * edit source xml file to get rid of it * remove it while you process your data * replace it with ordinary space * consider utf-8 Note, there are legitimate use cases for no-break space, for example one million can be written like 1 000 000, where spaces are non-breakable. This prevents the number to be broken by right margin like this: 1 000 000 Keep that in mind when you remove or replace no-break space. From andre.roberge at gmail.com Tue May 2 06:21:06 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 2 May 2006 03:21:06 -0700 Subject: Using elementtree: replacing nodes In-Reply-To: <mailman.5208.1146554899.27775.python-list@python.org> References: <1146529455.411024.83020@j73g2000cwa.googlegroups.com> <mailman.5208.1146554899.27775.python-list@python.org> Message-ID: <1146565266.102053.187350@j33g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Andr? wrote: > > > I've started using elementtree and don't understand how to use it to > > manipulate and replace nodes. [snip] It was mostly the following step which I couldn`t figure out... > # 2) mutate the pre element > pre.clear() > pre.tag = "form" > pre[:] = [form] > [snip] > another approach is to build a parent map; see the parent_map code > at > > http://effbot.org/zone/element.htm#the-element-type > Thanks! > </F> From first-name.last-name at gmail.com Sun May 7 15:47:42 2006 From: first-name.last-name at gmail.com (Nilton Volpato) Date: Sun, 7 May 2006 16:47:42 -0300 Subject: ANN: progressbar 2.2 - Text mode progressbar for console applications Message-ID: <mailman.5464.1147072159.27775.python-announce-list@python.org> Text progressbar library for python. http://cheeseshop.python.org/pypi/progressbar This library provides a text mode progressbar. This is tipically used to display the progress of a long running operation, providing a visual clue that processing is underway. The ProgressBar class manages the progress, and the format of the line is given by a number of widgets. A widget is an object that may display diferently depending on the state of the progress. There are three types of widget: - a string, which always shows itself; - a ProgressBarWidget, which may return a diferent value every time it's update method is called; and - a ProgressBarWidgetHFill, which is like ProgressBarWidget, except it expands to fill the remaining width of the line. The progressbar module is very easy to use, yet very powerful. And automatically supports features like auto-resizing when the terminal size is changed. It's also efficient, because the text is only updated if need, with a minimum overhead in the case there is no need for updating. It was tested and works under windows, linux and macosx. And should also work in many other untested operating systems. You may get it from pypi: http://cheeseshop.python.org/pypi/progressbar Thanks, Nilton. -- Nilton Volpato email: "%s.%s at gmail.com" % ('nilton', 'volpato') From santosh.pandey at gmail.com Thu May 4 15:45:55 2006 From: santosh.pandey at gmail.com (san) Date: 4 May 2006 12:45:55 -0700 Subject: Can I use python for this .. ?? Message-ID: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> Hi I am using windows xp and have installed python and win32. I am familiar with basic Python. I wanted to control some of the applications via python script. I would like to write a python script to say: 1. Open firefox and log on to gmail 2. Another firefox window to visit slickdeals 3. Open winamp and tune in to a shoutcast station 4. Open groupwise ... etc .. These are the task I do every day whenever I log on my computer .. it just seems repetitive and hence probably can be coded in python. Can I do this in python? Where do I find the COM objects/interfaces for all these different programs? Are there any sample codes ? Thanks. Santosh. From jiandong.gu at gmail.com Wed May 24 01:05:37 2006 From: jiandong.gu at gmail.com (lao_mage) Date: 23 May 2006 22:05:37 -0700 Subject: Looking for help with Regular Expression References: <1148428798.529016.319100@y43g2000cwc.googlegroups.com> <e508pg$c1l$1@daisy.noc.ucla.edu> Message-ID: <1148447137.306602.86440@i39g2000cwa.googlegroups.com> '''\[(.*?)\]''' ?-> when this char after(*, +, ?, {n}, {n,}, {n,m}), the match pattern is not greedy e.g.1 String: 512.16[3][b]] Pattern:'''\[(.*)\]''' This will match "[3][b]]" e.g.2 String: 512.16[3][b]] Pattern:'''\[(.*)?\]''' This will match "[3]" and "[b]" From runlevelten at gmail.com Thu May 11 20:30:15 2006 From: runlevelten at gmail.com (Ten) Date: Fri, 12 May 2006 01:30:15 +0100 Subject: Time to bundle PythonWin In-Reply-To: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> References: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> Message-ID: <200605120130.15390.runlevelten@gmail.com> On Thursday 11 May 2006 23:09, Dave Benjamin wrote: > Hey folks, > > Why is PythonWin (win32all) still a separate download from a third party? > Is it legal, technical, or what? I think it's about time it be part of the > standard distribution. > > There are many useful things that you ought to be able to do without > downloading third-party libraries. Terminating a process, for example. > Communicating with other applications via a standard, common protocol > (COM). We demand these things from our UNIX environments--why do we > tolerate their omission on the Windows platform? > There's a lot of omission on the windows platform, and that ain't python or win32all's fault. > Mac libraries are bundled with Python's *standard library*. I'm not even > advocating merging the win32 extensions with the standard library. All I'm > saying is that when you install Python on Windows, it should ask you if > you want to install PythonWin too, and that this option be selected by > default. > > I write applications that use COM and Tkinter to automate basic office > tasks. My users are thankfully benevolent enough to download and install > Python on their own. They don't know what PythonWin is, they aren't > remembering it, and frankly, I don't think it should be their concern. > Respectfully, that sounds like a reason for *you* to bundle pythonwin (and python, to be honest :) ), not a reason for everyone else to have to download an extra 40-50% of potentially superfluous cruft with their standard python setup. In more general terms I can see why it would be useful to some windows people to have more winapi stuff available. I can still think of quite a few things I'd rather be spending that extra download time on myself, though, like a sexed-up tkinter or maybe even a new gui toolkit. Still, it's not an either/or choice, I suppose. -- There are 10 types of people in this world, those who understand binary, and those who don't. From zhushenli at gmail.com Mon May 8 06:52:32 2006 From: zhushenli at gmail.com (Davy) Date: 8 May 2006 03:52:32 -0700 Subject: Python's regular expression? In-Reply-To: <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <e3mtdk$mp0$1@mlucom4.urz.uni-halle.de> Message-ID: <1147085552.824265.128220@i39g2000cwa.googlegroups.com> Hi Mirco, Thank you! More similar than Perl ;-) And what's 'integrated' mean (must include some library)? I like C++ file I/O, is it 'low' or 'high'? Regards, Davy From tbrkic at yahoo.com Thu May 18 07:48:36 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 04:48:36 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <446c5a80$0$7024$636a55ce@news.free.fr> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <446c3b2b$0$17368$636a55ce@news.free.fr> <1147947048.303912.109150@38g2000cwa.googlegroups.com> <446c5a80$0$7024$636a55ce@news.free.fr> Message-ID: <1147952916.536664.260700@38g2000cwa.googlegroups.com> > Adding ugly and unintuitive "operators" to try to turn a general purpose > programming language into a half-backed unusable HTML templating > language is of course *much* more pythonic... IT is not only for HTML. I do think html and xml are the biggest creators of hierarcical treestructures. But it would work for any package that manipulates, creates hierarchical data. I used HTML as example since it is a good example and most people would understand the intention. But could you elaborate on your comment that it is unusable. Do you think all template systems are unusable or what is the specific reason you think what i propose is unusable? IMO it is a mix between yml and python. Yml has the advantage that it can be read by many programming languages but the disadvantage is that it is static. From kent at kentsjohnson.com Tue May 9 14:37:13 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 09 May 2006 14:37:13 -0400 Subject: regular expressions, substituting and adding in one step? In-Reply-To: <yEI7g.2056$No6.45379@news.tufts.edu> References: <yEI7g.2056$No6.45379@news.tufts.edu> Message-ID: <4460e0d7$1_1@newspeer2.tds.net> John Salerno wrote: > Ok, this might look familiar. I'd like to use regular expressions to > change this line: > > self.source += '<p>' + paragraph + '</p>\n\n' > > to read: > > self.source += '<p>%s</p>\n\n' % paragraph > > Now, matching the middle part and replacing it with '%s' is easy, but > how would I add the extra string to the end of the line? Is it done all > at once, or must I make a new regex to match? > > Also, I figure I'd use a group to match the word 'paragraph', and use > that group to insert the word at the end, but how will I 'retain' the > state of \1 if I use more than one regex to do this? Do it all in one match / substitution using \1 to insert the value of the paragraph group at the new location: In [19]: test = "self.source += '<p>' + paragraph + '</p>\n\n'" In [20]: re.sub(r"'<p>' \+ (.*?) \+ '</p>\n\n'", r"'<p>%s</p>\n\n' % \1", test) Out[20]: "self.source += '<p>%s</p>\n\n' % paragraph" Kent From bj_666 at gmx.net Fri May 19 16:56:07 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Fri, 19 May 2006 22:56:07 +0200 Subject: altering an object as you iterate over it? References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> Message-ID: <pan.2006.05.19.20.56.05.245231@gmx.net> In <1Kpbg.42822$Qq.36241 at tornado.texas.rr.com>, Paul McGuire wrote: > 1. open("xxx") still works - not sure if it's even deprecated or not - but > the new style is to use the file class It's not deprecated and may be still used for opening files. I guess the main reason for introducing `file` as a synonym was the possibility to inherit from builtins. Inheriting from `open` looks quite strange. Ciao, Marc 'BlackJack' Rintsch From me+python at modelnine.org Thu May 18 03:50:09 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 18 May 2006 09:50:09 +0200 Subject: Reference Counts In-Reply-To: <1147937632.918370.300350@j55g2000cwa.googlegroups.com> References: <1147933695.752344.195350@u72g2000cwu.googlegroups.com> <mailman.5866.1147934567.27775.python-list@python.org> <1147937632.918370.300350@j55g2000cwa.googlegroups.com> Message-ID: <200605180950.09426.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 09:33 schrieb raghu: > However, the 'non-leaky' one showed a funny trend ...it kept increasing > the totalrefcount for five iterations (see 1 thru 5) and then dropped > down by 5 ( See Before 5 : 16584 > After 5 : 16580 ) suddenly and again increase as shown below. However, > at the time when the script finsished execution, we were not too far > from the starting totalrefcount (16584 from 16579), The cyclic garbage collector isn't run after every byte-code instruction, but only after several have executed (because of performance issues). That's why you see an increase in reference counts, until the interpreter calls the garbage collector, which frees the object cycles, and so forth. I don't exactly know what the "magic constant" (i.E. number of byte-code instructions between subsequent runs of the garbage collector) is, but I presume it's somewhere in the order of 100 bytecode instructions. Why you need the cyclic gc to clean up the data structures my sample creates is beyond be, but I'd guess it has something to do with the internal structure of dicts. Anyway, you can easily test this hypothesis by calling gc.collect() explicitly in the main loop after test() has run (remember to import gc... ;-)). This forces a run of the cyclic gc. If funny pattern still remains I wouldn't know of any other explanation... ;-) But, as long as references aren't being leaked (you don't see the drop in references after every x instructions), there's nothing to worry about. --- Heiko. From tim.golden at viacom-outdoor.co.uk Mon May 15 03:56:34 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 15 May 2006 08:56:34 +0100 Subject: Windows Copy Gui Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1B9@vogbs009.gb.vo.local> [placid] | Just wondering if anyone knows how to pop up the dialog that windows | pops up when copying/moving/deleting files from one directory to | another, in python ? http://timgolden.me.uk/python/win32_how_do_i/copy-a-file.html#shell 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 Serge.Orlov at gmail.com Wed May 31 14:22:23 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 31 May 2006 11:22:23 -0700 Subject: Are ActivePython scripts compatible with Linux? References: <Knjfg.1106$Su3.100610@news20.bellglobal.com> <SYCdnZBPbu0GTeDZnZ2dneKdnZydnZ2d@comcast.com> <Ckkfg.1120$Su3.101476@news20.bellglobal.com> Message-ID: <1149099743.003790.54730@g10g2000cwb.googlegroups.com> A.M wrote: > I am planning to develop python applications on windows and run them on > Linux. > "Larry Bates" <larry.bates at websafe.com> wrote in message > news:SYCdnZBPbu0GTeDZnZ2dneKdnZydnZ2d at comcast.com... > > Short answer: yes A.M wrote: > Thanks alot Larry for your comprehensive answer. Small addition: test, test, test. This is the only way to make sure your program works on another platform. VMware is offering now free virtual machine emulator, vmplayer. You have no excuse not to install linux! :) If you have dual-core processor or an idle machine you can even setup http://buildbot.sf.net to continuously test your source code changes. From zombek at gmail.com Tue May 16 09:59:30 2006 From: zombek at gmail.com (zombek at gmail.com) Date: 16 May 2006 06:59:30 -0700 Subject: saving file permission denied on windows In-Reply-To: <4468B96E.8080101@websafe.com> References: <1147708797.746442.19220@j73g2000cwa.googlegroups.com> <4468B96E.8080101@websafe.com> Message-ID: <1147787970.847918.70710@j55g2000cwa.googlegroups.com> That's right! I just didn't notice it. Thank you From johnjsal at NOSPAMgmail.com Thu May 4 22:49:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 04 May 2006 22:49:13 -0400 Subject: using urllib with ftp? In-Reply-To: <mailman.5347.1146776157.27775.python-list@python.org> References: <oqt6g.2048$No6.44127@news.tufts.edu> <mailman.5347.1146776157.27775.python-list@python.org> Message-ID: <445abddd$0$9424$c3e8da3@news.astraweb.com> Fredrik Lundh wrote: > John Salerno wrote: > >> I've tried this already and it seems to work, but I'm curious if it's >> okay to use urllib when trying to access a url that begins with ftp:// >> instead of http://. Does this matter? It's only a text file, so it's not >> really an FTP server I'm accessing, I don't think. I wasn't sure if >> using ftplib would be overkill in this case, or if you even could use it >> at all if you just want to get the page itself (the txt file). > > from the urllib documentation: > > Currently, only the following protocols are supported: HTTP, > (versions 0.9 and 1.0), Gopher (but not Gopher-+), FTP, and > local files. Thanks. So the ftp:// is something different than actually using ftplib to connect to an FTP server, right? I've used both urllib and ftplib, so I know what they do, I just was a little unclear about whether they can sometimes do each other's work as well. From rpdooling at gmail.com Tue May 2 15:53:56 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 2 May 2006 12:53:56 -0700 Subject: Python and Windows new Powershell In-Reply-To: <1146585636.121440.178890@e56g2000cwe.googlegroups.com> References: <1146585636.121440.178890@e56g2000cwe.googlegroups.com> Message-ID: <1146599636.210734.49700@e56g2000cwe.googlegroups.com> Actually the best bit I found was a guy on Slashdot who said they could have made the whole thing out of Python. here's a good article, but it's old http://arstechnica.com/guides/other/msh.ars/2 From onurb at xiludom.gro Thu May 11 04:12:27 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 11 May 2006 10:12:27 +0200 Subject: 2 books for me In-Reply-To: <87lkt9ytxx.fsf@localhost.localdomain> References: <87lkt9ytxx.fsf@localhost.localdomain> Message-ID: <4462f24d$0$311$636a55ce@news.free.fr> Gary Wessle wrote: > Hi > > I am about to order 2 books, and thought I should talk to you first. > I am getting Python Cookbook by Alex Martelli, David Ascher, Anna > Martelli Ravenscroft, Anna Martelli Ravenscroft, since Bruce Eckel's > Thinking in Python is not finished and didn't have any new revisions > since some time in 2001, having owned his Thinking in C++ v1 and v2 I > am used to learning from him. any way, the second book is gui one, I > notices there are 3 flavors according to > http://wiki.python.org/moin/GuiBooks, wxPython, Qt, and Tkinter.I am > not sure what package is best for and would like to know before I > order one of those three. I don't which is "better", but wxPython is still the best choice IMHO if you worry about portability and licencing issues. But what don't you take the time to at least have a look at tutorials and example code ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python.list at tim.thechases.com Wed May 31 14:47:17 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Wed, 31 May 2006 13:47:17 -0500 Subject: TSV to HTML In-Reply-To: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> References: <1149098823.979329.9220@f6g2000cwb.googlegroups.com> Message-ID: <447DE4B5.6000801@tim.thechases.com> > I was wondering if anyone here on the group could point me > in a direction that would expllaing how to use python to > convert a tsv file to html. I have been searching for a > resource but have only seen information on dealing with > converting csv to tsv. Specifically I want to take the > values and insert them into an html table. > > I have been trying to figure it out myself, and in > essence, this is what I have come up with. Am I on the > right track? I really have the feeling that I am > re-inventing the wheel here. > > 1) in the code define a css > 2) use a regex to extract the info between tabs > 3) wrap the values in the appropriate tags and insert into > table. > 4) write the .html file Sounds like you just want to do something like print "<table>" for line in file("in.tsv"): print "<tr>" items = line.split("\t") for item in items: print "<td>%s</td>" % item print "</tr>" print "</table>" It gets a little more complex if you need to clean each item for HTML entities/scripts/etc...but that's usually just a function that you'd wrap around the item: print "<td>%s</td>" % escapeEntity(item) using whatever "escapeEntity" function you have on hand. E.g. from xml.sax.saxutils import escape : : print "<td>%s</td>" % escape(item) It doesn't gracefully attempt to define headers using <thead>, <tbody>, and <th> sorts of rows, but a little toying should solve that. -tim From aleax at mac.com Tue May 23 23:11:54 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 23 May 2006 20:11:54 -0700 Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> Message-ID: <1hft3qc.6w70fc1ylhlvsN%aleax@mac.com> George Sakkis <george.sakkis at gmail.com> wrote: > Bruno Desthuilliers wrote: > > > George Sakkis a ?crit : > > > Although I consider dict(**kwds) as one of the few unfortunate design > > > choices in python since it prevents the future addition of useful > > > keyword arguments (e.g a default value or an orderby function), I've > > > been finding myself lately using it sometimes instead of dict literals, > > > for no particular reason. Is there any coding style consensus on when > > > should dict literals be preferred over dict(**kwds) and vice versa ? > > > > using dict literals means that you'll always have a builtin dict - you > > cannot dynamically select another dict-like class. OTHO, you can only > > use valid python identifiers as keys with dict(**kw). > > This is all good but doesn't answer my original question: under which > circumstances (if any) would {'name':'Mike, 'age':23} be preferred > over dict(name='Mike', age=23) and vice versa, or if it's just a matter > of taste, similar to using single vs double quote for string literals > (when both are valid of course). My personal favorite style is always to call the type when applicable (and reasonably forecast to _remain_ applicable in future code changes), because readability benefits. Alex From yinglcs at gmail.com Wed May 31 14:37:47 2006 From: yinglcs at gmail.com (yinglcs at gmail.com) Date: 31 May 2006 11:37:47 -0700 Subject: Save data to a file thru a http connection Message-ID: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> Hi, I am new to python. I read an example here about how to fetch data thru a HTTP connection: http://diveintopython.org/http_web_services/review.html, My question is how can i save the data to a file after reading it from a http connection. Thank you. From Serge.Orlov at gmail.com Wed May 10 09:29:10 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 10 May 2006 06:29:10 -0700 Subject: data entry tool References: <445f038f@news.maxnet.co.nz><4c8gkoF14mu9cU1@uni-berlin.de> <4461a499@news.maxnet.co.nz> Message-ID: <1147267750.833367.234180@v46g2000cwv.googlegroups.com> Peter wrote: > Diez B. Roggisch wrote: > > Make it a webapp. That will guarantee to make it runnable on the list of > > OSses you gave. Use Django/TurboGears/ZOPE for the application itself- > > whichever suits you best. > > A webapp isn't feasible as most of the users are on dial up (this is in New > Zealand and broadband isn't available for lots of people). I don't see connection here, why it's not feasible? > I was hoping for a simple tool. Even if it only worked on Windows, it would > be a start. It just needs to present a form of text entry fields to the > user, and place the data in a plain text file. You can do it using for example Tkinter <http://wiki.python.org/moin/TkInter> that comes with python distribution for windows. > > If python can't do this, can anyone suggest another language or approach? Sure you can code that application in Python, the problem is distribution and support of application running on multiple platforms. That's what webapp will help you to avoid. Keep in mind that standalone application for windows will be about 2Mb. Keep also in mind linux is not a platform, it is hmm, how to say it? a snapshot of random programs found on internet, so it's very hard to distribute and support programs for it. From steven.bethard at gmail.com Mon May 22 17:56:11 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 May 2006 15:56:11 -0600 Subject: Using metaclasses to inherit class variables In-Reply-To: <1148333276.914151.13910@j33g2000cwa.googlegroups.com> References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> <1148315581.385405.204750@i40g2000cwc.googlegroups.com> <KvCdncoHsJN4bezZnZ2dnUVZ_sydnZ2d@comcast.com> <1148321972.467689.148900@j73g2000cwa.googlegroups.com> <Hoidncqg-cNmj-_ZnZ2dnUVZ_sednZ2d@comcast.com> <1148333276.914151.13910@j33g2000cwa.googlegroups.com> Message-ID: <prudndLLENHkru_ZnZ2dnUVZ_tudnZ2d@comcast.com> telesphore4 at gmail.com wrote: > Fresh copies of class vars so the first one is the correct: ('foo', > 'bar', [], False) Ahh, yeah, then you definitely need the copy.copy call. >>>> import copy >>>> >>>> class ClassVars(type): > ... def __init__(cls, name, bases, dict): > ... for name, value in type(cls).classVars.iteritems(): > ... if name not in dict: > ... setattr(cls, name, copy.copy(value)) > ... >>>> def are(**kwargs): > ... return type('', (ClassVars,), {'classVars':kwargs}) > ... >>>> class C(object): > ... __metaclass__ = are(name='foo', desc='bar', list=[]) > ... name = 'not foo' #<<< Changing a copy only owned by this class > ... >>>> class D(C): > ... pass > ... >>>> C.name, C.desc, C.list > ('not foo', 'bar', []) <<<<<<<<<<<<<<<<<<<<<< Separate copy we changed >>>> D.name, D.desc, D.list, D.list is C.list > ('foo', 'bar', [], False) <<<<<<<<<<<<<<<<<<<< Defaults are not changed Hmm... I don't think I can get away with just a function for __metaclass__ in this situation since D doesn't invoke it: >>> class C(object): ... def __metaclass__(*args): ... print '__metaclass__%r' % (args,) ... return type(*args) ... __metaclass__('C', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <function __metaclass__ at 0x00FA89F0>}) >>> class D(C): ... pass ... >>> I'm not sure why this is. Anyone else out there know? D *does* invoke __metaclass__ if it's a subclass of type: >>> class C(object): ... class __metaclass__(type): ... def __init__(*args): ... print '__init__%r' % (args,) ... __init__(<class '__main__.C'>, 'C', (<type 'object'>,), {'__module__': '__main__', '__metaclass__': <class '__main__.__metaclass__'>}) >>> class D(C): ... pass ... __init__(<class '__main__.D'>, 'D', (<class '__main__.C'>,), {'__module__': '__main__'}) >>> So it seems you pretty much have to go with the approach you're currently using. It doesn't make any real difference, but I'd tend to do it with a nested class statement instead of a call to type: >>> def set_classvars(**kwargs): ... class __metaclass__(type): ... def __init__(cls, name, bases, classdict): ... for name, value in kwargs.iteritems(): ... if name not in classdict: ... setattr(cls, name, copy.copy(value)) ... return __metaclass__ ... >>> class C(object): ... __metaclass__ = set_classvars(name='foo', desc='bar', list=[]) ... name = 'not foo' ... >>> class D(C): ... pass ... >>> C.name, C.desc, C.list ('not foo', 'bar', []) >>> D.name, D.desc, D.list, D.list is C.list ('foo', 'bar', [], False) > Thanks for your help btw. No problem. This is much more fun than doing real work. ;-) STeVe From sjmachin at lexicon.net Fri May 26 17:16:25 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 27 May 2006 07:16:25 +1000 Subject: chop() and empty() functions In-Reply-To: <7xhd3cselw.fsf@ruckus.brouhaha.com> References: <mailman.6253.1148664337.27775.python-list@python.org> <44776377.7090304@lexicon.net> <7xhd3cselw.fsf@ruckus.brouhaha.com> Message-ID: <4477702b@news.eftel.com> On 27/05/2006 6:41 AM, Paul Rubin wrote: > John Machin <sjmachin at lexicon.net> writes: >> What is the use case? Why write something like """empty(foo, 42, >> cmd="xyzzy")""" when you could merely write "pass" or nothing at all? > > The function might be a parameter to something. Please bear with me; it's only about 7 a.m. in this neck of the woods and I've had only 2 cups of coffee so far :-) So one is calling some functions defined like: def something1(..., afunc, ...): ... if afunc([], 1.23, "plugh") is None: .... and def something2(bfunc, ...): ... if bfunc(sys.stdout, "teehee", 0666) is None: .... etc etc and there are so many xfuncs with different argument signatures and so many times that the caller wants to supply a do-nothing xfunc that defining a swallow-any-and-all-args empty() function is warranted??? Thanks in advance for any enlightenment, Cheers, John From bignose+hates-spam at benfinney.id.au Wed May 17 18:47:13 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 08:47:13 +1000 Subject: How to tell if function was passed a list or a string? References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> Message-ID: <87ejysnua6.fsf@benfinney.id.au> "rh0dium" <steven.klass at gmail.com> writes: > I want this function to be smart enough to tell if it's a list and > do the funky concatonation otherwise don't. Bad code smell. Don't try to be too clever with the data types passed to you; instead, operate on them as though the caller has passed the right thing. Write unit tests and integration tests to ensure that the code is behaving as expected, and to reduce the amount of clever code that gets in the way of understanding the function. > The question is how do you tell that the data you were passed is a > list or not? With difficulty, since strings are sequences. It's debatable whether this is a wart. Two options: Use 'isinstance', which unfortunately breaks the rule of duck typing. Currently there's no good duck-typing way to differentiate strings from other sequences. if isinstance(x, basestring): # do string stuff else: # do sequence-of-string stuff Or: If you want to operate on sequences of strings, simply specify that's all that can be passed and expect it inside your function. This is more Pythonic, IMO. -- \ "First they came for the verbs, and I said nothing, for verbing | `\ weirds language. Then, they arrival for the nouns and I speech | _o__) nothing, for I no verbs." -- Peter Ellis | Ben Finney From catdude at catfolks.net Tue May 9 14:37:15 2006 From: catdude at catfolks.net (CatDude) Date: Tue, 09 May 2006 11:37:15 -0700 Subject: Progress bar in web-based ftp? Message-ID: <pan.2006.05.09.18.37.13.238658@catfolks.net> I've got an application that prompts the user to select a file from his local computer, checks the user's selection, then sends the file via <form name="clients" method="POST" action="upload" enctype="multipart/form-data"> In the python code that receives the files I've got a section that does the following: if not os.path.isfile(filePath): file(filePath, 'wb').write(str(form[name].value)) else: print "File already exists - deleting" os.unlink(filePath) file(filePath, 'wb').write(str(form[name].value)) after error checking, etc. My question is whether anyone has ideas as to how I could implement a progress bar. When I send a large file this way it can take a long time, and I'd like to be able to reassure the user that something really is happening. From robin at reportlab.com Tue May 30 13:10:12 2006 From: robin at reportlab.com (Robin Becker) Date: Tue, 30 May 2006 18:10:12 +0100 Subject: Multiple Polynomial Quadratic Sieve In-Reply-To: <iG_eg.242782$xt.233497@fe3.news.blueyonder.co.uk> References: <iG_eg.242782$xt.233497@fe3.news.blueyonder.co.uk> Message-ID: <447C7C74.8080009@chamonix.reportlab.co.uk> Philip Smith wrote: > Just to announce that I have posted an experimental version of MPQS which I > am hoping those of a mathematical turn of mind would care to test, comment > on and maybe contribute to. > > There is work to do but it performs very well. > > The package is available via FTP at > http://www.pythonstuff.pwp.blueyonder.co.uk/ > account: python password: guest > not sure I can help, but clicking on that http link produces a 404 for me. -- Robin Becker From martin.witte at gmail.com Wed May 24 11:40:04 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 24 May 2006 08:40:04 -0700 Subject: How to find out a date/time difference In-Reply-To: <mailman.6149.1148480978.27775.python-list@python.org> References: <mailman.23408.1148480403.27774.python-list@python.org> <mailman.6149.1148480978.27775.python-list@python.org> Message-ID: <1148485203.979280.143180@i40g2000cwc.googlegroups.com> And if you want the number of days: py> d = datetime.datetime(2006,5,24,16,34) - datetime.datetime(2006,5,23,12,1) py> d.days 1 py> d = datetime.datetime(2006,5,24,16,34) - datetime.datetime(2006,5,23,19,1) py> d.days 0 From kentilton at gmail.com Tue May 9 00:45:23 2006 From: kentilton at gmail.com (Ken Tilton) Date: Tue, 09 May 2006 00:45:23 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147148036.512676.288190@i39g2000cwa.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> Message-ID: <z9V7g.119$u17.21@fe08.lga> Pisin Bootvong wrote: > Joe Marshall wrote: > >>Alex Martelli wrote: >>Most languages allow `unnamed numbers'. The `VAT_MULTIPLIER' argument >>is a >>strawman. Would you want to have to use a special syntax to name the >>increment >>in loop? >> >> defnumber zero 0 >> defnumber one { successor (zero); } >> >> for (int i = zero; i < limit; i += one) { ...} >> >>If you language allows unnamed integers, unnamed strings, unnamed >>characters, unnamed arrays or aggregates, unnamed floats, unnamed >>expressions, unnamed statements, unnamed argument lists, etc. why >>*require* a name for trivial functions? >>Wouldn't all the other constructs benefit by having a required name as >>well? >> > > > Is this a Slippery Slope fallacious argument? > (http://c2.com/cgi/wiki?SlipperySlope) > > "if python required you to name every function then soon it will > require you to name every number, every string, every immediate result, > etc. And we know that is bad. Therefore requiring you to name your > function is bad!!!! So Python is bad!!!!" > > > How about: > > If Common Lisp lets you use unnamed function, then soon everyone will > start not naming their function. Then soon they will start not naming > their variable, not naming their magic number, not naming any of their > class, not naming any function, and then all Common Lisp program will > become one big mess. And we know that is bad. So allowing unnamed > function is bad!!!! So Common Lisp is bad!!!!! Funny you should mention that. Cells (obviously) have turned out to be a gold mine for me in terms of development. And they have exactly one non-limiting limitation: once you start using them, you have to use them almost everywhere, because they create a different dataflow, or better put, the dataflow replaces the control flow of imperative programming, so there is no way to add a little subsection of functionality with imperative code because all the action is over in dataflow-land. I call it non-limiting because it is more like a healthy discipline: as a consequence, all application semantics end up expressed as so many discrete little cell rules. Which brings me to the punch line... try to debug an app where all the code is in anonymous functions!!! well, it was not a complete disaster because by hook or by crook one could figure out which rule was at fault even in the worst case, and most of the time there was not much question. But still... well, it took me embarrasingly long to notice something. I never actually coded (lambda (self) yada yada) for a rule. I always used a macro: (c? yada yada) This was great because it is more succinct and because once I had a couple hundred of these i had little problem making serious overhauls to the implementation. And of course if you know Lisp and macros... duhhhhh! They operate on the code! So in two seconds I added a new slot to a Cell called "code", and part of the macro expansion was to stuff the source code into the code slot. ie... The code: (c? (yada yada yada)) Becomes: (make-c-dependent :code '((yada yada yada)) :value-state :unevaluated :rule (c-lambda (yada yada yada))) c-lambda? I have a few of those c? macros, so I "submacro" the necessary lambda form: (lambda (slot-c &aux (self (c-model slot-c)) (.cache (c-value slot-c))) (declare (ignorable .cache self)) (yada yada yada)) I almost never have to look at that code slot (as I said, most of the time I can tell from the instance class and the slot name which rule I screwed up) but when I am stumped, I just inspect the source code. :) Oh, wait, this is not the "Should Python have macros" thread, is it? :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From george.sakkis at gmail.com Thu May 18 18:24:04 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 18 May 2006 15:24:04 -0700 Subject: Feature request: sorting a list slice References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <mailman.5898.1147974803.27775.python-list@python.org> Message-ID: <1147991044.082289.90100@j73g2000cwa.googlegroups.com> Fredrik Lundh wrote: > George Sakkis wrote: > >> It would be useful if list.sort() accepted two more optional >> parameters > > > useful for what? what's the use case ? > > </F> > Although there is a use case (see below), I don't think it's strictly necessary in this case. Arguments to add it: - Don't Repeat Yourself. - It doesn't introduce new syntax, builtin or standard library function; only two optional keywords in an existing method. - These keywords are already used in several list and string methods (index,find,..) and their meaning is instantly obvious. - Increased (even if small) efficiency. Yes, I know that in practice, and especially in apps that involve I/O, network, DB connections and so on, it's unlikely to be the bottleneck but this isn't a general argument for being sloppy. The fact that having a "for i in xrange(100000):pass" at the top of every file costs me only a few msec is not a reason to keep it there. IMO the only reason not to add it would be if it makes sort's implementation much more complicate that it already is. I don't know Timsort's details, but I doubt that this is the case; please correct me if I am wrong. And here's (a cut-down version of) the use case: a recursive generalization of groupby. On each recursive call, the argument list is sorted and regrouped. If sort() accepted a (start,end) range I could pass this over instead of creating a slice of the input each time. It's not hard to see that there can be an exponential number of calls wrt to the input's length, so cutting down the average cost of each call may be worthwhile for medium-largish sized inputs (of course it's still exponential asymptotically, so the constant factor does not make much difference for really large inputs). import itertools as it def groupBy(iterable, *keys): return _groupBy(list(iterable), keys, len(keys)) def _groupBy(lst, keys, depth): if depth == 0: return lst key = keys[-depth] # sort group before subgrouping lst.sort(key=key) # group by key and then recursively do the same for each subgroup return [(k, _groupBy(list(subgroup),keys,depth-1)) for k,subgroup in it.groupby(lst,key)] #==== example ======================================== class Struct(object): def __init__(self, args): self.args = args def __getitem__(self,index): return self.args[index] data = map(Struct, [ ('a', 2, True), ('b', 1, False), ('a', 1, True), ('a', 1, False), ('b', 2, True), ('b', 2, True), ('a', 2, True), ]) from pprint import pprint from operator import itemgetter pprint(groupBy(data, itemgetter(2), itemgetter(0), itemgetter(1))) #======= output ================================= [(False, [('a', [(1, [<__main__.Struct object at 0xb7dc128c>])]), ('b', [(1, [<__main__.Struct object at 0xb7dc124c>])])]), (True, [('a', [(1, [<__main__.Struct object at 0xb7dc126c>]), (2, [<__main__.Struct object at 0xb7dc122c>, <__main__.Struct object at 0xb7dc12ec>])]), ('b', [(2, [<__main__.Struct object at 0xb7dc12ac>, <__main__.Struct object at 0xb7dc12cc>])])])] George From lrasinen at iki.fi Mon May 15 01:10:25 2006 From: lrasinen at iki.fi (Lasse Rasinen) Date: 15 May 2006 08:10:25 +0300 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> Message-ID: <d6lu07r7u0u.fsf@vipunen.hut.fi> Ken Tilton <kentilton at gmail.com> writes: > > if any concepts have survived to the Python version. Since Python's object > > model is sufficiently different, the system is based on rules being > > defined per-class... > > That will be a total disaster for PyCells, if true. But I do not think it > is. You just need a constructor that takes some slot initializers, and > initialize the slots to one of: a normal value; an InputCell itself > initialized with a starting value, if only nil; or a RuledCell itself > initialized with a lambda. Hmm, just tried it: >>> class A(cells.cellular): ... def __init__(self): ... self.a = cells.InputCell(10) ... self.b = cells.RuleCell(lambda self: self.a+1, self, None) >>> a = A() >>> a.a 10 >>> a.b 11 So it does work out-of-the-box ;-) > PyCells looks like it will be a project for SoC2006, so you may as well > relax. You really want to start a SoC project on something that takes about two weeks from an average Python programmer? What does the guy do for the rest of the summer? (I think I spent 4-5 hours on this actually sitting on the computer, sandwiched between remodeling and cleaning and work. The rest of the two weeks would be making it more robust ;-) > > Features: > > - Tracks changes to input cells dynamically (normal attributes are not tracked) > > Ha! All your rules depend on the input cell itself! How about A depends on > B depends on C? :) Oops. I'm sorry for the inaccurate terminology. They depend only the cells they use as inputs (their "children"), and not only on InputCells. (I use the parent-child terminology because as English is not my native language, I had trouble remembering which depend* variable was which ;-) > Quite hard to test deliberately, but it happens "in nature". But it will > not happen until you do A->B->C. Once you have /that/ working, make A the > input, then have B and C both use A. But also have B use C, and jiggle > things around until A happens to think it should update B first, then C. > What happens is that B runs and uses C, but C has not been updated yet. C > is inconsistent with A, but is being used to calculate a new value for B > which does see the new value of A. Mismatch! B will get sorted out in a > moment when C gets recalculated and tells B to calculate a second time, > but meanwhile after the first recalculation of B the on-change callback > for that got invoked, missiles were launched, and Moscow has been > destroyed. If you check the testcase, you'll see there are such dependencies, and all the callbacks fire just once (and in dependency-related order). Furthermore, the timestamp mechanism SHOULD take care of those (if the cell is older than its children, it gets recalculated before it will provide any data, and thus C will get recalculated before B uses it. > ps. In the getattr for any Cell-mediated slot, look to see if "parent" is > non-nil. If so, set up a dependency. k Already done, see BaseCell.value() ;-) -- Lasse Rasinen lrasinen at iki.fi From johnjsal at NOSPAMgmail.com Tue May 9 13:38:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 17:38:52 GMT Subject: multiline strings and proper indentation/alignment Message-ID: <Ms48g.2070$No6.45827@news.tufts.edu> How do you make a single string span multiple lines, but also allow yourself to indent the second (third, etc.) lines so that it lines up where you want it, without causing the newlines and tabs or spaces to be added to the string as well? Example (pretend this is all on one line): self.DTD = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n\n' I want it to read: self.DTD = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n "http://www.w3.org/TR/html4/strict.dtd">\n\n''' Or anything like that, but I don't want the extra newline or tabs to be a part of the string when it's printed. Thanks. From olsongt at verizon.net Wed May 24 09:43:39 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 24 May 2006 06:43:39 -0700 Subject: John Bokma harassment In-Reply-To: <1148470149.596188.18500@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> Message-ID: <1148478219.803585.158850@g10g2000cwb.googlegroups.com> Tim N. van der Leeuw wrote: > ilitzroth at gmail.com wrote: > > I agree there are limits to you right to free speech, but I believe Xah > > Lee is not crossing > > any boundaries. If he starts taking over newspapers and TV stations be > > sure to notify me, > > I might revise my position. > > Immanuel > > Perhaps he's not crossing boundaries of free speech, but he's > repeatedly crossing boundaries on usenet nettiquette, even though > repeatedly he's being asked not to do so. (Extensive crossposting to > various usenetgroups / mailing lists, for instance). > > If he would just post his stuff on a blog and find a why to get people > to visit hist blog, without crossposting to 10 usenest groups for each > post he makes to his blog, then nobody would mind him expressing his > opinions, and those interested could discuss them wildly on the blog. > > But I've repeatedly seen people telling him not to crosspost his essays > to so many newsgroups, yet he continues doing it. > If that's enough to quit his subscription with his ISP I don't know, > but since I've stopped following threads originated by him I don't know > what other grounds there would be. > > Cheers, > > --Tim The trouble is there's no definitive definition of 'nettiquette' (and no the RFC on nettiquette doesn't count). Should people get kicked off of thier ISP for top posting? What about not asking 'smart' questions as defined by Eric Raymond? In addition, the people telling him not to cross-post don't really have any authority. They're just random people on the internet. For example, you've cross posted to several groups. I'm telling you to stop. Of course I'm doing the same thing and you can feel free to ignore me. I'm not the Supreme Master of comp.lang.python. But I think you would agree that it would be harrassment if I went to your ISP- nl.unisys.com - and said that you were abusing the internet and 'spamming' the usenet, especially if you are a unisys employee (not sure if they're a service provider over there, but I'm guessing not). If I got a hold of the wrong person on the wrong day, you could lose your job. Xah is an crackpot, but he doesn't spam or mailbomb groups. And besides, what fun would the usenet be without crackpots? From webraviteja at gmail.com Thu May 11 23:44:09 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 11 May 2006 20:44:09 -0700 Subject: Time to bundle PythonWin In-Reply-To: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> References: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> Message-ID: <1147405448.945781.272110@j33g2000cwa.googlegroups.com> > I write applications that use COM and Tkinter to automate basic office > tasks. My users are thankfully benevolent enough to download and install > Python on their own. They don't know what PythonWin is, they aren't > remembering it, and frankly, I don't think it should be their concern. > It's time to bundle PythonWin. Someone already has. http://www.activestate.com/Products/ActivePython/ > Mac libraries are bundled with Python's *standard library*. Are they? Only the documentation stubs are (in ActivePython anyway). It would be quite a feat to compile Mac libraries on Windows to distribute ;-). From softwindow at gmail.com Thu May 18 23:54:35 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 20:54:35 -0700 Subject: Script to make Windows XP-readable ZIP file In-Reply-To: <1148008563.178335.307330@j55g2000cwa.googlegroups.com> References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> <1148008563.178335.307330@j55g2000cwa.googlegroups.com> Message-ID: <1148010875.772803.62140@i40g2000cwc.googlegroups.com> my code can work, like below: import os import zipfile z = zipfile.ZipFile(r"c:\text.zip",mode="w",compression=zipfile.ZIP_DEFLATED) cwd = os.getcwd() try: for dirpath,dirs,files in os.walk(cwd): for file in files: z_path = os.path.join(dirpath,file) z.write(z_path) z.close() finally: if z: z.close() that is true but the archive include the absolute path . can you give me a way to build it with relative path. From skip at pobox.com Tue May 16 14:54:29 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 May 2006 13:54:29 -0500 Subject: round numbers in an array without importing Numeric or Math? In-Reply-To: <446a1ce0$0$61167$ae4e5890@news.nationwide.net> References: <446a1748$0$61168$ae4e5890@news.nationwide.net> <yfssln9q180.fsf@oc.ex.ac.uk> <446a1ce0$0$61167$ae4e5890@news.nationwide.net> Message-ID: <17514.8165.853388.700213@montanaro.dyndns.org> Lance> May have a complicating issue with the array? Have the numbers Lance> have been interpreted as strings? I have been pulling them from Lance> a Word doc using regex's [int(float(x)+0.5) for x in Test] S From rory.brandybuck at gmail.com Fri May 12 08:33:17 2006 From: rory.brandybuck at gmail.com (rory.brandybuck at gmail.com) Date: 12 May 2006 05:33:17 -0700 Subject: index of an element in a numarray array References: <1147430375.161743.29820@q12g2000cwa.googlegroups.com> Message-ID: <1147437197.778271.247110@j73g2000cwa.googlegroups.com> avharut at gmail.com wrote: > how can i find in an efficient way the index of the last occurrence of > a given element in a numarray array? Something like that: >>> where(arange(100) == 10) (array([10]),) >>> _[-1][-1] 10 Or: >>> your_array = arange(10) >>> value = 3 >>> indices = where(your_array == value) >>> last_index = indices[0][-1] >>> print last_index From andy at neotitans.com Wed May 17 12:21:01 2006 From: andy at neotitans.com (Andy Sy) Date: Thu, 18 May 2006 00:21:01 +0800 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> Message-ID: <e4fiat$gsj$1@sea.gmane.org> Sybren Stuvel wrote: >> then WHAT THE HECK do you need to use tab characters in the source >> code for anyway (besides saving a measly few bytes) ??!? > > To separate layout (how much indentation is used) from semantics (how > many intentation levels). Like I said, you'll *NEVER* get that fancy shmancy 'semantic indentation' idea to work properly in the most basic utilities which have the 8-space tabs assumption hardcoded in them. Code with anything other than 8-space tabs will *NEVER* display properly using everyday unix utilities such as less and cat. But then, 8-space tabs are just too wide to be practical, thus the simple conclusion I have reached: JUST STOP USING THEM. Heck, all those who actually believe that make's requirement of an invisible tab as a 'semantic' marker was a good idea raise their hands...! <rolling-eyes-to-high-heaven> >> Tab characters are EVIL *AND* STUPID. > > And someone who needs to resort to all-caps words (which many consider > shouting) needs to relax and use proper arguments. I know when I'll be able to relax... when I no longer need to waste time dealing with those stupid tabs in source code!!! ;-) From kent at kentsjohnson.com Tue May 2 07:54:48 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 02 May 2006 07:54:48 -0400 Subject: strip newlines and blanks In-Reply-To: <1146551463.451811.266960@j73g2000cwa.googlegroups.com> References: <1146551463.451811.266960@j73g2000cwa.googlegroups.com> Message-ID: <4457482f$1_2@newspeer2.tds.net> micklee74 at hotmail.com wrote: > hi > i have a file test.dat eg > > abcdefgh > ijklmn > <-----newline > opqrs > tuvwxyz > > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break break terminates the loop, so no more lines will be processed. Use continue, which ends only the current iteration of the loop. (Though you will need a separate test to terminate the loop when there are no more lines.) You can iterate an open file directly; here is a shorter version: for line in open('test.dat'): line = line.rstrip('\n') if line: print line Kent > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all w/o the newlines..? and what is the > proper way to skip printing blank lines while iterating file contents? > > thanks > From me+python at modelnine.org Tue May 2 16:52:56 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 22:52:56 +0200 Subject: simultaneous assignment In-Reply-To: <NrP5g.11087$Lm5.1177@newssvr12.news.prodigy.com> References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <NrP5g.11087$Lm5.1177@newssvr12.news.prodigy.com> Message-ID: <200605022252.56786.me+python@modelnine.org> Am Dienstag 02 Mai 2006 22:39 schrieb Edward Elliott: > Which raises an interesting parallel question: is there a way to clone an > arbitrary object? Yes, check the copy module. copy.copy() does a shallow copy of the parameter, copy.deepcopy() a deep copy of the parameter. For the difference between the two, check the manual. (basically, a deep copy copies the whole object tree for container objects such as lists/tuples/dicts/instances, a shallow copy copies only the topmost container) > <snip...> > but not small ones: > >>> a = 5 > >>> b = a + 0 > >>> id(a) == id(b) > > True What sense is there cloning integers/strings? Integer and string objects are immutable in Python, so why'd you want to have different IDs for an object of the same value? It's the value you're working with in a program, not the objects ID. At least it should be, if you're truly intent on working with the (pseudo-random) object-ID, something with your design is really, really broken. --- Heiko. From malvert at telenet.be Tue May 9 15:40:57 2006 From: malvert at telenet.be (malv) Date: 9 May 2006 12:40:57 -0700 Subject: Can Python installation be as clean as PHP? In-Reply-To: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> Message-ID: <1147203657.035578.153430@y43g2000cwc.googlegroups.com> If this bothers you, why don't you stick to a linux distro with Python installed. Very few don't. From mtobis at gmail.com Fri May 19 12:46:35 2006 From: mtobis at gmail.com (Michael Tobis) Date: 19 May 2006 09:46:35 -0700 Subject: Quoting relevant material for response (was: Re: python vs perl lines of code) In-Reply-To: <1148003186.350496.67670@g10g2000cwb.googlegroups.com> References: <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <Xns97C7BC8549BA0castleamber@130.133.1.4> <1147996169.818933.252420@u72g2000cwu.googlegroups.com> <Xns97C7C31D1A937castleamber@130.133.1.4> <1148002073.419819.295180@38g2000cwa.googlegroups.com> <mailman.5921.1148002657.27775.python-list@python.org> <1148003186.350496.67670@g10g2000cwb.googlegroups.com> Message-ID: <1148057195.332276.203370@y43g2000cwc.googlegroups.com> OT, sort of, but... akameswaran at gmail.com wrote: >If that > quoting mechanism is available on the web interface and I haven't found > it - I'd love to know how to use it. Click "show options" and THEN hit "reply". It's a bit counterintuitive, but the entire message to which you reply is then shown. It is best to (as I've just done) erase the parts you aren't replying to. If you are replying to multiple selected parts of the message it is good form to indicate the gaps with ellipses ("..."). It's worth noting that this group predates Google by severalyears, that usenet predates it by well over a decade, and that Google is only one of several alternative ways of participating (though it is my own preference) and that its conventions have emerged for good reasons. see http://en.wikipedia.org/wiki/Usenet and http://en.wikipedia.org/Google_Groups mt From sybrenUSE at YOURthirdtower.com.imagination Thu May 11 04:28:43 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 11 May 2006 10:28:43 +0200 Subject: Memory leak in Python References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <ccl062h5tc24b4qe3d66b7hvh7ujgrklcp@4ax.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> <slrne63ae3.96g.sybrenUSE@schuimige.stuvel.eu> <1147302164.557634.177170@v46g2000cwv.googlegroups.com> Message-ID: <slrne65tdr.8pb.sybrenUSE@schuimige.stuvel.eu> diffuser78 at gmail.com enlightened us with: > Sure, are there any available simulators...since i am modifying some > stuff i thought of creating one of my own. But if you know some > exisiting simlators , those can be of great help to me. Don't know any by name, but I'm sure you can find some on Google. Do you need a discrete-event or a discrete-time simulator? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From ptmcg at austin.rr._bogus_.com Sat May 20 00:09:05 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sat, 20 May 2006 04:09:05 GMT Subject: altering an object as you iterate over it? References: <1Mobg.2139$No6.46432@news.tufts.edu> <446e1def$0$6919$626a54ce@news.free.fr> <446e573a$0$4960$626a54ce@news.free.fr> Message-ID: <BDwbg.46957$CH2.44289@tornado.texas.rr.com> "Bruno Desthuilliers" <bdesth.quelquechose at free.quelquepart.fr> wrote in message news:446e573a$0$4960$626a54ce at news.free.fr... > bruno at modulix a ?crit : > (snip) > > (responding to myself) > (but under another identity - now that's a bit schizophrenic, isn't it ?-) > Do you ever flame yourself? -- Paul From johnjsal at NOSPAMgmail.com Sun May 7 23:19:46 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 07 May 2006 23:19:46 -0400 Subject: utility functions within a class? In-Reply-To: <1147055211.899384.323190@v46g2000cwv.googlegroups.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> Message-ID: <445eb995$0$9381$c3e8da3@news.astraweb.com> jeffshannon at gmail.com wrote: > Even if you don't end up referring to self or any instance > attributes within the method Hmm, follow-up: I *do* plan to refer to instance attributes inside these methods (self.something), but does that require that they be instance methods, or can they still reference 'self' since they are inside the class? They won't be called directly from an instance, which is why I wondered about making them static or class methods, but can static or class methods use self, or does it have to be an instance method in that case? From onurb at xiludom.gro Tue May 16 10:33:59 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 16 May 2006 16:33:59 +0200 Subject: my cryptogram program In-Reply-To: <A9lag.2104$No6.46276@news.tufts.edu> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <gh5ag.2100$No6.46182@news.tufts.edu> <4468f2c4$0$7135$626a54ce@news.free.fr> <7xfyjbrmzl.fsf@ruckus.brouhaha.com> <4468f9af$0$12816$636a55ce@news.free.fr> <A9lag.2104$No6.46276@news.tufts.edu> Message-ID: <4469e33d$0$21943$626a54ce@news.free.fr> John Salerno wrote: > Bruno Desthuilliers wrote: > >> At least someone reading this may learn about the max_split param of >> str.split() !-) > > > LOL. The first thing I did was scramble to the docs to see what that > second parameter meant! :) > > But I was a little confused about why you included it. Just to insure > that only two elements are returned? Yes. It may or not be a wise choice. Depends on the context, your design, etc... > I plan on making either a text file > or a database with quotes in that format (quote|author), so maybe the > maxsplit isn't needed? It's up to you. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From Florian.Lindner at xgm.de Thu May 4 11:56:40 2006 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Thu, 04 May 2006 17:56:40 +0200 Subject: Calling superclass Message-ID: <e3d88b$2pm$1@news.in.tum.de> Hello, I try to call the superclass of the ConfigParser object: class CustomizedConfParser(ConfigParser.SafeConfigParser): def get(self, section, attribute): try: return super(CustomizedConfParser, self).get(section, attribute) # [...] but that gives only return super(CustomizedConfParser, self).get(section, attribute) TypeError: super() argument 1 must be type, not classobj I don't really understand the error message. Thanks, Florian From finite.automaton at gmail.com Thu May 25 13:23:33 2006 From: finite.automaton at gmail.com (Lonnie Princehouse) Date: 25 May 2006 10:23:33 -0700 Subject: list comprehensions put non-names into namespaces! Message-ID: <1148577813.000229.225330@y43g2000cwc.googlegroups.com> List comprehensions appear to store their temporary result in a variable named "_[1]" (or presumably "_[2]", "_[3]" etc for nested comprehensions) In other words, there are variables being put into the namespace with illegal names (names can't contain brackets). Can't someone come up with a better hack than this? How about using "_1", "_2", etc, or actually making "_" a list of lists and using the real first, second, third elements? This is an unexpected wrench in the works for people trying to implement custom global namespaces. Illustration: class custom_namespace(dict): def __getitem__(self, i): print "GET", i return dict.__getitem__(self, i) eval("[x for x in range(10)]", custom_namespace()) From grflanagan at yahoo.co.uk Sun May 28 07:19:54 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 28 May 2006 04:19:54 -0700 Subject: starting some Python script from C# In-Reply-To: <e5bp9c$la0$1@fegnews.vip.hr> References: <e58ta7$jns$1@fegnews.vip.hr> <1148728940.440692.166330@i39g2000cwa.googlegroups.com> <e5bp9c$la0$1@fegnews.vip.hr> Message-ID: <1148815194.860060.43810@j73g2000cwa.googlegroups.com> > "Gerard Flanagan" <grflanagan at yahoo.co.uk> je napisao u poruci interesnoj > grupi:1148728940.440692.166330 at i39g2000cwa.googlegroups.com... > > tatamata wrote: > >> Hello. > >> > >> How can I run some Python script within C# program? > >> > > > > --------------------------------------------------------------------------------- > > ProcessStartInfo startInfo; > > Process process; > > string directory; > > string pyArgs; > > string script; > > > > startInfo = new ProcessStartInfo("python"); > > startInfo.WorkingDirectory = directory; > > startInfo.Arguments = script + " " + pyArgs; > > startInfo.UseShellExecute = false; > > startInfo.CreateNoWindow = true; > > startInfo.RedirectStandardOutput = true; > > startInfo.RedirectStandardError = true; > > > > process = new Process(); > > process.StartInfo = startInfo; > > process.Start(); > > > > string s; > > while ((s = process.StandardOutput.ReadLine()) != null) > > { > > //do something with s > > } > > --------------------------------------------------------------------------------- > > tatamata wrote: > Hello. I tried to implement ypour suggestion, but an error apears: > "Exception System.ComponentModel.Win32Exception was thrown in debugee: > The specified executable is not a valid Win32 application. > > namespace CS_script > { > class MainClass > { > public static void Main(string[] args) > { > > System.Diagnostics.ProcessStartInfo psi =new > System.Diagnostics.ProcessStartInfo(); > psi.FileName="my_script.py"; > psi.WorkingDirectory=Environment.CurrentDirectory; > psi.RedirectStandardOutput = true; > psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; > psi.UseShellExecute = false; > psi.CreateNoWindow = true; > > System.Diagnostics.Process script; > script = System.Diagnostics.Process.Start(psi); > > System.IO.StreamReader myOutput = script.StandardOutput; > script.WaitForExit(2000); > if (script.HasExited) > { > string output = myOutput.ReadToEnd(); > //this.processResults.Text = output; > } > MessageBox.Show("finished!"); > } > } > } > > When running the program, I have the following error: > > "Exception System.ComponentModel.Win32Exception was thrown in debugee: > The specified executable is not a valid Win32 application. > > StartWithCreateProcess() > Start() > Start() > Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop > Projects\CS_script\CS_script\Main.cs:32,5 " > I have no means of running C# programs at present and can't claim much expertise in any case. A guess is that a "valid Win32 application" means an '.exe' file, not a '.py' file. You are assuming that a Process object is as smart as the command interpreter ('cmd.exe') and will know to use 'python.exe' for a file with a 'py' extension? What happens if you use 'python.exe' (or 'cmd.exe') as your file and the script name as argument as in the code I posted? Gerard (PS. This group prefers that one doesn't top-post) From __peter__ at web.de Tue May 16 02:40:10 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 May 2006 08:40:10 +0200 Subject: Multiple inheritance : waht does this error mean ? References: <1147750957.673439.154420@g10g2000cwb.googlegroups.com> Message-ID: <e4bs0g$90n$02$1@news.t-online.com> jnair at ensim.com wrote: > I am using Python 2.4.3 > >>>>class K(object,list): > ...: pass > ...: > ------------------------------------------------------------ > Traceback (most recent call last): > File "<console>", line 1, in ? > TypeError: Error when calling the metaclass bases > Cannot create a consistent method resolution > order (MRO) for bases object, list class K(object, list): pass specifies that a method should be looked up first in object, then in list. As list inherits from object, its method resolution order >>> list.__mro__ (<type 'list'>, <type 'object'>) specifies that a method should be looked up first in list, then in object. Python refuses to resolve the conflict for you, but you can do it manually: >>> class K2(list, object): pass ... >>> K2.__mro__ (<class '__main__.K2'>, <type 'list'>, <type 'object'>) Now K2, list, and object can agree to look for a method in K2, then list, then object. However, you get the same effect by just inheriting from list: >>> class K3(list): pass ... >>> K3.__mro__ (<class '__main__.K3'>, <type 'list'>, <type 'object'>) Peter From nobody at 127.0.0.1 Tue May 2 16:50:21 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 20:50:21 GMT Subject: stripping blanks References: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> <445720fd$1_2@news.estpak.ee> <4457b7f3$1@nntp0.pdx.net> Message-ID: <hCP5g.11089$Lm5.1280@newssvr12.news.prodigy.com> Scott David Daniels wrote: > A little better: > > f = open("test.dat") > for line in f: > printLine = line.rstrip("\n") > if printLine: > print printLine [sys.stdout.write(line) for line in open('test.dat') if line.rstrip('\n')] Where's my prize? What do you mean, shorter isn't always better? ;) From maric at aristote.info Thu May 25 07:56:54 2006 From: maric at aristote.info (Maric Michaud) Date: Thu, 25 May 2006 13:56:54 +0200 Subject: Bind an instance of a base to a subclass - can this be done? In-Reply-To: <pecoraREMOVE-120DFE.15351024052006@ra.nrl.navy.mil> References: <pecoraREMOVE-120DFE.15351024052006@ra.nrl.navy.mil> Message-ID: <200605251356.56445.maric@aristote.info> Le Jeudi 25 Mai 2006 01:10, vous avez ?crit : > The ratio of two durations has no meaning??? Oh, sorry, sure it has, I wanted to say "it has no meaning in timedelta provided arithmetic". It's a ratio (no dimension) not a duration. In that sense the expected result should be a float, and the proposed operator will break the timedelta's arithmetic consistence. t, u, v <- timedeltas t+u # valid t / u # valid t / u + v # invalid while all terms are valids It's a big design flaw and I think it's the full answer to the original question. Le Jeudi 25 Mai 2006 02:26, Robert Kern a ?crit : > > what you want is : > > > > num_weeks = time_diff.days / 7 > > or > > num_weeks = (time_diff / 7).days > > Uh, no. Besides the integer division problem in your first line, keep in > mind that the .days attribute does not give you the time interval measured > in days. It gives you the number of *whole* days in the interval. The first > method will be incorrect if time_diff is not an even multiple of 1 day. > The latter will be incorrect if time_diff is not an even multiple of 7 days. In fact i was computing the exact number of whole weeks in the delta. In respect of that both expression are perfectly correct, but the second one isn't clear IMO (why this "days" attribute should give me the number of weeks ?). This said it's not hard to figure out the correct expression of the decimal value of weeks in deltas (discarding the microseconds which are not relevant) : num_weeks = (time_diff.days * 24* 3600 + time_diff.seconds) / (7.*24*3600) If I need to do much of these in a piece of code I would probably define some helper functions like this : def tomicroseconds(td) : return td.days * 24* 3600 * 10**6 + td.seconds * 10 ** 6 + td.microseconds def toseconds(td) : return float(tomicroseonds(td)) / 10 ** 6 tominute, tohours, todays, toweeks, etc... and use float and int / and % operators. This is an easy and clean implementation IMHO. -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From grante at visi.com Fri May 5 18:35:15 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 05 May 2006 22:35:15 -0000 Subject: NaN handling References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> <mailman.5401.1146866424.27775.python-list@python.org> Message-ID: <125nkp3c0ggqgb2@corp.supernews.com> On 2006-05-05, Ivan Vinogradov <vinogri at mcmaster.ca> wrote: >> <snip> >> There are those of us that need NaNs in production code, so it >> would have to be something that could be configured. I find >> that in my programs the places where I need to do something >> "exceptional" with a NaN are very limited. The vast majority >> of the time, I need them to propagate quietly. > > Our programming expectations may differ, but an option to > catch NaNs as an exception is a great idea. Unless it's done in hardware, it would be hopelessly slow. There some platforms where it's possible for an application to enable and handle FP interrupts (all of the exampls for that seem to be in Fortran). I don't know if the common platforms (IA32/MS-Windows, IA32/Linux) even have that ability. -- Grant Edwards grante Yow! I'm into SOFTWARE! at visi.com From france.macchi at tele2.it Tue May 9 17:03:09 2006 From: france.macchi at tele2.it (Heavy) Date: 9 May 2006 14:03:09 -0700 Subject: problemi con POST Message-ID: <1147208587.275024.317410@i40g2000cwc.googlegroups.com> Ciao a tutti, sto creando una applicazione in python, che deve fungere anche da server web... non ho assolutamente problemi a prendere i parametri di una 'GET', mi limito a fare il parsing della URL, ma come faccio a prendere i parametri di una 'POST'? io cerco di leggere dal socket di lettura 'rfile' ma poi resto bloccato all'infinito perch? evidemente resta in attesa di qualcosaltro... c'? gi? qualche metodo che mi pu? aiutare?? oppure sapete darmi qualche dritta? grazie... From abhijitng at gmail.com Wed May 10 12:31:34 2006 From: abhijitng at gmail.com (abhijitng at gmail.com) Date: 10 May 2006 09:31:34 -0700 Subject: Calling python functions from C In-Reply-To: <Cz58g.176027$bm6.8320@fed1read04> References: <1147194348.285669.218280@g10g2000cwb.googlegroups.com> <Cz58g.176027$bm6.8320@fed1read04> Message-ID: <1147278694.295434.232250@e56g2000cwe.googlegroups.com> Thanks Farshid, Thats helps me alot ! R. Farshid Lashkari wrote: > robert.differentone at gmail.com wrote: > > I want to call add from C. Could anybody please help me? > > Look at the "Pure Embedding" section of the python documentation. It > contains an example program that does exactly what you want. Here is a > link to the page: > > http://www.python.org/doc/ext/pure-embedding.html > > -Farshid From onurb at xiludom.gro Wed May 17 07:57:12 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 17 May 2006 13:57:12 +0200 Subject: common practice for creating utility functions? In-Reply-To: <Qbwag.88565$dW3.27773@newssvr21.news.prodigy.com> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <7xd5efdstn.fsf@ruckus.brouhaha.com> <4468e3af$0$7129$626a54ce@news.free.fr> <Qbwag.88565$dW3.27773@newssvr21.news.prodigy.com> Message-ID: <446b0fff$0$8198$626a54ce@news.free.fr> Edward Elliott wrote: > Bruno Desthuilliers wrote: > > >>Then it would be better to just alias it: >> >># def convert_quote(quote): >># return make_code(quote) >>convert_quote = make_code > > > The former makes sense if you're planning to do more with the calling > function later. Then it will be time to uncomment the def block and comment out the binding !-) > >>About the "fine to do" part, remember that Python's function calls are >>rather expansive... > > > Indeed, their expansiveness makes them great. Unfortunately they're > somewhat expensive too. ;) Lol !-) Please have mercy, I learned English a long long time ago - and mostly with the lyrics of my favorite rock bands... -- 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 Sun May 21 09:14:14 2006 From: sjmachin at lexicon.net (John Machin) Date: 21 May 2006 06:14:14 -0700 Subject: File encoding strategy question References: <126v3aufq22ip31@corp.supernews.com> Message-ID: <1148217254.675750.172190@j73g2000cwa.googlegroups.com> Andrew > I would like to be able to view the contents of the file if it is text while still maintaining the ability to transmit binary data. Like Dennis said ... and once you have read the RFC and understood it thoroughly :-) don't start writing code; it's one of the included batteries -- but beware of file size expansion for binary data: >>> import quopri >>> a = ''.join(chr(x) for x in range(256)) >>> b = quopri.encodestring(a) >>> c = quopri.decodestring(b) >>> [len(x) for x in a,b,c] [256, 530, 256] >>> a == c True >>> b '\x00\x01\x02\x03\x04\x05\x06\x07\x08=09\n\x0b\x0c\r\x0e\x0f\x10\x11\x12\x13\x14 \x15\x16\x17\x18\x19\x1a\x1b\x1c\x1d\x1e\x1f !"#$%&\'()*+,-./0123456789:;<=3D>?@ ABCDEFGHIJKLMNOPQRS=\nTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~=7F=80=81=82=8 3=84=85=86=87=88=\n=89=8A=8B=8C=8D=8E=8F=90=91=92=93=94=95=96=97=98=99=9A=9B=9C= 9D=9E=9F=A0=A1=\n=A2=A3=A4=A5=A6=A7=A8=A9=AA=AB=AC=AD=AE=AF=B0=B1=B2=B3=B4=B5=B6 =B7=B8=B9=BA=\n=BB=BC=BD=BE=BF=C0=C1=C2=C3=C4=C5=C6=C7=C8=C9=CA=CB=CC=CD=CE=CF=D 0=D1=D2=D3=\n=D4=D5=D6=D7=D8=D9=DA=DB=DC=DD=DE=DF=E0=E1=E2=E3=E4=E5=E6=E7=E8=E9= EA=EB=EC=\n=ED=EE=EF=F0=F1=F2=F3=F4=F5=F6=F7=F8=F9=FA=FB=FC=FD=FE=FF' >>> HTH, John From onurb at xiludom.gro Thu May 18 06:22:16 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 12:22:16 +0200 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <1147944267.585786.82730@i40g2000cwc.googlegroups.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> <446c3785$0$6981$626a54ce@news.free.fr> <1147944267.585786.82730@i40g2000cwc.googlegroups.com> Message-ID: <446c4b40$0$7602$636a55ce@news.free.fr> Pierre wrote: > I don't want to use getattr(object, property, default_value) because > I'm using external code and I don't want to modify or patch it. In this > code, the call is getattr(object, property). Seems like a perfectly valid reason !-) > On my objects, I must provide default values depending on the property > that was requested, the default value is not always the same. On what does it depends ? Attribute name ? Class ? Phase of the moon ? > And Yes I understand that obj.a is equivalent to getattr(obj, 'a') BUT > the difference between class attribute and instance attribute... :S If you mean you don't understand the difference between a class attribute and an instance attribute, then it would be time to learn Python's OO 101 - else you're in for trouble. For short, an instance attribute has a per-instance value and is (usually) stored in the object's __dict__, while a class attribute is shared by all instances of the class and is (usually) stored in the class's __dict__. class Parrot(object): cls_attr = 'class attribute' def __init__(self): self.instance_attr = 'instance attribute' import pprint pprint.pprint(Parrot.__dict__.items()) p = Parrot() pprint.pprint(p.__dict__.items()) print Parrot.cls_attr try: print Parrot.instance_attr except AttributeError, e: print e # will lookup 'cls_attr' in p, then in Parrot print p.cls_attr print p.instance_attr # will create an instance attribute 'cls_attr' in # object p, shadowing Parrot.cls_attr p.cls_attr = 'WTF ?' print p.cls_attr print Parrot.cls_attr del p.cls_attr print p.cls_attr print Parrot.cls_attr HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From elpX at adsihqX.com Thu May 25 22:53:14 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Fri, 26 May 2006 02:53:14 GMT Subject: Array? Message-ID: <u4udg.298$UT2.249@newsread3.news.pas.earthlink.net> I need a row of 127 bytes that I will use as a circular buffer. Into the bytes (at unspecified times) a mark (0<mark<128) will be written, one after the other. After some time the "buffer" will contain the last 127 marks and a pointer will point the next "usable" byte. What would be the Pythonic way to do the above? Thanks for any guidance. From john at castleamber.com Thu May 18 22:08:58 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 02:08:58 GMT Subject: python vs perl lines of code References: <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <mailman.5918.1147998380.27775.python-list@python.org> <i%8bg.73738$F_3.4617@newssvr29.news.prodigy.net> Message-ID: <Xns97C7D724FF476castleamber@130.133.1.4> Edward Elliott <nobody at 127.0.0.1> wrote: > Terry Hancock wrote: > >> But the real point is that no one here can make >> any reasonably objective assessment of whether your "data" is >> meaningful unless you post examples. That's what creates the >> hostility, I think. > > Fair enough. But see my other posts on why I'm not interested in > objective assessments of my code. For inquiries into real-world code, > it's enough to believe that I'm not lying, e.g. that I have the > programs and ran the tests described. The actual file contents are > almost irrelevant. Nothing one can say about my code tells us > anything about typical code in the wild. Producing more data points > _will_ tell us that. If my data are an outlier, they may be worthless > anyway. > > That's what I'm interested in. Others are interested in analyzing my > code. Which is fine, it's just not what I'm after. In that case I think it's safe to say that a majority of Perl code out in the wild is extrememly badly coded. Just download 10 free Perl CGI scripts to see my point. I wouldn't be amazed if this is not the case for Python, or at least way less. But be very carefull to draw any conclusion out of this :-D. -- 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 malvert at telenet.be Tue May 9 13:45:12 2006 From: malvert at telenet.be (malv) Date: 9 May 2006 10:45:12 -0700 Subject: Upgrading Class Instances Automatically on Reload Message-ID: <1147196712.192606.75160@g10g2000cwb.googlegroups.com> Upgrading Class Instances Automatically on Reload: Recipe 20.15 out of Python Cookbook #2. Did anybody get this recipe to work? The original example by Michael Hudson works without problems. I'm using Python 2.4.1 malv From jjl at pobox.com Fri May 5 16:00:57 2006 From: jjl at pobox.com (John J. Lee) Date: 05 May 2006 20:00:57 +0000 Subject: Python for Perl programmers References: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> <mailman.5340.1146765144.27775.python-list@python.org> <1heu1uo.13kryiryy0u8wN%aleaxit@yahoo.com> Message-ID: <87ejz81bt2.fsf@pobox.com> aleaxit at yahoo.com (Alex Martelli) writes: > John J. Lee <jjl at pobox.com> wrote: > > > "A.M" <alanalan at newsgroup.nospam> writes: > > > > > Is there any efficient online resource or book that help experienced Perl > > > programmers to Python? > > > > Worry instead about how you're going to keep maintaining your Perl > > code after you've developed an allergic response to it. > > Nah, that's easy -- you port it to Python (that's what I did back in the > day, and I've heard at least three others relate similar choices). Or, in my case, throwing away the Perl I had because I found I had written something much more useful in Python. A little bit of experience on a smallish (or largish!) from-scratch Python project does of course make a difference: Perl and Python are sufficiently close in many things that it's easy to get tunnel vision when porting Perl to Python. A little knowledge of Python idioms, techniques, standard library modules, etc., gained outside of that narrow context, goes a long way to prevent that. OTOH, the often-mechanical nature of porting .pl->.py, and the great flexibility of both languages, does certainly make it easier to switch. John From gdamjan at gmail.com Mon May 22 09:25:39 2006 From: gdamjan at gmail.com (Damjan) Date: Mon, 22 May 2006 15:25:39 +0200 Subject: Dumb-as-rocks WSGI serving using standard library References: <mailman.6067.1148285943.27775.python-list@python.org> Message-ID: <4471bbd3$0$15784$14726298@news.sunsite.dk> > What I can't find is a simple recipe to serve a WSGI application with > a dumb-as-rocks HTTP server, just using the standard Python library. > > The standard library includes BaseHTTPServer, which as far as I can > tell doesn't know anything about WSGI. > > Everything else that I can find leads to dependencies I don't want for > flexibility I don't need: cherrypy, paste, et al. > > Any suggestions for how to serve up a simple WSGI application with > just the standard library? There's no WSGI http server in the std lib as of Python 2.4. Paste[1] provides one, wsgiref[2] (probably will be included in Python 2.5) provides a SimpleHTTPServer and CGI based WSGI servers. There's also WSGIUtils[3] that provides that. [1] http://pythonpaste.org/ [2] http://svn.eby-sarna.com/wsgiref/ http://www.artima.com/weblogs/viewpost.jsp?thread=158191 [3] http://www.owlfish.com/software/wsgiutils/ -- damjan From skip at pobox.com Thu May 25 14:50:42 2006 From: skip at pobox.com (skip at pobox.com) Date: Thu, 25 May 2006 13:50:42 -0500 Subject: Request for comments on python distributed technologies In-Reply-To: <m28xoqjpsi.fsf@ordesa.cs.uu.nl> References: <mailman.5972.1148064796.27775.python-list@python.org> <m28xoqjpsi.fsf@ordesa.cs.uu.nl> Message-ID: <17525.64642.330155.943370@montanaro.dyndns.org> Piet> Python Web services developer: Messaging technologies compared Piet> http://www.ibm.com/developerworks/library/ws-pyth9/ Note a couple things. One, the article is four years old. You can't assume the various technologies have remained static since then. Two, the authors apparently didn't use sgmlop (at least it's not mentioned) to boost the decode performance of XML-RPC. Skip From liupeimail at gmail.com Mon May 1 12:32:02 2006 From: liupeimail at gmail.com (liupei) Date: 1 May 2006 09:32:02 -0700 Subject: how to do with the multi-frame GIF Message-ID: <1146501122.489588.11620@i39g2000cwa.googlegroups.com> how to do with the multi-frame GIF, I used the PIL ,but it seems not support? From pecoraREMOVE at THISanvil.nrl.navy.mil Thu May 25 09:17:21 2006 From: pecoraREMOVE at THISanvil.nrl.navy.mil (Lou Pecora) Date: Thu, 25 May 2006 09:17:21 -0400 Subject: Bind an instance of a base to a subclass - can this be done? References: <pecoraREMOVE-120DFE.15351024052006@ra.nrl.navy.mil> <4djshnF1asdovU1@uni-berlin.de> Message-ID: <pecoraREMOVE-844F8B.09172125052006@ra.nrl.navy.mil> In article <4djshnF1asdovU1 at uni-berlin.de>, "Diez B. Roggisch" <deets at nospam.web.de> wrote: > Lou Pecora schrieb: [cut] > > > > Then do something like (I know this isn't right, I'm just trying to > > convey the idea of what I would like) > > > > mf=myfile() > > > > mf=open("Afile","r") > > Possible in some way? Thanks in advance for any clues. > > Nope, not in that way. But you might consider writing a proxy/wrapper > for an object. That looks like this (rouch sketch from head): > > class FileWrapper(object): > def __init__(self, f): > self._f = f > > def __getattr__(self, name): > return getattr(self._f, name) > > def myreadline(self): > .... > > Then you do > > f = FileWrapper(open(name, mode)) > > Diez Interesting. I have to think about this to understand if it is a solution I can use. But, thank you for a very different angle on this. -- Lou Pecora (my views are my own) REMOVE THIS to email me. From manlio_perilloNO at SPAMlibero.it Fri May 5 05:30:20 2006 From: manlio_perilloNO at SPAMlibero.it (Manlio Perillo) Date: Fri, 05 May 2006 09:30:20 GMT Subject: SIGTERM handling Message-ID: <MWE6g.109883$A83.2581857@twister1.libero.it> Hi. I have tried this script: from ctypes import cdll, c_int from signal import SIGTERM, SIGINT from time import sleep msvcrt = cdll.LoadLibrary("MSVCR71") # is this the lib to use? sig = c_int(SIGTERM) raise_ = getattr(msvcrt, "raise") raise_(sig) sleep(10) The problem is that SIGTERM causes the program to exit (without calling atexit registered functions). Why? In the MSDN documentations it is written that SIGTERM is by default ignored and in the Python documentation for signal module it is written that there should be no handler for SIGTERM. Thanks Manlio Perillo From rupole at hotmail.com Wed May 17 00:44:09 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 17 May 2006 00:44:09 -0400 Subject: Creating an Active Desktop Window References: <1147437372.492243.245120@i40g2000cwc.googlegroups.com> Message-ID: <1147840803_3561@sp6iad.superfeed.net> rodmc wrote: > Hi, > > Does anyone know how I can create an Active Desktop window from within > a Python script? It would also be good to know how to refresh that > window and nothing else. > > At present I have an application which writes to a file which is read > by the Active Desktop (embeded IE), then a refresh command is issued > which refreshes the whole screen. This is a bit clumsy and also the > user needs to manually set up the Active Desktop component. > > I have been looking around for some solutions to this and as of today > my book on PyWin32 has still not arrived. > > Thanks in advance for any pointers. > > Best, > > rod The ActiveDesktop interfaces aren't in Pywin32 yet, but they should be in the next release, as part of the win32com.shell package. 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 bignose+hates-spam at benfinney.id.au Thu May 4 22:21:50 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 May 2006 12:21:50 +1000 Subject: Tuple assignment and generators? References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146787689.113964.85810@i40g2000cwc.googlegroups.com> Message-ID: <87r739b48x.fsf@benfinney.id.au> jemfinch at gmail.com writes: > There is only one zero in Python! It can never change! +0.5 QOTW -- \ "Madness is rare in individuals, but in groups, parties, | `\ nations and ages it is the rule." -- Friedrich Nietzsche | _o__) | Ben Finney From brochu121 at gmail.com Wed May 31 11:37:24 2006 From: brochu121 at gmail.com (david brochu jr) Date: Wed, 31 May 2006 11:37:24 -0400 Subject: Tkinter question Message-ID: <9583ed900605310837q57eb8b76h6ac5e9c435bf885@mail.gmail.com> I am trying to create a GUI that will display a new window with information about my program when the user clicks on the info button (a green "i" bitmap). So far all I can get my program to do is show the new window (using Toplevel() ) when the program loads, not when the user presses the information bitmap. I think it has something to do with my command for the information button. Anyone have any ideas or have a GOOD resource that they could point me to? Thanks from Tkinter import * class Application(Frame): """ A GUI application with three buttons. """ def __init__(self, master): """ Initialize the Frame. """ Frame.__init__(self,master) self.grid() self.create_widgets() def update_text(self): message = self.toolbar.get() self.results.delete(0.0, END) self.results.insert(0.0, message) def create_widgets(self): # create variable for single toolbar selection self.toolbar = StringVar() """Create button, text and entry widgets. """ #create welcome text welcome = Label(self) welcome["text"] = "You are now about to run Automation Testing.\n"\ "Please check the toolbar to be tested and then select\n"\ "the test you would like to perform." welcome.grid(row = 0, column = 0, columnspan = 3, sticky = W) #create Upr Radio Radiobutton(self, text = "Upr", variable = self.toolbar, value = "upr", command = self.update_text).grid(row = 1, column = 0, sticky = W) #create Com Radio Radiobutton(self, text = "Com", variable = self.toolbar, value = "com", command = self.update_text).grid(row = 1, column = 1, sticky = W) #create CI Radio Radiobutton(self, text = "CI", variable = self.toolbar, value = "ci", command = self.update_text).grid(row = 1, column = 2, sticky = W) #create text box self.results = Text(self, width = 40, height = 4, wrap = WORD) self.results.grid(row = 2, column = 0, columnspan = 3, sticky = W) #create Performance button self.perf_bttn = Button(self) self.perf_bttn["text"] = "Performance" self.perf_bttn["command"] = self.perf self.perf_bttn.grid(row = 3, column = 0, sticky = W) message = self.toolbar.get() #create PII button self.pii_bttn = Button(self) self.pii_bttn["text"] = "PII" self.pii_bttn.grid(row = 3, column = 1, sticky = W) #create info button self.info_bttn = Button(self) self.info_bttn["fg"] = "green" self.info_bttn["bitmap"] = "info" self.info_bttn.command = self.info() self.info_bttn.grid(row = 3, column = 2, sticky = W) #create exit button self.exit_bttn = Button(self) self.exit_bttn["fg"] = "red" self.exit_bttn["cursor"] = "pirate" self.exit_bttn["text"] = "EXIT" self.exit_bttn["command"] = root.quit self.exit_bttn.grid(row = 3, column = 3, sticky = W) def perf(self): import performance performance.perf(self.toolbar.get()) def info(self): # create child window win = Toplevel() # main root = Tk() root.title("Automation Testing") app = Application(root) root.mainloop() -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060531/e8cc43cc/attachment.html> From mackstevenson at hotmail.com Wed May 17 01:26:47 2006 From: mackstevenson at hotmail.com (MackS) Date: 16 May 2006 22:26:47 -0700 Subject: assignment in a for loop In-Reply-To: <mailman.5781.1147842350.27775.python-list@python.org> References: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> <mailman.5781.1147842350.27775.python-list@python.org> Message-ID: <1147843606.982432.269470@38g2000cwa.googlegroups.com> Thank you for your reply. > > 1) Is what I wrote above (minimally) correct? > > Correct for what? You can tell if it's *syntactically* correct by > simply running it. > > As for any other "correct", define that. Does it do what you want it > to do? I was referring to my attempted explanation, not the code snippet. > [...] > > What's preventing the use of list comprehensions? > > new_list = [x+1 for x in old_list] Suppose I want to do anything as trivial as modify the values of the list members _and_ print their new values. List comprehensions must not contain statements, I think. Mack From Mike.S.Duffy at gmail.com Mon May 8 02:54:08 2006 From: Mike.S.Duffy at gmail.com (pyGuy) Date: 7 May 2006 23:54:08 -0700 Subject: reading a column from a file In-Reply-To: <87y7xd83rc.fsf@localhost.localdomain> References: <87y7xd83rc.fsf@localhost.localdomain> Message-ID: <1147071248.566703.143260@j33g2000cwa.googlegroups.com> f = open("datafile.txt", "r") data = [line.split('\t') for line in f] f.close() pressure = [float(d[1]) for d in data] temp = [float(d[2]) for d in data] --------------------------------------------------- This will parse the file into a matrix stored in 'data'. The last two lines simply iterate through second and third columns respectively, converting each element to a float (from string as it was read in from file) and assign to the appropriate vars. From raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com Mon May 8 13:17:20 2006 From: raffaelcavallaro at pas-d'espam-s'il-vous-plait-mac.com (Raffael Cavallaro) Date: Mon, 8 May 2006 13:17:20 -0400 Subject: "Only one obvious way..." References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> <pan.2006.05.07.08.35.04.362248@gmail.com> <1heytan.zl0xgh9v134kN%aleaxit@yahoo.com> <slrne5tkhg.b7l.tomasz.zielonka@tomekz.gem.lan> <1hezn87.h8wwmp3kpz96N%aleax@mac.com> <1147071082.880568.237540@g10g2000cwb.googlegroups.com> Message-ID: <2006050813172075249-raffaelcavallaro@pasdespamsilvousplaitmaccom> On 2006-05-08 02:51:22 -0400, JShrager at gmail.com said: > The phrase "only one obvious way..." is nearly the most absurd > marketing bullshit I have ever heard; topped only by "it fits your > brain". Why are so many clearly intelligent and apparently > self-respecting hard-core software engineers repeating this kind of > claptrap? Really should read "only one obvious way to people with a similar background and little creativity" or "it fits your brain if you've mostly programmed in algol syntax languages and alternative ideas make said brain hurt." trimmed to c.l.python and c.l.lisp From eoinrogers at gmail.com Sun May 14 12:39:58 2006 From: eoinrogers at gmail.com (Byte) Date: 14 May 2006 09:39:58 -0700 Subject: Starting/launching eric3 Message-ID: <1147624798.827349.286970@y43g2000cwc.googlegroups.com> Decided to try the eric3 IDE, but I cant figure out how to start it! When I extract the file, all I can see is a ton of files and Python scripts. What script will run the program? Where is it? Please help! -- /usr/bin/byte From fredrik at pythonware.com Thu May 4 10:17:57 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 4 May 2006 16:17:57 +0200 Subject: Multiple Version Install? References: <gbtj52l54trlhekcht3mgdb8s60aa4k83d@4ax.com> Message-ID: <e3d2el$kjv$1@sea.gmane.org> David C.Ullrich wrote: > Would there be issues (registry settings, environment > variables, whatever) if a person tried to install > versions 1.x and 2.x simultaneously on one Windows > system? Windows 98, if it matters. > > (I can handle the file associations with no problem.) in general, no. (I usually have about a dozen Python's, or more, on most of my windows boxes) however, applications that look in the registry may only find the last one you've installed. </F> From michele.simionato at gmail.com Fri May 12 03:19:42 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 12 May 2006 00:19:42 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> Message-ID: <1147418382.845693.253320@u72g2000cwu.googlegroups.com> jayessay wrote: > "Michele Simionato" <michele.simionato at gmail.com> writes: > I can't get this to work at all - syntax errors (presumably you must > have 2.5?, I only have 2.4). You can download Python 2.5 from www.python.org, but the important bit, i.e. the use of threading.local to get thread-local variables is already there in Python 2.4. 'with' gives you just a nicer lisp-like syntax. > This has not so much to do with WITH as relying on a special "global" > object which you must reference specially, which keeps track (more or > less) of its attribute values, which you use as "faked up" variables. > Actually you probably need to hack this a bit more to even get that as > it doesn't appear to stack the values beyond a single level. Yes, but it would not be difficult, I would just instantiate threading.local inside the __init__ method of the dynamically_scoped class, so each 'with' block would have its own variables (and I should change getvar and setvar a bit). I was interested in a proof of concept, to show that Python can emulate Lisp special variables with no big effort. Michele Simionato From frank at chagford.com Mon May 22 02:51:55 2006 From: frank at chagford.com (Frank Millman) Date: 21 May 2006 23:51:55 -0700 Subject: Problem with odbc and Sql Server In-Reply-To: <1148206272.017343.75600@y43g2000cwc.googlegroups.com> References: <1148206272.017343.75600@y43g2000cwc.googlegroups.com> Message-ID: <1148280715.202510.319430@j33g2000cwa.googlegroups.com> Frank Millman wrote: > Hi all > > I have found a problem using MS Sql Server connecting via the odbc > module from python-win32. > > Assume a table 't1' with a column 'c1' of type varchar(10). > > >From Python, set c1 to an empty string - > cur.execute("UPDATE t1 SET c1 = ?",['']) > > The result is that c1 is actually set to a string of 10 spaces. > > If I execute the command without using parameters - > cur.execute("UPDATE t1 SET c1 = ''") > > it works - c1 is set to an empty string. > Thanks for the replies, Andrew and Dennis. I looked at Access Data Object, but I see that it uses OLE-DB to connect to the database, and this would not be a valid comparison, so I did not pursue that route. Then I followed Andrew's suggestion of trying mx.ODBC - I should have thought of that in the first place. Using exactly the same connection string, and exactly the same sql commands, it works correctly, where win32 odbc does not work correctly. That seems to indicate that the problem lies with win32. I will advise Mark of the result. Thanks again Frank From junkytownMAKNI at gmail.com Wed May 31 14:56:59 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Wed, 31 May 2006 20:56:59 +0200 Subject: ideas for programs? In-Reply-To: <mailman.6346.1149051733.27775.python-list@python.org> References: <mailman.6346.1149051733.27775.python-list@python.org> Message-ID: <e5kotr$jqa$1@ss408.t-com.hr> I agree with Fred. So here is a "problem" I had and wanted to solve. I needed an Atomic clock (well, not the real one but the one that connects to NTP server and gets the exact time) in a window that stays always on top. While I was writing it I included alarm, and a stopwatch. Than I wrote a simple e-mail client. First plain text and than included attachments, and even encryption. Ofc I could have found millions of such aplications on the net, but that's not the point, right? ;) From michele.simionato at gmail.com Fri May 5 03:20:39 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 5 May 2006 00:20:39 -0700 Subject: Tuple assignment and generators? In-Reply-To: <1146803131.996632.207770@v46g2000cwv.googlegroups.com> References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> Message-ID: <1146813639.825116.21780@g10g2000cwb.googlegroups.com> Carl Banks wrote: >>> q = 0 > >>> r = 0 > >>> s = 0 > >>> id(q) > 134536636 > >>> id(r) > 134536636 > >>> id(s) > 134536636 > > It is okay with constant object, really. No: >>> r=100001 >>> s=100001 >>> t=100001 >>> id(r) 135620508 >>> id(s) 135620532 >>> id(t) 135104688 It worked with the number 0 because of an implementation accident, in general Python can use different ids for constant objects that are equals in the == sense. Michele Simionato From phddas at yahoo.com Tue May 2 16:05:46 2006 From: phddas at yahoo.com (Gary Wessle) Date: 03 May 2006 06:05:46 +1000 Subject: redemo.py with Tkinter Message-ID: <87vesodwf9.fsf@localhost.localdomain> Hi I was reading the Regular Expression HowTo, it refers to redemo.py if you have Tkinter installed. a quick #locate redemo.py returned none on my debian/testing, however #locate Tkinter returned many. any body out there is using it, is it a separate download? thanks From aleaxit at yahoo.com Sat May 6 20:49:42 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 17:49:42 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> Message-ID: <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> Bill Atkins <NOatkinwSPAM at rpi.edu> wrote: ... > > > > Read again what I wrote: I very specifically said "ordinary > > *single-character* identifier" (as opposed to "one of many characters > > inside a multi-character identifier"). Why do you think I said > > otherwise, when you just quoted what I had written? (Even just a > > _leading_ ( at the start of an identifier may be problematic -- and just > > as trivial as having to give names to functions, of course, see below). > > Well, the same technique can obviously be used for: > > (let ((|(| 3))) > (+ |(| 4))) > ;; => 7 > > The length of the identifier is irrelevant... But it cannot be a SINGLE CHARACTER, *just* the openparenthesis. Wow, it's incredible to me that you STILL can't read, parse and understand what I have so clearly expressed and repeated! > Common Lisp does not support unnamed macros (how would these be > useful?), but nothing stops me from adding these. What use case do > you envision for anonymous macros? None, just like there is none for anonymous functions -- there is nothing useful I can do with anonymous functions that I cannot do with named ones. > > Anyway, I repeat: *any* design choice (in a language, or for that matter > > any other artefact) has consequences. As Paul Graham quotes and > > supports his unnamed friend as saying, Python lets you easily write code > > that *looks* good, and, as Graham argues, that's an important issue -- > > and, please note, a crucial consequence of using significant > > indentation. Alien whitespace eating nanoviruses are no more of a worry > > than alien parentheses eating nanoviruses, after all. > > It *is* an important issue, but it's also a subjective issue. I find > Lisp to be far prettier than any syntax-based language, so it's far > from an objective truth that Python code often looks good - or even at > all. The undeniable truth, the objective fact, is that *to most programmers* (including ones deeply enamored of Lisp, such as Graham, Tilton, Norvig, ...) Python code looks good; the Lisp code that looks good to YOU (and, no doubt them), and palatable to me (I have spoken of "eerie beauty"), just doesn't to most prospective readers. If you program on your own, or just with a few people who share your tastes, then only your taste matters; if you want to operate in the real world, maybe, as I've already pointed out, to build up a successful firm faster than had ever previously happened, this *DOESN'T SCALE*. Essentially the same issue I'm explaining on the parallel subthread with Tilton, except that he fully agrees with my aesthetic sense (quoting Tilton, "No argument. The little Python I wrote while porting Cells to Python was strikingly attractive") so this facet of the jewel needed no further belaboring there. > > Plus, I can easily write code that looks good without using a language > that enforces indentation rules. Lisp's regular syntax lets Emacs do > it for me with a simple C-M-a C-M-q. What could be easier? If you need to edit and reformat other people's code with Emacs to find it "looks good", you've made my point: code exists to be read, far more than it's written, and Python's design choice to keep punctuation scarce and unobtrusive obviates the need to edit and reformat code that way. Alex From johnjsal at NOSPAMgmail.com Tue May 16 16:25:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 20:25:04 GMT Subject: calling upper() on a string, not working? Message-ID: <Ayqag.2108$No6.45797@news.tufts.edu> Can someone tell me what's happening here. This is my code: PUNCT_SPACE_SET = set(string.punctuation + string.whitespace) def filter_letters(original): return ''.join(set(original) - PUNCT_SPACE_SET) 'original' is a string. The above works as expected, but when I change it to return ''.join(set(original.upper()) - PUNCT_SPACE_SET) it doesn't seem to work. The full code is below if it helps to understand. import string import random import itertools PUNCT_SPACE_SET = set(string.punctuation + string.whitespace) def convert_quote(quote): return encrypt_quote(quote).split('|') def encrypt_quote(original): original_letters = filter_letters(original) new_letters = list(string.ascii_uppercase) while True: random.shuffle(new_letters) trans_letters = ''.join(new_letters)[:len(original_letters)] if test_code(original_letters, trans_letters): trans_table = string.maketrans(original_letters, trans_letters) break return original.translate(trans_table) def filter_letters(original): return ''.join(set(original) - PUNCT_SPACE_SET) #return ''.join(set(original.upper()) - PUNCT_SPACE_SET) def test_code(original_letters, trans_letters): for pair in itertools.izip(original_letters, trans_letters): if pair[0] == pair[1]: return False return True if __name__ == '__main__': print convert_quote("The past is not dead. In fact, it's not even past.|William Faulkner") From cbrown at perpich.com Tue May 23 12:14:20 2006 From: cbrown at perpich.com (Cameron Brown) Date: Tue, 23 May 2006 12:14:20 -0400 Subject: Virtual Collaboratory Announcement Message-ID: <447334DC.8040607@perpich.com> This post if for informational purposes only. The Virtual Collaboratory is a GNU GPL open source project written almost entirely in python, using Py-MyCMS, Zope, Plone and Mailman as components. You may go to http://sourceforge.net/projects/vic to download the latest distribution and you may go to http://opensource.perpich.com/ to join the OpenSource Developers' Forum to discuss and learn more about the project. If you are unfamiliar with the Virtual Collaboratory, you can read the Wikipedia entry at http://en.wikipedia.org/wiki/Collaboratory. Also, please feel free to ask questions either by emailing me, or by joining the community collaboratory (opensource.perpich.com) and/or by attending the information session mentioned below. We will be hosting an informal question and answer meeting on May 31st at 12:30PM EST. You must first register as a Member at opensource.perpich.com to join the meeting. Please stop by and ask us any questions about the Collaboratory that you may have. Thanks, Cameron -------------- next part -------------- A non-text attachment was scrubbed... Name: cbrown.vcf Type: text/x-vcard Size: 295 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060523/ccb96fd7/attachment.vcf> From mhellwig at xs4all.nl Thu May 4 08:55:41 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 04 May 2006 14:55:41 +0200 Subject: This coding style bad practise? In-Reply-To: <44591463$0$31639$e4fe514c@news.xs4all.nl> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> Message-ID: <4459f9d4$0$31640$e4fe514c@news.xs4all.nl> <cut> Thanks for the input folks! I adapted my script to the given suggestions and it's now far more 'logical', for reference I added it below. -- mph ----- script ----- > import string > import time > > class IDGenerator(object): > """(leading_id, subversion_length, tz) # tz = 'local' or 'gm' (default) > Create an ID from a given string, a current datetimestamp and version > number which wraps around at given subversion_length. > > Example usage: > >>> id = IDGenerator('01',2) > >>> id() > '01_20060504_112304_1' > >>> id() > '01_20060504_112306_2' > >>> id() > '01_20060504_112307_1' > >>> > >>> id = IDGenerator(0005,99) # Note that an int will be cast to a string! > >>> id() > '5_20060504_112324_01' > >>> id() > '5_20060504_112327_02' > >>> id > <class '__main__.IDGenerator'> previous ID is 5_20060504_112324_01 and > current ID is 5_20060504_112327_02 > >>> > > """ > > def __init__(self,leading_id, subversion_length, timezone='gm'): > self.id = str(leading_id) > self.length = int(subversion_length) > fill_length = len(str(self.length)) > self.current = None > self.previous = None > > def fill(number): > return(string.zfill(number,fill_length)) > self.fill = fill > > if timezone == 'local': > self.timeset = time.localtime > else: > self.timeset = time.gmtime > > > def __call__(self): > # If the subversion length has been reached or the generator has not > # been defined, (re)define it, otherwise return the next value of the > # subversion. > try: > return_value = self.range_gen.next() > > except: > self.range_gen = ( number for number in range(1,self.length+1) ) > return_value = self.range_gen.next() > > # Create the version stamp. > return_value = self.id +\ > time.strftime("_%Y%m%d_%H%M%S_",self.timeset())+\ > self.fill(return_value) > > # Copy the current ID to the previous and assign a new one to current. > self.previous = self.current > self.current = return_value > > # And return it. > return(self.current) > > def __repr__(self): > return(str(self.__class__) + > ' previous ID is ' + > str(self.previous) + > ' and current ID is ' + > str(self.current)) ----- script ----- From seberino at spawar.navy.mil Wed May 17 13:15:50 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 17 May 2006 10:15:50 -0700 Subject: Any pointers/advice to help learn CPython source? Message-ID: <1147886150.819254.158880@i40g2000cwc.googlegroups.com> Anyone have any good advice to someone interested in learning about innards of Python implementation? e.g. What is best place to start? Where can I get a 10,000 ft. overview of general structure? Anyone written docs on helping do this? How did other people successfully make it through? Chris From abhijitng at gmail.com Wed May 10 12:32:58 2006 From: abhijitng at gmail.com (abhijitng at gmail.com) Date: 10 May 2006 09:32:58 -0700 Subject: Calling python functions from C In-Reply-To: <00t16251bd7qh1hjhmflu094blrq33h5i3@4ax.com> References: <1147194348.285669.218280@g10g2000cwb.googlegroups.com> <00t16251bd7qh1hjhmflu094blrq33h5i3@4ax.com> Message-ID: <1147278778.560434.260670@v46g2000cwv.googlegroups.com> Thanks Ronny, R. Ronny Mandal wrote: > On 9 May 2006 10:05:48 -0700, robert.differentone at gmail.com wrote: > > >I am a newbie to Python. I want to call python functions from C. I > >looked for examples but I couldn't get any simple one. Lets say my > >python code is : > >def add(a,b) > > return (a+b) > > > >I want to call add from C. Could anybody please help me? Thanks in > >advance. > This is also known as "callback". > > Check out > http://www.google.com/search?client=opera&rls=en&q=python+c+callback&sourceid=opera&ie=utf-8&oe=utf-8 > or > http://www.python.org/doc/current/ext/ext.html > > -RM > > > >R. From L.Plant.98 at cantab.net Wed May 24 05:30:03 2006 From: L.Plant.98 at cantab.net (Luke Plant) Date: 24 May 2006 02:30:03 -0700 Subject: hi,every body. a problem with PyQt. In-Reply-To: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> References: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> Message-ID: <1148463003.324183.279350@y43g2000cwc.googlegroups.com> > i use QT-designer to design application GUI. > now i save the test.ui file into e:\test\test.ui > next step,how can i run it? You should have a look at a PyQt tutorial, such as this one: http://vizzzion.org/?id=pyqt Luke From saurabh.ss at gmail.com Fri May 5 11:28:00 2006 From: saurabh.ss at gmail.com (Saurabh Sardeshpande) Date: 5 May 2006 08:28:00 -0700 Subject: Best IDE for Python? Message-ID: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> Pardon if this is already discussed extensively. But what is the best IDE for Python for a newbie? I have experience in C++ and Java and this is the first time I am learning a scripting language. Thanks in advance From bborcic at gmail.com Tue May 2 16:19:39 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 22:19:39 +0200 Subject: simultaneous assignment In-Reply-To: <125fecqqoro46e6@corp.supernews.com> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <4457b2fe$1_7@news.bluewin.ch> <125fecqqoro46e6@corp.supernews.com> Message-ID: <4457bee2$1_6@news.bluewin.ch> Grant Edwards wrote: > On 2006-05-02, Boris Borcic <bborcic at gmail.com> wrote: >> Grant Edwards wrote: >>> Python knows how to count. :) >>> >>> def countFalse(seq): >>> return len([v for v in seq if not v]) >>> >>> def countTrue(seq): >>> return len([v for v in seq if v]) >>> >>> def truth_test(seq): >>> return countTrue(seq) == 1 >>> >> I'd suggest the more direct >> >> def countFalse(seq) : >> return sum(1 for v in seq if not v) > > I guess I don't see how that is more direct. > > If you want to know how many items are in a seqneuce, you call > len(). sum doesn't construct a sequence > > That's what it's for. > > The number of objects in a list is returned in O(1) time by > len(sequence). yeah, but you need to construst the list first, and that isn't O(1) neither in time or space. > > Converting that list to a list of 1's that's not what my suggestion is doing and then summing the 1's > is O(N). > From sybrenUSE at YOURthirdtower.com.imagination Sun May 14 15:35:50 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Sun, 14 May 2006 21:35:50 +0200 Subject: Converting hex to char help References: <mailman.3510.1143024593.27775.python-list@python.org> <slrne22k5n.31g.sybrenUSE@schuimige.unrealtower.org> <mailman.5680.1147633376.27775.python-list@python.org> Message-ID: <slrne6f1km.3sm.sybrenUSE@schuimige.stuvel.eu> Ognjen Bezanov enlightened us with: > Hi all, I am trying to convert a hexdecimal value to a char using this code: > > print ' %c ' % int(0x62) This is an integer ^^^^ > this works fine, but if I want to do this: > > number = "62" > print ' %c ' % int("0x" + number) This is a string ^^^^^^^^^^^^^ > How can I convert a string "0x62" to int/hex without this problem? In [0]: exec('num=0x%s' % '62') In [1]: num Out[1]: 98 Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From mackstevenson at hotmail.com Wed May 17 00:46:26 2006 From: mackstevenson at hotmail.com (MackS) Date: 16 May 2006 21:46:26 -0700 Subject: assignment in a for loop In-Reply-To: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> References: <1147840589.967190.318460@i39g2000cwa.googlegroups.com> Message-ID: <1147841186.146299.114250@i40g2000cwc.googlegroups.com> Sorry, my previous post probably was not very good at explaining _why_ I want to do this. Suppose I want to do modify all arguments which are passed to a function. Do I need to use a list comprehension such as def f(arg1,arg2,arg3): arg1,arg2,arg3 = [i+1 for i in (arg1,arg2,arg3)] ... This would be awful when, eg, one adds an argument to the function definition. It would require edition of the code at two different locations. Thanks Mack MackS wrote: > Hello everyone > > Consider the following > > >>> l = [1,2] > >>> for i in l: > ... i = i + 1 > ... > >>> l > [1, 2] > > I understand (I think!) that this is due to the fact that in Python > what looks like "assignment" really is binding a name to an object. The > result is that inside the loop I am creating an object with value (i+1) > and then "pointing" the name i at it. Therefore, the object to which i > previously pointed (an element of list l) remains unchanged. > > Two brief questions: > > 1) Is what I wrote above (minimally) correct? > > 2) Independently of the answer to 1, is there a way for me to assign to > elements of a list inside a loop and without resorting to C-style > ugliness of > > for i in range(len(l)) > l[i] = l[i] + 1 > > ? > > (Note: not using a list comprehension.) > > Thanks in advance > > Mack From tjreedy at udel.edu Sat May 6 12:53:54 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 6 May 2006 12:53:54 -0400 Subject: NaN handling References: <mailman.5272.1146675632.27775.python-list@python.org><125hplqmppfeq29@corp.supernews.com><01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> <1146929327.30335.5.camel@kenshin.CASA> Message-ID: <e3ikb0$vl3$1@sea.gmane.org> "Felipe Almeida Lessa" <felipe.lessa at gmail.com> wrote in message news:1146929327.30335.5.camel at kenshin.CASA... > This works everywhere: > > nan = float('nan') Not. >>> nan = float('nan') Traceback (most recent call last): File "<pyshell#4>", line 1, in -toplevel- nan = float('nan') ValueError: invalid literal for float(): nan Above is Windows, which requires something else. tjr From andre.roberge at gmail.com Mon May 1 20:24:15 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 1 May 2006 17:24:15 -0700 Subject: Using elementtree: replacing nodes Message-ID: <1146529455.411024.83020@j73g2000cwa.googlegroups.com> I've started using elementtree and don't understand how to use it to manipulate and replace nodes. I know how to do this using a simple, but inefficient parser I wrote, but I'd rather learn to use a better tool - especially as it is to be added to the standard library. I'll use a simple, but representative example. Suppose I have the following text, where I inserted blank lines to isolate the part I want to manipulate. =================== <html> <body> <p> This is some text. </p> <pre class="text"> a = 6*7 print a </pre> <p> Done. </p> </body> </html> ==================== Now, I would like to find all <pre> tags of the "text" class and 1. change the class value 2. append another node ( <textarea> ) 3. surround the both nodes by a third one ( <form> ) ================== <html> <body> <p> This is some text. <p> <form> <pre class="text2"> a = 6*7 print a </pre> <textarea cols=80 name="code"> </textarea> <input type="submit"></input> </form> <p> Done. </p> </body> </html> =============== Any help would be appreciated. Andr? From larry.bates at websafe.com Tue May 16 16:50:51 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 16 May 2006 15:50:51 -0500 Subject: calling upper() on a string, not working? In-Reply-To: <Ayqag.2108$No6.45797@news.tufts.edu> References: <Ayqag.2108$No6.45797@news.tufts.edu> Message-ID: <R9OdnSQH9rC6pvfZnZ2dnUVZ_t-dnZ2d@comcast.com> John Salerno wrote: > Can someone tell me what's happening here. This is my code: > > > > PUNCT_SPACE_SET = set(string.punctuation + string.whitespace) > > def filter_letters(original): > return ''.join(set(original) - PUNCT_SPACE_SET) > > > > 'original' is a string. The above works as expected, but when I change > it to > > return ''.join(set(original.upper()) - PUNCT_SPACE_SET) > > it doesn't seem to work. The full code is below if it helps to understand. > > > > import string > import random > import itertools > > PUNCT_SPACE_SET = set(string.punctuation + string.whitespace) > > def convert_quote(quote): > return encrypt_quote(quote).split('|') > > def encrypt_quote(original): > original_letters = filter_letters(original) > new_letters = list(string.ascii_uppercase) > while True: > random.shuffle(new_letters) > trans_letters = ''.join(new_letters)[:len(original_letters)] > if test_code(original_letters, trans_letters): > trans_table = string.maketrans(original_letters, trans_letters) > break > return original.translate(trans_table) > > def filter_letters(original): > return ''.join(set(original) - PUNCT_SPACE_SET) > #return ''.join(set(original.upper()) - PUNCT_SPACE_SET) > > def test_code(original_letters, trans_letters): > for pair in itertools.izip(original_letters, trans_letters): > if pair[0] == pair[1]: > return False > return True > > if __name__ == '__main__': > print convert_quote("The past is not dead. In fact, it's not even > past.|William Faulkner") Not exactly sure why you think its not working. When you create a set from the original.upper() you get a smaller number of characters because you no longer get both 'T' and 't' as well as 'I' and 'i' as you do in the lower case version of the string. >>> set(original.split('|')[0]) set(['a', ' ', 'c', 'e', 'd', "'", 'f', 'i', 'h', ',', 'o', 'n', 'p', 's', 'T', 'v', 'I', '.', 't']) >>> set(original.split('|')[0].upper()) set(['A', ' ', 'C', 'E', 'D', "'", 'F', 'I', 'H', ',', 'O', 'N', 'P', 'S', 'T', 'V', '.']) >>> sets can only contain "unique" entries. Letters that are repeated only get added once. When you do .upper() you convert lowercase 't' to 'T' and lower case 'i' to 'I' so that letter only gets added to the set a single time. Hope info helps. Larry Bates From aleax at mac.com Tue May 9 23:22:29 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 9 May 2006 20:22:29 -0700 Subject: problemi con POST References: <1147208587.275024.317410@i40g2000cwc.googlegroups.com> Message-ID: <1hf378n.5ft6itcv2co8N%aleax@mac.com> Heavy <france.macchi at tele2.it> wrote: > Ciao a tutti, > sto creando una applicazione in python, che deve fungere anche da > server web... > non ho assolutamente problemi a prendere i parametri di una 'GET', mi > limito a fare il parsing della URL, ma come faccio a prendere i > parametri di una 'POST'? io cerco di leggere dal socket di lettura > 'rfile' ma poi resto bloccato all'infinito perch? evidemente resta in > attesa di qualcosaltro... c'? gi? qualche metodo che mi pu? > aiutare?? oppure sapete darmi qualche dritta? grazie... Riprova a it.comp.lang.python Try again at it.comp.lang.python Ciao, Alex From steve at hastings.org Wed May 3 00:02:15 2006 From: steve at hastings.org (Steve R. Hastings) Date: Tue, 02 May 2006 21:02:15 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <I9O5g.2039$No6.43918@news.tufts.edu> <pan.2006.05.02.19.35.15.219815@hastings.org> <4457b69b$1_1@news.bluewin.ch> Message-ID: <pan.2006.05.03.04.02.14.139249@hastings.org> On Tue, 02 May 2006 21:44:21 +0200, Boris Borcic wrote: > note that generators have no defined length - precisely because they feed > values one at a time while you need them all together to speak of a > length. The second expression will raise a TypeError because of that. Er, yes. If I had actually run that code, I would have seen that error. Thank you for the correction. > If you want to count objects > with a generator expression, use > > sum(1 for v in seq if some_condition(v)) > > which is also clearer imho; summing ones for each item satisfying a > condition - isn't that a definition of counting ? That is indeed very clear and I like it. You could also use a function that counts all different values in a list, reducing the list to a dictionary whose keys are the unique values from the list. I got the idea from a discussion here on comp.lang.python; I called my version of it tally(). d = tally(bool(x) for x in seq) print d[True] # prints how many true values in seq print d[False] # prints how many false values in seq tally() is in my iterwrap.py module, which you can get here: http://home.blarg.net/~steveha/iterwrap.tar.gz -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From johnjsal at NOSPAMgmail.com Thu May 25 12:38:48 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 25 May 2006 16:38:48 GMT Subject: how to "normalize" indentation sources In-Reply-To: <mailman.6198.1148570351.27775.python-list@python.org> References: <PKqdndjnUPVbgOjZRVn-hA@comcast.com> <447525b7$1@news.eftel.com> <dJjdg.2177$No6.47014@news.tufts.edu> <mailman.6198.1148570351.27775.python-list@python.org> Message-ID: <s4ldg.2178$No6.46954@news.tufts.edu> Tim Peters wrote: > [John Machin, quoting reindent.py docs] >>> remove empty lines at the end of files. Also ensure the last line ends >>> with a newline. > > [John Salerno] >> don't those two things conflict with one another? > > No. This is the repr of a file with (3) empty lines at the end: > > "a file\n\n \n \t \n" > reindent.py changes that to: > > "a file\n" > > This is the repr of a file with no newline at the end: > > "a file" > > reindent.py changes that to: > > "a file\n" > >> or is the newline added after empty lines are removed? > > False dichotomy ;-) So the line below the last line of the file isn't actually considered an empty line, even though you can move the cursor to it in a text editor? If you have a file that has one line and it ends with a newline, at least in my text editor the cursor then moves down to the next line, but is this just a detail of the way the editor itself works, and nothing to do with the file? (i.e., there is really only one line in the file, not two?) From mariano.difelice at gmail.com Fri May 26 13:40:21 2006 From: mariano.difelice at gmail.com (mardif) Date: 26 May 2006 10:40:21 -0700 Subject: PIL problem with biprocessor hardware In-Reply-To: <1148663531.254814.301790@i40g2000cwc.googlegroups.com> References: <1148661656.407762.147020@j73g2000cwa.googlegroups.com> <1148663531.254814.301790@i40g2000cwc.googlegroups.com> Message-ID: <1148665221.735821.211520@y43g2000cwc.googlegroups.com> OK, this is the code: """ image is the object instance of Image class which contains all informations """ pil = Image.open( os.path.join( image.path,image.name ) ) if image.rotation_angle != 2: try: pil = pil.rotate( rotation_levels[image.rotation_angle] ) except: traceback.print_exc() result = False if ( image.cropped ): box = [ float(image.cropX) , \ float(image.cropY) , \ (float(image.cropX)+float(image.cropW)), \ (float(image.cropY)+float(image.cropH)) ] try: pil = pil.crop( box ) except: traceback.print_exc() if pil.size[0] < pil.size[1]: try: pil = pil.rotate( 90 ) except: traceback.print_exc() filtro_compressione = Image.BILINEAR try: pil = pil.resize((image.realW,image.realH),filtro_compressione) except: traceback.print_exc() if not pil.mode == 'RGB': try: pil = pil.convert('RGB') except: traceback.print_exc() try: pil.save( path, format="JPEG", quality=80 ) except Exception,e: traceback.print_exc() I think this is very normal. It's NOT normal that don't work well on PC SMP processor... not? From aristotelian at onet.eu Sat May 20 17:56:59 2006 From: aristotelian at onet.eu (aristotelian at onet.eu) Date: 20 May 2006 14:56:59 -0700 Subject: buffers readlines and general popen2 confusion... Message-ID: <1148162219.463249.155680@j33g2000cwa.googlegroups.com> I'm interested in taking the output of a daemonized shell script that greps for patterns which would act as an argument to a script. Is it better to write this stuff to file and visit the file every few seconds or can this be done a better way. I'm hoping for a more elegant solution. So far I've seen some troubling info about buffer overflows with popen2 but it looks like the low-hanging fruit. I'm not a unixpro so I want to make sure anything I tackle is best practice. Suggestions welcomed. -Aris From robin.meier at gmail.com Mon May 29 07:49:46 2006 From: robin.meier at gmail.com (robin) Date: 29 May 2006 04:49:46 -0700 Subject: summarize text Message-ID: <1148903386.095226.249270@38g2000cwa.googlegroups.com> hello list, does anyone know of a library which permits to summarise text? i've been looking at nltk but haven't found anything yet. any help would be very welcome. thank you all in advance, robin From jemfinch at gmail.com Thu May 4 20:08:09 2006 From: jemfinch at gmail.com (jemfinch at gmail.com) Date: 4 May 2006 17:08:09 -0700 Subject: Tuple assignment and generators? In-Reply-To: <1vSdnRC7JP5K08fZRVn-rw@comcast.com> References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> Message-ID: <1146787689.113964.85810@i40g2000cwc.googlegroups.com> Larry Bates wrote: > Just wrote: > > In article <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d at comcast.com>, > > Larry Bates <larry.bates at websafe.com> wrote: > > > >> While I have never needed anything like this in my 5 years of Python > >> programming, here is a way: > >> > >> a,b,c = 3*[0] > >> q,r,s,t,u,v = 6*[0] > > > > This is (IMO) fairly idiomatic: > > > > a = b = c = 0 > > q = r = s = t = u = v = 0 > > > > Just > > You must be careful with this as they all point to > exactly the same object. Example: > > >>> q = r = s = t = u = v = 0 > >>> id(q) > 3301924 > >>> id(r) > 3301924 > >>> id(s) > 3301924 > >>> > > Notice that all of them point to exactly the same object, > not 6 copies of zero which is "probably" what the poster > was thinking. Numbers are immutable. They're never copied. Zero, in particular, is the same variable all throughout a Python interpreter. > Most of the time when I see this, it is because people are > thinking of variables having values which is mostly a > carry-over from old Fortran/Cobol/Basic programming ideas. Most of the time when I see it, it's written by someone who's used Python for quite some time. It's a standard Python idiom. You'll find it all over the standard library. It's not a carry-over from Fortran/Cobol/Basic at all. > In python variables are pointers to objects. Objects could > be values, but they are not placeholders where you store > stuff. And all immutable objects are indistinguishable from values. Immutable objects include ints, longs, strings, unicode objects, tuples, frozensets, and perhaps some others that I'm forgetting. > I read on this list (quite frequently) that people > think they are getting 6 separate variables each with > a zero stored in them. That's because they are. They're getting 6 different pointers (bindings) to zero. If you change one, the others remain pointed at (bound to) zero. > They are not. They are getting > six pointers that all point to an integer zero Six *different* pointers. Six *different* bindings. > (IMHO it > would be a rather odd application for a programmer > to want this). No, it wouldn't be. It's exactly how a person works with immutable (value) objects. > Here is where multiple assignments > causes problems for beginners: > > >>> a=[] > >>> b=c=a > >>> a.append(6) > >>> b > [6] Yes, that does sometimes trouble beginners to programming. But so do regular expressions. Programmers ought not to restrict themselves by what beginners will have no difficulty learning. > What?? 'b' should contain an empty list, right? Nope. > a, b, and c all point to the SAME list just like the > poster's q, r, s, t, u, v all point to the SAME zero. There is only one zero in Python! It can never change! > What they meant to write was: > > c=a[:] # Shallow copy of list > b=a[:] > > My rule, don't do it unless you know exactly why you > want to do it. It will trip you up at some point and > be VERY hard to find. Your rule should only be followed by people who obstinately refuse either to understand the way variable bindings work in Python, or by people who refuse to know or care whether a given kind of object is immutable. And that group of people doesn't seem to include any of the good Python programmers I know. Jeremy From zlatko.matic1 at sb.t-com.hr Sat May 27 02:58:16 2006 From: zlatko.matic1 at sb.t-com.hr (tatamata) Date: Sat, 27 May 2006 08:58:16 +0200 Subject: starting some Python script from C# Message-ID: <e58ta7$jns$1@fegnews.vip.hr> Hello. How can I run some Python script within C# program? Thanks, Zlatko From http Fri May 26 20:21:12 2006 From: http (Paul Rubin) Date: 26 May 2006 17:21:12 -0700 Subject: Thread vs. generator problem References: <7xodxkmmzl.fsf_-_@ruckus.brouhaha.com> <mailman.6262.1148684834.27775.python-list@python.org> Message-ID: <7xwtc8b9mv.fsf@ruckus.brouhaha.com> "Tim Peters" <tim.peters at gmail.com> writes: > > g = remote_iterate(itertools.count) > > You didn't run this code, right? itertools.count() was intended. Sorry, I made a cut-and-paste error posting the message. My test case did use itertools.count(). > In any case, as when calling any generator, nothing in the body of > remote_iterate() is executed until the generator-iterator's next() > method is invoked. Ooof, I see what happened now. My first test case was misleading and made me think that the generator immediately executed until it reached a yield statement. In fact it was the generator function (i.e. the thing that made the generator), a separate object, that printed the messages. Thanks! From duncan.booth at invalid.invalid Fri May 12 10:20:49 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 May 2006 14:20:49 GMT Subject: New tail recursion decorator References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <Xns97BF8E839A8D1duncanbooth@127.0.0.1> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> <1147437656.779139.54840@d71g2000cwd.googlegroups.com> <1147441799.331677.88460@d71g2000cwd.googlegroups.com> Message-ID: <Xns97C19C18C76A4duncanbooth@127.0.0.1> Tim N. van der Leeuw wrote: > The other thing I do not understand, due to my limited understanding of > what is tail-recursion: factorial2 (Duncan's definition) is not proper > tail-recursion. Why not? How does it differ from 'real' tail recursion? Tail recursion is when a function calls itself and then immediately returns the result of that call as its own result. So long as nothing except returning the result needs to be done it is possibly to avoid the recursive call altogether. This function is tail recursive: @tail_recursion def factorial(n, acc=1): "calculate a factorial" if n == 0: return acc res = factorial(n-1, n*acc) return res but this one isn't: @tail_recursion def factorial2(n): "calculate a factorial" if n == 0: return 1 return n * factorial2(n-1) because when the inner call to factorial2() returns the function still has to do some work (the multiplication). I don't understand your comments about speed differences. If you try to run factorial2() as defined above then it simply throws an exception: there are no results to compare. My guess is that when you wrote: @tail_recursion def factorial2(n): # do the stuff pass your 'do the stuff' actually had an erroneous call to 'factorial'. If you are going to rename the function you have to rename the recursive calls as well. (At least, that's what I forgot to do when I first tried it and couldn't understand why it gave me an answer instead of crashing.) The decorator also fails for functions which are tail-recursive but which contain other non-tail recursive calls within themselves. For example I would be pretty sure you couldn't write a working implementation of Ackermann's function using the decorator: def Ack(M, N): if (not M): return( N + 1 ) if (not N): return( Ack(M-1, 1) ) return( Ack(M-1, Ack(M, N-1)) ) From rNOSPAMon at flownet.com Fri May 19 18:53:49 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Fri, 19 May 2006 15:53:49 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> <1147998139.268318.315250@y43g2000cwc.googlegroups.com> <rNOSPAMon-AC0C9B.18040918052006@news.gha.chartermi.net> <1148001708.183506.296240@g10g2000cwb.googlegroups.com> <rNOSPAMon-96A79F.00032619052006@news.gha.chartermi.net> <1148029074.083644.112370@i40g2000cwc.googlegroups.com> Message-ID: <rNOSPAMon-6B18D8.15534919052006@news.gha.chartermi.net> In article <1148029074.083644.112370 at i40g2000cwc.googlegroups.com>, "Serge Orlov" <Serge.Orlov at gmail.com> wrote: > Ron Garret wrote: > > In article <1148001708.183506.296240 at g10g2000cwb.googlegroups.com>, > > "Serge Orlov" <Serge.Orlov at gmail.com> wrote: > > > > > Ron Garret wrote: > > > > > > I'm using an OS X terminal to ssh to a Linux machine. > > > > > > > > > > In theory it should work out of the box. OS X terminal should set > > > > > enviromental variable LANG=en_US.utf-8, then ssh should transfer this > > > > > variable to Linux and python will know that your terminal is utf-8. > > > > > Unfortunately AFAIK OS X terminal doesn't set that variable and most > > > > > (all?) ssh clients don't transfer it between machines. As a workaround > > > > > you can set that variable on linux yourself . This should work in the > > > > > command line right away: > > > > > > > > > > LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > > > > > > > Or put the following line in ~/.bashrc and logout/login > > > > > > > > > > export LANG=en_US.utf-8 > > > > > > > > No joy. > > > > > > > > ron at www01:~$ LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > Traceback (most recent call last): > > > > File "<string>", line 1, in ? > > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > > > > position 0: ordinal not in range(128) > > > > ron at www01:~$ > > > > > > What version of python and what shell do you run? What the following > > > commands print: > > > > > > python -V > > > echo $SHELL > > > $SHELL --version > > > > ron at www01:~$ python -V > > Python 2.3.4 > > ron at www01:~$ echo $SHELL > > /bin/bash > > ron at www01:~$ $SHELL --version > > GNU bash, version 2.05b.0(1)-release (i386-pc-linux-gnu) > > Copyright (C) 2002 Free Software Foundation, Inc. > > ron at www01:~$ > > That's recent enough. I guess the distribution you're using set LC_* > variables for no good reason. Nope: ron at www01:~$ export | grep LC ron at www01:~$ > Either unset all enviromental variables > starting with LC_ and set LANG variable or overide LC_CTYPE variable: > > LC_CTYPE=en_US.utf-8 python -c "print unichr(0xbd)" > > Should be working now :) Nope: ron at www01:~$ LC_CTYPE=en_US.utf-8 python -c "print unichr(0xbd)" Traceback (most recent call last): File "<string>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 0: ordinal not in range(128) rg From xi at gamma.dn.ua Mon May 15 07:48:11 2006 From: xi at gamma.dn.ua (Kirill Simonov) Date: Mon, 15 May 2006 14:48:11 +0300 Subject: [ANN] PyYAML-3.02: YAML parser and emitter for Python Message-ID: <20060515114811.GA21343@58sirius016.dc.ukrtel.net> ======================== Announcing PyYAML-3.02 ======================== A new bug-fix release of PyYAML is now available: http://pyyaml.org/wiki/PyYAML Changes ======= * Fix win32 installer. Apparently bdist_wininst does not work well under Linux. * Fix a bug in add_path_resolver. * Add the yaml-highlight example. Try to run on a color terminal: `python yaml_hl.py <any_document.yaml`. Resources ========= PyYAML homepage: http://pyyaml.org/wiki/PyYAML PyYAML documentation: http://pyyaml.org/wiki/PyYAMLDocumentation TAR.GZ package: http://pyyaml.org/download/pyyaml/PyYAML-3.02.tar.gz ZIP package: http://pyyaml.org/download/pyyaml/PyYAML-3.02.zip Windows installer: http://pyyaml.org/download/pyyaml/PyYAML-3.02.win32.exe PyYAML SVN repository: http://svn.pyyaml.org/pyyaml Submit a bug report: http://pyyaml.org/newticket?component=pyyaml YAML homepage: http://yaml.org/ YAML-core mailing list: http://lists.sourceforge.net/lists/listinfo/yaml-core About PyYAML ============ YAML is a data serialization format designed for human readability and interaction with scripting languages. PyYAML is a YAML parser and emitter for Python. PyYAML features a complete YAML 1.1 parser, Unicode support, pickle support, capable extension API, and sensible error messages. PyYAML supports standard YAML tags and provides Python-specific tags that allow to represent an arbitrary Python object. PyYAML is applicable for a broad range of tasks from complex configuration files to object serialization and persistance. Example ======= >>> import yaml >>> yaml.load(""" ... name: PyYAML ... description: YAML parser and emitter for Python ... homepage: http://pyyaml.org/wiki/PyYAML ... keywords: [YAML, serialization, configuration, persistance, pickle] ... """) {'keywords': ['YAML', 'serialization', 'configuration', 'persistance', 'pickle'], 'homepage': 'http://pyyaml.org/wiki/PyYAML', 'description': 'YAML parser and emitter for Python', 'name': 'PyYAML'} >>> print yaml.dump(_) name: PyYAML homepage: http://pyyaml.org/wiki/PyYAML description: YAML parser and emitter for Python keywords: [YAML, serialization, configuration, persistance, pickle] Copyright ========= The PyYAML module is written by Kirill Simonov <xi at resolvent.net>. PyYAML is released under the MIT license. -- xi From bignose+hates-spam at benfinney.id.au Mon May 22 04:18:34 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 22 May 2006 18:18:34 +1000 Subject: Dumb-as-rocks WSGI serving using standard library Message-ID: <87sln2321x.fsf@benfinney.id.au> Howdy all, I'm trying to implement some new functionality for an existing PHP web application. Rather than writing a whole lot of stuff in PHP, and looking toward a future when more of the application can be rewritten more sanely, I'd like to write a Python program that generates the content and serves it up to the existing application via HTTP. The existing architecture is as expected: web client <--(HTTP)--> existing app with the existing app also talking to a database. The new functionality involves generating a PDF document from input parameters and returning it to the browser. Rather than nestle this into the existing PHP, I'd like the existing app to simply make an HTTP request to a single-purpose application server written in Python which generates the content and serves it back as the response body. This would insert into the above architecture behind the existing application: existing app <--(HTTP)--> request server <--(WSGI)--> content generator The bulk of the new functionality would be in the generation of the content from the input parameters. The request server would run locally on the machine, listening for HTTP requests and invoking the content generator via WSGI; the generated document would simply be served back as the HTTP response body. The existing application would then just need to gather the input parameters needed, feed them in an HTTP request to the request server, and feed back the response to the web client. I can see how writing the content generator to talk WSGI would be beneficial: the application can be re-used in other application contexts. The WSGI protocol is easy to follow. What I can't find is a simple recipe to serve a WSGI application with a dumb-as-rocks HTTP server, just using the standard Python library. The standard library includes BaseHTTPServer, which as far as I can tell doesn't know anything about WSGI. The don't seem to be any recipes posted to the Python Cookbook <URL:http://aspn.activestate.com/ASPN/Python/Cookbook/> with "wsgi" in them. Everything else that I can find leads to dependencies I don't want for flexibility I don't need: cherrypy, paste, et al. Any suggestions for how to serve up a simple WSGI application with just the standard library? -- \ "A cynic is a man who, when he smells flowers, looks around for | `\ a coffin." -- Henry L. Mencken | _o__) | Ben Finney From ptmcg at austin.rr._bogus_.com Tue May 16 15:26:00 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 16 May 2006 19:26:00 GMT Subject: round numbers in an array without importing Numeric or Math? - SOLVED, sort of References: <446a1748$0$61168$ae4e5890@news.nationwide.net> <446a2032$0$61167$ae4e5890@news.nationwide.net> Message-ID: <cHpag.37880$CH2.22854@tornado.texas.rr.com> "Lance Hoffmeyer" <lance at augustmail.com> wrote in message news:446a2032$0$61167$ae4e5890 at news.nationwide.net... > The array comes out as unicode. This is probably because I am grabbing the numbers > from a Word Doc using regex's. > > So, before rounding I perform the following: > # Convert to String > Topamax = [str(x) for x in Topamax] > # Convert to floating > Topamax = [float(x) for x in Topamax] > # Finally, round the number > Topamax= [(x+0.5) for x in Topamax] > > Is there a shorter way? > > Lance > > ... or if you prefer the functional approach (using map)... roundToInt = lambda z : int(z+0.5) Topamax = map( roundToInt, map( float, map(str, Topamax) ) ) (Python also has a built-in round() function, but this returns floats, not ints - if that is okay, then just delete the lambda definition, and replace roundToInt with round.) -- Paul From nospam at invalid.com Tue May 9 15:21:35 2006 From: nospam at invalid.com (Jack) Date: Tue, 9 May 2006 12:21:35 -0700 Subject: Python editor recommendation. References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <fM-dnfMPYchfdv3ZRVn-gw@comcast.com> PyScripter, a nativen Windows application, free. > > Can any one please recommend me an editor for coding Python. Thank u. > I have Komodo (www.activestate.com) in my mind. Is the editor any good? > > regards. From webraviteja at gmail.com Fri May 12 04:11:08 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 12 May 2006 01:11:08 -0700 Subject: deleting texts between patterns In-Reply-To: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> Message-ID: <1147421468.912908.271280@i39g2000cwa.googlegroups.com> mickle... at hotmail.com wrote: > hi > say i have a text file > > line1 > line2 > line3 > line4 > line5 > line6 > abc > line8 <---to be delete > line9 <---to be delete > line10 <---to be delete > line11 <---to be delete > line12 <---to be delete > line13 <---to be delete > xyz > line15 > line16 > line17 > line18 > > I wish to delete lines that are in between 'abc' and 'xyz' and print > the rest of the lines. Which is the best way to do it? Should i get > everything into a list, get the index of abc and xyz, then pop the > elements out? or any other better methods? > thanks In other words ... lines = open('test.txt').readlines() for line in lines[lines.index('abc\n') + 1:lines.index('xyz\n')]: lines.remove(line) for line in lines: print line, Regular expressions are better in this case import re pat = re.compile('abc\n.*?xyz\n', re.DOTALL) print re.sub(pat, '', open('test.txt').read()) From apardon at forel.vub.ac.be Tue May 9 04:15:19 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 May 2006 08:15:19 GMT Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> Message-ID: <slrne60jsm.dac.apardon@rcpc42.vub.ac.be> Op 2006-05-09, Pisin Bootvong schreef <joesb.coe9 at gmail.com>: > > Joe Marshall wrote: >> Alex Martelli wrote: >> Most languages allow `unnamed numbers'. The `VAT_MULTIPLIER' argument >> is a >> strawman. Would you want to have to use a special syntax to name the >> increment >> in loop? >> >> defnumber zero 0 >> defnumber one { successor (zero); } >> >> for (int i = zero; i < limit; i += one) { ...} >> >> If you language allows unnamed integers, unnamed strings, unnamed >> characters, unnamed arrays or aggregates, unnamed floats, unnamed >> expressions, unnamed statements, unnamed argument lists, etc. why >> *require* a name for trivial functions? >> Wouldn't all the other constructs benefit by having a required name as >> well? >> > > Is this a Slippery Slope fallacious argument? > (http://c2.com/cgi/wiki?SlipperySlope) No it is not. > "if python required you to name every function then soon it will > require you to name every number, every string, every immediate result, > etc. And we know that is bad. Therefore requiring you to name your > function is bad!!!! So Python is bad!!!!" I think this is a strawman. IMO requiring to name a function can make things cumbersome. I don't suppose anyone thinks the following is good practice. one = 1. lst.append(one) Yet this practice is forced upon you in a number of cases when you require functions to be named. Look at the following: def incr_cnt_by_one(obj): obj.cnt += 1 treat_all(lst, incr_cnt_by_one) So the question I have is: Why is requiring me to give this function a name considered a good thing, when it leads to a situation that is considered bad practice in case of a number. -- Antoon Pardon From onurb at xiludom.gro Wed May 3 09:08:09 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 15:08:09 +0200 Subject: Sorting a list of dictionaries by dictionary key In-Reply-To: <mailman.5260.1146660794.27775.python-list@python.org> References: <mailman.5260.1146660794.27775.python-list@python.org> Message-ID: <4458ab95$0$2055$626a54ce@news.free.fr> Nico Grubert wrote: > Hi there, > > I am looking for a way to sort a list containing dictionaries. > > This is my example list: > [{'Title': 'ABC', 'from_datetime': DateTime('2006/04/25 12:45:00 > GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 > 12:45:00 GMT+2')}, {'Title': 'GHI', 'from_datetime': > DateTime('2006/03/10 12:45:00 GMT+2')}] > > I want to sort the list by dictionary's key 'from_datetime' so the > sorted list should be: > > [{'Title': 'GHI', 'from_datetime': DateTime('2006/03/10 12:45:00 > GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 > 12:45:00 GMT+2')}, {'Title': 'ABC', 'from_datetime': > DateTime('2006/04/25 12:45:00 GMT+2')}] > > Any idea how I can sort this list? The common idiom for this is called decorate-sort-undecorate. unsorted_list = [ {'Title': 'ABC', 'from_datetime': DateTime('2006/04/25 12:45:00 GMT+2')}, {'Title': 'DEF', 'from_datetime': DateTime('2006/04/18 12:45:00 GMT+2')}, {'Title': 'GHI', 'from_datetime': DateTime('2006/03/10 12:45:00 GMT+2')}] decorated_list = [(d['from_datetime'], d) for d in unsorted_list] decorated_list.sort() sorted_list = [t[1] for t in decorated_list] HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aahz at pythoncraft.com Thu May 4 12:36:45 2006 From: aahz at pythoncraft.com (Aahz) Date: 4 May 2006 09:36:45 -0700 Subject: Python for Perl programmers References: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> Message-ID: <e3dait$4us$1@panix2.panix.com> In article <Xxp6g.1766$VV2.132570 at news20.bellglobal.com>, A.M <alanalan at newsgroup.nospam> wrote: > >Is there any efficient online resource or book that help experienced Perl >programmers to Python? Don't use the Martin Brown book, whatever you do. The Perl/Python Phrasebook isn't bad, but it's ten years out of date. Really, your best bet is to just dive into the Python tutorial. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "Argue for your limitations, and sure enough they're yours." --Richard Bach From onurb at xiludom.gro Fri May 5 12:04:45 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 18:04:45 +0200 Subject: Drop Down Menus... In-Reply-To: <mailman.5383.1146844590.27775.python-list@python.org> References: <mailman.5383.1146844590.27775.python-list@python.org> Message-ID: <445b77fa$0$21261$636a55ce@news.free.fr> bruce wrote: > Hi... > > Never used python, but I have a question regarding Drop Down Menus. Does > Python allow me to create a website, Yes. > that will permit the user to create > Drop Down menus that can be initiated with the right mouse click? Not sure to understand what you mean, but this is nothing Python-specific - web-programming is web-programming, whatever the server-side techno/language. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From timx at nospam.dev.null Thu May 25 04:40:38 2006 From: timx at nospam.dev.null (Tim X) Date: Thu, 25 May 2006 18:40:38 +1000 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> <447479A1.8050809@hotORgooMAIL.invalid> <Xns97CD6AB19B4F3castleamber@130.133.1.4> <447485B6.4070507@hotORgooMAIL.invalid> Message-ID: <87verumr95.fsf@tiger.rapttech.com.au> Mitch <spudtheimpaler at hotORgooMAIL.invalid> writes: > John Bokma wrote: >> Mitch <spudtheimpaler at hotORgooMAIL.invalid> wrote: >> >>> John Bokma wrote: >>> [...] >>>> You're mistaken. All you need to do is report it. After some time Xah >>>> will either walk in line with the rest of the world, or has found >>>> somewhere else to yell. As long as it's not my back garden and not >>>> around 4AM, I am ok with it. >>>> >>> Walk in line with the rest of the world? Pah. >>> >>> This is no-ones back garden. >> Funny how people who always think they can "change Usenet" have no >> clue about what Usenet is and how it works in the first place. > > Who said anything about changing it? I like it just the way it is. > >> Usenet is just that, each server participating can be thought of as >> being the back yard of the news master. > > Sure, each server has terms and conditions that apply, doesn't mean > you should be able to ban people from speaking just because you don't > like what they say. My point is that this isn't *your* back garden, > it isn't *my* back garden. It isn't something I own, and it *IS* > something I can filter and/or ignore. Someone shouting in your back > garden is a whole different ball game where your desires prevail. Not > here. You know what you are getting into when you sign in, and it is > your responsibility to deal with those you don't agree with > personally. > > I understand you consider his writings spam, and so can see why you > have reported him. All I'm saying is that as long as the articles are > remotely on topic, I believe he has a right to post his opinions here. > >> If you have no clue about how Usenet works, first read up a bit. >> What a Usenet server is, a feed, and how Usenet is distributed. >> And then come back if you finally have something to say that you can >> back up. >> > > Thankfully I'm aware enough of all the above that I don't feel the need. > > As these are all opinions, I don't see any need to "back up" any of it. Personally, I think this is getting a bit out of hand. Originally, John and others suggested reporting Xah to his ISP for spamming multiple groups. There was never any suggestion I have seen (except from Xah himself) that the objective was to gag his "contraversial" thoughts/comments/ideas. I have no problem with him posting comments which are relevant to the group he posts to. However, I do object to anyone who has the arrogance to believe their opinions are so important they should be posted to any remotely related group they can think of. I don't agree with nearly 99% of what Xah says - he often raises a well known issue (i've not seen anything original yet), outlines it reasonably well, but then proposes solutions which strike me as being very poorly considered or narrow of thought. He also tends to look at something for a couple of days and then rubbish it with a tone of authority and experience he obviously hasn't yet obtained. However, he has just as much right to do so as anyone else and therefore, its not because of his content he should be reported - its because of his irresponsability in how he distributes it. I also seem to remember a page on his website from a couple of years back in which he admits enjoying trolling and starting flame wars - but I can't find it now, so maybe I'm mistaken. However, I suspect this is the main motivation for his posts rather than a genuine desire to solve problems he perceives. At any rate, its not like he hasn't been told his constant behavior of mass cross posting was considered bad form - he has been told many many times and just ignores it. If someone wrote up there essays and got them printed on millions of leaflets which they then dumped all over the place, would you be outraged when they were fined for littering and claim their right to free speech was being gagged? Of course not. This is the same. I think most would have no problem with Xah posting if he did it in a responsible manner. Note that normally I try to remove all the cross posted groups in replies to Xah's thread, but this time, I'm leaving them as I feel the nature of this thread warrants it. If you disagree, please don't hesitate to report me to my ISP as I'm more than willing to defend my decision. If I lose, there not an ISP I'd want to stay with anyway! Tim -- tcross (at) rapttech dot com dot au From johnjsal at NOSPAMgmail.com Wed May 10 11:57:37 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 15:57:37 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: <1147275917.411823.15150@j73g2000cwa.googlegroups.com> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <1147275917.411823.15150@j73g2000cwa.googlegroups.com> Message-ID: <R3o8g.2081$No6.45875@news.tufts.edu> BartlebyScrivener wrote: > Right about now somebody usually jumps in and shows you how to do this > without using regex and using string methods instead. > > I'll watch. > > rd > Heh heh, I'm sure you're right, but this is more just an exercise for me in REs, so I'm curious how you might do it, unless the answer is that it's just too complicated to be worth it (like Murali's example!) That goes beyond just an RE pattern. From alisonken1 at gmail.com Mon May 8 13:21:20 2006 From: alisonken1 at gmail.com (alisonken1) Date: 8 May 2006 10:21:20 -0700 Subject: Logging vs printing In-Reply-To: <4c8teiF142m3nU1@individual.net> References: <4c6o1sF14hhjuU1@individual.net> <1147035825.643595.139800@e56g2000cwe.googlegroups.com> <4c8qroF14g6feU1@individual.net> <slrne5udla.30k.sybrenUSE@schuimige.stuvel.eu> <4c8teiF142m3nU1@individual.net> Message-ID: <1147108880.177377.217250@j33g2000cwa.googlegroups.com> Leo Breebaart wrote: <SNIP> > Also, assume that I have set it up as above. Now I want certain > other print statements to go to sys.stderr alone. If I understand > the docs correctly (possibly I don't), the way to do this is to > start attaching explicit StreamHandlers and whatnot. Whereas with > print, I can say "print >>sys.stderr, msg". <SNIP> Something else to consider, every time your script calls "print >>sys.stderr, msg", it is making another file open request. I've run across situations where this format will actually cause a system to return "too many open files" error. As was pointed out earlier, it's much easier to learn how to use the logging facility and create a default stdout logger as well as a secondary stderr logger that only maintains one file handle than to try to find out where you're getting some errors that are not script errors but system limit errors. The other nice aspect of using the logging facility is the availability of changing the logger to save output to a file or stdout/stderr than to try and go through a more-than-one-file program. It's easy to learn how to redirect stdout/stderr within a script, but it's usually more flexible to use the logging facility that's already been included. Before the logging module was included in the library, I usually ended up writing my own logging module to do the same thing. Especially since the logger allows you to specify levels. For example, I typically have my logging facility setup as follows: 10 - Very basic logging - typically main routine changes 20 - Log imports 30 - Log class instantiation 40 - Log module calls 50 - Log function calls The other aspect of using the logging facility, you can also define your own in-between log levels: 51 - Entering function 52 - Exiting function 53 - Function sub-routines 60 - Everyhing under the sun As part of the configParser options: -v : Increment logging level by 1 level for every -v option on command line -loglevel=<level> : Specify log level -logfile=<filename> : File to save stdout messages -errfile=<filename> : File to save stderr messages Once you get used to the logging module, it's hard to go back to using file redirects and the <sometimes> system limits troubleshooting in larger programs. From taleinat at gmail.com Wed May 17 07:47:45 2006 From: taleinat at gmail.com (taleinat at gmail.com) Date: 17 May 2006 04:47:45 -0700 Subject: IDLE confusion In-Reply-To: <1147767977.928350.261650@i39g2000cwa.googlegroups.com> References: <1147767977.928350.261650@i39g2000cwa.googlegroups.com> Message-ID: <1147866465.226577.98790@y43g2000cwc.googlegroups.com> This isn't really an IDLE issue, it's a Python feature which needs to be understood. In Python, once you've imported a module once, importing it again is ignored. This works fine under the assumption that modules don't change during a single Python session. However, when you're developing a module this isn't true, and a workaround for this mechanism is needed. The safest way to go is to start a new Python session. In the IDLE interpreter ("Shell" window) you can do this from the Shell menu. Running a module from an IDLE editor window (Run->Run Module) will also restart the interpreter. Notice, however, that these will only work if IDLE has a sub-process for the interpreter! If not, the Shell menu won't exist, and Run Module won't restart the interpreter. On Windows, opening IDLE by right-clicking a file and choosing 'Edit with IDLE' will cause it to open without a subprocess. If you change a module and want to use the newer version in the same Python session, use the built-in 'reload' function: import Test reload(Test) Notice that if you use the 'from <module> import ...' syntax, you need to import the module itself (i.e. import <module>) before you can reload it. I advise to use this with care, as things can get quite confusing after a few reloads... From vbgunz at gmail.com Fri May 26 07:56:16 2006 From: vbgunz at gmail.com (vbgunz) Date: 26 May 2006 04:56:16 -0700 Subject: how to clear up a List in python? In-Reply-To: <mailman.6234.1148642663.27775.python-list@python.org> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148612582.510390.48040@i39g2000cwa.googlegroups.com> <mailman.6227.1148638689.27775.python-list@python.org> <1148639516.244264.37500@i40g2000cwc.googlegroups.com> <mailman.6234.1148642663.27775.python-list@python.org> Message-ID: <1148644576.877303.298270@38g2000cwa.googlegroups.com> > Well, given that you did post it on purpose and had no "intent to mess > anyone up over it", it is clear that the antecedent in Fredrik's > if-statement is not satisfied and therefore your mind should've skipped > the consequent statement when reading his response. Why get so upset > about something that didn't even apply to you? :-) I wish I could've intepreted it like that... I guess that is one of the evils of being human. the uncanny ability to intepret ambiguous understatements and then say fork it when technically you're correct... it really did not apply to me... The evil of being human I suppose :P I apologize to Fredrik for my outburst but would like to request that next time a better suited address be in order even if in doubt. Not everyone is aware of egoless programming... From jstroud at ucla.edu Sun May 28 02:14:44 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 27 May 2006 23:14:44 -0700 Subject: Using a package like PyInstaller In-Reply-To: <ZX5eg.287$xO5.197@trnddc03> References: <FyYdg.2216$As2.860@trnddc02> <e5ab5l$tkm$1@daisy.noc.ucla.edu> <DD4eg.2432$As2.2216@trnddc02> <e5amec$64m$1@daisy.noc.ucla.edu> <ZX5eg.287$xO5.197@trnddc03> Message-ID: <e5bf4k$of9$1@daisy.noc.ucla.edu> LittlePython wrote: > That is very close to what I have being doing, however I was unable to > enclose a bmp or another file for that matter in the exe. I used both DATA > and BINARY key words with no luck. I checked what was in the package and > there were there. I guess for some reason it could not locate then when > executed. I used snap 274 if I remember correctly. You can include files with innosetup under the [FILES] section. The docs show how. You can then code absolute paths to these resources in your code according to the results of 'sys.platform'. If you use the "--onedir" option, then you may want to look here: http://pyinstaller.hpcf.upr.edu/docs/Manual_v1.1.html#accessing-data-files > I am worrying that > when the py script is run I am leaving behind files. That the components of > my stand-alone exe is somehow coming out of the exe (PyInstaller) and being > installed. Im 99.999% confident that this will not happen from the .exe file generated by pyinstaller (unless you specify--see link above). However, innosetup will put files in the 'Program Files' directory or wherever you specify. This would be similar to just about every other application out there for windows. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From stephan.diehl at gmx.net Fri May 5 09:23:05 2006 From: stephan.diehl at gmx.net (Stephan Diehl) Date: Fri, 05 May 2006 15:23:05 +0200 Subject: Active Directory Authentication References: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> Message-ID: <pan.2006.05.05.13.23.04.976877@gmx.net> On Fri, 05 May 2006 05:39:08 -0700, D wrote: > Is it possible to have Python authenticate with Active Directory? > Specifically what I'd like to do is have a user enter a > username/password, then have Python check the credentials with AD - if > what they entered is valid, for example, it returns a 1, otherwise a > 0.. Thanks! It's possible and you need the python-ldap package for it. The actual authentication will look like (simplified): def authenticate(user='',passwd=''): dn = find_user_dn(user) try: l = ldap.open(AD_HOST_URL) l.protocol_version = ldap.VERSION3 l.simple_bind_s(dn,passwd) l.search_s(SEARCHDN,ldap.SCOPE_SUBTREE,'objectType=bla') l.unbind_s() return True except ldap.LDAPError: return False obviously, you need to supply some function 'find_user_dn' that maps the user to its DN. From fredrik at pythonware.com Fri May 26 14:36:14 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 26 May 2006 20:36:14 +0200 Subject: write() vs. writelines() In-Reply-To: <1148667630.902170.310930@i40g2000cwc.googlegroups.com> References: <1148667630.902170.310930@i40g2000cwc.googlegroups.com> Message-ID: <e57hqr$epq$1@sea.gmane.org> Gregory Petrosyan wrote: > My question is: why write(''.join(...)) works slowly than > writelines(...)? Here's the code: the first copies all the substring to a single string large enough to hold all the data, before handing it over to the file object, while the second just writes the substrings to the file object. </F> From "reverse[nepank.noot]" at fft.be Wed May 17 03:40:40 2006 From: "reverse[nepank.noot]" at fft.be (Toon Knapen) Date: Wed, 17 May 2006 09:40:40 +0200 Subject: CFLAGS are not taken into account properly Message-ID: <446ad377$0$438$6c56d894@reader0.news.be.easynet.net> To configure python on a Solaris 9 box with sunstudio11 installed and to compile it in 64bit, I execute following: <code> export CC=cc export CFLAGS="-xarch=v9" export CXX=CC export CXXFLAGS="-xarch=v9" export F77=f77 export FFLAGS="-xarch=v9" export LDFLAGS="-xarch=v9" ./configure </code> When doing 'make' afterwards, the '-xarch=v9' option is not on the command-line however? Should'nt the CFLAGS be propagated to the Makefile that is generated by configure? Or is there any other way to do this? Thanks in advance, toon From deets at nospam.web.de Fri May 5 10:13:08 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 16:13:08 +0200 Subject: how to remove 50000 elements from a 100000 list? References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> <4c13mdF13esivU1@uni-berlin.de> Message-ID: <4c14snF13tbobU1@uni-berlin.de> > How about a listcomprehension? > > > new_list = [e for e in old_list if predicate(e)] > # Possibly you need this, too: > old_list[:] = new_list forgot the predicate. And you should use a set of objects to remove, as then you'd have O(1) behavior for the in-operator So: to_remove = set(b) new_list = [e for e in a if e not in to_remove] Diez From kriv.john at gmail.com Mon May 29 13:52:13 2006 From: kriv.john at gmail.com (Kriv) Date: 29 May 2006 10:52:13 -0700 Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional Message-ID: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> Hi friends, I found this eBook on the web. This book is very very good. I refer to them. http://rapidshare.de/files/21704644/Apress.Beginning.Python.From.Novice.to.Professional.Sep.2005.rar.html Thx John From bignose+hates-spam at benfinney.id.au Wed May 17 00:58:47 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 14:58:47 +1000 Subject: A better way of making subsclassing of built-in types stick for attributes? References: <1147839432.816504.318290@38g2000cwa.googlegroups.com> Message-ID: <87ac9hp7qw.fsf@benfinney.id.au> "telesphore4 at gmail.com" <telesphore4 at gmail.com> writes: > Is there a better way to make the subclassing of built-in types > stick? They stick. Your new classes are available until you get rid of them. > The goal is to have the the fields of a class behave like strings > with extra methods attached. That is, I want the fact that the > fields are not strings to be invisible to the client > programmers. But I always want the extras to be there for the > clients too. > > What I'm doing is subclassing str. Sounds like the right way to do what you're describing. Your subclass can then be used to instantiate objects that behave like 'str' objects, except for the different behaviour you define in your class. > Of course, whenever you then set mystr = 'a string' ... you're instantiating a 'str' object, since that's what the syntax you use will do. > you loose the extra goodies that I have attached in the > subclass. Because you haven't created an object of that subclass. >>> class GroovyStr(str): ... """ Our groovy extended string class """ ... pass ... >>> foo = "Larry" >>> bar = str("Curly") >>> baz = GroovyStr("Moe") >>> print [type(x) for x in foo, bar, baz] [<type 'str'>, <type 'str'>, <class '__main__.GroovyStr'>] The syntax used to make the object assigned to 'foo' is just a shortcut for the syntax used to assign to 'bar'. If you want to instantiate anything else, you need to use that explicit syntax, such as for the object assigned to 'baz'. If you're hoping that "subclass" means "modify the behaviour of the original class", you're mistaken. It makes a *new* class that has behaviour *inherited from* the original class. -- \ "I stayed up all night playing poker with tarot cards. I got a | `\ full house and four people died." -- Steven Wright | _o__) | Ben Finney From michael at stroeder.com Sat May 6 07:04:10 2006 From: michael at stroeder.com (=?ISO-8859-1?Q?Michael_Str=F6der?=) Date: Sat, 06 May 2006 13:04:10 +0200 Subject: Active Directory Authentication In-Reply-To: <pan.2006.05.05.13.23.04.976877@gmx.net> References: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> <pan.2006.05.05.13.23.04.976877@gmx.net> Message-ID: <aecui3-lt7.ln1@nb2.stroeder.com> Stephan Diehl wrote: > On Fri, 05 May 2006 05:39:08 -0700, D wrote: > >>Is it possible to have Python authenticate with Active Directory? >>Specifically what I'd like to do is have a user enter a >>username/password, then have Python check the credentials with AD - if >>what they entered is valid, for example, it returns a 1, otherwise a >>0.. Thanks! > > It's possible and you need the python-ldap package for it. > The actual authentication will look like (simplified): > > def authenticate(user='',passwd=''): > dn = find_user_dn(user) > try: > l = ldap.open(AD_HOST_URL) > l.protocol_version = ldap.VERSION3 > l.simple_bind_s(dn,passwd) > l.search_s(SEARCHDN,ldap.SCOPE_SUBTREE,'objectType=bla') > l.unbind_s() > return True > except ldap.LDAPError: > return False > > obviously, you need to supply some function 'find_user_dn' that maps > the user to its DN. Since MS AD does not allow anonymous search in its default configuration find_user_dn() would have to bind as an application user with search rights to search the user entry by UPN. Hack not LDAPv3 compliant: When sending a simple bind request to MS AD over LDAP you can also directly use the UPN for 'dn' when invoking l.simple_bind_s(). Note that this is a special semantic of LDAP bind request for MS AD. It is not a LDAPv3 compliant! But if you're sure you won't use this code for binding to another LDAP server you could use this hack. The nice thing about python-ldap is that it also works on other platforms than Win32. The caveat is that you might need to build the OpenLDAP libs. If you're solely on Win32 using ADSI through Win32 extensions for Python as stated by others in this thread might be the better approach. Ciao, Michael. From remm1 at member.fsf.org Wed May 3 20:18:58 2006 From: remm1 at member.fsf.org (Rob E) Date: Wed, 03 May 2006 19:18:58 -0500 Subject: scope of variables References: <874q06bz4c.fsf@localhost.localdomain> Message-ID: <pan.2006.05.04.00.18.52.805305@member.fsf.org> > is the code below correct? > > b = 3 > def adding(a) > print a + b > > it seams not to see the up-level scope where b is defined. Yes except for the missing : at the end of the "def" line. Rob From onurb at xiludom.gro Fri May 19 10:28:08 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 16:28:08 +0200 Subject: noob import question In-Reply-To: <mailman.5949.1148047024.27775.python-list@python.org> References: <mailman.5945.1148045097.27775.python-list@python.org> <4d5vqaF18i4l1U1@uni-berlin.de> <mailman.5949.1148047024.27775.python-list@python.org> Message-ID: <446dd660$0$5149$626a54ce@news.free.fr> PA wrote: > > On May 19, 2006, at 15:33, Diez B. Roggisch wrote: > >> And it seems as if you have some JAVA-background, putting one class in >> one >> file called the same as the class. Don't do that, it's a stupid >> restriction >> in JAVA and should be avoided in PYTHON. > > Restrictive or not, what's so fundamentally devious in putting a class > declaration in a separate file whose name is that of the declared class > (class Queue -> Queue.py)? > > Sounds like a handy way of organizing your code, no? > Not in Python. Python classes tend to be smaller than Java classes. Also, Python, while fully OO, is not anal-retentive about putting everything in classes - functions are fine too. Would you advocate putting each function in its own file ?-) And finally, with Python's file<->module equivalence, grouping related classes and functions in a same module greatly simplify imports. wrt/ naming, having the module named after the class (your example) leads to confusions like the one experimented by the OP. FWIW, Zope2 uses this convention, and I found this confusing too. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From oliphant.travis at ieee.org Sat May 27 03:22:15 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Sat, 27 May 2006 01:22:15 -0600 Subject: Looking for triangulator/interpolator In-Reply-To: <127fp09e6v176a5@corp.supernews.com> References: <127f313dbhl7gf4@corp.supernews.com> <mailman.6267.1148697006.27775.python-list@python.org> <127fp09e6v176a5@corp.supernews.com> Message-ID: <e58un8$baj$1@sea.gmane.org> Grant Edwards wrote: > On 2006-05-27, Travis E. Oliphant <oliphant.travis at ieee.org> wrote: > >>> I need to interpolate an irregularly spaced set of sampled >>> points: Given a set of x,y,z points, I need to interpolate z >>> values for a much finer x,y grid. >> How many x,y,z points do you have? > > I've got about 700 data points. They're arranged irregularly > along arcs arranged in sort of truncated fan-shape. > >> Did you try the fitpack function bisplrep in scipy? > > Not recently. I spent a month or so wrestling with bisplrep a > while back, but was unable to get stable results (either with > real world data or with the example from the tutorial): > > http://www.visi.com/~grante/scipy/interpolate.html > http://www.scipy.net/pipermail/scipy-user/2004-December/003921.html > > I switched to a trianguation scheme shortly after that posting, > and haven't tired bisplrep since then. > Not that you made a bad choice. I do wonder, how much of your difficulty was with the interface to the underlying fitpack routines. The interface is pretty involved as there are lots of parameter choices to the underlying routine. It's very possible the interface is broken in some strange way. Given how many people want to do interpolation. I'm surprised nobody has looked into fixing up the fitpack routines that do it. I suppose it's possible that the underlying fitpack routines are faulty in 2-d. Your examples will help in that study. Pearu made some nice class-based interfaces to fitpack in 2003. They are in SciPy, but, it appears that people aren't making much use of them. Did you try them? They are in fitpack2.py There are new wrappers for it From johnjsal at NOSPAMgmail.com Fri May 26 10:04:54 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 26 May 2006 14:04:54 GMT Subject: Python Programming Books? In-Reply-To: <1148591971.405787.237790@38g2000cwa.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148591971.405787.237790@38g2000cwa.googlegroups.com> Message-ID: <aWDdg.2183$No6.47096@news.tufts.edu> Michael Tobis wrote: > Of the books that are out there, Learning Python and Dive Into Python > are best for the hobbyist as opposed to classroom setting, but my sense > is that both of them go a bit too fast for the typical beginner with no > formal training. I agree that Dive Into Python moves too fast, but it's not really for beginners anyway. It doesn't really teach the basics, it assumes you know some Python already. But I disagree about Learning Python. I think it's laid out and paced perfectly. You start with data types and move slowly on from there. You don't even learn about the actual syntax of Python until well into the book! From brian at sweetapp.com Mon May 22 11:37:30 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 22 May 2006 17:37:30 +0200 Subject: Vancouver Python Workshop - registration open Message-ID: <4471DABA.4080409@sweetapp.com> What's New? =========== Early-bird registration for the Vancouver Python conference is now open. Participants who register before June 30th will receive a substantial discount. To register, see: http://www.vanpyz.org/conference/registration For general conference information, see: http://www.vanpyz.org/conference About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st by Guido van Rossum [1] and Jim Hugunin [2]. Further talks (and tutorials for beginners) will take place on August 5th and 6th. The Vancouver Python Workshop is a community organized and designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers * tracks on multimedia, Web development, education and more More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world [3]. For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Talk proposals accepted: May 15th to June 15th Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th [1] Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Guido works at Google and spends half of his time on Python. [2] Jim Hugunin (Microsoft) is the creator of numerous innovations that take Python into new application domains. Jim's most recent project, IronPython integrates Python into Microsoft's .NET runtime. Jim's previous project, Jython is Python for the Java runtime and was the second production-quality implementation of Python. Before that, Jim's Numeric Python adapted Python to the needs of number crunching applications. Jim works at Microsoft adapting the .NET runtime to the needs of dynamic languages like Python. [3] http://news.bbc.co.uk/2/hi/business/2299119.stm Cheers, Brian From http Tue May 23 15:01:16 2006 From: http (Paul Rubin) Date: 23 May 2006 12:01:16 -0700 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <Xns97CC91CC89166BaldHeadedJohn@216.196.109.145> Message-ID: <7xirnwpnur.fsf@ruckus.brouhaha.com> John D Salt <jdsalt_AT_gotadsl.co.uk> writes: > What exciting new ideas exist in software that are both important and > cannot be traced back to 1986 or earlier? Automated spamming tools? ;-) From ask at me Tue May 9 22:37:06 2006 From: ask at me (AndyL) Date: Tue, 09 May 2006 22:37:06 -0400 Subject: __all__ does not work? In-Reply-To: <mailman.5542.1147223799.27775.python-list@python.org> References: <j9ydnXEhmIkbrPzZnZ2dnUVZ_sadnZ2d@comcast.com> <mailman.5542.1147223799.27775.python-list@python.org> Message-ID: <iM2dnTsOYONswPzZRVn-qw@comcast.com> skip at pobox.com wrote: > Andy> This a mm.py module: > Andy> _all__=('getsize1',) > > Andy> size=85 > > Andy> def getsize1(): > Andy> return size > > Andy> def getsize2(): > Andy> return 2*size > > > Andy> I do not know why but getsize2 is not kept priviate? > > That's not what __all__ is used for. Try this: > > from mm import * > > The only name added to your namespace will be getsize1. > > Skip Okay, got it. Thx. From martin at v.loewis.de Wed May 17 02:08:26 2006 From: martin at v.loewis.de (=?UTF-8?B?Ik1hcnRpbiB2LiBMw7Z3aXMi?=) Date: Wed, 17 May 2006 08:08:26 +0200 Subject: A Unicode problem -HELP In-Reply-To: <1147843788.969853.159420@g10g2000cwb.googlegroups.com> References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <446AAFE6.4080008@v.loewis.de> <1147843788.969853.159420@g10g2000cwb.googlegroups.com> Message-ID: <446abddb$0$31040$9b622d9e@news.freenet.de> manstey wrote: > a=str(word_info + parse + gloss).encode('utf-8') > a=a[1:len(a)-1] > > Is this clearer? Indeed. The problem is your usage of str() to "render" the output. As word_info+parse+gloss is a list (or is it a tuple?), str() will already produce "Python source code", i.e. an ASCII byte string that can be read back into the interpreter; all Unicode is gone from that string. If you want comma-separated output, you should do this: def comma_separated_utf8(items): result = [] for item in items: result.append(item.encode('utf-8')) return ", ".join(result) and then a = comma_separated_utf8(word_info + parse + gloss) Then you don't have to drop the parentheses from a anymore, as it won't have parentheses in the first place. As the encoding will be done already in the output file, the following should also work: a = u", ".join(word_info + parse + gloss) This would make "a" a comma-separated unicode string, so that the subsequent output_file.write(a) encodes it as UTF-8. If that doesn't work, I would like to know what the exact value of gloss is, do print "GLOSS IS", repr(gloss) to print it out. Regards, Martin From jacob.rael at gmail.com Mon May 1 12:13:43 2006 From: jacob.rael at gmail.com (Jacob Rael) Date: 1 May 2006 09:13:43 -0700 Subject: Using a browser as a GUI: which Python package In-Reply-To: <1146291031.457212.237370@g10g2000cwb.googlegroups.com> References: <1146267924.602318.238640@j73g2000cwa.googlegroups.com> <1146291031.457212.237370@g10g2000cwb.googlegroups.com> Message-ID: <1146500023.878800.141240@j73g2000cwa.googlegroups.com> I am looking for the samething. I was thinking of Karrigell. http://karrigell.sourceforge.net/ From nobody at 127.0.0.1 Sun May 21 18:10:31 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 22:10:31 GMT Subject: PEP-xxx: Unification of for statement and list-comp syntax References: <200605211711.25043.me+python@modelnine.org> <mailman.6034.1148237188.27775.python-list@python.org> <1148237544.579470.43420@i40g2000cwc.googlegroups.com> <mailman.6035.1148237860.27775.python-list@python.org> <1148247633.377696.157820@38g2000cwa.googlegroups.com> Message-ID: <rz5cg.20468$Lm5.8909@newssvr12.news.prodigy.com> George Sakkis wrote: > Em Dom, 2006-05-21 ?s 17:11 +0200, Heiko Wundram escreveu: >> for?node?in?tree?if?node.haschildren(): >> <do?something?with?node> >> >> as?syntactic?sugar?for: >> >> for?node?in?tree: >> if?not?node.haschildren(): >> continue >> <do?something?with?node> [snip] > > 2) "There should be one and preferably only one way to do it." You mean like this: s = "foo" + "bar" s = 'foo' + 'bar' s = 'foo' 'bar' s = '%s%s' % ('foo', 'bar') This one and only one way stuff is overrated. I don't care how many ways there are as long as: 1. at least one way is intuitive 2. every way is easily comprehendible (readable, no side effects, etc) Now 'one way to do it' is a good mantra for keeping language complexity down and achieving the second goal. But it needs to be flexible. The proposed syntax is short, intuitive, and consistent with comprehension/generator syntax. I'd say it's entirely in keeping with a number of rules which trump 'one way': Beautiful is better than ugly. Flat is better than nested. Readability counts. Special cases aren't special enough to break the rules. (proposal eliminates the current special case for comprehensions/generators) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From heidi.hunter at fantasy-interactive.com Tue May 23 03:03:52 2006 From: heidi.hunter at fantasy-interactive.com (heidi.hunter at fantasy-interactive.com) Date: 23 May 2006 00:03:52 -0700 Subject: Running script in __main__ shows no output in IDLE In-Reply-To: <44724be3$1@nntp0.pdx.net> References: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> <44724be3$1@nntp0.pdx.net> Message-ID: <1148367832.691286.320790@j33g2000cwa.googlegroups.com> Thanks for your help! Shouldn't Idle have shown an error when trying to read the string constant if it's not interpretable as a normal string, then? /Heidi From doug.bromley at gmail.com Fri May 5 19:15:00 2006 From: doug.bromley at gmail.com (Doug Bromley) Date: Sat, 6 May 2006 00:15:00 +0100 Subject: Best IDE for Python? In-Reply-To: <20060505185559.GB4911@workaround.org> References: <1146842880.561320.274410@v46g2000cwv.googlegroups.com> <288425520605050850i6f94518nafd34adb6ae6581e@mail.gmail.com> <20060505185559.GB4911@workaround.org> Message-ID: <288425520605051615j6a5fb14bp630d2a20224c082@mail.gmail.com> On 5/5/06, Christoph Haas <email at christoph-haas.de> wrote: > > On Fri, May 05, 2006 at 04:50:11PM +0100, Doug Bromley wrote: > > I have a Python IDE review I did a few months back you may want to view: > > http://www.straw-dogs.co.uk/blog/python-ide-review > > Sounds interesting. Could you fix the screenshots? I just get a 404 here. > > Kindly > Christoph > > P.S.: [Rant about TOFU posting suppressed.] > -- > http://mail.python.org/mailman/listinfo/python-list Apologies for that - Thanks for pointing it out. The links and images are now fixed. All the best. Doug -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060506/5079224e/attachment.html> From bignose+hates-spam at benfinney.id.au Wed May 24 01:20:57 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 24 May 2006 15:20:57 +1000 Subject: how to change sys.path? References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <4473867f$0$7721$626a54ce@news.free.fr> <mailman.6124.1148424338.27775.python-list@python.org> <1148434309.969730.50700@i39g2000cwa.googlegroups.com> Message-ID: <87verw0zie.fsf@benfinney.id.au> [Please provide some context when you respond in an existing discussion, by quoting the original message and removing any parts irrelevant to your reply.] "Ju Hui" <phpbird at gmail.com> writes: > yes, we can change PYTHONPATH to add some path to sys.path value, but > how to remove item from sys.path? As pointed out already, sys.path is a list, which can be manipulated like any other list. <URL:http://docs.python.org/lib/typesseq-mutable.html> -- \ "I have never made but one prayer to God, a very short one: 'O | `\ Lord, make my enemies ridiculous!' And God granted it." -- | _o__) Voltaire | Ben Finney From george.sakkis at gmail.com Wed May 24 10:28:41 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 24 May 2006 07:28:41 -0700 Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> Message-ID: <1148480921.004282.134490@38g2000cwa.googlegroups.com> bruno at modulix wrote: > When all your keys are valid Python identifiers, and you may want to use > another dict-like instead of the builtin dict. It's easy to replace the > dict() factory in a function, class, or whole module : > > class MyDict(...): > # dict-like class > > dict = MyDict > > then all following calls to dict(**kw) in this namespace will use MyDict > instead of the builtin's one. Can't do that with dict litterals. Hm, as far as I know shadowing the builtins is discouraged. This is not the same as duck typing, when you may define a function like def foo(dict_like_class): return dict_like_class(x=1,y=2).iteritems() and call it as foo(MyDict) In either case, I would guess that for the vast majority of cases the builtin dicts are just fine and there's no compelling reason for dict(**kwds). Perhaps it's something that should be reconsidered for Py3K. George From softwindow at gmail.com Fri May 19 01:04:07 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 22:04:07 -0700 Subject: Script to make Windows XP-readable ZIP file In-Reply-To: <1148014650.844340.212540@38g2000cwa.googlegroups.com> References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> <Xns97C7E851F9CC2castleamber@130.133.1.4> <1148011001.613000.294750@g10g2000cwb.googlegroups.com> <Xns97C7ED9E857DEcastleamber@130.133.1.4> <1148014650.844340.212540@38g2000cwa.googlegroups.com> Message-ID: <1148015047.664560.32300@i40g2000cwc.googlegroups.com> aha now it's right like this: import os import zipfile z = zipfile.ZipFile(r"c:\text.zip",mode="w",compression=zipfile.ZIP_DEFLATED) cwd = os.getcwd() try: for dirpath,dirs,files in os.walk(cwd): for file in files: z_path = os.path.join(dirpath,file) start = cwd.rfind(os.sep)+1 z.write(z_path,z_path[start:]) z.close() finally: if z: z.close() From roy at panix.com Sun May 21 08:52:22 2006 From: roy at panix.com (Roy Smith) Date: Sun, 21 May 2006 08:52:22 -0400 Subject: dict!ident as equivalent of dict["ident"] References: <mailman.6027.1148213981.27775.python-list@python.org> Message-ID: <roy-D7CEAE.08522221052006@reader1.panix.com> In article <mailman.6027.1148213981.27775.python-list at python.org>, Alexander Kozlovsky <alexander.kozlovsky at gmail.com> wrote: > Hello all! > I have small silly syntax suggestion (SSSS) > > In many cases, keys in dictionary-like objects are strings, > and moreover - valid Python identifiers. Something like: > > foo["bar"]["baz"].x = y > > How about small syntactic sugar: > > foo!bar!baz.x = y Ugh. Syntactic sugar like that leads to language obesity. Anyway, you can already do what you want with just a little bit of work. Define a class (perhaps a subclass of dict, if you like) with a __getattr__ method. Then you can just do foo.bar.baz.x = y with no changes needed to the language. From python.list at tim.thechases.com Tue May 23 14:25:17 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Tue, 23 May 2006 13:25:17 -0500 Subject: how to work with tab-delimited files? In-Reply-To: <j1Icg.2154$No6.46850@news.tufts.edu> References: <j1Icg.2154$No6.46850@news.tufts.edu> Message-ID: <4473538D.6080208@tim.thechases.com> > So in this situation, when the file is being read, is that > single space still determined to be a tab, or do you have to > press tab twice to put a full tab between the names? If there is a literal tab in the file, it will come in (to your code) as a real tab. Your editor may have settings you can tweak to make it a little more apparent. Vim (my preferred poison) allows you to :set list to see representations the literal tabs in your file. To turn it off, do :set nolist You can also tweak your tabstops: :set ts=12 (or whatever number/size accomodates your widest columns) which would make a single tab character expand to your desired size. This should help line matters up visually a little better. Alternatively, with vim you can highlight the tabs to make them stand out a bit more: :match ErrorMsg /\t/ (or you can use another color instead of the ErrorMsg color...if you hit <tab> after typing ":match ", it will successively show you alternatives, or you can use ctrl+D to show a number of them) Just a few ideas with a vim spin. Other quality editors should support similar functionality. -tkc From python.list at tim.thechases.com Sun May 14 20:33:52 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 14 May 2006 19:33:52 -0500 Subject: Converting String to int In-Reply-To: <200605142123.52846.ognjen@mailshack.com> References: <mailman.3510.1143024593.27775.python-list@python.org> <200605141933.57679.ognjen@mailshack.com> <44678C99.5020003@tim.thechases.com> <200605142123.52846.ognjen@mailshack.com> Message-ID: <4467CC70.5070105@tim.thechases.com> > Hi all, Another problem, with the same error (error: "invalid literal for > int()") Having the actual code would be helpful... > code: > > mynums = "423.523.674.324.342.122.943.421.762.158.830" > > mynumArray = string.split(mynums,".") > > x = 0 > for nums in mynumArray: > if nums.isalnum() == true: This line would likely bomb, as in python, it's "True", not "true" (unless you've defined lowercase versions elsewhere) > x = x + int(nums) > else: > print "Error, element contains some non-numeric characters" > break However, I modified your code just a spot, and it worked like a charm: mynums = "423.523.674.324.342.122.943.421.762.158.830" mynumArray = mynums.split(".") x = 0 for num in mynumArray: if num.isdigit(): x = x + int(num) else: print "Error" break and it worked fine. A more pythonic way may might be x = sum([int(q) for q in mynumArray if q.isdigit()]) or, if you don't need mynumArray for anything, you can just use x = sum([int(q) for q in mynum.split(".") if q.isdigit()]) Hope this gives you some stuff to work with, -tkc From tbrkic at yahoo.com Thu May 18 06:00:49 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 03:00:49 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147941477.650222.318420@38g2000cwa.googlegroups.com> Message-ID: <1147946449.402120.143610@g10g2000cwb.googlegroups.com> > You also repeat yourself: head("head"), title("title"), body("body") > > What about this: > > # build a tree structure > root = ET.Element("html") > !root > !head > !title > if A is True: > &text = "Page A" > else: > &text = "Page B" > !body > &bgcolor = "#ffffff" > &text = "Hello, World!" > > Yes this is how it should be. But It depends on which package would be used. If you used xist it would look like that since they have one class for each html tag. I really propose a generic solution that any package that support the method append and __settiem__ could use the new syntax. But minor isssues but it would look something like this with xist: !root !head(): !title(): if A is True: &text = "Page A" else: &text = "Page B" !body() &bgcolor = "#ffffff" &text = "Hello, World!" > mmm...yamlthon? yython...:-) Guess what I have for suffix on the files before preprocessing? ....pyml ofcourse. From against at spam.pl Wed May 17 03:00:56 2006 From: against at spam.pl (=?ISO-8859-2?Q?Grzegorz_=A6lusarek?=) Date: Wed, 17 May 2006 09:00:56 +0200 Subject: formEncode and validation depended on forms field Message-ID: <e4eheu$n0j$1@node3.news.atman.pl> Hi all. I'm using formEncode to validate my forms, and I'm stopped on how to do a complicated validation that depened on what forms element was filled. I mean in my code (without formEncode) i have: if form.select is checked: #if select is checked then I checked for others fields on form #if select is not checked that I abandon validation code... else: if form.login != '' and form.password !='': code.. else: code.. How to achieve something like this in formEncode? i can validate all form but I need validate some fields of form only if others form are filled. Thanks for any help Gregor From johnjsal at NOSPAMgmail.com Wed May 17 23:01:59 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 23:01:59 -0400 Subject: I'm just not cut out for web programming, I guess :) In-Reply-To: <%0Mag.2117$No6.46299@news.tufts.edu> References: <%0Mag.2117$No6.46299@news.tufts.edu> Message-ID: <446be498$0$9391$c3e8da3@news.astraweb.com> John Salerno wrote: > Ok, I've tinkered with this thing for a while, and I keep fixing little > problems, but I always get a 500 Internal Server error when I go to this > site: Ok, in case anyone is curious, I figure out my problems. Let me first give you a hint: my web server is running Python 2.2.1 On to the fun: 1. cgi traceback was not being displayed because the problem was with the first import statement; i moved import cgitb above it and finally got the nice-looking traceback info 2. i was importing itertools, which of course is not standard 3. i was using the built-in set(), which is new in 2.4 4. i tried to import sets, but that was new in 2.3 So the bottom line is I'm kind of screwed until I can get 1and1 to update their Python! :) But at least I figured out some stuff. From antroy at gmail.com Wed May 17 07:15:18 2006 From: antroy at gmail.com (Ant) Date: 17 May 2006 04:15:18 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147862865.142339.117610@j55g2000cwa.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <Xns97C65986E948Dduncanbooth@127.0.0.1> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> <1147862865.142339.117610@j55g2000cwa.googlegroups.com> Message-ID: <1147864517.941435.259580@j73g2000cwa.googlegroups.com> > Not that it's relevant, but I've never actually encountered anyone who > mixed tabs and spaces.. I've lived a sheltered life I guess. It's not individuals using a mixture, but when working in a development team of some kind. Consider person A who writes a file using spaces for indent. Person B then edits that file, adding a few lines of code, indenting using tabs. It could soon get messy! From webraviteja at gmail.com Thu May 25 01:49:43 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 24 May 2006 22:49:43 -0700 Subject: IronPython 1.0 Beta 7 Released In-Reply-To: <1148532003.624344.88030@38g2000cwa.googlegroups.com> References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> <1148518396.856710.173810@g10g2000cwb.googlegroups.com> <1148532003.624344.88030@38g2000cwa.googlegroups.com> Message-ID: <1148536183.520726.289960@i39g2000cwa.googlegroups.com> Also, IronPython cannot access CPython libraries. So it cannot be used as a drop-in replacement for CPython in most non-trivial apps. Python for .NET however allows you to both use both CPython and .NET libraries. > Ironpython is not a first class .NET language. > That means that although you can write programs that run on .NET and > you have access to all its libraries, you can't write libraries that > could be consumed by other languages. I was hoping that it would eventually, like Jython by method signatures in docstrings. But if it does not, I wonder what significant benefit does it provide at all compared to Python for .NET (once the .NET 2.0 version is out, atleast). From jared at hpalace.com Sun May 21 12:34:44 2006 From: jared at hpalace.com (M Jared Finder) Date: Sun, 21 May 2006 09:34:44 -0700 Subject: Software Needs Philosophers In-Reply-To: <1148225181.251089.261160@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <1148225181.251089.261160@j55g2000cwa.googlegroups.com> Message-ID: <Q4adnUJPk5w0C-3ZnZ2dnUVZ_sidnZ2d@speakeasy.net> SamFeltus wrote: > Religious Fanaticism is a very strong in the Computer community. But, > is it really a surprise that when a bunch of hairless apes created a > new mental world, they created it with a complicated Quilt of religions > and nationalities, and many became fanatical? > > I am confidant the responces Xah will recieve will validate his > observation on religious fanaticism. It is funny, Xah always questions > people's Sacred Cow's, I have often noted that the reponces often read > like the writings of religious fanatics. As a Georgian (US), the > responces often remind me of the Dark Side (there is a Light) of the > Southern Baptist Church, translated into Computer Speak. > > Software needs philosophers is an interesting point, perhaps the most > important function of Philosophers is exposing Sacred Cows as just > Cattle. Finally, someone else who sees that Xah's posts consistently expose valid problems! (Though his solutions are usually not well thought out.) -- MJF From paolopantaleo at gmail.com Wed May 24 17:55:33 2006 From: paolopantaleo at gmail.com (Paolo Pantaleo) Date: Wed, 24 May 2006 23:55:33 +0200 Subject: Request for comment: programmer starting page (micro knowledge base) Message-ID: <83e8215e0605241455g1f5e33caue070c41f7a14a39@mail.gmail.com> I am writting down a pege with useful links for a Python programmer. That is reference, tutorials and anything that can be useful. I use it regulary when programming in Python and I can't do without it. I would be happy if you go and see that page, and tell me what you think about and suggest links to be added. The page is : http://ppp3.co.nr Thnx Paolo Pantaleo From larry.bates at websafe.com Fri May 5 13:18:53 2006 From: larry.bates at websafe.com (Larry Bates) Date: Fri, 05 May 2006 12:18:53 -0500 Subject: [ConfigParser] value with ; and the value blank In-Reply-To: <1146846701.912321.202730@u72g2000cwu.googlegroups.com> References: <1146846701.912321.202730@u72g2000cwu.googlegroups.com> Message-ID: <-9-dnXg0FLCQFMbZRVn-pQ@comcast.com> kai wrote: > Hello, > > how can I use/save/read values with ";" (start comment) and the value > blank? > When I write (set) my config file often the part behind the ";" > disappears. > e.g. > myKey = startMyValue ; endMyValue > > Thank's for your hints, Kai > No, but you can write it as: mykey=startMyValue,endMyValure or use any other separator (~,:, etc.) mykey=startMyValue~endMyValue or you could do something like: startvalue=startMyValue endvalue=endMyValue To do what you ask you would have to write something custom (not recommended unless you don't control the format of the file). -Larry Bates From aleaxit at yahoo.com Thu May 4 10:15:14 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Thu, 4 May 2006 07:15:14 -0700 Subject: Sorting a list of dictionaries by dictionary key References: <4458A61F.3010004@gmail.com> <e3a9v3$kia$1@sea.gmane.org> <mailman.5262.1146662807.27775.python-list@python.org> Message-ID: <1hesxdq.1r7mstx10ig2cxN%aleaxit@yahoo.com> Tim Chase <python.list at tim.thechases.com> wrote: > > assuming that DateTime returns something that compares correctly, you can > > do something like: > > > > def sortkey(item): > > return item.get("from_datetime") > > > > data.sort(key=sortkey) > > > > (assuming Python 2.4 or later) > > Building on Fredrik's solution, for 2.3 (or earlier?), you > can use > > data.sort(lambda a,b: cmp(a['from_datetime'], > b['from_datetime'])) ...and get a potentially very slow sort, if the list is long. Much faster: _aux = [ (d['from_datetime'], i, d) for (i, d) in enumerate(data) ] _aux.sort() data[:] = [ t[-1] for t in _aux ] Google Search for DSU or [Decorate Sort Undecorate] ... Alex From robert.kern at gmail.com Fri May 26 22:49:38 2006 From: robert.kern at gmail.com (Robert Kern) Date: Fri, 26 May 2006 21:49:38 -0500 Subject: Looking for triangulator/interpolator In-Reply-To: <127fagudgh3fa7e@corp.supernews.com> References: <127f313dbhl7gf4@corp.supernews.com> <44778e7f$1@nntp0.pdx.net> <127f61eluend535@corp.supernews.com> <127f7rrn8i2qea3@corp.supernews.com> <127fagudgh3fa7e@corp.supernews.com> Message-ID: <e58eo1$2cu$1@sea.gmane.org> Grant Edwards wrote: > I found another module that claims to do what I want > > http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/griddata.html > > But, no matter what data I pass, I get either all zeros or all > NaNs back. :/ > > I'm 0 for 3 now. I pointed you to http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data earlier. Does that not do what you want? -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From benji at benjiyork.com Fri May 5 11:31:11 2006 From: benji at benjiyork.com (Benji York) Date: Fri, 05 May 2006 11:31:11 -0400 Subject: Progamming python without a keyboard In-Reply-To: <445B4907.6010101@harvee.org> References: <mn.24387d656d1f89f2.43626@yahoo.fr.invalid> <445B4907.6010101@harvee.org> Message-ID: <445B6FBF.3070701@benjiyork.com> Eric S. Johansson wrote: > So if you want to make a serious difference in people's lives from your > keyboard, you can help out in two ways. ... Second is working with probably > myself and a couple of other folks in gnome at-spi land building a > bridge between speech recognition on Windows and complete control of the > environment on Linux. I'm interested in what you mean here. My interpretation is that you want to/are building a system to interact with a Linux desktop from a Windows box leveraging the voice recognition built into Windows. Is this right? -- Benji York From deets at nospam.web.de Wed May 3 12:27:59 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 03 May 2006 18:27:59 +0200 Subject: Strange Threads Behaviour... References: <1146672934.622365.99020@u72g2000cwu.googlegroups.com> Message-ID: <4bs411F12uj13U1@uni-berlin.de> > I have written an application which uses threads and the XMPP library - > this is a library which supports the jabber instant messaging protocol. > The application works fine when run from Idle, however I get thread > errors when I try to run it as an EXE created with Py2Exe or when it is > run within other editors such as SPE. > > I need to ship the application to end users so any pointers on thread > handling when creating shipping apps would be useful. > > For reasons of confidentiality I cannot post all the source code, > however the error log is below. > > Thanks in advance. > > Best, > > rod > > update (server adddress deleted) > Jabber Login Successful > Greg forced SASL not to be used. Auhentication fails if it is used. > Warning: unable to perform SASL auth os (serger address deleted). Old > authentication method used! > idname: > glocopex executing > Exception in thread Thread-1 (most likely raised during interpreter > shutdown): > Traceback (most recent call last): > File "C:\Python23\lib\threading.py", line 442, in __bootstrap > File "I:\My Documents\pyscripts\Newclient\newclient.py", line 368, in > run > File "I:\My Documents\pyscripts\Newclient\newclient.py", line 404, in > GoOn > File "I:\My Documents\pyscripts\Newclient\newclient.py", line 399, in > StepOn > File "C:\Python23\lib\site-packages\xmpp\dispatcher.py", line 116, in > Process > File "C:\Python23\lib\site-packages\xmpp\transports.py", line 101, in > receive > Script terminated. I got errors in this style when shutting down a multi-threaded app. Does this appear by any chance when quitting your client? Then you can ignore it. diez From liupeimail at gmail.com Sat May 6 21:24:59 2006 From: liupeimail at gmail.com (liupei) Date: 6 May 2006 18:24:59 -0700 Subject: MySQLdb problem Message-ID: <1146965099.427945.114620@i40g2000cwc.googlegroups.com> I am use mod_python3.2.8,MySQL-python-1.2.1_p2,mysql5.0.20,centOS when I run the script below(I have also saved this script in utf-8): #coding: utf-8 from MySQLdb import connect connection=connect(user='root',passwd='',host='localhost',db='test') cursor = connection.cursor() cursor.execute("INSERT INTO `fee` ( `affair` ) VALUES ('??')") #'??' is a chinese word means test it raise error: Traceback (most recent call last): File "test.py", line 8, in ? cursor.execute("INSERT INTO `fee` ( `affair` ) VALUES ('??')") File "/opt/python/lib/python2.4/site-packages/MySQLdb/cursors.py", line 146, in execute query = query.encode(charset) UnicodeDecodeError: 'ascii' codec can't decode byte 0xe6 in position 40: ordinal not in range(128) From rNOSPAMon at flownet.com Thu May 18 18:04:08 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 May 2006 15:04:08 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> Message-ID: <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> In article <mailman.5906.1147989402.27775.python-list at python.org>, Robert Kern <robert.kern at gmail.com> wrote: > Ron Garret wrote: > > > I forgot to mention: > > > >>>>sys.getdefaultencoding() > > > > 'utf-8' > > A) You shouldn't be able to do that. What can I say? I can. > B) Don't do that. OK. What should I do instead? > C) It's not relevant to the encoding of stdout which determines how unicode > strings get converted to bytes when printing them: > > >>> import sys > >>> sys.stdout.encoding > 'UTF-8' > >>> sys.getdefaultencoding() > 'ascii' > >>> print u'\xbd' > 1???2 OK, so how am I supposed to change the encoding of sys.stdout? It comes up as US-ASCII on my system. Simply setting it doesn't work: >>> import sys >>> sys.stdout.encoding='utf-8' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: readonly attribute >>> rg From nobody at 127.0.0.1 Fri May 19 18:57:29 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 19 May 2006 22:57:29 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> Message-ID: <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> akameswaran at gmail.com wrote: > But first things first... and this one I think is solvable - their has > got to be an equitable way to count how much code was written - maybe > it isn't lines maybe it is.... > ANd that's it - not can we make a qualitative > statement beyond that. But simply can we quanitfy the amount of code > in some fashion that allows a reasonable comparison? Maybe a count of identifiers and keywords. Symbols like ()[];,. don't add much beyond where to parse the code. And even though operators like +-*/^&| et al convey semantics, they need expressions to operate on, in which the identifiers are already counted. You could make a case either way but I'd leave them out for simplicity. The question is how to count explicit names like module.class.func; should that be 1 identifier or 3? Counting as 3 would reward things like "from X import *" which are generally frowned on in python while 'use MOD qw(id)' is encouraged in perl. I'm inclined to just count explicit names as 1. It's still a single object, and I'm not sure a.b.c is more work to process than just c anyway. If you don't care where c is, they're equivalent. If you do care, you've got to remember where the naked c lives, so it just shifts the work from the code to your brain. Then you've got problems with implicit variables/operations. Should perl's $_ be counted? What about python's copy-slice [:]? You can drive yourself crazy worrying about such things, so I'd just start with the simple case by ignoring them. This id-keyword count would appear to be related to how much information you must process to read through the code. Unfortunately you need a parser for each language to measure it. If anyone can provide such a beast, I'll gladly run it against my code. In the meantime, line/char counts are the best I've got. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From deets at nospam.web.de Tue May 9 05:04:55 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 May 2006 11:04:55 +0200 Subject: clear memory? how? References: <e3pjop$rqd$1@enyo.uwa.edu.au> Message-ID: <4cb49uF15811rU1@uni-berlin.de> N/A wrote: > Hi all, > I am learning Python. Just wondering how to clear saved memory in > Python? Like in Matlab I can simply use "clear all" to clear all saved > memory. You don't - python does it for you. It is called garbage collection. All you have to to is get into granny-mode(tm): forget about things. That means: once an object is not referenced by your code anymore, it will be cleaned up. For example: >>> l = range(100000) >>> del l will make python garbage collect the list referred to by l. Actually, this will work too: >>> l = range(100000) >>> l = None Because l now refers another object (None in this case), the _list_ that was refered beforehand gets freed as it's reference counter is reduced by one. Generally speaking: don't worry. HTH, Diez From sjmachin at lexicon.net Thu May 25 16:00:07 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 26 May 2006 06:00:07 +1000 Subject: how to "normalize" indentation sources In-Reply-To: <s4ldg.2178$No6.46954@news.tufts.edu> References: <PKqdndjnUPVbgOjZRVn-hA@comcast.com> <447525b7$1@news.eftel.com> <dJjdg.2177$No6.47014@news.tufts.edu> <mailman.6198.1148570351.27775.python-list@python.org> <s4ldg.2178$No6.46954@news.tufts.edu> Message-ID: <44760CC7.4040305@lexicon.net> On 26/05/2006 2:38 AM, John Salerno wrote: [snip] > > So the line below the last line of the file isn't actually considered an > empty line, even though you can move the cursor to it in a text editor? That line doesn't exist in a file *until* you (a) type something into the editor and (b) save the revised contents back to disk. > > If you have a file that has one line and it ends with a newline, at > least in my text editor the cursor then moves down to the next line, but > is this just a detail of the way the editor itself works, and nothing to > do with the file? (i.e., there is really only one line in the file, not > two?) Please consider, if the answer to your question were "no", how could anyone add lines to a file using such an editor. Why you don't fire up your Python and try something for yourself, like: print repr(open("my_one_line_file.txt".read())) ? From defcon8 at gmail.com Sat May 13 19:09:38 2006 From: defcon8 at gmail.com (defcon8 at gmail.com) Date: 13 May 2006 16:09:38 -0700 Subject: Cellular automata and image manipulation Message-ID: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> Hello. I have recently been experimenting with cellular automata and I would like to know how I could convert a 2d list of 0's and 1's into white and black squares on an image. I have tried to install matplotlib and also NumTut but both to no avail. There seem to be bugs in their installation and I have not been able to figure out how to resolve them. I would be happy for someone to suggest a library and maybe give a simple example of how to do what I want to do. From songyi012133 at gmail.com Fri May 5 21:36:37 2006 From: songyi012133 at gmail.com (hankssong) Date: 5 May 2006 18:36:37 -0700 Subject: how to construct a binary-tree using python? Message-ID: <1146879397.871842.183790@u72g2000cwu.googlegroups.com> Hi everyone, I'm wondering whether it's possible to construct a binary-tree using python. Since python don't have pointer, it can't dynamically allocate memory like C language. But some important data structures like linked list, binary-tree and hash table are closely linked with dynamic memory technology. Any help that can be provided would be greatly appreciated. Thanks in advance From http Sun May 14 04:05:41 2006 From: http (Paul Rubin) Date: 14 May 2006 01:05:41 -0700 Subject: Question regarding checksuming of a file References: <126d1u4ke4itg7f@corp.supernews.com> <roy-1E8950.21485413052006@reader1.panix.com> <126d3g8tkfovs19@corp.supernews.com> <1147593420.907522.325920@i40g2000cwc.googlegroups.com> Message-ID: <7xhd3tav56.fsf@ruckus.brouhaha.com> "Ant" <antroy at gmail.com> writes: > def getSum(self): > md5Sum = md5.new() > f = open(self.filename, 'rb') > for line in f: > md5Sum.update(line) > f.close() > return md5Sum.hexdigest() This should work, but there is one hazard if the file is very large and is not a text file. You're trying to read one line at a time from it, which means a contiguous string of characters up to a newline. Depending on the file contents, that could mean gigabytes which get read into memory. So it's best to read a fixed size amount in each operation, e.g. (untested): def getblocks(f, blocksize=1024): while True: s = f.read(blocksize) if not s: return yield s then change "for line in f" to "for line in f.getblocks()". I actually think an iterator like the above should be added to the stdlib, since the "for line in f" idiom is widely used and sometimes inadvisable, like the fixed sized buffers in those old C programs that led to buffer overflow bugs. From bencvt at gmail.com Mon May 22 18:49:46 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 22 May 2006 15:49:46 -0700 Subject: File attributes References: <1148336239.342164.285680@j73g2000cwa.googlegroups.com> <1148337788.615072.115990@y43g2000cwc.googlegroups.com> Message-ID: <1148338186.883974.302870@i39g2000cwa.googlegroups.com> Ben Cartwright wrote: > acatejr at gmail.com wrote: > > I know how to "walk" a folder/directory using Python, but I'd like to > > check the archive bit for each file. Can anyone make suggestions on > > how I might do this? Thanks. > > > Since the archive bit is Windows-specific, your first place to check is > Mark Hammond's Python for Windows Extensions (aka win32all). It's a > quick and painless install; grab it here: > http://python.net/crew/skippy/win32/ > > Once you have that installed, look in the PyWin32.chm help file for the > function calls you need. If the documentation is too sparse, check > MSDN or google it. > > For what you're trying to do: > > import win32file > import win32con > > def togglefileattribute(filename, fileattribute, value): > """Turn a specific file attribute on or off, leaving the other > attributes intact. > """ > bitvector = win32file.GetFileAttributes(filename) > if value: > bitvector |= fileattribute > else: > bitvector &= ~fileattribute > win32file.SetFileAttributes(filename, bitvector) > > # Sample usage: > togglefileattribute('foo.txt', win32con.FILE_ATTRIBUTE_ARCHIVE, True) Or to just check the value of the bit: def fileattributeisset(filename, fileattr): return bool(win32file.GetFileAttributes(filename) & fileattr) print fileattributeisset('foo.txt', win32con.FILE_ATTRIBUTE_ARCHIVE) --Ben From iddw at hotmail.com Wed May 17 15:17:04 2006 From: iddw at hotmail.com (Dave Hansen) Date: Wed, 17 May 2006 14:17:04 -0500 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> Message-ID: <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> On Wed, 17 May 2006 12:02:46 -0700 in comp.lang.python, "Carl J. Van Arsdall" <cvanarsdall at mvista.com> wrote: >Andy Sy wrote: >> Carl J. Van Arsdall wrote: >> >> >>>> Next major objection then, how can one practically use 'tabs as >>>> semantic indentation' without screwing up formatting of code like >>>> the below?? >>>> >>>> >>>> def sqlcall(): >>>> cursor.execute('select id, item, amount, field4, field5, field6'+ >>>> 'from table1 where amount>100') >>>> >>>> >>>> >>> Why couldn't you tab your third line over as close as possible to the >>> start of the quote then use a couple spaces? Then the tabs would work >>> just fine and you could still have your pretty line. >>> >> >> >> This will break if someone tries to view my code using different >> tab settings from the one I'm using >> >Uh, no it won't. It should be read in as "one tab and two spaces" >regardless of the tabstop setting. Think about it a little harder. What does that "one tab" mean? Assume the code was written by someone using 4-space tabs. To them, the code is: def sqlcall(): --->cursor.execute('select id, item, amount, field4, <etc> --->--->--->--->...'from table1 where amount>100') (where -------> represents an 4-space tab and . represents a space) Which looks fine. But if I then load the code into my editor with 3-space tabs, it looks like: def sqlcall(): -->cursor.execute('select id, item, amount, field4, <etc> -->-->-->-->...'from table1 where amount>100') Then my colleage loads it into his editor with 8-space tabs, and it looks like (assuming I didn't change it to make it look reasonable): def sqlcall(): ------->cursor.execute('select id, item, amount, field4, <etc> ------->------->------->------->...'from table1 where amount>100') In each case the second line has four TABs and three spaces. But only with the original TAB settings does it line up properly. The only solution (as posted elsewhere) is to somehow enforce tabs for indentation and spaces for spacing: def sqlcall(): --->cursor.execute('select id, item, amount, field4, <etc> --->...............'from table1 where amount>100') However, to twist an observation I've read about C++, while it's clearly possible to use TABs in a sensible manner like this, it seems that no one does. Or at least, it doesn't last much beyond the original author of the code... Regards, -=Dave -- Change is inevitable, progress is not. From johnjsal at NOSPAMgmail.com Fri May 26 11:59:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 26 May 2006 15:59:36 GMT Subject: hide python window, cont'd In-Reply-To: <mailman.6248.1148658466.27775.python-list@python.org> References: <mailman.6248.1148658466.27775.python-list@python.org> Message-ID: <IBFdg.2186$No6.47093@news.tufts.edu> Bell, Kevin wrote: > Bell, Kevin wrote: >> Great! And now that it's hiding w/ .pyw, how would I kill it if I > want? >> Just log off, or is there a better way? >> >> Kevin >> >> > >>> JOE WROTE: >>> Close it in the Task Manager? > > > I don't see it in the task manager. > > You might have to look at running processes instead of applications. See if any of the names looks like your program. From tbrkic at yahoo.com Thu May 18 05:52:15 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 02:52:15 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <4d2pr4F18giccU1@uni-berlin.de> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <4d1l5nF188kcuU1@uni-berlin.de> <1147934663.306885.220860@g10g2000cwb.googlegroups.com> <4d2pr4F18giccU1@uni-berlin.de> Message-ID: <1147945935.542804.13490@38g2000cwa.googlegroups.com> > You can put any python expression in there, and in the Node class you can do > what you want. But the main advantage is any python code not only expressions. In addition to that you get nice flow style. Can set variables which you later use as want. > Seems that you are after a templating-system. Well, there are plenty of them > available, including yours. A preprocessor is nothing but a template system > - see TurboGears-utilized KID (http://kid.lesscode.org/) for example, it > generates python files. And way more readable, because you are working in > the domain of your application (HTML) instead of some crude syntax that is > neither fish or flesh. What I propose is for all data that is hierarcical. Not only HTML. I dont use it for creating html. Templating systems have the drawback IMO that the more code you get the more undreadable it gets. If the code part is small they are very nice. The other part is that indentation, syntax highlighting and so on works not so well when working with such code. I would translate your example to the below. Which I think is much more readable, since you see the python code flow much easier. I realised that you realy should do Element("html") and not html("html") when adding nodes in my syntax and using elementtree. from urllib import urlopen from elementtree.ElementTree import parse, tostring feed = 'http://naeblis.cx/rtomayko/weblog/index.atom' root = parse(urlopen(feed)).getroot() ns = '{http://purl.org/atom/ns#}' title = root.findtext(ns + 'title') root = ET.Element("html") *+* root: *+* Element("head"): *+* Element("title") *+* Element("body"): *=* bgcolor = "blue" *=* text = "yellow" *+* Element("table"): *=* cellpadding="4" *=* cellspacing="4" for i, entry in enumerate(root): *+* Element("tr"): if entry.tag==ns + 'entry': *+* Element("td"): *=* bgcolor = ('white', 'yellow')[i % 2] *+* Element("a"): *=* href = entry.find(ns + 'link').attrib['href'] *=* text = "entry.findtext(ns + 'title')" With the above you can use your favorite editor to do the coding and get indentation, syntax highlightning and so on. Which I find can be quite a burden with a templating system especially the more code that is in there. It is also easier to debug in comparison when using a templating system. From me+python at modelnine.org Thu May 18 17:18:19 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 18 May 2006 23:18:19 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <446cdd6b$0$7043$636a55ce@news.free.fr> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147980462.464427.323030@u72g2000cwu.googlegroups.com> <446cdd6b$0$7043$636a55ce@news.free.fr> Message-ID: <200605182318.19314.me+python@modelnine.org> Am Freitag 19 Mai 2006 02:08 schrieb Bruno Desthuilliers: > We'd need the make: statement, but the BDFL has pronounced against. > > I'm still -2 against your proposition, but it could make a good use case > for the make statement. I gave an eye at the new 'with' statement, but > I'm not sure it could be used to solve this. Couldn't. "with" is a blatant misnomer for that it's functionality is (basically a "protected" generator), at least if you know what with does in VB (god, am I really comparing VB with Python? And I've never even programmed in the former...) --- Heiko. From birchb at ozemail.com.au Tue May 16 00:42:11 2006 From: birchb at ozemail.com.au (birchb at ozemail.com.au) Date: 15 May 2006 21:42:11 -0700 Subject: Argument Decorators Enhancement? Message-ID: <1147754531.481364.82940@j33g2000cwa.googlegroups.com> Guido has proposed a syntax for type annotations in Python-3000. Example: def foo(x: t1, y: t2) -> t3: ...body... http://www.artima.com/weblogs/viewpost.jsp?thread=87182 The types are dynamic and there is significant execution of code prior to the function body being called. Which tends to make the above closer to a decorator than a static type declaration. That being so, it occurred to me that perhaps an argument decorator would be more general and perhaps less restrictive. The example using decorators: def foo(@T1 x, @t2 y) @ t3: ...body... The compiler would do something like this: def foo__(x, y): # original function ...body... def foo(x, y): # wrapper function x = T1.__decarg__(foo_, x) y = t2.__decarg__(foo_, y) r = foo__(x, y) return t3.__decreturn___(foo__, r) More examples: def func(@between(1,400) x) @bool : # between checks input range def func(@NotNone x): # x must be a real object def func(@long x) @coerce(float): # coerce forces type conversion def func(@sequence s, @function fn) @sequence: # more abstract types To someone used to reading decorators, the @ character is a flag that some kind of dynamic magic is being run. So IMHO using @ here too is consistent with its existing usage. Argument decorators would be an object (not a function) with methods corresponding to their usage: class T1(object): def __decarg__(self, function, arg): # returns arg def __decreturn__(self, function, arg): # returns arg This will allow existing types to be used if they implement these methods: def bar(@int x, @float y) @float : ...body... Because this syntax is just a decorator, you could use or abuse it as you wished. So you could define and use your own type-checking classes and semantics: def bar(@StrictlyInt x, @DuckCompatibleSequence seq) : ...body... Since the decorator is an *object*, not a function, we could add other methods for use by IDEs for intellisense etc. Any views on this? Something to put forward to the python-3000 list maybe? From niemand.leermann at thomas-guettler.de Wed May 24 07:59:47 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Wed, 24 May 2006 13:59:47 +0200 Subject: Best way to handle exceptions with try/finally References: <mailman.6122.1148413632.27775.python-list@python.org> Message-ID: <pan.2006.05.24.11.59.47.24496@thomas-guettler.de> Am Tue, 23 May 2006 12:47:05 -0700 schrieb Carl J. Van Arsdall: > Hey python people, > > I'm interested in using the try/finally clause to ensure graceful > cleanup regardless of how a block of code exits. However, I still am > interested in capturing the exception. You can reraise the exception: try: something() except: cleanup() raise # reraise the caught exception -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From sybrenUSE at YOURthirdtower.com.imagination Fri May 12 11:59:48 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 12 May 2006 17:59:48 +0200 Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> <44644a76$0$290$626a54ce@news.free.fr> <4464959f$1$13578$5402220f@news.sunrise.ch> Message-ID: <slrne69c7k.l3g.sybrenUSE@schuimige.stuvel.eu> Martin Blume enlightened us with: > Another question: Isn't decorating / wrapping usually done at > runtime, so that the @deco notation is pretty useless (because you'd > have to change the original code)? Please explain why that would make the @deco notation pretty useless. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From vbgunz at gmail.com Thu May 25 19:38:33 2006 From: vbgunz at gmail.com (vbgunz) Date: 25 May 2006 16:38:33 -0700 Subject: how to clear up a List in python? In-Reply-To: <mailman.6213.1148598607.27775.python-list@python.org> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> Message-ID: <1148600313.776440.61710@i39g2000cwa.googlegroups.com> I will not try and stop helping others because you don't like my answers. I found a perfectly good way how not to do something that wasn't exactly wrong anyway. if you can take another persons honest attempt to help someone and twist it into something it is not, I can only suggest you look in the mirror and only if you're truly perfect you continue your banter. by the way, I am not here to promote Python. but if this is of your concern, perhaps maybe you should rethink how you respond in kind towards post you do not exactly agree with. Others are reading this and it might not come off as promotional material. Also, if you're having a bad day, take a rest and relax. You just might deserve it. From ask at me Tue May 9 19:27:32 2006 From: ask at me (AndyL) Date: Tue, 09 May 2006 19:27:32 -0400 Subject: __all__ does not work? Message-ID: <j9ydnXEhmIkbrPzZnZ2dnUVZ_sadnZ2d@comcast.com> This a mm.py module: _all__=('getsize1',) size=85 def getsize1(): return size def getsize2(): return 2*size I do not know why but getsize2 is not kept priviate? $ python Python 2.4.2 (#67, Sep 28 2005, 12:41:11) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>>>>> import mm >>>>>> mm.getsize2() 170 Any ideas? A. From robert.kern at gmail.com Thu May 25 13:17:38 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 25 May 2006 12:17:38 -0500 Subject: script vs inneractive In-Reply-To: <roob729shic7rufbd6hebmkor5siiu334o@4ax.com> References: <1148574517.158866.157280@38g2000cwa.googlegroups.com> <roob729shic7rufbd6hebmkor5siiu334o@4ax.com> Message-ID: <e54orf$b3s$1@sea.gmane.org> Dennis Lee Bieber wrote: > If that "return 1" is the last line in the program, at the most it > will be treated as a return code to the OS signaling that the program > succeeded or failed. I'm not really sure how Python handles a return > from main program. It's a syntax error. -- 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 Sun May 14 18:56:50 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 00:56:50 +0200 Subject: continue out of a loop in pdb In-Reply-To: <87ac9kwdl8.fsf@localhost.localdomain> References: <87mzdkwke3.fsf@localhost.localdomain> <PIK9g.28632$CH2.27494@tornado.texas.rr.com> <87ac9kwdl8.fsf@localhost.localdomain> Message-ID: <4cpqtcF16e1gaU1@uni-berlin.de> > the code works with no problem, I am playing around with the pdb, i.e > > **************** > from pdb import * > set_trace() > > for i in range(1,500000): > print i > print "tired of this" > print "I am out" > **************** > > fred at debian:~/python/practic$ python practic.py >> /home/fred/python/practic/practic.py(4)?() > -> for i in range(1,500000): > (Pdb) n >> /home/fred/python/practic/practic.py(5)?() > -> print i > (Pdb) n > 1 >> /home/fred/python/practic/practic.py(4)?() > -> for i in range(1,500000): > (Pdb) b 6 > Breakpoint 1 at /home/fred/python/practic/practic.py:6 > (Pdb) c >> /home/fred/python/practic/practic.py(5)?() > -> print i <<<< I expected (print "tired of this") > (Pdb) In TFM it says that set_trace() puts a breakpoint to the current frame. I admit that I also wouldn't read that as "each and every instruction in this very frame", but that is what essentially happens. I think the docs could need some enhancement here. Try debugging a called function, there things will work as expected. Diez From cvanarsdall at mvista.com Wed May 17 18:16:19 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 17 May 2006 15:16:19 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <1147899701.004246.294580@g10g2000cwb.googlegroups.com> References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> Message-ID: <446BA0B3.40706@mvista.com> glomde wrote: >> > > But If you work in a team it is kind of hard to make sure that > everybody use tabs and not spaces. And it is not very easy to spot > either. > The converse can also be said, "it's difficult to make sure everyone uses spaces and not tabs". I think we've just about beat this discussion to death... nice work everyone! -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From johnjsal at NOSPAMgmail.com Mon May 15 16:10:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 20:10:58 GMT Subject: common practice for creating utility functions? In-Reply-To: <4468d9d5$1@nntp0.pdx.net> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <Uq4ag.2096$No6.46172@news.tufts.edu> <Az4ag.2098$No6.46267@news.tufts.edu> <4468d9d5$1@nntp0.pdx.net> Message-ID: <mf5ag.2099$No6.46182@news.tufts.edu> Scott David Daniels wrote: > John Salerno wrote: >>> How can I create two separate conditions in a for loop? >> ... I tried this: >> >> punc_space = string.punctuation + string.whitespace >> for char in punc_space: > > That's probably best. If the sources are not so simple, you could use: > > import itertools > > for char in itertools.chain(onesource, anothersource, yetanother): > ... > > --Scott David Daniels > scott.daniels at acm.org Cool. Iterators are fun! :) From bdesth.quelquechose at free.quelquepart.fr Sat May 13 07:54:04 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 13 May 2006 13:54:04 +0200 Subject: compiling module from string and put into namespace In-Reply-To: <1147474282.618115.60590@u72g2000cwu.googlegroups.com> References: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> <4464754a$0$306$626a54ce@news.free.fr> <1147474282.618115.60590@u72g2000cwu.googlegroups.com> Message-ID: <446599de$0$5314$626a54ce@news.free.fr> glomde a ?crit : > Tanks but that isn't what I am looking for. > I really want a function that you can call and imports > the module into the calling functions namespace. Please read the documentation of the __import__() *function*. (notice the double leading and ending underscores and the parenthesis). > I dont want the caller to call import but a function. Please read the documentation of the __import__() *function*. (notice the double leading and ending underscores and the parenthesis). From heikki at osafoundation.org Tue May 23 14:02:14 2006 From: heikki at osafoundation.org (heikki at osafoundation.org) Date: 23 May 2006 11:02:14 -0700 Subject: PHP's openssl_sign() using M2Crypto? In-Reply-To: <slrne74b18.92s.usenet2@localhost.localdomain> References: <slrne6v5vk.f2c.usenet2@localhost.localdomain> <1148319025.745324.171890@i40g2000cwc.googlegroups.com> <slrne74b18.92s.usenet2@localhost.localdomain> Message-ID: <1148407334.274505.314250@i39g2000cwa.googlegroups.com> That is really strange, because PKey has had sign_init method since 2004. That code works for me (just tested). What version of M2Crypto are you using? I'd advice you upgrade to 0.15 if possible. See http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto -- Heikki Toivonen From kentilton at gmail.com Wed May 10 11:22:02 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 10 May 2006 11:22:02 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <4461b9d5_3@news.bluewin.ch> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> <yfshd41yeaj.fsf@oc.ex.ac.uk> <O7A7g.59$sC4.54@fe09.lga> <1147068524.966560.52210@y43g2000cwc.googlegroups.com> <0UG7g.8$u17.6@fe08.lga> <4461b9d5_3@news.bluewin.ch> Message-ID: <vyn8g.2$%L2.1@fe12.lga> Boris Borcic wrote: > Ken Tilton wrote: > >> "Now if you are like most people, you think that means X. It does not." > > > As far as natural language and understanding are concerned, "to mean" > means conformity to what most people understand, Humpty Dumpties > notwithstanding. Nonsense. You are confusing that quality of natural language with most people's quality of being sloppy readers, or in your case, a sloppy thinker. Misapplying an analogy is not a question of usage -- when I said spreadsheet and they thought of spreadsheets, so far so good, right? -- it just sloppiness and laziness. I do it, too, all the time. :) Life is too short, we get by precisely by using partial information. You remind me of American educators recent (past several decades, that is) history of apologizing for asking students to work and softening the curriculum until they all get A's. Here is another analogy. Sometimes people hit the gas and think they hit the brake pedal. They crash around a parking lot pushing the gas pedal down harder and harder. Did they take out the brake pedal to avoid that confusion? No, they put an interlock between the brake and the ignition key. Same thing. :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From sjmachin at lexicon.net Sun May 21 03:40:32 2006 From: sjmachin at lexicon.net (John Machin) Date: 21 May 2006 00:40:32 -0700 Subject: Python update trouble (2.3 to 2.4): x<<y References: <cef393a0512232219w6fab1b09tfb10debd31fd12b7@mail.gmail.com> <mailman.6016.1148188117.27775.python-list@python.org> Message-ID: <1148197232.312628.255650@i39g2000cwa.googlegroups.com> For a start, >>> 22002496167782427386022437441624938050682666541682 & 0xffffffffL 67560050L >>> so you could just do that at the end. But you don't really want to be carrying all that rubbish around, getting longer and longer each time around the loop. And let's further the translation into Python by getting rid of the xrange gizmoid and a few other undesirables: # tested on your 1 test value def CalcCRC16v2(astr): # don't shadow str() # global gCRC16Table # don't need this crc = 0xFFFFL # start as a long for c in astr: crc = gCRC16Table[((crc >> 8) & 255)] ^ ((crc & 0xFFFFFF) << 8) ^ ord(c) return crc That should get you going. Although the whole calculation will be done with longs instead of ints, the longs will never exceed 32 bits so it shouldn't be too slow. HTH, John From sigzero at gmail.com Thu May 11 21:31:21 2006 From: sigzero at gmail.com (Robert Hicks) Date: 11 May 2006 18:31:21 -0700 Subject: which windows python to use? In-Reply-To: <mailman.5589.1147359382.27775.python-list@python.org> References: <mailman.5589.1147359382.27775.python-list@python.org> Message-ID: <1147397481.679424.87460@v46g2000cwv.googlegroups.com> I tend to do ActivePython because the OSX version seems to come out a bit quicker. Although that might change in the future. Robert From NA at NA.com Tue May 9 02:20:27 2006 From: NA at NA.com (N/A) Date: Tue, 09 May 2006 14:20:27 +0800 Subject: Import data from Excel Message-ID: <e3pcbc$jsf$1@enyo.uwa.edu.au> Hi, Is it possible to import data from Excel for doing numerical analysis in Python? If so how? Thank u! From randomtalk at gmail.com Mon May 1 00:52:48 2006 From: randomtalk at gmail.com (randomtalk at gmail.com) Date: 30 Apr 2006 21:52:48 -0700 Subject: returning none when it should be returning a list? Message-ID: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> hello, i have another problem i feel that i have to be missing something.. Basically, i've written a recursive function to find all the prime up to a number (lim).. here is the function: The function basically takes in a list of all the prime number found, it takes the next number to be tested for (next) and the limit it will go up to. It divide next by the list of previous prime numbers if next is not bigger than lim, count up all the times where it's not evenly divdided, if the result is equal the length of prime number, then we have another prime number, lather rinse and repeat :) def findPrime(seed, next, lim): print("seed: " + str(seed) + " next: " + str(next) + " lim: " + str(lim)) print(seed) if(next >= lim): print(seed) return seed else: count = 0; for num in seed: modu = math.modf(float(next)/float(num)); if(modu[0] > 0): count += 1 if(count == len(seed)): seed.append(next) findPrime(seed, next+2, lim) else: findPrime(seed, next+2, lim) As you can probably see, i've printed the value of seed up until the point where i'm returning the seed, however, the function still returns None.. From fredrik at pythonware.com Fri May 19 02:20:59 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 08:20:59 +0200 Subject: Which is More Efficient? In-Reply-To: <1147991742.990761.144730@j73g2000cwa.googlegroups.com> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> <1147990753.406649.80150@y43g2000cwc.googlegroups.com> <mailman.5912.1147991444.27775.python-list@python.org> <1147991742.990761.144730@j73g2000cwa.googlegroups.com> Message-ID: <e4jo4b$20t$1@sea.gmane.org> Dustan wrote: > Obviously it takes a geek to know you have to time it, as opposed to > any other task you could be talking about. wasn't the original question "my program uses a lot of CPU, and I want to make it more efficient" ? what does "a lot of CPU" and "more efficient" mean to you, and how do you know that your program uses "a lot of CPU" ? </F> From kylotan at gmail.com Tue May 2 10:48:03 2006 From: kylotan at gmail.com (Ben Sizer) Date: 2 May 2006 07:48:03 -0700 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> Message-ID: <1146581282.876190.87390@j33g2000cwa.googlegroups.com> tsaar2003 at yahoo.com wrote: > To begin with I'd like to apologize that I am not very experienced > Python programmer so please forgive me if the following text does not > make any sense. > > I have been missing constants in Python language. There are some > workarounds available, for example the const-module. To me, this looks > quite cumbersome and very unintuitive. For the interpreter, in the > efficiency-wise, I just cannot tell. The question is, why have you been missing them? Constants serve a variety of purposes in other languages, some of which might not be worthwhile in Python. There was a thread about 'symbols' a while back which covers many of the uses of constants. -- Ben Sizer From luis at geodynamics.org Fri May 26 06:53:41 2006 From: luis at geodynamics.org (Luis Armendariz) Date: Fri, 26 May 2006 03:53:41 -0700 Subject: how to clear up a List in python? In-Reply-To: <1148639516.244264.37500@i40g2000cwc.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <1148612582.510390.48040@i39g2000cwa.googlegroups.com> <mailman.6227.1148638689.27775.python-list@python.org> <1148639516.244264.37500@i40g2000cwc.googlegroups.com> Message-ID: <4476DE35.2050506@geodynamics.org> vbgunz wrote: > Steve, I have no qualm with Fredrik over this '''if you don't know how > to do things, you don't need to post.''' but this ''' if you know why > this is about the dumbest way to do what you're doing, and you're > posted this on purpose, you really need to grow up.'''. Well, given that you did post it on purpose and had no "intent to mess anyone up over it", it is clear that the antecedent in Fredrik's if-statement is not satisfied and therefore your mind should've skipped the consequent statement when reading his response. Why get so upset about something that didn't even apply to you? :-) -Luis From manojk at sasken.com Mon May 22 00:21:39 2006 From: manojk at sasken.com (Manoj Kumar P) Date: Mon, 22 May 2006 09:51:39 +0530 Subject: Web based application in python Message-ID: <BHEEKBFODALGBHHKCOFFEEBGCGAA.manojk@sasken.com> Hi, I would like to know whether it is possible to develop web based application using Python. If yes, what are the challenges or areas I've to concentrate. How would be the performance, handling hits, scalability etc? What are the pros and cons of using python in place of JAVA or J2EE? Thank You, -Manoj- "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" SASKEN BUSINESS DISCLAIMER This message may contain confidential, proprietary or legally Privileged information. In case you are not the original intended Recipient of the message, you must not, directly or indirectly, use, Disclose, distribute, print, or copy any part of this message and you are requested to delete it and inform the sender. Any views expressed in this message are those of the individual sender unless otherwise stated. Nothing contained in this message shall be construed as an offer or acceptance of any offer by Sasken Communication Technologies Limited ("Sasken") unless sent with that express intent and with due authority of Sasken. Sasken has taken enough precautions to prevent the spread of viruses. However the company accepts no liability for any damage caused by any virus transmitted by this email From blair.bethwaite at gmail.com Tue May 9 04:30:58 2006 From: blair.bethwaite at gmail.com (blair.bethwaite at gmail.com) Date: 9 May 2006 01:30:58 -0700 Subject: Enumerating Regular Expressions In-Reply-To: <IHX7g.55413$hD6.14115@fe25.usenetserver.com> References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> <IHX7g.55413$hD6.14115@fe25.usenetserver.com> Message-ID: <1147163458.940646.303270@i40g2000cwc.googlegroups.com> Dale Strickland-Clark wrote: > Any regular expression that has an asterisk in it has an infinite number of > possible matches. > > If it has two asterisks, that's an infinite number squared and that's a > really big number. > > You wouldn't want to print them out. We've been over this already. Why are people getting stuck on infinite regular languages? I've made it quite clear that I'm only really interested in doing this for finite languages, but that shouldn't matter anyway. Maybe I should phrase it differently; I want a tool that can enumerate a regex, with support for generating each string described by the regex in some predefined order. So something like: # pattern is the regex representing language L reg_lang_gen = re.compile('pattern').enumerator() while len(s) < n: s = reg_lang_gen.next() # get next string in L ... It's easy to imagine a problem where you'd want to enumerate a regex that represents an infinite regular language. E.g. a particularly dumb bruteforce password cracker, you might want to keep generating strings from the language of choice until you find one that matches your encrpyted version, naturally you might want to stop if you hadn't found it within 10 characters or so. Cheers, -B From 63q2o4i02 at sneakemail.com Mon May 15 22:06:18 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 15 May 2006 19:06:18 -0700 Subject: Why does stack.inspect take so long? Message-ID: <1147745178.664795.326020@v46g2000cwv.googlegroups.com> Hi, I've written a top-down recursive decent parser for SPICE circuit descriptions. For debugging purposes, I wanted each production rule/function to know what its own name was, so at the beginning of each rule/function, I make a call to inspect.stack()[0][3] (I think...) and that fetches the name from someplace. However, with a bunch of test text input, this takes ~10 seconds to run. When I comment out the inspect.stack() function from each production/function, the program speeds up to 0.04s, or 250x !! I loaded up the profiler to see what was there, and although I don't understand the output entirely, it looks like the stack frame functions are used in disproportionately large amounts compared to other often-used functions. This is a *recursive* parser, so it's being called a lot even for simple things. I'm wondering still why there is a 250x speed up when I comment it out. Any clues? thanks ms From sjmachin at lexicon.net Fri May 12 21:57:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 May 2006 11:57:16 +1000 Subject: getting rid of pass In-Reply-To: <4ckrmbF16kr2bU1@news.dfncis.de> References: <4ckrmbF16kr2bU1@news.dfncis.de> Message-ID: <44653CFC.8010504@lexicon.net> On 13/05/2006 11:40 AM, David Murmann wrote: > Hi all! > > i just had this crazy idea: You said it. > late-in-the-night idea. You said it again. > > what do you people think? I agree with you. From paul at boddie.org.uk Thu May 18 12:47:58 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 18 May 2006 09:47:58 -0700 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5872.1147945818.27775.python-list@python.org> <1147961360.404525.203520@j55g2000cwa.googlegroups.com> Message-ID: <1147970878.626936.102900@i39g2000cwa.googlegroups.com> SamFeltus wrote: > I guess there isn't much to understand. If you are satisfied with a > text based, static image web, that is light on artistic possabilities, > all that HTML stuff is acceptable. Perhaps the HTML/JS group will even > get off their rear ends and bring some decent cross platform graphics > capabilities to the web one decade? Perhaps even bring some 90's style > graphics to the browser one decade? Well, various browsers do support SVG to differing extents, and some of the best graphical systems of the 1990s were highly oriented around vector graphics. Not that SVG is necessarily ready or suitable for every kind of application, but it's probably the best hope for a display technology that fits in with the general Web conceptual model, unlike the messing around having canvas elements just so one can program applet-like stuff in JavaScript, ultimately leading up to the day when someone writes a Web browser to run in a canvas element. But as for Flash: even if one suppresses the legitimate sentiment that Flash is a "dirty", proprietary technology originating from a mindset that can best be described as "we don't get this Web thing - let's just dump some multimedia gadget into a Web page", there's almost nothing as annoying on the Web as going to a site laden with Flash adverts, having the browser stop in its tracks (like Michael Schumacher turning the corner to find the track drenched in treacle), in order to fire up the dancing, audio-infused animations of meaninglessness, sometimes bringing the browser itself down with a misfiring interaction through an interface designed for Netscape Communicator. I haven't set up Flash on my computer - not even the open source, reverse-engineered implementations of the technology - despite the increased obsession with various services that want you to run Flash to show movie clips instead of just providing standard video format files, for example. If I visit a site that just has an empty page, because the "user experience" is just one big Flash applet (usually giving textual information anyway), then as far as I'm concerned, they might as well have a big sign saying "we don't get the Web". > WC3 at Work - Beware Falling Luddites I'm not saying that the W3C have moved swiftly and decisively to roll out wonderful new technologies on a timely basis - perhaps because the corporate posturing that forms part of any such standardisation initiatives (possibly involving the beloved creators of Flash, whoever owns them now) makes it fairly difficult to do so - but you should at least read up a bit more before coming out with such nonsense. Paul From johnjsal at NOSPAMgmail.com Mon May 8 15:18:50 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 19:18:50 GMT Subject: utility functions within a class? In-Reply-To: <98uu52hiic72dtt9ibu0e7anfgndv6o8qb@4ax.com> References: <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> <USH7g.2052$No6.45672@news.tufts.edu> <SdI7g.2055$No6.45780@news.tufts.edu> <98uu52hiic72dtt9ibu0e7anfgndv6o8qb@4ax.com> Message-ID: <uQM7g.2060$No6.45697@news.tufts.edu> Dennis Lee Bieber wrote: > tOn Mon, 08 May 2006 14:04:34 GMT, John Salerno > <johnjsal at NOSPAMgmail.com> declaimed the following in comp.lang.python: > >> I tried the underscore method, but I was still able to call it as a >> regular instance method in the interpreter. Is that what's supposed to >> happen? > > Single underscores are a convention/signal to the programmer that > "this method/attribute" is considered "private" and should only be used > by other methods within the class that defined it. The language does no > enforcement of usage. For example: I see. But isn't there something about a single leading underscore that doesn't import when you use from X import *? Or am I thinking of something else? Is that also the double underscore? From spamspam at spam.eggs Tue May 9 11:48:41 2006 From: spamspam at spam.eggs (Ben C) Date: 9 May 2006 15:48:41 GMT Subject: do "some action" once a minute References: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> Message-ID: <slrne61eko.e9e.spamspam@bowser.marioworld> On 2006-05-09, Petr Jakes <petr at tpc.cz> wrote: > I would like to do "some action" once a minute. You can try the sched module (import sched). You give it a time at which to call a callback. Then in the callback you can reset the "alarm" for a minute later, using enterabs. If the task might take longer than a minute, it just means you'll be setting an alarm for a time in the past, but it should still get called. But there is another problem, which is that the queue will presumably get very big over time, so you'll need to clear it out now and again with empty()... which means keeping track of the event objects yourself, which is annoying. From pjm at spe.com Sun May 7 05:59:04 2006 From: pjm at spe.com (Patrick May) Date: Sun, 07 May 2006 10:59:04 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> Message-ID: <m2iroiupef.fsf@Dagney.local> aleaxit at yahoo.com (Alex Martelli) writes: > In my opinion (and that of several others), the best way for Python to > grow in this regard would be to _lose_ lambda altogether, since named > functions are preferable Why? I find the ability to create unnamed functions on the fly to be a significant benefit when coding in Common Lisp. Regards, Patrick ------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm at spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML) From fredrik at pythonware.com Thu May 25 17:35:28 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 May 2006 23:35:28 +0200 Subject: Problem with itertools.groupby. In-Reply-To: <1148591325.875006.246120@j55g2000cwa.googlegroups.com> References: <1148591325.875006.246120@j55g2000cwa.googlegroups.com> Message-ID: <e557ur$u1$3@sea.gmane.org> trebucket at gmail.com wrote: > What am I doing wrong here? > >>>> import operator >>>> import itertools >>>> vals = [(1, 11), (2, 12), (3, 13), (4, 14), (5, 15), > ... (1, 16), (2, 17), (3, 18), (4, 19), (5, 20)] >>>> for k, g in itertools.groupby(iter(vals), operator.itemgetter(0)): > ... print k, [i for i in g] > ... > 1 [(1, 11)] > 2 [(2, 12)] > 3 [(3, 13)] > 4 [(4, 14)] > 5 [(5, 15)] > 1 [(1, 16)] > 2 [(2, 17)] > 3 [(3, 18)] > 4 [(4, 19)] > 5 [(5, 20)] > > What I want is tuples starting with identical numbers to be grouped. I > cannot figure out why this is not working. If anyone has any insights, > I would appreciate it. itertools only looks for changes to the key value (the one returned by operator.itemgetter(0) in your case); it doesn't sort the list for you. this should work: for k, g in itertools.groupby(sorted(vals), operator.itemgetter(0)): print k, [i for i in g] </F> From tismer at stackless.com Mon May 15 09:53:12 2006 From: tismer at stackless.com (Christian Tismer) Date: Mon, 15 May 2006 15:53:12 +0200 Subject: Iterating generator from C In-Reply-To: <op.s9ic3nhpplgmb3@localhost> References: <op.s9ic3nhpplgmb3@localhost> Message-ID: <446887C8.4070705@stackless.com> Sven Suursoho wrote: > Hi, > > > I am working on project that has embedded python interpreter to run > user-specified python procedures. Those procedures might return any > iterable object with set of result data -- basically everything for which > iter() returns valid object (list, tuple, dict, iterator etc) > > It works ok, except generator under Python 2.4 with debugging enabled (see > http://sourceforge.net/tracker/index.php?func=detail&aid=1483133&group_id=5470&atid=105470). > > Is there any way to rewrite following program to handle returned generator > without hitting this bug? I found this bug as well, and I think the fix should be back-ported. This problem can only show up when you are comiling a C extension, anyway. Why don't you just apply the fix and compile your own? It is just a wrong assertion, anyway. ciao - chris -- Christian Tismer :^) <mailto:tismer at stackless.com> tismerysoft GmbH : Have a break! Take a ride on Python's Johannes-Niemeyer-Weg 9A : *Starship* http://starship.python.net/ 14109 Berlin : PGP key -> http://wwwkeys.pgp.net/ work +49 30 802 86 56 mobile +49 173 24 18 776 fax +49 30 80 90 57 05 PGP 0x57F3BF04 9064 F4E1 D754 C2FF 1619 305B C09C 5A3B 57F3 BF04 whom do you want to sponsor today? http://www.stackless.com/ From jack2004fb at 126.com Tue May 30 18:29:35 2006 From: jack2004fb at 126.com (jack2004fb at 126.com) Date: 30 May 2006 15:29:35 -0700 Subject: TIming In-Reply-To: <447cae5a$1@nntp0.pdx.net> References: <pan.2006.05.30.01.24.04.677340@none.none> <ecin725eh7mk1teolpfi2ulj349ogptdir@4ax.com> <pan.2006.05.30.05.23.09.936650@none.none> <mailman.6326.1148969845.27775.python-list@python.org> <pan.2006.05.30.19.50.38.152274@none.none> <447cae5a$1@nntp0.pdx.net> Message-ID: <1149028175.563551.164880@38g2000cwa.googlegroups.com> You can try this EnergyKey http://www30.webSamba.com/SmartStudio This may be help you. Now I always use EnergyKey, it helps me so much in my work. From deets at nospam.web.de Tue May 2 13:08:01 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 02 May 2006 19:08:01 +0200 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> Message-ID: <4bphvsF12acj1U1@uni-berlin.de> John Salerno wrote: > Is there a way to assign multiple variables to the same value, but so > that an identity test still evaluates to False? > > e.g.: > > >>> w = x = y = z = False > >>> w > False > >>> x > False > >>> w == x > True > >>> w is x > True # not sure if this is harmful > > The first line above is the only way I know to do it, but it seems to > necessarily lead to the true identity test. Yes, and there is no way around that - given that python has not an overloadable assignment operator as e.g. C++ offers (praise the BDFL!). The semantics of what looks like assignment in python is "I've got a fancy object somewhere, and now I want to be able to refer to it by that nice name here". Actually things are somewhat more complicated in case of list/dictionary element assignment, but for your case that is irrelevant. Besides, depending on what you assign (e.g. integers, as well as the boolean constants I guess) you might not even have the choice to guarantee how the identity test results anyway. Consider this: >>> a = 1000000 >>> b = 1000000 >>> a is b False >>> a = 100 >>> b = 100 >>> a is b False >>> a = 10 >>> b = 10 >>> a is b True >>> I can't imagine what you're actually after here, but assuming that you really need this and that we're talking "real" objects here, sequence unpacking and assignment might come handy here, together with a small list-comp: a, b, c = [copy.copy(o) for i in xrange(3)] Diez From onurb at xiludom.gro Mon May 15 10:21:20 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 15 May 2006 16:21:20 +0200 Subject: Web development with python. In-Reply-To: <1147699600.770756.123120@v46g2000cwv.googlegroups.com> References: <1147699600.770756.123120@v46g2000cwv.googlegroups.com> Message-ID: <44688ec6$0$6931$626a54ce@news.free.fr> j.paston.cooper at gmail.com wrote: > Is Plone analoguous to ASP.NET? Certainly not. > Is it a python web developing platform? No, it's a CMS. FWIW, it's written in bold on the project's home page: """ Plone: A user-friendly and powerful open source Content Management System """ (http://www.plone.org) FWIW, it's based on Zope, which is a Python-based web application server > I am confused on what Turbogears is aswell A Python web MVC framework. > because of the lack of > documentation for it. I think there's at least enough informations on the turbogears website to understand that it's a framework for doing web applications : """ TurboGears is the rapid web development megaframework """ (http://www.turbogears.org/index.html) """ Create great web apps faster """ (http://www.turbogears.org/about/index.html) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From onurb at xiludom.gro Mon May 15 04:31:00 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 15 May 2006 10:31:00 +0200 Subject: retain values between fun calls In-Reply-To: <87d5ehh6z6.fsf@localhost.localdomain> References: <87d5ehh6z6.fsf@localhost.localdomain> Message-ID: <44683caa$0$7637$626a54ce@news.free.fr> Gary Wessle wrote: > Hi > > the second argument in the functions below suppose to retain its value > between function calls, the first does, the second does not and I > would like to know why it doesn't? Fisrt thing to remember is that function's default args are eval'd only once - when the def block is eval'd, which is usually at import time. > # it does > def f(a, L=[]): > L.append(a) Here, you are modifying the (list) object bound to local name L. > return L > print f('a') > print f('b') > > > # it does not > def f(a, b=1): > b = a + b And here, you are *rebinding* the local name b to another object. Understand that modifying an object in-place and rebinding a name are two really different operations... > return b > print f(1) > print f(2) > and how to make it so it does? The Q&D solution is to wrap : def f(a, b = [1]) b[0] = b[0] + a return b[0] But this is really a hack - it's ok for a throw-away script, but may not be the best thing to do in a more serious piece of software. The clean solution to maintain state between calls is to use a custom class - hopefully, Python is OO enough to let you write your own callables: class MyFunc(object): def __init__(self, initstate=1): self._state = default def __call__(self, a): self._state += a return self._state f = MyFunc(1) print f(1) print f(2) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gabriel.becedillas at gmail.com Wed May 10 14:23:08 2006 From: gabriel.becedillas at gmail.com (gabriel.becedillas at gmail.com) Date: 10 May 2006 11:23:08 -0700 Subject: PyThreadState_SetAsyncExc, PyErr_Clear and boost::python Message-ID: <1147285388.867881.237350@q12g2000cwa.googlegroups.com> I use PyThreadState_SetAsyncExc to stop a python thread but there are situations when the thread doesn't stop and continues executing normally. After some debugging, I realized that the problem is that PyThreadState_SetAsyncExc was called when the thread was inside a native extension, that for some reason calls PyErr_Clear. That code happens to be inside boost::python. I do need to stop the thread from executing Python code as soon as possible (as soon as it returns from a native function is also acceptable). Because we have embedded Python's VM in our product, I'm thinking of modifying PyErr_Clear() to return immediately if the thread was stopped (we determine if the thread should stop using our own functions). Example: void PyErr_Clear(void) { if (!stop_executing_this_thread()) PyErr_Restore(NULL, NULL, NULL); } Does anybody see any problem with this approach ?, Does anybody have a cleaner/better solution ? Thanks. From rpdooling at gmail.com Thu May 18 18:44:50 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 18 May 2006 15:44:50 -0700 Subject: Strange error References: <1147962206.900840.19130@38g2000cwa.googlegroups.com> <mailman.5883.1147962743.27775.python-list@python.org> <1147963014.880378.44270@i39g2000cwa.googlegroups.com> <446c8c4c$0$14894$626a54ce@news.free.fr> Message-ID: <1147992290.394256.252540@g10g2000cwb.googlegroups.com> Sorry, Never mind. wtf.func_defaults Thanks for the examples. Rick From drs Sat May 20 15:58:32 2006 From: drs (drs) Date: Sat, 20 May 2006 14:58:32 -0500 Subject: mod_python, COM, on win2k3 server Message-ID: <7u2dnWkphP166fLZnZ2dnUVZ_vSdnZ2d@comcast.com> I have an application that runs on mod_python/apache using the publisher handler. It uses an access db as the backend and connects via ADO. In a test environment on XP it runs fine, but when on a win2k3 server it will load one page, but all subsequent page loads throw a pythoncom.CoInitializeEX error until I restart the apache. Presumably, this is a threading issue, but I am not sure what the best approach to fixing it is. Should I simply wrap all COM calls with pythoncom.CoInitialize/pythoncom.CoUninitialize calls, or is this somethig that needs to be done at a lower level. This is mod_python 3.2, Python 2.3.5, apache2.0.*, win2k3, ado 2.8, and the server has 2 processors in case that matters. Thanks, -d From digitalorganics at gmail.com Tue May 23 10:11:41 2006 From: digitalorganics at gmail.com (Cloudthunder) Date: Tue, 23 May 2006 10:11:41 -0400 Subject: Method Delegation To Subinstances Message-ID: <af3c42f10605230711r5f0597eeifab2617391c0475d@mail.gmail.com> In the example: class Boo: def __init__(self, parent): self.parent = parent print self.parent.testme def run(): print "Yahooooo!" class Foo: testme = "I love you!" def __init__(self): test = Boo(self) A = Foo() How can I set up method delegation so that I can do the following: A.run() and have this call refer to the run() method within the boo instance? Also, what if I have tons of functions like run() within the boo instance and I want all them to be directly accessible as if they were part of their parent (the Foo instance)? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060523/2deaa53f/attachment.html> From yamadora1999 at naver.com Wed May 24 02:59:59 2006 From: yamadora1999 at naver.com (freshman) Date: 23 May 2006 23:59:59 -0700 Subject: problem select object in pyode Message-ID: <1148453999.640970.304750@j33g2000cwa.googlegroups.com> # test code: http://pyode.sourceforge.net/tutorials/tutorial3.html # #i want selecting object in pyode test code. # what's wrong? # under modify code # see selectObject() function # pyODE example 3: Collision detection # Originally by Matthias Baas. # Updated by Pierre Gay to work without pygame or cgkit. import sys, os, random, time from math import * from OpenGL.GL import * from OpenGL.GLU import * from OpenGL.GLUT import * import ode # geometric utility functions def scalp (vec, scal): vec[0] *= scal vec[1] *= scal vec[2] *= scal def length (vec): return sqrt (vec[0]**2 + vec[1]**2 + vec[2]**2) obj_map = {} def _mousefunc(b, s, x, y): if b == 0 and s == 0: selectObject(x, y) def selectObject(x, y): print x, y glSelectBuffer(512) viewport = glGetIntegerv(GL_VIEWPORT) glMatrixMode(GL_PROJECTION) glPushMatrix() glRenderMode(GL_SELECT) glLoadIdentity() gluPickMatrix(x, viewport[3]-y, 2, 2, viewport) gluPerspective (45,1.333,0.1,100) gluLookAt (2.4, 3.6, 4.8, 0.5, 0.5, 0, 0, 1, 0) glMatrixMode(GL_MODELVIEW) glLoadIdentity() _drawfunc() buffer = glRenderMode(GL_RENDER) for hit_record in buffer: print hit_record if buffer: obj_name = buffer[0][2][0] else: obj_name = 0 glMatrixMode(GL_PROJECTION) glPopMatrix() glMatrixMode(GL_MODELVIEW) # prepare_GL def prepare_GL(): """Prepare drawing. """ # Viewport glViewport(0,0,640,480) # Initialize glClearColor(0.8,0.8,0.9,0) glClear(GL_COLOR_BUFFER_BIT | GL_DEPTH_BUFFER_BIT); glEnable(GL_DEPTH_TEST) glDisable(GL_LIGHTING) glEnable(GL_LIGHTING) glEnable(GL_NORMALIZE) glShadeModel(GL_FLAT) # Projection glMatrixMode(GL_PROJECTION) glLoadIdentity() gluPerspective (45,1.3333,0.2,20) # Initialize ModelView matrix glMatrixMode(GL_MODELVIEW) glLoadIdentity() # Light source glLightfv(GL_LIGHT0,GL_POSITION,[0,0,1,0]) glLightfv(GL_LIGHT0,GL_DIFFUSE,[1,1,1,1]) glLightfv(GL_LIGHT0,GL_SPECULAR,[1,1,1,1]) glEnable(GL_LIGHT0) # View transformation gluLookAt (2.4, 3.6, 4.8, 0.5, 0.5, 0, 0, 1, 0) # draw_body def draw_body(body): """Draw an ODE body. """ global obj_map x,y,z = body.getPosition() R = body.getRotation() rot = [R[0], R[3], R[6], 0., R[1], R[4], R[7], 0., R[2], R[5], R[8], 0., x, y, z, 1.0] glPushMatrix() glMultMatrixd(rot) if body.shape=="box": sx,sy,sz = body.boxsize glScale(sx, sy, sz) glPushName(obj_map[body]) glutSolidCube(1) glPopName() glPopMatrix() # create_box def create_box(world, space, density, lx, ly, lz): """Create a box body and its corresponding geom.""" # Create body body = ode.Body(world) M = ode.Mass() M.setBox(density, lx, ly, lz) body.setMass(M) # Set parameters for drawing the body body.shape = "box" body.boxsize = (lx, ly, lz) # Create a box geom for collision detection geom = ode.GeomBox(space, lengths=body.boxsize) geom.setBody(body) return body # drop_object def drop_object(): """Drop an object into the scene.""" global bodies, counter, objcount body = create_box(world, space, 1000, 1.0,0.2,0.2) body.setPosition( (random.gauss(0,0.1),3.0,random.gauss(0,0.1)) ) theta = random.uniform(0,2*pi) ct = cos (theta) st = sin (theta) body.setRotation([ct, 0., -st, 0., 1., 0., st, 0., ct]) bodies.append(body) counter=0 objcount+=1 global obj_map obj_map[body] = objcount # explosion def explosion(): """Simulate an explosion. Every object is pushed away from the origin. The force is dependent on the objects distance from the origin. """ global bodies for b in bodies: l=b.getPosition () d = length (l) a = max(0, 40000*(1.0-0.2*d*d)) l = [l[0] / 4, l[1], l[2] /4] scalp (l, a / length (l)) b.addForce(l) # pull def pull(): """Pull the objects back to the origin. Every object will be pulled back to the origin. Every couple of frames there'll be a thrust upwards so that the objects won't stick to the ground all the time. """ global bodies, counter for b in bodies: l=list (b.getPosition ()) scalp (l, -1000 / length (l)) b.addForce(l) if counter%60==0: b.addForce((0,10000,0)) # Collision callback def near_callback(args, geom1, geom2): """Callback function for the collide() method. This function checks if the given geoms do collide and creates contact joints if they do. """ # Check if the objects do collide contacts = ode.collide(geom1, geom2) # Create contact joints world,contactgroup = args for c in contacts: c.setBounce(0.2) c.setMu(5000) j = ode.ContactJoint(world, contactgroup, c) j.attach(geom1.getBody(), geom2.getBody()) ###################################################################### # Initialize Glut glutInit ([]) # Open a window glutInitDisplayMode (GLUT_RGB | GLUT_DOUBLE) x = 0 y = 0 width = 640 height = 480 glutInitWindowPosition (x, y); glutInitWindowSize (width, height); glutCreateWindow ("testode") # Create a world object world = ode.World() world.setGravity( (0,-9.81,0) ) world.setERP(0.8) world.setCFM(1E-5) # Create a space object space = ode.Space() # Create a plane geom which prevent the objects from falling forever floor = ode.GeomPlane(space, (0,1,0), 0) # A list with ODE bodies bodies = [] # A joint group for the contact joints that are generated whenever # two bodies collide contactgroup = ode.JointGroup() # Some variables used inside the simulation loop fps = 50 dt = 1.0/fps running = True state = 0 counter = 0 objcount = 0 lasttime = time.time() # keyboard callback def _keyfunc (c, x, y): sys.exit (0) glutKeyboardFunc (_keyfunc) # draw callback def _drawfunc (): # Draw the scene prepare_GL() for b in bodies: draw_body(b) glutSwapBuffers () glutDisplayFunc (_drawfunc) # idle callback def _idlefunc (): global counter, state, lasttime t = dt - (time.time() - lasttime) if (t > 0): time.sleep(t) counter += 1 if state==0: if counter==20: drop_object() if objcount==30: state=1 counter=0 # State 1: Explosion and pulling back the objects elif state==1: if counter==100: explosion() if counter>300: pull() if counter==500: counter=20 glutPostRedisplay () # Simulate n = 2 for i in range(n): # Detect collisions and create contact joints space.collide((world,contactgroup), near_callback) # Simulation step world.step(dt/n) # Remove all contact joints contactgroup.empty() lasttime = time.time() glutIdleFunc (_idlefunc) glutMouseFunc(_mousefunc) glutMainLoop () From me+python at modelnine.org Sun May 21 16:48:18 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 21 May 2006 22:48:18 +0200 Subject: Iterators: Would "rewind" be a good idea? In-Reply-To: <4470C2E5.1020004@earthlink.net> References: <4470C2E5.1020004@earthlink.net> Message-ID: <200605212248.18531.me+python@modelnine.org> Am Sonntag 21 Mai 2006 21:43 schrieb Charles D Hixson: > I was reading through old messages in the list and came up against an > idea that I thought might be of some value: > "Wouldn't it be a good idea if one could "rewind" an iterator?" > Not stated in precisely those terms, perhaps, but that's the way I read it. Yes, that certainly would be a neat idea. But, think of the following: what if the iterator computes the values at runtime, and you're not iterating over a "predefined" list of some sort? Do you want the machinery to store the state of the iterator at every earlier point in time (sometimes this may not even be possible, think of socket communication handled by iterators, or of some state being kept in a C extension outside of the grasp of the Python interpreter), and to restore the iterator to this point? Even if the generator you're trying to rewind can be "pickled" at each yield statement, memory requirements come to mind when thinking about this for the general case, where you simply don't want to rewind, but just iterate forward. Anyway, an easy way out (if the aforementioned concerns don't apply) is always to create a list of the generator, and then to index that list directly: x = list(gen()) A list can be freely indexed, so basically if you implement the iterator logic using a while loop, you're free to rewind as much as you'd like. --- Heiko. From mwilson-to at sympatico.ca Tue May 23 13:07:08 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Tue, 23 May 2006 13:07:08 -0400 Subject: "Thinking like CS" problem I can't solve In-Reply-To: <1148402620.032735.60000@g10g2000cwb.googlegroups.com> References: <1148402620.032735.60000@g10g2000cwb.googlegroups.com> Message-ID: <1jHcg.1154$%Z2.168831@news20.bellglobal.com> Alex Pavluck wrote: > Hello. On page 124 of "Thinking like a Computer Scientist". There is > an exercise to take the following code and with the use of TRY: / > EXCEPT: handle the error. Can somone help me out? Here is the code: > [ ... ] What error? Python 2.4.2 (#1, Jan 23 2006, 21:24:54) [GCC 3.3.4] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> def inputNumber(n): ... if n == 17: ... raise 'BadNumberError: ', '17 is off limits.' ... else: ... print n, 'is a nice number' ... return n ... >>> inputNumber(17) Traceback (most recent call last): File "<stdin>", line 1, in ? File "<stdin>", line 3, in inputNumber BadNumberError: : 17 is off limits. That error, I guess. try:/except...: can catch it and prevent the traceback. You could, say, print your own message and continue with your script. Look up how to use try:/except... . Cheers, Mel. From manstey at csu.edu.au Mon May 22 20:41:38 2006 From: manstey at csu.edu.au (manstey) Date: 22 May 2006 17:41:38 -0700 Subject: NEWB: reverse traversal of xml file Message-ID: <1148344898.351787.159540@i40g2000cwc.googlegroups.com> Hi, I have an xml file of about 140Mb like this: <book> <record> ... <wordpartWTS>1</wordpartWTS> </record> <record> ... <wordpartWTS>2</wordpartWTS> </record> <record> ... <wordpartWTS>1</wordpartWTS> </record> </book> I want to traverse it from bottom to top and add another field to each record <totalWordPart>1</totalWordPart> which would give the highest value of wordpartWTS for each record for each word so if wordparts for the first ten records were 1 2 1 1 1 2 3 4 1 2 I want totalWordPart to be 2 2 1 1 4 4 4 4 2 2 I figure the easiest way to do this is to go thru the file backwards. Any ideas how to do this with an xml data file? Thanks From me+python at modelnine.org Tue May 2 17:36:13 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 23:36:13 +0200 Subject: urllib2 not support proxy on SSL connection? In-Reply-To: <1146604944.658622.119860@u72g2000cwu.googlegroups.com> References: <1146604944.658622.119860@u72g2000cwu.googlegroups.com> Message-ID: <200605022336.13609.me+python@modelnine.org> Am Dienstag 02 Mai 2006 23:22 schrieb itay_k: > Is it possible that urllib2 doesnt support for proxy over https > connections? Are you sure this a proxy which is accessed by https, or rather a proxy that supports CONNECT, and thus allows you to access https-sites? I'd guess the latter, which I haven't gotten to work with urllib2 so far. AFAICT, that's why you get an unknown protocol error from the SSL library, because the proxy starts a plaintext session, and urllib2 expects an SSL session (which you try to use to access the proxy, because you specify https as the proxy URL), and so doesn't know what to do with the data it gets. I'd guess you'd have to rethink what you're doing here... --- Heiko. From bj_666 at gmx.net Wed May 3 17:17:06 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Wed, 03 May 2006 23:17:06 +0200 Subject: scope of variables References: <874q06bz4c.fsf@localhost.localdomain> Message-ID: <pan.2006.05.03.21.17.04.507172@gmx.net> In <874q06bz4c.fsf at localhost.localdomain>, Gary Wessle wrote: > is the code below correct? No... > b = 3 > def adding(a) ...a colon is missing at the end of the above line. > print a + b > > it seams not to see the up-level scope where b is defined. It does. And you could easily find out yourself by just trying that code. Running this:: b = 3 def adding(a): print a + b adding(5) Puts out 8 as expected. Ciao, Marc 'BlackJack' Rintsch From ben at wintersun.org Tue May 2 09:31:09 2006 From: ben at wintersun.org (Ben Caradoc-Davies) Date: Tue, 02 May 2006 21:31:09 +0800 Subject: Strange result with math.atan2() In-Reply-To: <chuji3xd2m.ln2@pollux.home> References: <chuji3xd2m.ln2@pollux.home> Message-ID: <44575f1d$0$16971$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Vedran Fura? wrote: > I think that this results must be the same: > In [3]: math.atan2(-0.0,-1) > Out[3]: -3.1415926535897931 > In [4]: math.atan2(-0,-1) > Out[4]: 3.1415926535897931 -0 is converted to 0, then to 0.0 for calculation, losing the sign. You might as well write 0.0 instead of -0 The behaviour of atan2 conforms to the ISO C99 standard (Python is implemented in C). Changing the sign of the first argument changes the sign of the output, with no special treatment for zero. > In [5]: -0 == -0.0 > Out[5]: True The constant -0 is an integer and is immediately converted to 0 (an integer). Two's-complement integers have no separate sign bit, and only one representation for zero. The integer -0 is identical in all respects to the integer 0 The constant -0.0 is a float, stored as an IEEE 754 bit pattern, and has a bit used to represent sign. The constants 0.0 and -0.0 compare equal, and both compare equal to 0, yet 0.0 and -0.0 have distinct bit patterns. Because Python uses the C implementation of atan2, both arguments are converted to floats before calculation. -0 is converted to 0, then to 0.0 The behaviour of atan2 is mandated by ISO C99 (ISO/IEC 9899:1999). See the manuals of some implementers who tabulate these special values: http://developer.apple.com/documentation/Darwin/Reference/ManPages/man3/atan2.3.html http://www.ugcs.caltech.edu/manuals/libs/mpfr-2.2.0/mpfr_22.html -- Ben Caradoc-Davies <ben at wintersun.org> http://wintersun.org/ "Those who deny freedom to others deserve it not for themselves." - Abraham Lincoln From onurb at xiludom.gro Fri May 12 08:05:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 14:05:44 +0200 Subject: design a Condition class In-Reply-To: <mailman.5567.1147298249.27775.python-list@python.org> References: <1147297217.372888.167960@v46g2000cwv.googlegroups.com> <mailman.5567.1147298249.27775.python-list@python.org> Message-ID: <44647a7b$0$287$626a54ce@news.free.fr> Carl J. Van Arsdall wrote: (snip) > I just wanted to make the comment that there already exists a > Condition() class in the threading module. If you plan on using your > class with the threading module you might wish to use another name. > As far as I remember, Python has namespaces, so I don't see the point here... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From duncan.booth at invalid.invalid Tue May 16 17:09:22 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 21:09:22 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> Message-ID: <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> achates wrote: >>In particular a common convention is to have indentations at 4 >>spaces and tabs expanding to 8 spaces. > > Like all space-indenters, you seem to be hung up on the idea of a tab > 'expanding' to n spaces. It only does that if you make your editor > delete the tab character and replace it with spaces! Really, that is > the only sense in which your statement makes any sense. If you want > your indentation to have the width of four, eight, or nineteen spaces, > set your tabstops accordingly. It is strange. You use many of the same words as me, but they don't make any sense. The point is about separating the presentation of the source file from the semantic content. When displaying the file you can choose to expand tabs to any suitable positions. These may be evenly spaced every n characters, or may vary across the page. However the important thing is that a tab does not map to a single indentation level in Python: it can map to any number of indents, and unless I know the convention you are using to display the tabs I cannot know how many indents are equivalent to a tabstop. > Seriously people, this is about separating the content of a source file > from how it is displayed. It's about letting people work together while > also allowing them to have control over their own environments, > something which is and always has been central to the hacker ethos. Precisely. Using spaces everywhere allows this, using tabs everywhere allows this, mixing spaces and tabs is a bad thing. You have to agree a convention for the project and conform to it. My experience is that 'spaces only' is more common, but your experience may differ. From diffuser78 at gmail.com Tue May 16 09:46:56 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 16 May 2006 06:46:56 -0700 Subject: Python script for remotely shutting down Windows PC from Linux ? In-Reply-To: <4cu2dcF17t9juU1@uni-berlin.de> References: <1147784786.317200.238780@v46g2000cwv.googlegroups.com> <4cu2dcF17t9juU1@uni-berlin.de> Message-ID: <1147787216.421492.323520@y43g2000cwc.googlegroups.com> > ssh Admin at IP_ADDR shutdown -s Than indeed worked....Thanks > use the subprocess module or shellutils to execute the above. I am a python newbie and how easy or difficult it is using the sub process module and shell utils. Thanks, I really appreciate your help. From just at xs4all.nl Fri May 26 14:20:14 2006 From: just at xs4all.nl (Just) Date: Fri, 26 May 2006 20:20:14 +0200 Subject: list comprehensions put non-names into namespaces! References: <1148577813.000229.225330@y43g2000cwc.googlegroups.com> <mailman.6256.1148666976.27775.python-list@python.org> Message-ID: <just-6650A9.20201426052006@news1.news.xs4all.nl> In article <mailman.6256.1148666976.27775.python-list at python.org>, "Terry Reedy" <tjreedy at udel.edu> wrote: > "Mel Wilson" <mwilson-to at sympatico.ca> wrote in message > news:7hBdg.2071$ho5.166428 at news20.bellglobal.com... > > Point of information, would this be the interpreter putting > > the result of its last calculation in _ ? > > Yes, [ ... ] No, actually. It's an implementation detail of list comps. From nospam at nospam.nospam Tue May 16 04:22:18 2006 From: nospam at nospam.nospam (Nic) Date: Tue, 16 May 2006 10:22:18 +0200 Subject: Python and Combinatorics References: <44697b5c$0$14794$4fafbaef@reader4.news.tin.it> <e4c0dh$197$03$1@news.t-online.com> Message-ID: <44698bc0$0$14791$4fafbaef@reader4.news.tin.it> I forgot them. Sorry. They should be included. Nic "Peter Otten" <__peter__ at web.de> ha scritto nel messaggio news:e4c0dh$197$03$1 at news.t-online.com... > Nic wrote: > > [Algorithm that I may have misunderstood] > >> 12a 13a 23a >> 12a 13b 23a >> 12a 13b 23b >> 12b 13a 23a >> 12b 13b 23a >> 12b 13b 23b > > What about 12a 13a 23b and 12b 13a 23b? > > Peter > > PS: Please don't top-post. From kentilton at gmail.com Sat May 6 01:30:04 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 01:30:04 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <pan.2006.05.06.03.54.17.404055@hastings.org> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> Message-ID: <wvW6g.1646$Ez6.507@fe09.lga> Steve R. Hastings wrote: > On Fri, 05 May 2006 21:16:50 -0400, Ken Tilton wrote: > >>The upshot of >>what he wrote is that it would be really hard to make semantically >>meaningful indentation work with lambda. > > > Pretty much correct. The complete thought was that it would be painful > all out of proportion to the benefit. > > See, you don't need multi-line lambda, because you can do this: > > > def make_adder(x): > def adder_func(y): > sum = x + y > return sum > return adder_func > > add5 = make_adder(5) > add7 = make_adder(7) > > print add5(1) # prints 6 > print add5(10) # prints 15 > print add7(1) # prints 8 > > > Note that make_adder() doesn't use lambda, and yet it makes a custom > function with more than one line. Indented, even. > > You could also do this: > > > lst = [] # create empty list > def f(x): > return x + 5 > lst.append(f) > del(f) # now that the function ref is in the list, clean up temp name > > print lst[0](1) # prints 6 > > > Is this as convenient as the lambda case? > > lst.append(lambda x: x + 7) > print lst[1](1) # prints 8 > > > No; lambda is a bit more convenient. But this doesn't seem like a very > big issue worth a flame war. <g> Hopefully it can be a big issue and still not justify a flame war. Mileages will always vary, but one reason for lambda is precisely not to have to stop, go make a new function for this one very specific use, come back and use it as the one lambda statement, or in C have an address to pass. but, hey, what are editors for? :) the bigger issue is the ability of a lambda to close over arbitrary lexically visible variables. this is something the separate function cannot see, so one has to have a function parameter for everything. but is such lexical scoping even on the table when Ptyhon's lambda comes up for periodic review? > If GvR says multi-line lambda would make > the lexer more complicated and he doesn't think it's worth all the effort, > I don't see any need to argue about it. Oh, no, this is just front porch rocking chair BS. But as an enthuiastic developer I am sensitive to how design choices express themselves in ways unanticipated. Did the neat idea of indentation-sensitivity doom pythonistas to a life without the sour grapes of lambda? If so, Xah's critique missed that issue and was unfair to GvR in ascribing his resistance to multi-statement lamda to mere BDFLism. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From alanalan at newsgroup.nospam Thu May 4 16:35:01 2006 From: alanalan at newsgroup.nospam (A.M) Date: Thu, 4 May 2006 16:35:01 -0400 Subject: Python sample code for PLSQL REF CURSORS References: <0Cm6g.3838$ix6.280105@news20.bellglobal.com> <mailman.5332.1146751430.27775.python-list@python.org> Message-ID: <4xt6g.4070$ix6.293538@news20.bellglobal.com> Exactly what I was looking for. Thanks alot "Gerhard H?ring" <gh at ghaering.de> wrote in message news:mailman.5332.1146751430.27775.python-list at python.org... > A.M wrote: >> Hi, >> >> I am having hard time to find a sample that shows me how to return an OUT >> REF CURSOR from my oracle stored procedure to my python program. [...] > > import cx_Oracle > > con = cx_Oracle.connect("me/secret at tns") > cur = con.cursor() > outcur = con.cursor() > cur.execute(""" > BEGIN > MyPkg.MyProc(:cur); > END;""", cur=outcur) > > for row in out_cur: > print row > > HTH, > > -- Gerhard From babar.zafar at gmail.com Fri May 26 20:41:16 2006 From: babar.zafar at gmail.com (Babar K. Zafar) Date: 26 May 2006 17:41:16 -0700 Subject: Safe eval critique (homework done) Message-ID: <1148690476.015704.170500@j55g2000cwa.googlegroups.com> Hi guys! I know this subject has been beaten to death and I am not going to whine about lacking features for proper restricted execution in the Python runtime. It's the OS job, I get it. Anyways, I thought about using a restricted *subset* of the language for simple configuration scripts and storing data in a user-friendly way. I'm fully aware about the dangers of introducing "eval" into the picture so I took different route and hacked together the following module: http://www.zafar.se/dump/safe.py Could some of you perhaps give some feedback on the implementation? By default the module imposes the following restrictions: * importing modules is disabled * unsafe builtins are disabled * timeout limit ('while 1:pass' can't block forever) * getattr, setattr, delattr are disabled * lowlevel attributes like __subclasses__ are disabled * enviroment passed to 'exec' can't contain modules or builtins Is there some obvious security hole I'm missing? How easily could one compromise the restricted enviroment? Thanks, Babar K. Zafar PS. Here are some simple unittests to give you a feel for the module: class TestSafeEval(unittest.TestCase): def test_builtin(self): # attempt to access a unsafe builtin self.assertRaises(SafeEvalException, safe_eval, "open('test.txt', 'w')") def test_getattr(self): # attempt to get arround direct attr access self.assertRaises(SafeEvalException, \ safe_eval, "getattr(int, '__abs__')") def test_func_globals(self): # attempt to access global enviroment where fun was defined self.assertRaises(SafeEvalException, \ safe_eval, "def x(): pass; print x.func_globals") def test_lowlevel(self): # lowlevel tricks to access 'object' self.assertRaises(SafeEvalException, \ safe_eval, "().__class__.mro()[1].__subclasses__()") def test_timeout_ok(self): # attempt to exectute slow code which finishes within timelimit def test(): time.sleep(2) env = {'test':test} safe_eval("test()", env, timeout_secs = 5) def test_timeout_exceed(self): # attempt to exectute code which never teminates self.assertRaises(SafeEvalException, \ safe_eval, "while 1: pass") def test_invalid_context(self): # can't pass an enviroment with modules or builtins env = {'f' : __builtins__.open, 'g' : time} self.assertRaises(SafeEvalException, \ safe_eval, "print 1", env) def test_callback(self): # modify local variable via callback self.value = 0 def test(): self.value = 1 env = {'test':test} safe_eval("test()", env) self.assertEqual(self.value, 1) From skn at skn.com Tue May 9 08:49:54 2006 From: skn at skn.com (Shankar) Date: Tue, 9 May 2006 18:19:54 +0530 Subject: Accessing std::wstring in Python using SWIG Message-ID: <e3q35k$nsu$1@daniel-new.mch.sbs.de> Hello, I have a C++ dll with one class which has one public function. This function returns an std::list<std::wstring> as an argout. I am using SWIG to generate Python extensions for this dll. I have the following code in python to access the string from the list. . . for item in myList: print str(item) . . When I run this program I see that the address of the string is printed, but not the actual content. Within Python code how can I dereference this wstring pointer to actually print the value and not the address. Thanks in advance, With best regards, Shankar From bugbear at trim_papermule.co.uk_trim Thu May 25 04:55:40 2006 From: bugbear at trim_papermule.co.uk_trim (bugbear) Date: Thu, 25 May 2006 09:55:40 +0100 Subject: John Bokma harassment In-Reply-To: <447485B6.4070507@hotORgooMAIL.invalid> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> <447479A1.8050809@hotORgooMAIL.invalid> <Xns97CD6AB19B4F3castleamber@130.133.1.4> <447485B6.4070507@hotORgooMAIL.invalid> Message-ID: <4475710d$0$2679$ed2619ec@ptn-nntp-reader01.plus.net> Mitch wrote: > Sure, each server has terms and conditions that apply, doesn't mean you > should be able to ban people from speaking just because you don't like > what they say. You are a silly person. BugBear From chaosquant at tele2.fr Wed May 10 18:22:58 2006 From: chaosquant at tele2.fr (chaosquant at tele2.fr) Date: 10 May 2006 15:22:58 -0700 Subject: Calling C/C++ functions in a python script Message-ID: <1147299778.630583.83380@q12g2000cwa.googlegroups.com> I'm kind of beginner in Python, so I must ask what are probably silly questions. Here is my problem: I have a static library say, a file library.lib, which can be linked to C or C++ programs. Now I would like to use the functions of the library in Python script, under Win XP. Can someone give me a simple example of how to do so? Thanks a lot, Jean-Claude Please reply also to chaosquant at tele2.fr From onurb at xiludom.gro Fri May 12 07:50:52 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 13:50:52 +0200 Subject: deleting texts between patterns In-Reply-To: <44645c27$0$301$636a55ce@news.free.fr> References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <44645c27$0$301$636a55ce@news.free.fr> Message-ID: <446476ff$0$306$626a54ce@news.free.fr> bruno at modulix wrote: > micklee74 at hotmail.com wrote: > (snip) > > Don't know if it's better for your actual use case, but this avoids > reading up the whole file: > def skip(iterable, skipfrom, skipuntil): > """ example usage : > >>> f = open("/path/to/my/file.txt") > >>> for line in skip_print(f, 'abc', 'yyz'): > >>> print line > >>> f.close() > """ (snip code) Forgot to say this will also skip markers. If you want to keep them, see the effbot answer... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From john at castleamber.com Thu May 18 23:50:17 2006 From: john at castleamber.com (John Bokma) Date: 19 May 2006 03:50:17 GMT Subject: Script to make Windows XP-readable ZIP file References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> Message-ID: <Xns97C7E851F9CC2castleamber@130.133.1.4> "pac" <pac at fernside.com> wrote: > I'm preparing to distribute a Windows XP Python program and some > ancillary files, > and I wanted to put everything in a .ZIP archive. It proved to be > inordinately > difficult and I thought I would post my solution here. Is there a > better one? heresy maybe, but I use Ant to do such things (with my Perl projects): http://ant.apache.org/ -- 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 mblume at socha.net Fri May 12 15:51:33 2006 From: mblume at socha.net (Martin Blume) Date: Fri, 12 May 2006 21:51:33 +0200 Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> <44644a76$0$290$626a54ce@news.free.fr> <4464959f$1$13578$5402220f@news.sunrise.ch> <4464b6ad$0$6828$636a55ce@news.free.fr> <4464c90b$1$13570$5402220f@news.sunrise.ch> <4464d026$0$7672$626a54ce@news.free.fr> Message-ID: <4464e6a3$1$13565$5402220f@news.sunrise.ch> "bruno at modulix" schrieb > > [lucid introduction into decorators] > Thanks for the help in understanding decorators. Martin From diffuser78 at gmail.com Wed May 3 02:01:24 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 2 May 2006 23:01:24 -0700 Subject: Wake on LAN and Shutdown for Windows and Linux In-Reply-To: <4bqhdvF130514U1@news.dfncis.de> References: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> <4bqhdvF130514U1@news.dfncis.de> Message-ID: <1146636084.266789.146410@e56g2000cwe.googlegroups.com> Thanks, In fact I checked that. I thought that any other literature would help. David Murmann wrote: > diffuser78 at gmail.com schrieb: > > How can I shutdown Windows box from my Main (Linux) ? > > Have you seen this? > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 > > it probably won't work on linux (maybe with wine or similar?), but you > can try to invoke this script on a windows machine somehow... > > have fun, David. From aprameya at students.iiit.net Fri May 12 04:33:41 2006 From: aprameya at students.iiit.net (I.V. Aprameya Rao) Date: Fri, 12 May 2006 14:03:41 +0530 (IST) Subject: Python-list Digest, Vol 32, Issue 209 In-Reply-To: <mailman.21480.1147422604.27774.python-list@python.org> References: <mailman.21480.1147422604.27774.python-list@python.org> Message-ID: <Pine.LNX.4.61.0605121403350.8942@students.iiit.net> which files? On Fri, 12 May 2006 python-list-request at python.org wrote: > Send Python-list mailing list submissions to > python-list at python.org > > To subscribe or unsubscribe via the World Wide Web, visit > http://mail.python.org/mailman/listinfo/python-list > or, via email, send a message with subject or body 'help' to > python-list-request at python.org > > You can reach the person managing the list at > python-list-owner at python.org > > When replying, please edit your Subject line so it is more specific > than "Re: Contents of Python-list digest..." > -- To steal information from a person is called plagiarism. To steal information from the enemy is called gathering intelligence. Have no fear of perfection - you will never reach it Teamwork is essential; it gives the enemy other people to shoot at. Consciousness: That annoying time between naps. From john at castleamber.com Tue May 30 21:25:12 2006 From: john at castleamber.com (John Bokma) Date: 31 May 2006 01:25:12 GMT Subject: how to print newline in xml? References: <1149023930.292203.152540@u72g2000cwu.googlegroups.com> Message-ID: <Xns97D3CFB7B50DCcastleamber@130.133.1.4> "anatoli.barski at googlemail.com" <anatoli.barski at googlemail.com> wrote: > which is already not very readable - but it becomes even worse along > with increasing number of comments How about: <robot> <description>armar3</description> : : </robot> XML editor + xpath makes this way more easier to use by humans compared to normal comments. Also, if you declare several of comment elements (summary, description, author, etc.) you can auto generate documentation etc. -- 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 meyer.p at gmail.com Thu May 18 05:24:27 2006 From: meyer.p at gmail.com (Pierre) Date: 18 May 2006 02:24:27 -0700 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <446c3785$0$6981$626a54ce@news.free.fr> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> <446c3785$0$6981$626a54ce@news.free.fr> Message-ID: <1147944267.585786.82730@i40g2000cwc.googlegroups.com> I don't want to use getattr(object, property, default_value) because I'm using external code and I don't want to modify or patch it. In this code, the call is getattr(object, property). On my objects, I must provide default values depending on the property that was requested, the default value is not always the same. And Yes I understand that obj.a is equivalent to getattr(obj, 'a') BUT the difference between class attribute and instance attribute... :S From gmc at serveisw3.net Wed May 3 05:37:56 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Wed, 03 May 2006 11:37:56 +0200 Subject: [PythonCE] Curious about Python for Windows CE In-Reply-To: <e24752a10605021645p358656d5uf9e7c4ed9fa22bbe@mail.gmail.com> References: <e24752a10605021645p358656d5uf9e7c4ed9fa22bbe@mail.gmail.com> Message-ID: <445879F4.4010107@serveisw3.net> Redefined Horizons escribi?: > I am still pretty new to Python, but my company is investigating the > possibilty of developing applications on Windows CE Devices, and I had > a couple of questions: > > I'd like to use Python as my development environment for Windows CE > Devices. What is the current status of Python on Windows CE? Is it > still very "experimental", or is it something that I can use for > development of a relatively stable application? > > Is there a GUI toolkit for Windows CE that I can use in Python? > Something like a port of PyGTK or wxWidgets? > > Is there any work being done with Python for Pocket PCs that run > Linux, and not Windows CE? > > Thanks, > > Scott Huey > >------------------------------------------------------------------------ > >_______________________________________________ >PythonCE mailing list >PythonCE at python.org >http://mail.python.org/mailman/listinfo/pythonce > > Hi Scott, I've been using Python for some of my projects on handhelds from the very beginning of the Python 2.3.x WinCE port. IMHO Python for WindowsCE is, really, very very stable. We have developed some applications with it, and I know from first hand experience, that it is anything but experimental. Python for WinCE is really a great success in terms of reliability. I'm glad to say we can develop the app. on the PC or the Mac, and then just copy the files to the PocketPC, and run as expected: perfect. No need for emulators, cross-compilation... Can tell you that we have some developments running on PocketPC, and being process intensive applications, work smooth and without a single problem until today, we stressed it until handheld reached CPU and memory usage limits, and have never suffered from crashes. We did some more "extreme" testings, pushing to the limits our PocketPC's ARM CPU & IO in a multi-threaded communication and data visualization application we did develop, and it keeps working smooth until you have no more free memory (after 12 hours of intensive network data transmission, processing, and in-memory data structures generation), then we got the "out of memory" dialog error and Python closes flawlessly. If I'd got a PC with the same memory than in the handheld, result would't be different... this application when running on a PC for such time and data overhead, eats more than 50 Mb of RAM.... it's obvious the program would continue running it handhelp had more memory. And remember, ctypes is your best friend, when optimizing for memory usage (and speed!). There are only a few hints you need to have in mind when targeting your app. to the Python for WinCE, anyway I can say all my scripts that do work on WinXP or in MacOS, do work on the WinCE, with only a few occasional minor adjustments, in things like Python not knowing what the current directory it is (as WinCE OS doesnt have the concept of "current" directory, it is an OS issue, but there are easy workarounds). I only would't use PythonCE if in need to develop a very very fast running application, in the case I'd code the interface in C++, and maybe, then use Python from inside, or not using it at all... who said Python is the right tool for everything? :-) But if your needs for speed are more focused in the development side, I doubt anything can beat Python, and you still get a pretty good execution speed for the application. And last but not least, I'd like to tell my suggestions about the version update from 2.3.x to 2.4.x It has been a big step forwards: improved performance, awesome new console implementation, and lot of improvements inherited from the long list of 2.3 to 2.4 Pyhon changes. About GUI development, I use Tkinter but isn't as fast as I'd like, anyway it works smooth if you don't need to populate thousands and thousands of items in lists or suchs tasks. There is a port of wxWidgets for 2.3.x, but seems to have some little bug as thought did I read some months ago, on this mail list. Hope a 2.4 version could be possible soon! And about Python for Linux handhelds, I really don't know much, but I thought the main Python distribution should work. Perhaps I'm wrong... could someone point towards this issue? Thanks to Luke Dunstan and all the Python & PythonCE contributors for such a sucessful work. Gonzalo Monz?n. From tomerfiliba at gmail.com Fri May 19 17:09:28 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 19 May 2006 14:09:28 -0700 Subject: sock2 Message-ID: <1148072968.566306.250400@38g2000cwa.googlegroups.com> sock2 is an attempt to improve python's socket module, by a more pythonic version (options are properties, protocols are classes, etc.etc) you can get it here (including a small demo) http://iostack.wikispaces.com/download i would like to receive comments/bug reports, to improve it. just reply to this post with your comments. it's part of the iostack library, which is not released yet. -tomer From robert.kern at gmail.com Fri May 19 00:21:42 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 May 2006 23:21:42 -0500 Subject: Python trig precision problem In-Reply-To: <newscache$13fhzi$5xd$1@lyris.knx.tva.gov> References: <newscache$13fhzi$5xd$1@lyris.knx.tva.gov> Message-ID: <e4jh4l$hvo$1@sea.gmane.org> Cary West wrote: > Hello all, having a small problem with a trig routine using python math > module. This code is designed to convert geodetic coordinates to lambert > conformal conic coordinates. It implements the formulas found at > http://mathworld.wolfram.com/LambertConformalConicProjection.html . The > problem is that, at least on my machine, the precision is off to the tune of > around 1 km, which is unacceptable. (using the calculator found at > http://www.deh.gov.au/erin/tools/geo2lam-gda.html ) Anyone have any ideas? > here is the offending code. If you want to do map projections, I highly recommend using PyProj instead of implementing the calculations yourself. Geodesy is nontrivial, and MathWorld doesn't tell you half the details you need to take care of. http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/pyproj.html -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From onurb at xiludom.gro Fri May 12 13:53:19 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 19:53:19 +0200 Subject: which is better, string concatentation or substitution? In-Reply-To: <1147103073.724710.177040@y43g2000cwc.googlegroups.com> References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <roy-A5FC8E.09284008052006@reader1.panix.com> <IWH7g.2053$No6.45672@news.tufts.edu> <e3nnv0$jbm$1@reader1.panix.com> <1147103073.724710.177040@y43g2000cwc.googlegroups.com> Message-ID: <4464cbf2$0$10968$626a54ce@news.free.fr> Ted wrote: > Thank you Roy. > > It seems if you lurk here long enough you eventually get all you > questions answered without even asking! > ;-) > +1 QOTW <OT> please avoid top-posting, and please avoid posting back a long message just to add three lines. </OT> -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From andreasp+python at qbcon.com Fri May 12 05:00:23 2006 From: andreasp+python at qbcon.com (Andreas Pauley) Date: Fri, 12 May 2006 11:00:23 +0200 Subject: Python Translation of C# DES Encryption Message-ID: <44644EA7.5030502@qbcon.com> Hi all, I'm trying to implement a Python equivalent of a C# method that encrypts a string. My Python attempt is in the attached file, but does not return the same value as the C# method (see below). Any hints? Thanks, Andreas The C# method: public static string Encrypt(string decrypted) { byte[] data = System.Text.ASCIIEncoding.ASCII.GetBytes(decrypted); byte[] rgbKey = System.Text.ASCIIEncoding.ASCII.GetBytes("12345678"); byte[] rgbIV = System.Text.ASCIIEncoding.ASCII.GetBytes("87654321"); MemoryStream memoryStream = new MemoryStream(1024); DESCryptoServiceProvider desCryptoServiceProvider = new DESCryptoServiceProvider(); CryptoStream cryptoStream = new CryptoStream(memoryStream, desCryptoServiceProvider.CreateEncryptor(rgbKey, rgbIV), CryptoStreamMode.Write); cryptoStream.Write(data, 0, data.Length); cryptoStream.FlushFinalBlock(); byte[] result = new byte[(int)memoryStream.Position]; memoryStream.Position = 0; memoryStream.Read(result, 0, result.Length); cryptoStream.Close(); return System.Convert.ToBase64String(result); } _____________________________________________________________________________________________ This e-mail contains official information from Quality Business Consultants (Pty) Ltd and is intended for use by the addressee only. Important notice: Important restrictions, qualifications and disclaimers ("the Disclaimer") apply to this email. To read this click on the following address: http://www.qbcon.com/disclaimer The Disclaimer forms part of the content of this email in terms of section 11 of the Electronic Communications and Transactions Act, 25 of 2002. If you are unable to access the Disclaimer, send a blank e-mail to disclaimer at qbcon.com and we will send you a copy of the Disclaimer. -------------- next part -------------- An embedded and charset-unspecified text was scrubbed... Name: des-encrypt.py URL: <http://mail.python.org/pipermail/python-list/attachments/20060512/1965b7ce/attachment.ksh> From steve at holdenweb.com Mon May 1 08:16:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Mon, 01 May 2006 13:16:19 +0100 Subject: using break in exec() In-Reply-To: <7CF2534088731741A719AB7F5ED036F61144C7@moritz.faps.uni-erlangen.de> References: <7CF2534088731741A719AB7F5ED036F61144C7@moritz.faps.uni-erlangen.de> Message-ID: <e34u6i$4g0$1@sea.gmane.org> Weber Matthias wrote: > Hi, > > has anybody a suggestion to get this example to work? I have the need to > jump out of the loop within the exec statement. > > while True: > exec("break") > You can't do that, just as you can't break out of a loop by executing a break within a function that's called inside the loop. Python insists that break only occurs inside a loop construct. You will have use some construct like while True: try: exec(your_code) except SomeException: break then have your executed code raise the appropriate exception to break out of the loop. If you'll forgive me saying so you seem to be relatively new to programming, and newcomers often make inappropriate use of "exec", which should really only be a last resort. If you explain the problem in a little more depth (i.e. say exactly what it is you are trying to do) you might get more helpful suggestion. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From ask at me Thu May 11 08:07:00 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 08:07:00 -0400 Subject: redirecting print to a a file In-Reply-To: <1147352171.658508.187490@y43g2000cwc.googlegroups.com> References: <7JudnYwllewrrv7ZRVn-vA@comcast.com> <1147352171.658508.187490@y43g2000cwc.googlegroups.com> Message-ID: <FbWdnZGzBY9hqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> Harold Fellermann wrote: >>>>import sys >>>>sys.stdout = file("output","w") >>>>print "here you go" > > And what if I want to still send the output to stdout and just a log it in the file as well? A. From raims at dot.com Mon May 8 03:27:17 2006 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 08 May 2006 09:27:17 +0200 Subject: Python's regular expression? References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> Message-ID: <87lktd9dt6.fsf@voodoo.myself> "Davy" <zhushenli at gmail.com> writes: > Does Python support robust regular expression like Perl? Yep, Python regular expression is robust. Have a look at the Regex Howto: http://www.amk.ca/python/howto/regex/ and the re module: http://docs.python.org/lib/module-re.html -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From sybrenUSE at YOURthirdtower.com.imagination Mon May 8 08:05:21 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 8 May 2006 14:05:21 +0200 Subject: get Windows file type References: <1147089470.336984.173510@u72g2000cwu.googlegroups.com> Message-ID: <slrne5ud00.2m9.sybrenUSE@schuimige.stuvel.eu> BartlebyScrivener enlightened us with: > Using Python on Windows XP, I am able to get almost all file and > path info using os.path or stat, but I don't see a way to retrieve > the file type? E.g. Microsoft Word file, HTML file, etc, the > equivalent of what is listed in the "Type" column in the Windows > Explorer box. I'm afraid you'll have to get that from the registry. That will only give you the descriptive name of the extension, though, and not the type of contents of the file, i.e. if you have a HTML file named 'somefile.avi', Windows recognises it as an AVI and not an HTML file. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From fabiofz at gmail.com Thu May 18 07:43:53 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Thu, 18 May 2006 08:43:53 -0300 Subject: How to couple pyunit with GUI? In-Reply-To: <107ccd5e0605180411x60b3c5c9j26b2d81e9a69dd44@mail.gmail.com> References: <1147879480.640335.252950@y43g2000cwc.googlegroups.com> <cfb578b20605171135q254b6e0fsfbe81a16bc4ab9ab@mail.gmail.com> <107ccd5e0605180411x60b3c5c9j26b2d81e9a69dd44@mail.gmail.com> Message-ID: <cfb578b20605180443r1aa95616v623842629df6d03e@mail.gmail.com> Hi Mark, On 5/18/06, Mark Geyzer <mark.geyzer at gmail.com> wrote: > > Fabio, thank you for your response, but I'm afraid that you misunderstood > me - probably, I was not too clear. I do no test GUI - on the contrary, I am > testing a HW interface. What I do need is a GUI equivalent of the > TextTestRunner method. Any ideas? > My fault, I did just a 'fast-read'. Well, I use pydev (http://pydev.sf.net), which allows me to select a folder and then recursively run all the unit-tests below that folder. Pydev is the gui, but the underlying module that actually runs the tests does not actually need a gui (I'm sending it attached). Just send it the dir you want and it will recursively inspect the modules, get the unit-tests and run them. You can probably easily extend it to run the files you want and not get things recursively if you don't want it... But with all that, It is still a command-line utility -- if you stilll want a gui to it, try pydev, which will allow you to right-click a folder and run all the unit-tests below it. Cheers, Fabio On 5/17/06, Fabio Zadrozny <fabiofz at gmail.com> wrote: > > > > > > > > On 17 May 2006 08:24:40 -0700, volcano < Mark.Geyzer at gmail.com> wrote: > > > > > > I am desperately looking for an info how to combine a testing > > > application with decent GUI interface - the way most xUnits do. I > > > believe I have seen something about using Tkinter, but I do not > > > remember - where. > > > I am working on a complex testing application built over unittest > > > module, and I need GUI interface that will alllow me to select tests > > > at > > > different levels of test hierarchy tree. > > > I am new to python, so say everything slow and repeat it twice:) > > > > > > -- > > > http://mail.python.org/mailman/listinfo/python-list > > > > > > > > > > Have you checked http://pyguiunit.sourceforge.net/ -- it is for PyQt, > > but can probably be adapted for other GUIs. > > > > -- Fabio > > > > > > -- > Mark Geyzer > Software Engineer, > tel: +972-52-6782603 > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060518/80b9751c/attachment.html> -------------- next part -------------- A non-text attachment was scrubbed... Name: runfiles.py Type: text/x-python Size: 5979 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060518/80b9751c/attachment.py> From bigblueswope at gmail.com Sun May 21 16:52:31 2006 From: bigblueswope at gmail.com (BJ Swope) Date: Sun, 21 May 2006 16:52:31 -0400 Subject: Slicing Issues Message-ID: <fca207170605211352k5c707688u63102558898dfe57@mail.gmail.com> **Given this set of data (88 characters wide) in a file... 067AARON WAY 30043002500002599A 098 0670000017 129 672 067ABBA CT 30518000882000902A 025 11 0670163227 365 670 067ABBEY HILL RD 30024000100000299A 004 12 0670000027 276 667 067ABBEY LN SW30047004900005099A 052 0670000036 093 659 067ABBEY PARK WAY 30044000901000967A 043 0670161916 177 622 067ABBEY POINTE WAY 30024000103000176A 100 12 0670178087 235 667 067ABBIE KILGORE WAY 30052001314001487A 041 0670155595 096 649 067ABBOTT DR 30519002103002236A 129 0670176283 007 682 067ABBOTTS BRIDGE RD 30096003550003578E 096 04 0670128036 293 697 067ABBOTTS BRIDGE RD 30096003551003935O 056 04 0670128046 293 697 and this code... dafile = 'gwinnett_streets_short.txt' f = open(dafile, 'r') for line in f: line=line.strip('\r\n') county_code=line[0:3] street_name=line[3:30] district_combo=line[85:3] print county_code, '|' , street_name , '|' , district_combo , '|' , len(line), '|' I get this output... 067 | AARON WAY | | 88 | 067 | ABBA CT | | 88 | 067 | ABBEY HILL RD | | 88 | 067 | ABBEY LN | | 88 | 067 | ABBEY PARK WAY | | 88 | 067 | ABBEY POINTE WAY | | 88 | 067 | ABBIE KILGORE WAY | | 88 | 067 | ABBOTT DR | | 88 | 067 | ABBOTTS BRIDGE RD | | 88 | 067 | ABBOTTS BRIDGE RD | | 88 | If I change the slice for district_combo to district_combo=line[85:] The output is what I want... 067 | AARON WAY | 672 | 88 | 067 | ABBA CT | 670 | 88 | 067 | ABBEY HILL RD | 667 | 88 | 067 | ABBEY LN | 659 | 88 | 067 | ABBEY PARK WAY | 622 | 88 | 067 | ABBEY POINTE WAY | 667 | 88 | 067 | ABBIE KILGORE WAY | 649 | 88 | 067 | ABBOTT DR | 682 | 88 | 067 | ABBOTTS BRIDGE RD | 697 | 88 | 067 | ABBOTTS BRIDGE RD | 697 | 88 | Why does the final slice have to be an open slice? Why can the slice not be like the previous slices in which it is a specified range of characters? -- We are all slave to our own paradigm. -- Joshua Williams -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060521/d0b55936/attachment.html> From raghavan.viswanathan at wipro.com Wed May 24 06:11:02 2006 From: raghavan.viswanathan at wipro.com (raghu) Date: 24 May 2006 03:11:02 -0700 Subject: referrers In-Reply-To: <4dio43F1aju6aU1@uni-berlin.de> References: <1148463646.603330.275000@i40g2000cwc.googlegroups.com> <4dio43F1aju6aU1@uni-berlin.de> Message-ID: <1148465462.360499.172450@y43g2000cwc.googlegroups.com> Diez, I did look into gc, specifically gc.get_referrers(), but it seemed to give me something that I cant decipher. I added the following line. print "referrers ",gc.get_referrers(x0) This is what I got. referrers [{'__builtins__': <module '__builtin__' (built-in)>, '__file__': './tst1.py', 'pdb': <module 'pdb' from '/home/raghavan/Python-2.4/my_install/lib/python2.4/pdb.pyc'>, 'sys': <module 'sys' (built-in)>, 'y': 24012, 'gc': <module 'gc' (built-in)>, 'myfuncs': <module 'myfuncs' from '/home/Raghavan/tst/myfuncs.dll'>, '__name__': '__main__', 'x0': 24012, 'z': 24012, 'os': <module 'os' from '/home/raghavan/Python-2.4/my_install/lib/python2.4/os.pyc'>, '__doc__': None, 'types': <module 'types' from '/home/raghavan/Python-2.4/my_install/lib/python2.4/types.pyc'>}, (None, '/home/Raghavan/tst', 'my pid is ', 24012, 'ref count ', 'referrers ')] Also the len of this is 2, while I got refcount=5. So I dont know whether this can be used in the same way. Thanks. Bye, Raghavan V From a.schmolck at gmail.com Fri May 12 19:53:18 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 13 May 2006 00:53:18 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <yV49g.15$Id.13@fe10.lga> <yfsody3t4jd.fsf@oc.ex.ac.uk> <zf79g.34$8U3.30@fe08.lga> Message-ID: <yfswtcqssup.fsf@oc.ex.ac.uk> Ken Tilton <kentilton at gmail.com> writes: > Alexander Schmolck wrote: > > Ken Tilton <kentilton at gmail.com> writes: > > > > >>In Common Lisp we would have: > >> > >> (defvar *x*) ;; makes it special > >> (setf *x* 1) > >> (print *x*) ;;-> 1 > >> (let ((*x* 2)) > >> (print *x*)) ;; -> 2 > >> (print *x*) ;; -> 1 > > You seem to think that conflating special variable binding and lexical > > > variable binding is a feature and not a bug. What's your rationale? > > Transparency. That's is circular. You might be right, but you failed to provide a rationale and not just a restatement. > That is where power comes from. I did the same things with Cells. Reading a > slot with the usual Lisp reader method transparently creates a dependency on > the variable. Let me see if I understand it right -- if an instance of class A has a ruled slot a that reads an instance of class B's slot b then it is noted somewhere that A's a depends on b? > To change a variable and have it propagate throughout the datamodel, Just > Change It. > > > Exposed wiring means more work and agonizing refactoring. Well, you claim that in that instance python suffers from exposed wiring and I claim that CL suffers from a (minor) booby trap. You can't typically safely ignore whether a variable is special as a mere wiring detail or your code won't work reliably (just as you can't typically safely ignore whether something is rigged or not even if booby-trapness is pretty transparent) -- it's as simple as that (actually its a bit worse because the bug can be hard to detect as lexical and special variables will result in the same behaviour in many contexts). So in the case of booby traps and special variables, I generally prefer some exposed wiring (or strong visual clues) to transparency. I'd like to see a demonstration that using the same binding syntax for special and lexical variables buys you something apart from bugs. 'as From invalidemail at aerojockey.com Sun May 21 18:53:37 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 21 May 2006 15:53:37 -0700 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <mailman.6031.1148224219.27775.python-list@python.org> References: <mailman.6031.1148224219.27775.python-list@python.org> Message-ID: <1148252017.377426.131050@38g2000cwa.googlegroups.com> Heiko Wundram wrote: > The following PEP tries to make the case for a slight unification of for > statement and list comprehension syntax. -1 Adds complexity to the language and saves you nothing but an indent level. However, I encourage you to submit this PEP and get a (almost certianly negative) pronouncement, so we have it on the record. Carl Banks From bdesth.quelquechose at free.quelquepart.fr Fri May 26 18:57:08 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 27 May 2006 00:57:08 +0200 Subject: dict literals vs dict(**kwds) In-Reply-To: <1148662896.693077.213140@u72g2000cwu.googlegroups.com> References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> <1148650269.190130.209840@i39g2000cwa.googlegroups.com> <44772b4c$0$312$626a54ce@news.free.fr> <1148662896.693077.213140@u72g2000cwu.googlegroups.com> Message-ID: <4477586b$0$2140$636a55ce@news.free.fr> George Sakkis a ?crit : > Bruno Desthuilliers wrote: > > >>George Sakkis a ?crit : >> >>>The thing is there are four (at least?) ways to get a dict instance: >>> (snip) >>This actually makes 2 (two) ways of creating a dict: >>- the default call to type (ie : dict(...) >>- the syntactic sugar dict-litteral syntax. >> (snip) > > Even without the syntactic-sugar form, I fail to see why you seem to > think that dict(items), dict(otherdict) and dict(**kwds) are all one > thing. Of course it's all one thing: a call to a callable that happens to be a factory for dict instances. > >>>2) restricting in a more serious sense: the future addition of optional >>>keyword arguments that affect the dict's behaviour. >> >>This has already been discussed, and IIRC no-one managed to make a >>*serious* point about it. The actual signature of dict() is perfectly >>sensible for 99% of uses case, and I *never* had a need for "keyword >>arguments that affect the dict's behaviour" in 6+ years of Python >>programming. >> >>If you want another behaviour, feel free to subclass dict or implement >>your own dict-like - FWIW, that's what I do when the need arises. > > > Me too, but I'd gladly toss them if one day dicts were extended to > accept, say a default value or ordering. Ordering ? What "ordering" ? Anyway, there's no need to change the actual constructor for this - just adding a factory would be enough: d = dict.with_default(default) But I'm actually -1 on this. I don't like the idea of a dict with default values for non existing keys. > Plus, adding new functionality > by subclassing often leads to combinatorial explosion Yes - and this is usually solved with either decorators (the design pattern - not our beloved @decorators) and/or strategy. Also, this is more of a statically-typed langages problem. With dynamic typing, inheritance is only about implementation. Please re-read what I said : "to subclass dict or implement your own dict-like". There was a time when subclassing wasn't even an option. > (think of "class > OrderedDefaultPrettifiedDict(defaultdict, odict, prettydict)"). I don't know what is supposed to be a "prettydict". But even if your monster class is dict-like, it's clearly not a dict no more. From steve at holdenweb.com Sun May 21 01:37:19 2006 From: steve at holdenweb.com (Steve Holden) Date: Sun, 21 May 2006 06:37:19 +0100 Subject: Feature request: sorting a list slice In-Reply-To: <1147974696.448816.119100@i39g2000cwa.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> Message-ID: <e4ouaa$cu6$1@sea.gmane.org> The effbot wrote: > George Sakkis wrote: > >>> It would be useful if list.sort() accepted two more optional >>> parameters > > useful for what? what's the use case ? > John Machin then wrote, without quoting any context at all: > Use case? > He means "under what circumstances do you see someone actually using the proposed feature rather than just nodding and saying "that looks useful". IOW, who would use the new feature, and why? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From felipe.lessa at gmail.com Sat May 6 11:28:47 2006 From: felipe.lessa at gmail.com (Felipe Almeida Lessa) Date: Sat, 06 May 2006 12:28:47 -0300 Subject: NaN handling In-Reply-To: <01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> Message-ID: <1146929327.30335.5.camel@kenshin.CASA> Em Sex, 2006-05-05 ?s 16:37 -0400, Ivan Vinogradov escreveu: > This works to catch NaN on OSX and Linux: > > # assuming x is a number > if x+1==x or x!=x: > #x is NaN This works everywhere: nan = float('nan') . . . if x == nan: # x is not a number -- Felipe. From johnjsal at NOSPAMgmail.com Wed May 31 15:23:29 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 31 May 2006 19:23:29 GMT Subject: using import * with GUIs? Message-ID: <R2mfg.2200$No6.47332@news.tufts.edu> Hi all. Quick question (but aren't they all?) :) Do you think it's a good idea to use the 'from <name> import *' statement when using a GUI module? It seems on wxPython's site, they recommend using import wx nowadays, but I wonder if that advice is followed. Also, I'm still reading some Tkinter docs that seem to use 'from Tkinter import *' a lot. I understand the danger of doing this, but is it safer in these cases, given the more specific names that GUI frameworks tend to use (sometimes!)? Or should you still qualify all your calls with the module? From __peter__ at web.de Mon May 8 14:46:03 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 08 May 2006 20:46:03 +0200 Subject: Using StopIteration References: <1147112608.374083.99030@u72g2000cwu.googlegroups.com> Message-ID: <e3o3i0$4le$00$1@news.t-online.com> tkpmep at hotmail.com wrote: > I create list of files, open each file in turn, skip past all the blank > lines, and then process the first line that starts with a number (see > code below) > > filenames=glob.glob("C:/*.txt") > for fn in filenames: f = open(fn) for line in f: if line[:1] in digits: ProcessLine(line) break f.close() A for instead of the inner while loop makes the f.next() call implicit. > If a file has only blank lines, the while loop terminates with a > StopIteration. How can I just close this file andd skip to the next > file if a StopIteration is raised? I tried the following: > > filenames=glob.glob("C:/*.txt") > for fn in filenames: > f =file(fn) > line = " " > while line[0] not in digits: > try: > line = f.next() > except StopIteration: break else: # only if StopIteration was not triggered # and thus break not reached ProcessLine(line) f.close() > but got only a ValueError: I/O operation on closed file for line = > f.next(). It appears that the continue is taking me back to the top of > the while loop. How can I get back to the top of the for loop? By breaking out of the while loop as shown above. (all changes untested) Peter From duncan.booth at invalid.invalid Tue May 16 04:03:36 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 08:03:36 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> <roy-765731.09112115052006@reader1.panix.com> <e4abj6$p6a$1@panix1.panix.com> <1147751674.531058@teuthos> Message-ID: <Xns97C55C27D99C5duncanbooth@127.0.0.1> Chris Foote wrote: > > Don't forget that adding keys >> requires resizing the dict, which is a moderately expensive operation. > > Yep, that's why I probably need a dictionary where I can pre-specify > an approximate size at the time of its creation. Try splitting the creation of the keys from the creation of the dictionary and you'll see where the bottleneck really is. On my system: >>> r = range(5000000) >>> d = dict.fromkeys(r) takes less than 1 second to create the dictionary. So creating a dictionary with 5 million elements is not in itself a terribly expensive operation (and yes, even with fromkeys there is no attempt to work out in advance what size the dictionary should be). Trying to simulate your data: >>> scale = 2**32 >>> data = [ (i*scale,i) for i in range(5000000) ] >>> d = dict.fromkeys(data) the assignment to data took 42 seconds. Creating the dictionary took 6 seconds. Trying the variation someone else suggested: >>> scale = 2**32 >>> data = [ i*scale+i for i in range(5000000) ] >>> d = dict.fromkeys(data) creating data took under 6 seconds and about 1 second for d. so it looks like the issue is not creating a large dictionary, nor lots of integers, but creating lots of tuples is expensive. Oh, and if anyone tells you that the intermediate list I created in the tests above is going to make it slow and you should use iterators instead: >>> r = range(5000000) >>> scale = 2**32 >>> s = [ i*scale for i in r ] >>> from itertools import izip >>> d = dict.fromkeys(izip(s,r)) The first few lines took a couple of seconds, the last one 1 minute 50 seconds. The alternative version: >>> scale = 2**32 >>> r = range(5000000) >>> d = dict.fromkeys((i*scale,i) for i in r) takes a similar time. From bignose+hates-spam at benfinney.id.au Wed May 17 21:53:12 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 11:53:12 +1000 Subject: excel centering columns References: <446ba8bd$0$61161$ae4e5890@news.nationwide.net> Message-ID: <87odxwm73r.fsf@benfinney.id.au> Lance Hoffmeyer <lance at augustmail.com> writes: > import win32com.client > import re > import codecs > import win32com.client.dynamic > import time > import datetime > from win32com.client.dynamic import Dispatch > from win32com.client import constants These statements create code objects (some of them module objects) and give them names you can use later. They're like assignment statements, but a shortcut that also makes the code objects. > sh2.Columns(lastcol).HorizontalAlignment = xlCenter > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > NameError: name 'xlCenter' is not defined Yep, since you have no name 'xlCenter' bound to anything. > sh2.Columns(lastcol).HorizontalAlignment = constant.xlCenter > > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > NameError: name 'constant' is not defined Yep, since you have no name 'constant' bound to anything. You do have the name 'constants' though; you imported it from 'win32com.client'. Perhaps that's what you meant? -- \ "I have one rule to live by: Don't make it worse." -- Hazel | `\ Woodcock | _o__) | Ben Finney From deets at nospam.web.de Tue May 16 10:59:29 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 16 May 2006 16:59:29 +0200 Subject: what is the difference between tuple and list? References: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> Message-ID: <4cu7n5F16vd9vU1@uni-berlin.de> daniel wrote: > is there any typical usage that shows their difference? >>> d = {} >>> d[('multi', 'part', 'key')] = 'schnarz' >>> d[['multi', 'part', 'key']] = 'schnarz' Traceback (most recent call last): File "<stdin>", line 1, in ? TypeError: list objects are unhashable A lot of discussions regarding this have been fiercly fought on this list - go google :) Diez From 7abc at sogetthis.com Wed May 24 14:39:35 2006 From: 7abc at sogetthis.com (PofN) Date: 24 May 2006 11:39:35 -0700 Subject: Xah Lee network abuse In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <1148495974.975395.12920@i40g2000cwc.googlegroups.com> Xah Lee wrote: > I'm sorry to trouble everyone. Liar. You were never sorry when you troubled us with your posting excrements in the past, you are not sorry now. > But as you might know, due to my > controversial writings and style, Liar. You are a net abuser, a kook and a troll. It has nothing to do with your writings and style. It has everything to do with your vialoation of netiquette, with you x-posting of off-topic messages, with your trolling and kookery. > recently John Bokma lobbied people to > complaint to my web hosting provider. Liear. John asked people do do their duty as net citizens and to report a serial net abuser. > After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. Shit. So they gave you 30 more days to abuse the net. Shit, shit, shit. They should have pulled the plug immediately. > I'm not sure I will be able to keep using their service, but I do hope > so. Lets hope not. > I do not like to post off-topic messages, Liar. Your whole usenet "career" is build around the posting of off-topic messages. > but this is newsgroup > incidence is getting out of hand, Liar. You were getting out of hand for some time now. > and I wish people to know about it. People know very well about you, Xah Lee, the serial newsgroup abuser, troll, liar, and kook. > I wrote some full detail here: > http://xahlee.org/Periodic_dosage_dir/t2/harassment.html More lies. > If you believe this lobbying to my webhosting provider is unjust, > please write to my web hosting provider abuse at dreamhost.com I believe it is justified, and I wrote dreamhost to thank them. You now reap what you saw. You refused to play nice with us in the past, now don't be surprised that people don't come to your aid. > Your help is appreciated. Thank you. I appreciate the courage of John and friends to stand up against someone who is out of control. You are not even affraid off accusing John of a crime (harrasment) and starting a smear campaing on your web site. You have sunken so low that you are fast approaching the earth's metal core. *Thanks John for making usenet a better place!* From robert.kern at gmail.com Mon May 22 22:00:05 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 22 May 2006 21:00:05 -0500 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1148344720.139905.282630@y43g2000cwc.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> <1148251275.211468.221460@g10g2000cwb.googlegroups.com> <mailman.6055.1148262320.27775.python-list@python.org> <1148344720.139905.282630@y43g2000cwc.googlegroups.com> Message-ID: <e4tqb4$v87$1@sea.gmane.org> Jim Lewis wrote: > Still problems :-( > > I have a directory c:\data\code\test\pyrex containing: > > build_and_install.bat: > "C:\program files\Python\python.exe" setup.py build_ext > --compiler=mingw32 > pause > But running run.py gives: "ImportError: No module named worldimport" > > Should worldimport.def be going to C:\program > files\python\Lib\site-packages? > Why isn't it? You also have to run the distutils install command as well to place the results of the build in site-packages. -- 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 matthew.garrish at sympatico.ca Mon May 22 09:58:23 2006 From: matthew.garrish at sympatico.ca (Matt Garrish) Date: Mon, 22 May 2006 09:58:23 -0400 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <nfecg.192$Sf2.171@newsread1.news.pas.earthlink.net> Message-ID: <%rjcg.681$%Z2.81457@news20.bellglobal.com> "Mumia W." <mumia.w.18.spam+fbi.gov at earthlink.net> wrote in message news:nfecg.192$Sf2.171 at newsread1.news.pas.earthlink.net... > Xah Lee wrote: >> Software Needs Philosophers >> >> by Steve Yegge, 2006-04-15. >> >> Software needs philosophers. >> >> [...] >> ---- >> This post is archived at: >> http://steve-yegge.blogspot.com/2006/04/software-needs-philosophers.html >> >> and >> http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html >> >> This essay is reported with permission. >> >> Xah >> xah at xahlee.org >> ? http://xahlee.org/ >> > > Remember that this was a blog post from Steve Yegge that Xah > Lee got permission to repost. > > It was a little long, and I got bored in the middle, but I > think I understand (a little) Steve's point. He thinks we need > software philosophers to break programmers' religious-like > devotion to their languages of choice. I don't agree with > this. > > I'd say we need software philosophers to help us see where > software is taking us so that we can avoid bad spots if > necessary. After all, the computer might just be the cotton > gin of our time. We might be virtually enslaved by > our own information if we don't watch out. > > Philosophers have the ability to think long, to think big, > and to think about the future, and to think about the > consequences of actions in a rational manner. They would be > able to warn us if we were about to do something stupid with > our society. > Thank you for that laugh. I think you're the first person I've read in this century who advocates Plato's silly notion of the philosopher kings. If you want to talk philosophy, please jump foward past the Enlightment. Matt From wojciech_mula at poczta.null.onet.pl.invalid Thu May 18 15:45:18 2006 From: wojciech_mula at poczta.null.onet.pl.invalid (Wojciech =?iso-8859-2?Q?Mu=B3a?=) Date: Thu, 18 May 2006 19:45:18 +0000 (UTC) Subject: Sorting of list containing tuples References: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> Message-ID: <slrne6pjih.b7n.wojciech_mula@cat.tac> Ronny Mandal wrote: > Assume we have a list l, containing tuples t1,t2... > > i.e. l = [(2,3),(3,2),(6,5)] > > And now I want to sort l reverse by the second element in the tuple, > i.e the result should ideally be: > > l = [(6,5),(2,3),(3,2)] > > > Any ideas of how to accomplish this? def cmpfun(a,b): return cmp(b[1],a[1]) l.sort(cmpfun) From tdelaney at avaya.com Tue May 30 20:58:21 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Wed, 31 May 2006 10:58:21 +1000 Subject: genexp performance problem? Message-ID: <2773CAC687FD5F4689F526998C7E4E5F07437E@au3010avexu1.global.avaya.com> Giovanni Bajo wrote: > python -mtimeit "sum(int(L) for L in xrange(3000))" > 100 loops, best of 3: 5.04 msec per loop > > python -mtimeit "import itertools; sum(itertools.imap(int, > xrange(3000)))" 100 loops, best of 3: 3.6 msec per loop > > I thought the two constructs could achieve the same speed. What does it give you with: python -mtimeit -s "g = (int(L) for L in xrange(3000))" "sum(g)" ? I get: python -mtimeit "import itertools; sum(itertools.imap(int, xrange(3000)))" 100 loops, best of 3: 3.99 msec per loop python -mtimeit -s "import itertools" "sum(itertools.imap(int, xrange(3000)))" 100 loops, best of 3: 3.97 msec per loop python -mtimeit "sum(int(L) for L in xrange(3000))" 100 loops, best of 3: 6.76 msec per loop python -mtimeit -s "g = (int(L) for L in xrange(3000))" "sum(g)" 1000000 loops, best of 3: 1.09 usec per loop The generator comprehension needs to create a new generator each time around. Tim Delaney From phpbird at gmail.com Wed May 24 21:00:08 2006 From: phpbird at gmail.com (Ju Hui) Date: 24 May 2006 18:00:08 -0700 Subject: how to change sys.path? In-Reply-To: <YE0dg.2171$No6.46883@news.tufts.edu> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <5aGcg.2150$No6.46806@news.tufts.edu> <e4vn3u$brc$1@atlantis.news.tpi.pl> <W8Kcg.2156$No6.46787@news.tufts.edu> <e2n772hhn9rhqi0arkc6qdns0aql6nrvfc@4ax.com> <Dk_cg.2161$No6.46749@news.tufts.edu> <532972pkqut50suspvi4qhmkkeporlcopv@4ax.com> <YE0dg.2171$No6.46883@news.tufts.edu> Message-ID: <1148518808.792129.83450@j33g2000cwa.googlegroups.com> yes, we can add path to PYTHONPATH,but how to remove some items? my sys.path: >>> import sys >>> for x in sys.path: ... print x ... D:\usr\local\lib\site-packages\setuptools-0.6a11-py2.4.egg D:\usr\local\lib\site-packages\clientcookie-1.3.0-py2.4.egg c:\temp C:\WINDOWS\system32\python24.zip C:\Documents and Settings\phpbird D:\usr\local\DLLs D:\usr\local\lib D:\usr\local\lib\plat-win D:\usr\local\lib\lib-tk D:\usr\local D:\usr\local\lib\site-packages >>> the value of HKEY_LOCAL_MACHINE\SOFTWARE\Python\PythonCore\2.4\PythonPath D:\usr\local\Lib;D:\usr\local\DLLs;D:\usr\local\Lib\lib-tk; the content are difference, how to remove C:\WINDOWS\system32\python24.zip or D:\usr\local\lib\site-packages\clientcookie-1.3.0-py2.4.egg ? thanks. From sjmachin at lexicon.net Wed May 31 00:40:00 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 May 2006 14:40:00 +1000 Subject: shuffling elements of a list In-Reply-To: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> Message-ID: <447D1E20.4010600@lexicon.net> On 31/05/2006 1:18 PM, greenflame wrote: > I would like to make a function that takes a list, more specificaly a > list of strings, and shuffles its elements, like a pile of cards. The > following is a script I tryed to make that implements pile shuffling. > In general, if you can't see why Python is complaining, insert print statements. Anyhow, read the following, run it, read it again, ... HTH, John def pileshuffle1(deck, numpiles, fix1bug=False): piles = [[]] * numpiles # 2nd bug: n references to *same* sublist card = 0 pilenum = 0 while card < len(deck): print card, pilenum assert 0 <= pilenum < numpiles piles[pilenum].append(deck[card]) card += 1 if not fix1bug: if pilenum < numpiles: pilenum += 1 else: pilenum = 0 else: pilenum = (pilenum + 1) % numpiles print print piles def pileshuffle2(deck, numpiles): piles = [[] for x in range(numpiles)] # n *different* sublists for cardindex, card in enumerate(deck): piles[cardindex % numpiles].append(card) print print piles pileshuffle1('qwertyuiop', 3, True) pileshuffle2('qwertyuiop', 3) pileshuffle1('qwertyuiop', 3, False) From duncan.booth at invalid.invalid Tue May 2 11:35:24 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 2 May 2006 15:35:24 GMT Subject: stripping blanks References: <1146551010.297649.314610@y43g2000cwc.googlegroups.com> <445720fd$1_2@news.estpak.ee> <mailman.5213.1146583430.27775.python-list@python.org> Message-ID: <Xns97B7A8C067267duncanbooth@127.0.0.1> Fulvio wrote: > Alle 17:06, marted? 02 maggio 2006, seeker ha scritto: >> ? ? ?printLine = line.rstrip("\n") > > I think that nobody considered if the text has (\r) or (\r\n) or (\n) > at the end of the line(s). > You think wrongly. The suggested code opens the file in text mode so the line endings are automatically normalised to '\n'. From ronnyma at math.uio.no Thu May 18 15:29:59 2006 From: ronnyma at math.uio.no (Ronny Mandal) Date: Thu, 18 May 2006 21:29:59 +0200 Subject: Sorting of list containing tuples Message-ID: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> Hi! Assume we have a list l, containing tuples t1,t2... i.e. l = [(2,3),(3,2),(6,5)] And now I want to sort l reverse by the second element in the tuple, i.e the result should ideally be: l = [(6,5),(2,3),(3,2)] Any ideas of how to accomplish this? Thanks, Ronny Mandal From steve.poe at gmail.com Mon May 1 16:06:13 2006 From: steve.poe at gmail.com (Steve Poe) Date: Mon, 1 May 2006 13:06:13 -0700 Subject: How do I take a directory name from a given dir? In-Reply-To: <5f56302b0605011251t2169bad1m70e3f5fc2198ffec@mail.gmail.com> References: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> <5f56302b0605011251t2169bad1m70e3f5fc2198ffec@mail.gmail.com> Message-ID: <721b21dc0605011306r6d2fcc3bh8f8852f8d630bf53@mail.gmail.com> Daniel, Before writing your script, what is your general approach to backup configuration files? Do you tar/zip them into one file? Do you ftp/ssh each file to another server? One approach I've used in backing up files from another server is: from ftplib import FTP def handleDownload(block): file.write(block) # print "." os.chdir('/home/backup') ftp = FTP('10.0.0.2') ftp.login('backuserid','backuppasswd') ftp.cwd('/home/backup') # Start downloading filename = 'main_config.tar.bz2' file = open(filename,'wb') print 'Getting ' + filename ftp.retrbinary('RETR ' + filename, handleDownload, 1024) print 'Closing file ' + filename file.close() #Finish downloading The 'Start downloading' and 'Stop downloading' are what I repeat for each file I need. I am sure there are better ways, but this works. I imagine you could do this with wildcards as well. Good luck. Steve Poe On 5/1/06, Daniel Nogradi <nogradi at gmail.com> wrote: > > > Hi, > > > > I am trying to write a script to backup all my company's server configs > > weekly. The script will run in a cronjob, on whatever I set it. > > > > The issue I am currently having isto "extract" the directory name from > > a given directory string. For example: from the string > > "/home/testuser/projects/" I need to extract the "projects" part. The > > problem is that the directory names that needs to be used will never be > > the same lenght, so as far as my (very limited) knowledge stretches, > > slicing and indicing is out of the question. > > > > Can anybody help me, or give me an idea of what I should look at, > > seeing as I'm seriously stuck. I only started coding at the beginnig of > > the year, and was never interested before that, so my knowlege is > > basically non-existent. > > You can try this: > > >>> '/home/testuser/projects/'.strip( '/' ).split( '/' ) > ['home', 'testuser', 'projects'] > > strip gets rid of the first and last / and split splits the remaining > part and puts the results into a list. > > HTH :) > -- > http://mail.python.org/mailman/listinfo/python-list > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060501/cff7d750/attachment.html> From danmcleran at yahoo.com Fri May 26 13:15:31 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 26 May 2006 10:15:31 -0700 Subject: "Learning Python" 2nd ed. p479 error? In-Reply-To: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> References: <1148646764.589068.160690@j55g2000cwa.googlegroups.com> Message-ID: <1148663730.950031.219830@38g2000cwa.googlegroups.com> Looks like an error. I didn't see it the errata: http://www.oreilly.com/catalog/lpython2/errata/ From tzot at sil-tec.gr Wed May 3 06:33:52 2006 From: tzot at sil-tec.gr (Christos Georgiou) Date: Wed, 03 May 2006 13:33:52 +0300 Subject: redemo.py with Tkinter References: <87vesodwf9.fsf@localhost.localdomain> Message-ID: <0l1h52dcofq362g44dpta15c63u2qff3jk@4ax.com> On 03 May 2006 06:05:46 +1000, rumours say that Gary Wessle <phddas at yahoo.com> might have written: >I was reading the Regular Expression HowTo, it refers to redemo.py if >you have Tkinter installed. a quick #locate redemo.py returned none on >my debian/testing, however #locate Tkinter returned many. >any body out there is using it, is it a separate download? The easiest way is to download it directly from subversion: http://svn.python.org/view/python/trunk/Tools/scripts/ Click on the number link right next to redemo.py, and then you can click the "download" link. -- TZOTZIOY, I speak England very best. "Dear Paul, please stop spamming us." The Corinthians From george.sakkis at gmail.com Sun May 14 18:06:00 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 14 May 2006 15:06:00 -0700 Subject: count items in generator In-Reply-To: <7x4pzswmhe.fsf@ruckus.brouhaha.com> References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> <tj2kj3-82b.ln1@lairds.us> <7x4pzswmhe.fsf@ruckus.brouhaha.com> Message-ID: <1147644360.298154.220820@u72g2000cwu.googlegroups.com> Paul Rubin wrote: > claird at lairds.us (Cameron Laird) writes: > > For that matter, would it be an advantage for len() to operate > > on iterables? > > print len(itertools.count()) > > Ouch!! How is this worse than list(itertools.count()) ? From onurb at xiludom.gro Thu May 11 12:35:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 11 May 2006 18:35:44 +0200 Subject: Python memory deallocate In-Reply-To: <1147358549.473182.89950@i40g2000cwc.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <-yy*V4mgr@news.chiark.greenend.org.uk> <1147355266.189030.131420@y43g2000cwc.googlegroups.com> <4463462a$0$297$626a54ce@news.free.fr> <1147358549.473182.89950@i40g2000cwc.googlegroups.com> Message-ID: <44636843$0$278$626a54ce@news.free.fr> mardif wrote: > In python 2.5 this was resolved, ok, but i can't use any python version > then 2.3.5. > > This project was initializated with this version, and now it can be > dangerous change version, even because I use McMillan installer for > compile e build an executable. Err... I'm sorry I don't understand your problem here. You don't plan on sticking to 2.3.5 forever, aren't you ? > So, my initial window is a "menu window", when i can choose, for > example, upload foto for print, or create an object as PhotoAlbum. > > If i'will choose PhotoAlbum, it will allocate 200Mb. well! if i decide > to abort this work, i will return to initial window. and if i will > click in PhotoAlbum ago, the memory will increase to 350-400Mb. > > It's that!!! I don't understand why!!! when i abort the work the first > time, i call > > app.Destroy() > del app > > Why Python ( or GarbageCollector, or.... ) don't deallocate memory?? *please* re-read carefully what I and Diez wrote earlier in this thread before jumping to possibly erroneous conclusion. I didn't say that the problem *actually* was with Python - just that it *may* have to do with a memory management issue fixed in 2.5. And, while we're at it : your application uses a GUI toolkit and does image manipulations, so the problem can also come from one of these packages... I also suggested that it may have to do with your code keeping references to objects. del' an object just decrease the reference counter - the object won't be freed until there are no more reference to it *anywhere*. If I was in your place, I'd *really* make sure the problem is not in my code. Like, amongst other things, installing Python 2.5 and testing the program with it... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From userprogoogle-139 at yahoo.co.uk Mon May 22 10:27:18 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 22 May 2006 07:27:18 -0700 Subject: Win32: Detecting when system is locked or sleeping Message-ID: <1148308038.487624.201690@i40g2000cwc.googlegroups.com> I have written an application which works perfectly when the machine is operating under normal conditions, however when the screen becomes locked it imediately starts to fill up several hundred MB's of memory. Is there a way to detect when the system is locked? Best, rod From gmnation at gmail.com Tue May 9 23:18:12 2006 From: gmnation at gmail.com (=?iso-8859-1?B?Ry4gTW9uevNu?=) Date: 9 May 2006 20:18:12 -0700 Subject: Can Python installation be as clean as PHP? References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> <1147211815.312069.135140@u72g2000cwu.googlegroups.com> Message-ID: <1147231092.546800.100860@j73g2000cwa.googlegroups.com> Please don't compare PHP with Python... They are very different worlds. Maybe not all the Python's core functions are implemented in C, but Python is really a lot more efficient than PHP in every case you want to compare. If you "look inside", there's nothing to compare... they are extremely different worlds... they are like hell and heaven, from the awesome brilliant C Python implementation, to the ugly C PHP hack... (after all it is my personal opinion, I've worked with PHP for more than 4 years, for websites and console scripting). Python is more efficient than PHP in every aspect... I don't know why got (and still is) so popular, IMHO Python should have taken its place as the best "web scripting language". OTOH, my php install have lots more than a single executable file. Perhaps you don't use any php extension? don't think so... do you use pear? and pecl? you need lots of files too, and until you don't know what do they are and what you need or not, you will be in the same issue as you're with Python. I think you will get it early, as you find everything is more straightforward than you thought. Gonzalo Monz?n. From robin.meier at gmail.com Sun May 28 14:16:45 2006 From: robin.meier at gmail.com (robin) Date: 28 May 2006 11:16:45 -0700 Subject: html 2 plain text Message-ID: <1148840205.741356.209310@i40g2000cwc.googlegroups.com> hi, i remember seeing this simple python function which would take raw html and output the content (body?) of the page as plain text (no <..> tags etc) i have been looking at htmllib and htmlparser but this all seems to complicated for what i'm looking for. i just need the main text in the body of some arbitrary webbpage to then do some natural-language processing with it... thanks for pointing me to some helpful resources! robin From taleinat at gmail.com Mon May 1 12:34:23 2006 From: taleinat at gmail.com (taleinat at gmail.com) Date: 1 May 2006 09:34:23 -0700 Subject: self modifying code In-Reply-To: <445622EF.6050708@jessikat.plus.net> References: <445399A1.9020506@jessikat.plus.net> <slrne57r50.uh0.spamspam@bowser.marioworld> <44548536.7060409@jessikat.plus.net> <1146469385.334797.128930@i39g2000cwa.googlegroups.com> <4455D863.6070906@jessikat.plus.net> <1146492266.605324.282670@u72g2000cwu.googlegroups.com> <445622EF.6050708@jessikat.plus.net> Message-ID: <1146501263.350318.21340@i39g2000cwa.googlegroups.com> Personally, I would almost always pay the x2 efficiency price in order to use a class. But then I don't know what you're writing. Of course, if you really need it to be efficient, you can write it as a C extension, or use Pyrex, etc. and get -much- better results. From jeremit0 at gmail.com Thu May 25 14:11:56 2006 From: jeremit0 at gmail.com (jeremito) Date: 25 May 2006 11:11:56 -0700 Subject: Distutils -- specifying compiled output name Message-ID: <1148580716.472148.130600@i39g2000cwa.googlegroups.com> I am using distutils to comiple/install a c extension created with SWIG. However I need to be able to specify the output filename from gcc. I tried doing this with the "extra_compile_args" and "extra_link_args" by setting them equal to "-o MyOutputName.so" but that didn't work. Can someone show me how to specify the output name? Thanks, Jeremy From me at modelnine.org Mon May 8 19:01:37 2006 From: me at modelnine.org (Heiko Wundram) Date: Tue, 9 May 2006 01:01:37 +0200 Subject: advanced number recognition in strings? In-Reply-To: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> References: <1147107798.576836.178640@i40g2000cwc.googlegroups.com> Message-ID: <200605090101.37514.me@modelnine.org> Am Montag 08 Mai 2006 19:03 schrieb s.schmeier at gmail.com: > we want extract numbers from strings and wonder if there is already a > module around for doing this. An example in our case would look like > this: > > 0.032 +/- 0.5 x 10(-4) Should work beautifully with the re.finditer function (untested!): >>> import re numre = re.compile(r"""([+-]?[0-9]+(\.[0-9]*)?) # 0.032 matches this (\s*+/-\s*([0-9]+(\.[0-9]*)))? # +/- 0.5 matches this (\s*10\(([+-]?[0-9]+)\))? # 10(-4) matches this.""", re.X) data = """<your data here>""" for match in numre.finditer(data): number = float(match.group(1)) if match.group(4) is not None: prec = float(match.group(4)) else: prec = 0 if match.group(7) is not None: mantissa = int(match.group(7)) else: mantissa = 0 print number, prec, mantissa >>> --- Heiko. From bearophileHUGS at lycos.com Fri May 26 08:44:08 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 May 2006 05:44:08 -0700 Subject: Speed up this code? In-Reply-To: <4476d3ac_2@newspeer2.tds.net> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <4476d3ac_2@newspeer2.tds.net> Message-ID: <1148647447.804097.228580@j33g2000cwa.googlegroups.com> If you are interested in such programs, you can take a look at this one too: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/366178 It requires more memory, but it's quite fast. Bye, bearophile From antroy at gmail.com Sun May 14 03:57:00 2006 From: antroy at gmail.com (Ant) Date: 14 May 2006 00:57:00 -0700 Subject: Question regarding checksuming of a file In-Reply-To: <126d3g8tkfovs19@corp.supernews.com> References: <126d1u4ke4itg7f@corp.supernews.com> <roy-1E8950.21485413052006@reader1.panix.com> <126d3g8tkfovs19@corp.supernews.com> Message-ID: <1147593420.907522.325920@i40g2000cwc.googlegroups.com> A script I use for comparing files by MD5 sum uses the following function, which you may find helps: def getSum(self): md5Sum = md5.new() f = open(self.filename, 'rb') for line in f: md5Sum.update(line) f.close() return md5Sum.hexdigest() From pmartin at snakecard.com Fri May 5 12:09:50 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 11:09:50 -0500 Subject: Is this a legal / acceptable statement ? References: <2AI6g.10201$9c6.5375@dukeread11><-JWdnWb2t_PF_cbZRVn-jQ@comcast.com> <zvJ6g.10203$9c6.6603@dukeread11> <mailman.5377.1146841435.27775.python-list@python.org> Message-ID: <iNK6g.8737$B42.4563@dukeread05> Fredrik Lundh wrote: > Philippe Martin wrote: > >> l_init really is a boolean parameter and l_value a value that _might_ >> exist in a shelve. >> >> So I just want to have a parameter to a method so if the first value >> tested is false (l_init) then the second (l_value) does not get tested >> ... because it is the second in the statement and only seems to get >> evaluated if the > > how do you look things up in the shelve ? > > </F> l_value = m_data['MY_KEY'] Philippe From robert.h.boyd at gmail.com Wed May 24 11:47:26 2006 From: robert.h.boyd at gmail.com (Robert Boyd) Date: Wed, 24 May 2006 11:47:26 -0400 Subject: John Bokma harassment In-Reply-To: <1148484597.410529.219960@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148484597.410529.219960@j33g2000cwa.googlegroups.com> Message-ID: <e9e3813b0605240847g6e21dcdeyc3c8d50cc093b3f7@mail.gmail.com> On 24 May 2006 08:29:57 -0700, Rune Strand <rune.strand at gmail.com> wrote: > > I can just declare my support. Reading Mr. Bokmas comments below [*] > certainly makes my suport stronger. > I sent an email in support of Xah, which I wouldn't have bothered to do had I not read the rapid-fire posts from Bokma which were abusive, insulting, and arrogant. Xah's posts often make me roll my eyes, or I skip them, but sometimes (and more so lately) they have been intriguing and foster thought-provoking replies. I'd prefer debate and discussion be fostered, rather than squelched. But what does this clueless sock-puppet know? ;) From ankyhe at gmail.com Mon May 8 02:58:19 2006 From: ankyhe at gmail.com (ankyhe at gmail.com) Date: 7 May 2006 23:58:19 -0700 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> Message-ID: <1147071499.135783.193610@e56g2000cwe.googlegroups.com> Thanks a lot! However, I wonder why L.sort() don't return the reference L, the performance of return L and None may be the same. If L.sort() return L, we shouldn't do the awful things such as: keys = dict.keys() keys.sort() for key in keys: ...do whatever with dict[key]... we can only write the code as follows: for key in dict.iterkeys().sort(): ...do whatever with dict[key]... Why? From nicogrubert at gmail.com Wed May 31 08:39:22 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Wed, 31 May 2006 14:39:22 +0200 Subject: os.popen3() - how to close cmd window automatically? Message-ID: <447D8E7A.700@gmail.com> Dear Python developers, I use a short python script in order to run an external application plus to open a browser displaying a default page. My Setup: Python 2.4.3. / Windows2000 # ---------------------------------------------------------------------- # Script "shortcut.py" import os import webbrowser import win32api # open default web browser and display webbpage page = 'C:\\Temp\\Welcome.html' webbrowser.open(page) # path to application that is opened path = "C:\\Program Files\\ExternalApplication.exe" # get short name shortpath = win32api.GetShortPathName(path) # open external application stdin, stdout, stderr = os.popen3(shortpath) output = stdout.read() errors = stderr.read() stdin.close() stdout.close() stderr.close() print output print errors # ---------------------------------------------------------------------- In order to make this Script available on other Windows2000 machines where no Python installation is present, I made this script executable using "py2exe" (http://www.py2exe.org/). This creates a "shortcut.exe" file. If I run "shortcut.exe" everything works fine but a black empty cmd window opens and its kept open until I close the application "ExternalApplication.exe". How can I close that black empty window automatically? Thanks in advance, Nico From vaikings at gmail.com Fri May 19 02:53:17 2006 From: vaikings at gmail.com (vaibhav) Date: 18 May 2006 23:53:17 -0700 Subject: who can give me the detailed introduction of re modle? In-Reply-To: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: <1148021597.308527.24850@i39g2000cwa.googlegroups.com> easy and convenient way to get a good introduction for any module [especially if ur stuck and dont have internet connectivity]: 1. start python interpreter $ python 2. import the module and ask it for help :-) >>> import re >>> help(re) -vaibhav From lialie at 126.com Tue May 9 21:15:32 2006 From: lialie at 126.com (Lialie KingMax) Date: Wed, 10 May 2006 09:15:32 +0800 Subject: hyperthreading locks up sleeping threads Message-ID: <44613EB4.1010409@126.com> I haven't try the files yet. But have got a similar problem before. The situation is nearly the same. Always at random time , it reported that the memory read or write violently.But I use Windows 2000(Python 2.3, wxPython 2.4). Windows issue says 2000 doesn't support HP, so I simply turn it off. It didn't appear. From duncan.booth at invalid.invalid Tue May 16 03:43:03 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 16 May 2006 07:43:03 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> Message-ID: <Xns97C558AB7C9B4duncanbooth@127.0.0.1> achates wrote: > A tab is not equivalent to a number of spaces. It is a character > signifying an indent, just like the newline character signifies the end > of a line. If your editor automatically converts tabs to spaces (i.e. > you are unable to create source files containing tabs) then either it's > broken or you have misconfigured it. Either way you probably shouldn't > be using it to write code. That is true so far as it goes, but equally if your editor inserts a tab character when you press the tab key it is as broken as though it inserted a backspace character when you press the backspace key. In both of these cases you have an operation (move to next tabstop, move back one space) and an ascii control character which is intended to reflect that operation when rendering the file to an output device. An editor should be capable of letting you create or modify files containing control characters without gratuitously corrupting them, but the keys should perform the expected operations not insert the characters. From spam-me at microsoft.com Wed May 10 17:53:55 2006 From: spam-me at microsoft.com (Frank Goenninger DG1SBG) Date: Wed, 10 May 2006 23:53:55 +0200 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147252695.346762.20020@y43g2000cwc.googlegroups.com> <xcn8g.11$FO5.5@fe08.lga> Message-ID: <m2mzdpk0lo.fsf@pcsde001.local> Ken Tilton <kentilton at gmail.com> writes: > sross wrote: >>>I do wonder what would happen to Cells if I ever want to support >>>multiple threads. Or in a parallel processing environment. >> AFAIK It should be fine. >> In LW, SBCL and ACL all bindings of dynamic variables are thread-local. >> > > Ah, I was guilty of making an unspoken segue: the problem is not with > the *dependent* special variable, but with the sequentially growing > numeric *datapulse-id* ("the ID") that tells a cell if it needs to > recompute its value. The ID is not dynamically bound. If threads T1 > and T2 each execute a toplevel, imperative assignment, two threads > will start propagating change up the same dependency > graph... <shudder> > > Might need to specify a "main" thread that gets to play with Cells and > restrict other threads to intense computations but no Cells? Hmmm. I am wondering if a Cells Manager class could be the home for all Cells. Each thread could the have its own Cells Manager... > > Actually, I got along quite a while without an ID, I just propagated > to dependents and ran rules. This led sometimes to a rule running > twice for one change and transiently taking on a garbage value, when > the dependency graph of a Cell had two paths back to some changed > Cell. > > Well, Cells have always been reengineered in the face of actual use > cases, because I am not really smart enough to work these things out > in the abstract. Or too lazy or something. Probably all three. Nah. It's me asking again and again those silly questions about real Cells usage in some real life apps ;-) Frank From stormtoad at gmail.com Thu May 4 15:54:05 2006 From: stormtoad at gmail.com (Stormcoder) Date: 4 May 2006 12:54:05 -0700 Subject: CRC calculation In-Reply-To: <1146772014.264899.203740@j73g2000cwa.googlegroups.com> References: <1146772014.264899.203740@j73g2000cwa.googlegroups.com> Message-ID: <1146772445.400722.174730@i39g2000cwa.googlegroups.com> Check out http://docs.python.org/lib/module-zlib.html comes with a CRC function. From kbk at shore.net Fri May 5 23:35:38 2006 From: kbk at shore.net (Kurt B. Kaiser) Date: Fri, 5 May 2006 23:35:38 -0400 (EDT) Subject: Weekly Python Patch/Bug Summary Message-ID: <200605060335.k463Zc9n003686@bayview.thirdcreek.com> Patch / Bug Summary ___________________ Patches : 378 open ( +0) / 3216 closed (+17) / 3594 total (+17) Bugs : 894 open ( -7) / 5811 closed (+19) / 6705 total (+12) RFE : 216 open ( +2) / 215 closed ( +1) / 431 total ( +3) New / Reopened Patches ______________________ Rename functional to functools (2006-04-29) http://python.org/sf/1478788 opened by Collin Winter Take advantage of BaseException/Exception split in cookielib (2006-04-29) http://python.org/sf/1478993 opened by John J Lee Split open() and file() (2006-04-29) CLOSED http://python.org/sf/1479181 opened by Aahz ColorDelegator - Several bug fixes (2006-04-30) http://python.org/sf/1479219 opened by Tal Einat Fix building with SWIG's -c++ option set in setup.py (2006-04-30) http://python.org/sf/1479255 opened by dOb Make urllib2 digest auth and basic auth play together (2006-04-30) http://python.org/sf/1479302 opened by John J Lee with statement context managers - with should be keyword (2006-04-30) CLOSED http://python.org/sf/1479438 opened by Matt Fleming speed up function calls (2006-04-30) http://python.org/sf/1479611 opened by Neal Norwitz Heavy revisions to urllib2 howto (2006-05-01) http://python.org/sf/1479977 opened by John J Lee weakref dict methods (2006-05-01) CLOSED http://python.org/sf/1479988 opened by Fred L. Drake, Jr. urllib2 digest auth redirection bug causes 400 error (2006-05-01) CLOSED http://python.org/sf/1480067 opened by John J Lee patch smtplib:when SMTPDataError, rset crashes with sslerror (2006-05-03) http://python.org/sf/1481032 opened by kxroberto Support HTTP_REFERER in CGIHTTPServer.py (2006-05-03) http://python.org/sf/1481079 opened by S??bastien Martini Python long option support (2006-05-03) http://python.org/sf/1481112 opened by Heiko Wundram Cleaned up 16x16px icons for windows. (2006-05-03) http://python.org/sf/1481304 opened by goxe imputil "from" os.path import bug (2006-05-03) CLOSED http://python.org/sf/1481530 opened by Eric Huss Patches Closed ______________ --enable-universalsdk on Mac OS X (2006-04-17) http://python.org/sf/1471883 closed by ronaldoussoren Split open() and file() (2006-04-29) http://python.org/sf/1479181 closed by nnorwitz urllib2 ProxyBasicAuthHandler broken (2006-04-15) http://python.org/sf/1470846 closed by gbrandl Forbid iteration over strings (2006-04-16) http://python.org/sf/1471291 closed by gbrandl Fix for urllib/urllib2 ftp bugs 1357260 and 1281692 (2006-04-15) http://python.org/sf/1470976 closed by gbrandl cPickle produces locale-dependent dumps (2006-04-20) http://python.org/sf/1473625 closed by gbrandl IndentationError for unexpected indent (2006-04-25) http://python.org/sf/1475845 closed by loewis rlcompleter to be usable without readline (2006-04-19) http://python.org/sf/1472854 closed by gbrandl fix for #1472251 (2006-04-18) http://python.org/sf/1472263 closed by gbrandl with statement context managers - with should be keyword (2006-04-30) http://python.org/sf/1479438 closed by gbrandl fixed handling of nested comments in mail addresses (2006-04-05) http://python.org/sf/1464708 closed by bwarsaw weakref dict methods (2006-05-01) http://python.org/sf/1479988 closed by fdrake urllib2 digest auth redirection bug causes 400 error (2006-05-01) http://python.org/sf/1480067 closed by gbrandl Fix to allow urllib2 digest auth to talk to livejournal.com (2005-02-18) http://python.org/sf/1143695 closed by gbrandl pdb: fix for #1472191('clear' command bug) (2006-04-18) http://python.org/sf/1472184 closed by gbrandl __init__.py'less package import warnings (2006-04-26) http://python.org/sf/1477281 closed by gbrandl imputil "from" os.path import bug (2006-05-04) http://python.org/sf/1481530 closed by gbrandl New / Reopened Bugs ___________________ urllib2.Request constructor to urllib.quote the url given (2006-04-20) CLOSED http://python.org/sf/1473560 reopened by gbrandl 'compile' built-in function failures when missing EOL (2006-04-30) http://python.org/sf/1479099 opened by Ori Peleg test_inspect fails on WinXP (2.5a2) (2006-04-30) CLOSED http://python.org/sf/1479226 opened by Miki Tebeka Segmentation fault while using Tkinter (2006-05-01) http://python.org/sf/1479586 opened by Ali Gholami Rudi Uninstall does not clearn registry (2006-05-01) http://python.org/sf/1479626 opened by Miki Tebeka float->str rounding bug (2006-05-01) CLOSED http://python.org/sf/1479776 opened by Michael Nolta Quitter object masked (2006-05-01) http://python.org/sf/1479785 opened by Jim Jewett mmap tries to truncate special files (2006-05-02) CLOSED http://python.org/sf/1480678 opened by Carl Banks long(float('nan'))!=0L (2006-05-03) http://python.org/sf/1481296 opened by Erik Dahl parse_makefile doesn't handle $$ correctly (2006-05-03) http://python.org/sf/1481347 opened by Han-Wen Nienhuys Docs on import of email.MIMExxx classes wrong (2006-05-04) http://python.org/sf/1481650 opened by Hugh Gibson hpux ia64 shared lib ext should be ".so" (2006-05-04) http://python.org/sf/1481770 opened by David Everly Shift+Backspace exhibits odd behavior (2006-05-04) http://python.org/sf/1482122 opened by NothingCanFulfill socket.getsockopt bug (2006-05-05) CLOSED http://python.org/sf/1482328 opened by ganges master Forwarding events and Tk.mainloop problem (2006-05-05) http://python.org/sf/1482402 opened by Matthias Kievernagel asyncore is not listed in test_sundry (2006-05-05) http://python.org/sf/1482746 opened by jackilyn Bugs Closed ___________ urllib2.Request constructor to urllib.quote the url given (2006-04-20) http://python.org/sf/1473560 closed by gbrandl size limit exceeded for read() from network drive (2006-04-28) http://python.org/sf/1478529 closed by tim_one urllib2 AuthHandlers can pass a bad host to HTTPPasswordMgr (2004-02-20) http://python.org/sf/900898 closed by gbrandl test_inspect fails on WinXP (2.5a2) (2006-04-30) http://python.org/sf/1479226 closed by gbrandl urllib violates rfc 959 (2005-09-04) http://python.org/sf/1281692 closed by gbrandl urllib/urllib2 cannot ftp files which are not listable. (2005-11-15) http://python.org/sf/1357260 closed by gbrandl test_ctypes: undefined symbol: XGetExtensionVersion (2006-04-28) http://python.org/sf/1478253 closed by gbrandl compiler module does not detect a syntax error (2005-12-19) http://python.org/sf/1385040 closed by gbrandl Tkinter hangs in test_tcl (2006-04-23) http://python.org/sf/1475162 closed by loewis float->str rounding bug (2006-05-01) http://python.org/sf/1479776 closed by tim_one setup.py --help-commands exception (2006-04-16) http://python.org/sf/1471407 closed by jwpye HTMLParser doesn't treat endtags in <script> tags as CDATA (2004-10-21) http://python.org/sf/1051840 closed by fdrake HTMLParser can't handle page with javascript (2004-11-30) http://python.org/sf/1076070 closed by fdrake mmap tries to truncate special files (2006-05-02) http://python.org/sf/1480678 closed by tim_one urllib2 authentication problem (2003-02-05) http://python.org/sf/680577 closed by gbrandl urllib has trouble with Windows filenames (2006-02-22) http://python.org/sf/1436428 closed by gbrandl Defining a class with __dict__ brakes attributes assignment (2006-03-11) http://python.org/sf/1448042 closed by gbrandl pdb 'clear' command doesn't clear selected bp's (2006-04-18) http://python.org/sf/1472191 closed by gbrandl socket.getsockopt bug (2006-05-05) http://python.org/sf/1482328 closed by gangesmaster New / Reopened RFE __________________ Add SeaMonkey to webbrowser.py (2006-04-25) CLOSED http://python.org/sf/1476166 reopened by phd IOBaseError (2006-05-03) http://python.org/sf/1481036 opened by kxroberto RFE Closed __________ Add SeaMonkey to webbrowser.py (2006-04-25) http://python.org/sf/1476166 closed by gbrandl "idna" encoding (drawing unicodedata) necessary in httplib? (2006-04-18) http://python.org/sf/1472176 closed by gbrandl From cvanarsdall at mvista.com Mon May 22 14:25:30 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Mon, 22 May 2006 11:25:30 -0700 Subject: Software Needs Philosophers In-Reply-To: <1148321303.525258.180590@j55g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148254714.668727.298420@y43g2000cwc.googlegroups.com> <1148321303.525258.180590@j55g2000cwa.googlegroups.com> Message-ID: <4472021A.5070603@mvista.com> vjg wrote: > nikie wrote: > >> (BTW: Have you ever considered the possibility that philosophers might >> not be interested in tab-versus-spaces-debates in the first place? >> Maybe they have more interesting matters to discuss. Just like the rest >> of us.) >> > > Debate? There's no valid dabate. Tabs bad. Spaces good. > > Hrmms, I think we should debate about the debate now, I mean we've already beaten the actual topic to DEATH. .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From mike.klaas at gmail.com Wed May 24 19:42:38 2006 From: mike.klaas at gmail.com (Klaas) Date: 24 May 2006 16:42:38 -0700 Subject: Large Dictionaries In-Reply-To: <1147874585.728471@teuthos> References: <1147699064.107490@teuthos> <e49va0$m72$1@newsreader3.netcologne.de> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> Message-ID: <1148514158.790760.205630@i40g2000cwc.googlegroups.com> Chris: > class StorageBerkeleyDB(StorageTest): > def runtest(self, number_hash): > db = bsddb.hashopen(None, flag='c', cachesize=8192) > for (num, wildcard_digits) in number_hash.keys(): > key = '%d:%d' % (num, wildcard_digits) > db[key] = None > db.close() BDBs can accomplish what you're looking to do, but they need to be tuned carefully. I won't get into too many details here, but you have a few fatal flaws in that code. 1. 8Kb of cache is _pathetic_. Give it a few hundred megs. This is by far your nbiggest problem. 2. Use BTREE unless you have a good reason to use DBHASH 3. Use proper bdb env creation instead of the hash_open apis. 4. Insert your keys in sorted order. -Mike From fredrik at pythonware.com Tue May 2 03:15:49 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 May 2006 09:15:49 +0200 Subject: strip newlines and blanks References: <1146551463.451811.266960@j73g2000cwa.googlegroups.com> Message-ID: <e370vd$ue0$1@sea.gmane.org> micklee74 at hotmail.com wrote: > i have a file test.dat eg > > abcdefgh > ijklmn > <-----newline > opqrs > tuvwxyz > > > I wish to print the contents of the file such that it appears: > abcdefgh > ijklmn > opqrs > tuvwxyz > > here is what i did: > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line == '': > break > print line > > but it always give me first 2 lines, ie > abcdefgh > ijklmn > > What can i do to make it print all w/o the newlines..? and what is the > proper way to skip printing blank lines while iterating file contents? assuming you want to skip *all* blank lines (even if they have whitespace on them), for line in open("test.dat"): if line.strip(): print line </F> From grante at visi.com Tue May 9 10:13:31 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 09 May 2006 14:13:31 -0000 Subject: Why 3.0/5.0 = 0.59999... References: <1147159404.498386.58860@g10g2000cwb.googlegroups.com> Message-ID: <12618sbapnnij07@corp.supernews.com> On 2006-05-09, Davy <zhushenli at gmail.com> wrote: > When I type 3.0/5.0, the result is 0.59999... > > Is there some precision loss? And how to overcome it? Doesn't anybody read the FAQ? Or even browse through current threads before posting? Sheesh. This has been in the FAQ forever, and was answered again in the group just yesterday. > Any suggestions will be appreciated! I doubt it. -- Grant Edwards grante Yow! I'LL get it!! It's at probably a FEW of my visi.com ITALIAN GIRL-FRIENDS!! From paddy3118 at netscape.net Tue May 23 13:25:36 2006 From: paddy3118 at netscape.net (Paddy) Date: 23 May 2006 10:25:36 -0700 Subject: What's with the @ sign In-Reply-To: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> References: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> Message-ID: <1148405136.743780.46950@i40g2000cwc.googlegroups.com> Oh please, please, can I answer! They are decorators. Check-out http://zephyrfalcon.org/weblog2/arch_e10_00610.html#e610 (decorate this), or http://paddy3118.blogspot.com/ " Python function attributes" and then " Function Attributes assigned by decorator". Of course there is also: http://wiki.python.org/moin/PythonDecoratorLibrary - Pad. From anyab5 at gmail.com Sun May 28 02:27:51 2006 From: anyab5 at gmail.com (anya) Date: 27 May 2006 23:27:51 -0700 Subject: send an email with picture/rich text format in the body In-Reply-To: <iAJ9g.76667$H71.54770@newssvr13.news.prodigy.com> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <iAJ9g.76667$H71.54770@newssvr13.news.prodigy.com> Message-ID: <1148797671.937857.151250@y43g2000cwc.googlegroups.com> Acctualy there is a solution: see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 (thanks darrin massena for sharing) and , if you will set all the neccessary parametrs, it won't be recognized as a spam, thanks From collinw at gmail.com Sat May 27 19:44:23 2006 From: collinw at gmail.com (Collin Winter) Date: Sun, 28 May 2006 01:44:23 +0200 Subject: [ANNOUNCE]: typecheck 0.3.5 released Message-ID: <43aa6ff70605271644l388352e4qea9c7994b5eac194@mail.gmail.com> Hello all, I have released version 0.3.5 of my typecheck module, a Python module providing run-time typechecking facilities for function parameters and return values, as well as generator yield values. The main workhorses of this module, the functions accepts, returns and yields, are used as function/method decorators. These operate on a function arguments, function return values and generator yield values, respectively. A number of utility classes are provided to assist in building more complex signatures, for example, by creating boolean expressions based on classes and/or types. It is possible to incorporate typechecking facilities into user-defined classes. A mixin class, UnorderedIteratorMixin, is provided to allow easy typechecking of iterators. Numerous examples are provided as to how to integrate your own container classes into typecheck. Where to get it: ######### typecheck is available from the project's website at http://oakwinter.com/code/typecheck/ and from the Python Package Index at http://cheeseshop.python.org/pypi/typecheck Both source tarballs and Python Eggs for Python versions 2.4 and 2.5 are available. Release Notes ######## This is a bug-fix release: + After fixing an issue with the test suite, typecheck is now compatible with Python 2.5 + Compatibility issues: - Typeclass instances are no longer callable. This means that "Number() is not Number" is True. This was done to fix a bug with typeclasses. + Bug fixes: - Add an __all__ list to typecheck/__init__.py - Instances with __call__ methods can now be used as functions (ie, in conjunction with Function) - Unicode can now be used to specify type variables - Rename all message() methods on the internal _TC_* extensions to error_message() (Python 2.5's exceptions already have message attribute) - Add repr() and str() support to Typeclass instances - Fix a bug related to typecheck_args()'s checking of the number of arguments passed to the typechecked function - Fix SF #1495358; typeclasses can now actually be used. As always, feedback welcome! Collin Winter From wesbrooks at gmail.com Mon May 1 11:54:29 2006 From: wesbrooks at gmail.com (Wesley Brooks) Date: Mon, 1 May 2006 16:54:29 +0100 Subject: Passing events Message-ID: <eec9f8ee0605010854vcf82916hf1409d31221ce0ca@mail.gmail.com> Dear Users, Is it possible to pass events such as keyboard, mouse, and joystick events to any software application and take screen shots? In this example I would like to be able to control a car racing game using python script. Is it difficult to recieve and create events from devices like the steering wheels and pedals? Thanks again in advance of any help. Yours Sincerely, Wesley Brooks -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060501/7b65ee23/attachment.html> From justin.azoff at gmail.com Thu May 18 20:41:36 2006 From: justin.azoff at gmail.com (Justin Azoff) Date: 18 May 2006 17:41:36 -0700 Subject: newb: comapring two strings In-Reply-To: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> Message-ID: <1147999296.272119.155320@u72g2000cwu.googlegroups.com> manstey wrote: > Hi, > > Is there a clever way to see if two strings of the same length vary by > only one character, and what the character is in both strings. > > E.g. str1=yaqtil str2=yaqtel > > they differ at str1[4] and the difference is ('i','e') something like this maybe? >>> str1='yaqtil' >>> str2='yaqtel' >>> set(enumerate(str1)) ^ set(enumerate(str2)) set([(4, 'e'), (4, 'i')]) >>> -- - Justin From kent at kentsjohnson.com Wed May 3 08:17:17 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 03 May 2006 08:17:17 -0400 Subject: string.find first before location In-Reply-To: <87mze0dpg0.fsf@localhost.localdomain> References: <87hd49m0xc.fsf@localhost.localdomain> <e370ro$415$02$2@news.t-online.com> <87zmi0emhd.fsf@localhost.localdomain> <e37ff0$km9$00$1@news.t-online.com> <1146571862.234132.8670@u72g2000cwu.googlegroups.com> <87mze0dpg0.fsf@localhost.localdomain> Message-ID: <44589eec$1_3@newspeer2.tds.net> Gary Wessle wrote: > ps. is there a online doc or web page where one enters a method and it > returns the related docs? The index to the library reference is one place: http://docs.python.org/lib/genindex.html and of course help() in the interactive interpreter... Kent From bblais at bryant.edu Wed May 31 14:07:59 2006 From: bblais at bryant.edu (Brian Blais) Date: Wed, 31 May 2006 14:07:59 -0400 Subject: python to NQC converter? Message-ID: <447DDB7F.1030909@bryant.edu> Hello, I was wondering if anyone has written a converter between python code and NQC (http://bricxcc.sourceforge.net/nqc/) used for programming LEGO Mindstorms? I am thinking that a small modification to Pyrex might be used, but I am not sure how to proceed with something like that. I was thinking that 90% of it could be done by converting indentation to {}, cdef int X to int X declarations at the top, and other simple text-replace features. Brian Blais -- ----------------- bblais at bryant.edu http://web.bryant.edu/~bblais From rdjdvd at inwind.it Mon May 15 03:20:11 2006 From: rdjdvd at inwind.it (.) Date: 15 May 2006 00:20:11 -0700 Subject: Web framework to recommend In-Reply-To: <e495q1$1085$1@news.hgc.com.hk> References: <e495q1$1085$1@news.hgc.com.hk> Message-ID: <1147677611.333660.121430@j73g2000cwa.googlegroups.com> Hi Jacky, if you want make a good experiment, you can use: LocaWapp - localhost web applications http://cheeseshop.python.org/pypi/LocaWapp/09 Post here your feedback. Bye and good work D. Jacky ha scritto: > Hi all, > > I just started learning Python and would like to starting writing some > web-based applications with Python. > > I did have pretty much experience with doing so with PHP and Java, but > Python seems a bit different for me. > > Do you guys have some good web framework to recommend? (I don't want to > use CGI mode) > > Thanks a lot. > > -- > Jacky From Henk at PA3BTL.demon.nl Fri May 26 05:48:28 2006 From: Henk at PA3BTL.demon.nl (Henk van Asselt) Date: Fri, 26 May 2006 11:48:28 +0200 Subject: wincerapi In-Reply-To: <mailman.6185.1148550806.27775.python-list@python.org> References: <mailman.6185.1148550806.27775.python-list@python.org> Message-ID: <127djp45enfjief@corp.supernews.com> Tim Williams wrote: > Does anyone have a copy of the wincerapi module. It appears not to > be in the win32 extensions anymore, and I've googled lots but not > found it available anywhere. > > Thanks > Well, This is something I have been struggling for a long time as well. I have been writing something from scratch, which I hope to publish soon. It will be capable of copying files to/and from a CE Device, modify the registry, run programs on the CE device etc. Please stay tuned as I'm still working on it. I will upload it to http://henk.van.asselt.googlepages.com/home as soon as possible. Henk From bruno at modulix.org Fri May 26 07:58:06 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 26 May 2006 04:58:06 -0700 Subject: Python for my mum In-Reply-To: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> References: <1148643849.246001.105190@y43g2000cwc.googlegroups.com> Message-ID: <1148644686.320793.306180@38g2000cwa.googlegroups.com> > Someone has give my 78 year old mother a tool for learning French > vocabulary written in Python. Is it the tool or the vocabulary that's written in Python ? <g> > She has a plain vanilla Windows XP system and does not know what a > compiler is. One doesn't need to know what's a compiler is to use a program written in Python. Most of the time (that is: if the program is packaged for end-users), it's not even needed to know what's Python. Could you give more details about this tool and your problem with it ? From larry.bates at websafe.com Tue May 16 17:38:16 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 16 May 2006 16:38:16 -0500 Subject: Beautiful parse joy - Oh what fun In-Reply-To: <1147813885.337318.141070@g10g2000cwb.googlegroups.com> References: <1147813885.337318.141070@g10g2000cwb.googlegroups.com> Message-ID: <446A4648.6040402@websafe.com> rh0dium wrote: > Hi all, > > I am trying to parse into a dictionary a table and I am having all > kinds of fun. Can someone please help me out. > > What I want is this: > > dic={'Division Code':'SALS','Employee':'LOO ABLE'} > > Here is what I have.. > > html="""<table> <tr valign="top"><td width="24"><img > src="/icons/ecblank.gif" border="0" height="1" width="1" alt="" > /></td><td width="129"><b><font size="2" face="Arial">Division Code: > </font></b></td><td width="693"><font size="2" > face="Arial">SALS</font></td></tr> <tr valign="top"><td width="24"><img > src="/icons/ecblank.gif" border="0" height="1" width="1" alt="" /> <td > width="129"><b><font size="2" face="Arial">Employee: > </font></b></td> <td width="693"><font size="2" > face="Arial">LOO</font><b><font size="2" face="Arial"> </font></b><font > size="2" face="Arial">ABLE</font></td></tr></table> """ > > > from BeautifulSoup import BeautifulSoup > soup = BeautifulSoup() > soup.feed(html) > > dic={} > for row in soup('table')[0]('tr'): > column = row('td') > print column[1].findNext('font').string.strip(), > column[2].findNext('font').string.strip() > dic[column[1].findNext('font').string.strip()]= > column[2].findNext('font').string.strip() > > for key in dic.keys(): > print key, dic[key] > > The problem is I am missing the last name ABLE. How can I get "ALL" > of the text. Clearly I have something wrong with my font string.. but > what it is I am not sure of. > > Please and thanks!! > In the last row you have 3 <font> tags. The first one contains LOO the second one is empty and the third one contains ABLE. <td width="693"><font size="2" face="Arial">LOO</font><b> <font size="2" face="Arial"> </font></b> <font size="2" face="Arial">ABLE</font></td> Your code is not expecting the second (empty) tag. -Larry Bates From owong at castortech.com Tue May 23 11:14:03 2006 From: owong at castortech.com (Oliver Wong) Date: Tue, 23 May 2006 15:14:03 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147793491.658982.131450@v46g2000cwv.googlegroups.com> <1147796116.826750@elch.in-berlin.de> <1147905290_7@news-east.n> <87ves3wpuy.fsf@thalassa.informatimago.com> <1147963328.479963.4390@j33g2000cwa.googlegroups.com> Message-ID: <%EFcg.21898$zn1.7255@clgrps13> "Jonathon McKitrick" <j_mckitrick at bigfoot.com> wrote in message news:1147963328.479963.4390 at j33g2000cwa.googlegroups.com... > Pascal Bourguignon wrote: >> (defun ???? (&key (????? 10) (?? 1) (???? 0)) >> (loop :for i :from ???? :to ????? :by ?? :collect i)) > > How do you even *enter* these characters? My browser seems to trap all > the special character combinations, and I *know* you don't mean > selecting from a character palette. > > ? hey, this is weird... > > ? > > I've got something happening, but I can't tell what. > > Yes, I'm an ignorant Western world ASCII user. :-) What OS are you using? In Windows XP, you'd have to let the XP know that you're interested in input in languages other than English via "Control Panel -> Regional Settings -> Languages -> Text Services and Input Languages". There, you'd add input methods other than English. Each "input method" works in a sort of unique way, so you'll just have to learn them. For example, under English, you can use the "keyboard" input method which probably is what you're using now, or the "handwriting recognition" input method, or the "speech recognition" input method to insert english text. There are other input methods for the Asian languages (e.g. Chinese, Japanese, etc.) - Oliver From bjourne at gmail.com Sun May 28 01:20:20 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 28 May 2006 07:20:20 +0200 Subject: Best way to check that a process is running on a Unix system? In-Reply-To: <16de708d0605272205m66cbadc9h25e699fe4f7b32ec@mail.gmail.com> References: <16de708d0605272205m66cbadc9h25e699fe4f7b32ec@mail.gmail.com> Message-ID: <740c3aec0605272220ue9a1317r627ad38c914e4583@mail.gmail.com> > What is the best way to check that a process is running (or better yet > number of instances) based on the name of the process? Would have to > work on a unix/linux system. Use "ps -C proc_name". Then either read the nr of lines in the output (for the number of instances) or read the return value. 0 if the process is running. Or read the /proc/*/status files and check if your process is in any of them. -- mvh Bj?rn From fredrik at pythonware.com Thu May 18 10:52:40 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 16:52:40 +0200 Subject: Strange error In-Reply-To: <1147963014.880378.44270@i39g2000cwa.googlegroups.com> References: <1147962206.900840.19130@38g2000cwa.googlegroups.com> <mailman.5883.1147962743.27775.python-list@python.org> <1147963014.880378.44270@i39g2000cwa.googlegroups.com> Message-ID: <e4i1no$luc$1@sea.gmane.org> WSobczuk at gmail.com wrote: > The default values are both tags = {}, and still inside mysearch() I > sometimes get some value from previous call inside tags, when the tags > keyword argument is not specified. which is exactly what happens if you *update* the default argument. did you even bother to read the FAQ entry? </F> From singletoned at gmail.com Tue May 16 04:54:47 2006 From: singletoned at gmail.com (Ed Singleton) Date: Tue, 16 May 2006 09:54:47 +0100 Subject: Tabs versus Spaces in Source Code In-Reply-To: <4468B996.5000407@sweetapp.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <qz2ag.6572$fb2.2976@newssvr27.news.prodigy.net> <4468B996.5000407@sweetapp.com> Message-ID: <34bb7f5b0605160154i403f9b73q28c0579b1d82f8d9@mail.gmail.com> On 5/15/06, Brian Quinlan <brian at sweetapp.com> wrote: > The problem with tabs is that people use tabs for alignment e.g. > > def foo(): > ->query = """SELECT * > -> -> -> FROM sometable > -> -> -> WHERE condition""" > > Now I change my editor to use 8-space tabs and the code is all messed > up. Of course, a very disciplined group of people could be trained to > never use tabs except to align with the current block level but, in > practice, that doesn't work. Therefore tabs are bad. def foo(): ->query = """SELECT * -> .......FROM sometable -> .......WHERE condition""" That would solve it. Tabs for indentation, spaces for spacing. Ed From johnjsal at NOSPAMgmail.com Sun May 14 20:59:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 14 May 2006 20:59:13 -0400 Subject: comparing values in two sets In-Reply-To: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> Message-ID: <4467d343$0$9377$c3e8da3@news.astraweb.com> John Salerno wrote: > I'd like to compare the values in two different sets Oops, I guess I was a little too loose in my use of the word 'set'. I'm using sets in my program, but by this point they actually become strings, so I'm really comparing strings. Thanks for pointing that out to me, and I'll look into izip as well. I was wondering if I could use an iterator for this somehow. :) From ajones1 at gmail.com Wed May 24 14:28:55 2006 From: ajones1 at gmail.com (Adam Jones) Date: 24 May 2006 11:28:55 -0700 Subject: Web framework comparison video In-Reply-To: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> References: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> Message-ID: <1148495335.093460.153480@j55g2000cwa.googlegroups.com> Just as a note, TurboGears has added a lot that would change the scoring on this. The project has been moving pretty quickly towards 1.0 lately, and I would advise anyone interested in a comparison to check out the recent changes before making a final decision. The same will probably hold true for many of the projects mentioned though. From ullrich at math.okstate.edu Fri May 5 08:44:45 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Fri, 05 May 2006 07:44:45 -0500 Subject: Multiple Version Install? References: <gbtj52l54trlhekcht3mgdb8s60aa4k83d@4ax.com> <mailman.5338.1146763189.27775.python-list@python.org> Message-ID: <rjgm5299fp5pvostqlbnmi8gvipegl838s@4ax.com> On Thu, 4 May 2006 13:19:46 -0400, "Tim Peters" <tim.peters at gmail.com> wrote: >[David C.Ullrich] >> Would there be issues (registry settings, environment >> variables, whatever) if a person tried to install >> versions 1.x and 2.x simultaneously on one Windows >> system? Windows 98, if it matters. >> >> (I can handle the file associations with no problem.) > >There are generally no issues One more thing you Python guys got right. Just curious: How does pythonxx.dll determine things like where to find the standard library? That's the sort of thing I'd feared might cause confusion... >beyond file associations. Which is no problem. Either you add "Run 1.x" and "Run 2.x" to the context menu or you associate .py with a tiny windowless .exe that emulates the UNIX thing, reading the first line of the file and then running the appropriate python.exe. (Before I tried it I thought that second might slow down startup, but evidently even Windows is willing to load a program quickly if it's small enough - I've never noticed any delay.) > On Windows, >Python versions i.j.k and i'.j'.k' coexist happily so long as i != i' >or j != j'. For example, I currently have the python.org-released >Pythons 2.2.3, 2.3.5, and 2.4.3 installed on my Windows box. I wouldn't have bothered explaining why I cared except that I was under the impression that the official line was that if I wanted to use two versions I must be doing something wrong. I guess not, fine. > It would >be a challenge only if I wanted, say, 2.4.2 and 2.4.3 installed >simultaneously. > >Another possible issue is that whenever the major or minor version >numbers (i or j) change on Windows, you also need to install matching >versions of any 3rd party extensions you want. The major and minor >version numbers appear in the _name_ of the core Python DLL (like >python23.dll and python24.dll), and extensions with C code must be >compiled to link with the correct version of the Python DLL. No problem with the one emedding I want to use - no recompile needed, it requires that I simply set the name of the dll as a "property" of the "engine". (But simply setting dllname = "python2whatever.dll" gives errors about functions not found. Is this just me doing something wrong or did functions with certain names actually disappear? Not a complaint, just curious.) >> If anyone feels like pointing out that there's simply >> no reason to want to keep 1.x after installing the >> current version: By all means talk me into that! > >If you've been using extensions with 1.j.k, then as above they have no >chance of working with 2.j'.k' bejore you install 2.j' versions of >those extensions. That's a good reason to keep an old version. > >There have been thousands of bugfixes and language enhancements since >1.j.k too, and not all are 100% backward-compatible. > >In all, best advice is to keep the old version around until you're >sure you no longer need it. > >> The problem is not that I'm concerned about backwards >> compatibility of Python code. The problem is that I >> use Python embedded in various Delphi programs, >> including a "DIDE" that I use really a lot, via >> a certain set of Delphi "components". These components >> don't seem to work with 2.x. Presumably the PyDelphi >> people have new versions of the components that do >> work with Python 2.x. These presumably use much >> newer versions of Delphi than what I have. A new >> version of Delphi is not free... If I could use >> Python 2.x when I need to while continuing to >> use 1.x the way I have been for things that >> don't need 2.x that would be convenient. > >That should work fine. I don't know about PyDelphi, but found what >appears to be a still-active discussion list: > > http://groups.yahoo.com/group/pythonfordelphi/ > >The theoretical joy of open source is that if they _don't_ support the >Python+Delphi combo you have, you can fix that yourself ;-) Crossed my mind, but only briefly - "theoretically" seems right. (One of the big improvements in later versions of Delphi is reference-counted/garbage-colleted dynamically sized arrays. Taking code using them and converting it to code with manual memory management seems like it would be a fairly major pain. Especially if a person wanted to get it right...) But thanks, theoretically. ************************ David C. Ullrich From bignose+hates-spam at benfinney.id.au Wed May 3 17:46:17 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 May 2006 07:46:17 +1000 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <mailman.5241.1146613795.27775.python-list@python.org> <D6T5g.66662$F_3.65091@newssvr29.news.prodigy.net> Message-ID: <87lktidbo6.fsf@benfinney.id.au> Edward Elliott <nobody at 127.0.0.1> writes: > As long as we're trotting out aphorisms The ones I quoted were from Python. >>> import this > how about DRY: Don't Repeat Yourself. The rule couldn't be clearer: > don't repeat your SELF. ;) Yet that's exactly what explicitly > declaring self does, forces me to needlessly repeat what everyone > already knows: methods take the object instance as their first > parameter. You've misunderstood "don't repeat yourself". It advocates *one* definition of any given thing in the code. You are advocating *zero* definitions of 'self' in the code. -- \ "No wonder I'm all confused; one of my parents was a woman, the | `\ other was a man." -- Ashleigh Brilliant | _o__) | Ben Finney From deets at nospam.web.de Fri May 26 10:58:56 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 26 May 2006 16:58:56 +0200 Subject: a good explanation In-Reply-To: <1148651639.899363.83240@y43g2000cwc.googlegroups.com> References: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> <4dlmsqF1abojeU1@uni-berlin.de> <1148561036.982387.316920@j33g2000cwa.googlegroups.com> <slrne7bhrs.rhj.nick@irishsea.home.craig-wood.com> <1148651639.899363.83240@y43g2000cwc.googlegroups.com> Message-ID: <4dojdgF1b2r34U1@uni-berlin.de> > Something that is being missed is the idea of changing conditions. A > for loop assumes known boundaries. > > def condition_test(): > # check socket status > # return true if socket good, false otherwise > > while condition_test(): > # do stuff > > allows the loopiing code to react to changing conditions. Which of > couse is why we like to keep while loops around ;-0 You can always use break to, well, break out of the loop - and as for is working over iterables which might very well be generators that deliver an infinite amount of data, the break-condition can (and often will, even if one used while) work on the current object instead of some otherwise unsused index. So above becomes: for item in items: if condition(item): break ... where the while would be still pretty ugly IMHO :) Diez From levub137 at wi.rr.com Sun May 7 12:14:19 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 07 May 2006 16:14:19 GMT Subject: python rounding problem. In-Reply-To: <87ody9amsd.fsf@localhost.localdomain> References: <mailman.5443.1146987087.27775.python-list@python.org> <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> Message-ID: <v1p7g.2791$WP5.2031@tornado.rdc-kc.rr.com> Gary Wessle wrote: > Erik Max Francis <max at alcyone.com> writes: > > >>chun ping wang wrote: >> >> >>>Hey i have a stupid question. >>>How do i get python to print the result in only three decimal >>>place... >>>Example>>> round (2.995423333545555, 3) >>>2.9950000000000001 >>>but i want to get rid of all trailing 0's..how would i do that? >> >>Floating point arithmetic is inherently imprecise. This is not a >>Python problem. > > > does python support true rations, which means that 1/3 is a true > one-third and not 0.333333333 rounded off at some arbitrary precision? > Python doesn't directly support rationals but there are at least two third party modules that add this capability to Python. http://calcrpnpy.sourceforge.net/clnumManual.html http://gmpy.sourceforge.net/ From klaus at seistrup.dk Wed May 24 10:23:53 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Wed, 24 May 2006 14:23:53 +0000 (UTC) Subject: How to find out a date/time difference References: <1148479557.226541.323100@i40g2000cwc.googlegroups.com> Message-ID: <e51q9p$onh$1@minji.szn.dk> Lad skrev: > How can I find out the date/time difference ( in days) of such > two fields? Did you try to subtract one value from the other? Mvh, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From tsaar2003 at yahoo.com Wed May 3 01:28:55 2006 From: tsaar2003 at yahoo.com (tsaar2003 at yahoo.com) Date: 2 May 2006 22:28:55 -0700 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <4457cb5b$0$16422$626a54ce@news.free.fr> Message-ID: <1146634135.469447.54670@j73g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > tsaar2003 at yahoo.com a ?crit : > > Hi Pythonians, > > > > To begin with I'd like to apologize that I am not very experienced > > Python programmer so please forgive me if the following text does not > > make any sense. > > > > I have been missing constants in Python language. > > Why so ? > > I guess you're talking about named (symbolic) constants ? If so, just > follow the convention : a name in ALL_UPPERCASE is a constant (or at > least will be treated as such by anyone not wanting to mess with your > package's implementation). No need to add extra syntax here IMHO. Hi Bruno, For example: >>> A = [] # let's declare a "constant" here >>> b = A # and let's assign the constant here >>> b.append('1') # OOPS! >>> c = A >>> print A ['1'] >>> print b ['1'] >>> print c ['1'] As you can see, the "constant" A can be modified this easily. But if there were an intuitive mechanism to declare a symbol to be immutable, then there won't be this problem. Br, - T.S. From nobody at 127.0.0.1 Sat May 20 14:43:39 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 20 May 2006 18:43:39 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> Message-ID: <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> A little out-of-order execution seems useful here. ;) John Bokma wrote: > Edward Elliott <nobody at 127.0.0.1> wrote: >> I can readily believe that the "community" frequenting the newsgroups, >> mailing lists, and blogs don't encourage it anymore. But that's a >> tiny fraction of all perl programmers, and most of them have no >> exposure to this little clique. > > Pfft, you are just guessing around now. How many organizations have you worked at? How much exposure to coders whose daily job description doesn't include the word programming? I've been at Fortune 100 companies with thousands of programmers and support staff, and at startups with a half dozen employees. I've been employed at 3 universities from small to huge. I know full-time software developers, software testers, sys admins, network admins, managers, web developers, graphic artists, physics researchers, bioinformatics researchers, instructors, librarians, consultants, contractors, hardware engineers, forensic analysts, and even a law professor. They all code perl to some degree. Many of them don't even know what a newsgroup is, and you can have their cookbook when you pry it from their cold dead hands. Guessing? Hardly. Just not trapped in your insular world of who makes up the perl "community". >>> Don't forget that most >>> of the book was written around 1998. Yes, 8 years ago. >> >> Doesn't matter. > > Yes it matters. 8 years is a lot of time in IT. In 1998 Perl5.005 was > announced (22 July). [1] Which should tell you a lot if you indeed have > 3 years of Perl skills. Tell that to everyone who relies on the cookbook. It gets their job done. They don't care if it was written in the dark ages. Until a replacement comes along, that's what they'll use. Of course Perl itself has moved on, that's not the point. > If they are serious with their study they know that a 8 year old book is > hardly up to date. I tend to take most IT related books I use that are > older then 3-4 years with quite a grain of salt. I am not going to take > an 8 year old Java CookBook very seriously for example. Many/most people aren't "serious with their study" of perl. They just want to get things done. Perl 5 works for them now, it will work for them 10 years from now. Unless something significantly better comes along to justify the cost of switching, they'll stick with what they know. And that includes perl 6. One would hope an updated cookbook is out before then. Or maybe it's not needed because the current one works just fine. Time isn't a great measure of language change. A C++ book from 8-10 years ago is just as good as one today in most respects (maybe exceptions and templates are a bit underused). A C book from 20 years ago is perfectly fine for most purposes (how well does K&R stand the test of time?). C99 and C++0x aren't revolutionary changes (ISO committees frown on such things). God only knows how far back useful LISP resources go. >>> You can even find examples on my site that use imported functions >>> (which I will fix, because I frown upon it :-) ). But I doubt you can >>> find a majority in the perl community that *encourages* the use of >>> imported functionality. I'm not arguing what best practices the hardcore community recommends. Many/most perl programmers aren't part of that community, their only exposure is the perl books (especially the cookbook), and they'll do whatever it says in there. Call perl a victim of its own success (a nice position to be in). >> For many people, whatever the >> cookbook says goes. If it's wrong, update it. > > Well, contact the authors or O'Reilly. Sorry, I've got a bad case of "not my problem". ;) > Seriously, are you using 8 year > old Python recipes without thinking? Sure, if they do the job and an updated reference isn't handy. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From asmirnov1234567890 at yahoo.com Wed May 10 12:19:42 2006 From: asmirnov1234567890 at yahoo.com (asmirnov1234567890 at yahoo.com) Date: 10 May 2006 09:19:42 -0700 Subject: Python module generation (in C) from XML spec Message-ID: <1147277982.749508.284370@y43g2000cwc.googlegroups.com> Hi does anybody knows any tool to accomplish such task: given XML spec of Python module C code should be produced. Regards, Andrei Smirnov From chris.cavalaria at free.fr Thu May 4 09:26:08 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 04 May 2006 15:26:08 +0200 Subject: Because of multithreading semantics, this is not reliable. In-Reply-To: <4459f1dd$1_2@newspeer2.tds.net> References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <mailman.5280.1146690817.27775.python-list@python.org> <1146691613.911363.242620@e56g2000cwe.googlegroups.com> <4459c03b$0$2633$636a55ce@news.free.fr> <4459f1dd$1_2@newspeer2.tds.net> Message-ID: <445a014a$0$18281$636a55ce@news.free.fr> Olaf Meding a ?crit : >>return result before that line, some other thread added a value ! > > > Sure, but that is the nature of using threads and a mutex. I hope you are > you not saying that every function that uses a mutex should have a comment > saying this is not "reliable"? That function can return a value that was already obsolete even before it finished executing. And so special care should be taken by the user so that he can either cope with that or make sure that it doesn't happens. As was said, it's the same reason the user should not do a if fileExists() followed by a openFile. Same reason that there is a warning in the "os.access" manual From iddw at hotmail.com Thu May 18 15:43:21 2006 From: iddw at hotmail.com (Dave Hansen) Date: Thu, 18 May 2006 14:43:21 -0500 Subject: Sorting of list containing tuples References: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> Message-ID: <bgjp62p2o57lrh162fah3d0oe3e6p9gm8h@4ax.com> On Thu, 18 May 2006 21:29:59 +0200 in comp.lang.python, Ronny Mandal <ronnyma at math.uio.no> wrote: >Hi! > >Assume we have a list l, containing tuples t1,t2... > >i.e. l = [(2,3),(3,2),(6,5)] > >And now I want to sort l reverse by the second element in the tuple, >i.e the result should ideally be: > > l = [(6,5),(2,3),(3,2)] > > >Any ideas of how to accomplish this? > > >Thanks, > >Ronny Mandal >>> def my_cmp(t1,t2): c1 = t1[1] c2 = t2[1] if c1 > c2: return 1 if c2 > c1: return -1 return 0 >>> l [(2, 3), (3, 2), (6, 5)] >>> l.sort(cmp=my_cmp, reverse = True) >>> l [(6, 5), (2, 3), (3, 2)] HTH, -=Dave -- Change is inevitable, progress is not. From usenet.loser at usenet.loser Wed May 3 20:10:20 2006 From: usenet.loser at usenet.loser (Usenet Loser) Date: Thu, 04 May 2006 00:10:20 GMT Subject: OT: CAD Message-ID: <MDb6g.9511$9o4.5810@tornado.tampabay.rr.com> I am completely empty and shallow. I use no CAD package at all now. I would like to buy one for recreational use, instead of watching American Idol. What CAD package has integrated FEA and rigid body calculations so that I could design a bar stool, and easily determine: a) if it is top-heavy, so that drunken customers could easily tip it over, and b) if a fat drunken customer sat on it, which part would give way first. Also, are there such things as libraries of materials that I could specify, which the FEA would take into account, so that a bar stool made of PVC would bend differently from a bar stool made of tungsten? Also, what about Python and CAD? I've seen http://free-cad.sourceforge.net and pythoncad, but have any major CAD vendors incorporated Python, sort of the way that ESRI used Python in it's ArcView GIS product? From rdjdvd at inwind.it Fri May 12 18:24:50 2006 From: rdjdvd at inwind.it (.) Date: 12 May 2006 15:24:50 -0700 Subject: LocaWapp 09 - localhost web applications (add thread, add "Request" object, new "locawapp_main" function, fixed files.py, " ...) Message-ID: <1147472690.904373.324830@j33g2000cwa.googlegroups.com> http://daviderognoni.blogspot.com?locawapp - MAIN NEWS =========== * add thread * add "Request" object * new "locawapp_main" function * fixed files.py * ... - DESCRIPTION ============= LocaWapp want use HTML and Python not only for the web, but also for the local applications: Local + HTML + Python = LocaWapp HTML = (CSS, images, JS, ...) The LocaWapp mission is to build useful and beautiful LWA-UI (LocaWapp User Interfaces) for the main functions of the system operator. LocaWapp is searching free programmers, free designers, free business-men that want advertise yourself with this open project. - QUICKSTART ============ * Run: python run.py * and browse: http://localhost:8080/locawapp/main.py * You can change the port: python run.py 8081 - DEVELOPING WITH THIS FRAMEWORK ================================ * Put your application folder in root directory: [your_application] [locawapp] ....__init__.py ....common.py ....main.py ....[static] ........logo.gif ........main.css ........main.js LICENSE.html README.html run.py * Your application must have "init" and "main" files (for convention): [your_application] ....__init__.py ....main.py ....other web applications (ex. main2.py) ....your files or folders (ex. your [static]) * main.py is a web application, then it has "locawapp_main" function: def locawapp_main(request): [...] html = [...String...] request.sendResponse(html) * See locawapp.main.py and locawapp.common.py - UNDER CONSTRUCTION ==================== Aioxml - is not xml (data formatter) From raims at dot.com Mon May 8 02:44:57 2006 From: raims at dot.com (Lawrence Oluyede) Date: Mon, 08 May 2006 08:44:57 +0200 Subject: Why list.sort() don't return the list reference instead of None? References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> Message-ID: <87wtcx9frq.fsf@voodoo.myself> "ankyhe at gmail.com" <ankyhe at gmail.com> writes: > I want to ask why the designer of Python do so? I'm not a Python core developer nor a designer but I've always known that sort() is a in-place sort and since the list is a mutable object it mutates the list sending the "sort()" message. If you want to get back a sorted iterable use... sorted :) L = [3, 1, 2] ls = sorted(L) now ls is your list, sorted. -- Lawrence - http://www.oluyede.org/blog "Nothing is more dangerous than an idea if it's the only one you have" - E. A. Chartier From smadim2 at grads.ece.mcmaster.ca Fri May 26 19:15:17 2006 From: smadim2 at grads.ece.mcmaster.ca (M.N.A.Smadi) Date: Fri, 26 May 2006 19:15:17 -0400 Subject: stupid perl question Message-ID: <44778C05.9020701@grads.ece.mcmaster.ca> hi guys; sorry for sending a perl question here, but python guy "HAD TO" look at perl code; how can i split a string that contains white spaces and '_' any clue? thanks moe smadi From santosh.pandey at gmail.com Thu May 4 18:09:53 2006 From: santosh.pandey at gmail.com (san) Date: 4 May 2006 15:09:53 -0700 Subject: Can I use python for this .. ?? In-Reply-To: <1146779044.307500.50810@u72g2000cwu.googlegroups.com> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146774288.904851.278130@i39g2000cwa.googlegroups.com> <1146779044.307500.50810@u72g2000cwu.googlegroups.com> Message-ID: <1146780593.481020.272500@g10g2000cwb.googlegroups.com> Petr I dont want hibernation .. its more like starting a list of programs when i want to have fun time on my pc... but thanx for ur reply .. From steve at hastings.org Wed May 3 17:37:02 2006 From: steve at hastings.org (Steve R. Hastings) Date: Wed, 03 May 2006 14:37:02 -0700 Subject: scope of variables References: <874q06bz4c.fsf@localhost.localdomain> Message-ID: <pan.2006.05.03.21.37.01.804277@hastings.org> On Thu, 04 May 2006 07:02:43 +1000, Gary Wessle wrote: > b = 3 > def adding(a) > print a + b > > it seams not to see the up-level scope where b is defined. Assuming you put a ':' after the "def adding(a)", this should work in recent versions of Python. In Python 2.0 and older, this will not work. In Python 2.1, it will only work if you do this: from __future__ import nested_scopes When you first start Python interactively, it should print version information. Here's what my Python prints when I start it: Python 2.4.3 (#2, Apr 27 2006, 14:43:58) [GCC 4.0.3 (Ubuntu 4.0.3-1ubuntu5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. As you can see, I'm running Python 2.4.3. Make sure you aren't running an old version of Python, and that code should do what you expect. -- Steve R. Hastings "Vita est" steve at hastings.org http://www.blarg.net/~steveha From michele.simionato at gmail.com Tue May 9 03:59:41 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 May 2006 00:59:41 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hf1hlk.uf6b5hc60js1N%aleax@mac.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <m264kguu4c.fsf@Dagney.local> <1hf1hlk.uf6b5hc60js1N%aleax@mac.com> Message-ID: <1147161581.850130.164530@i40g2000cwc.googlegroups.com> Alex Martelli wrote: yes, if that was my only > choice, I'd much rather use small, simple Scheme than huge, complicated, > rich, powerful Common Lisp. ((But in this case I'm biased by early > experiences, since when I learned and used Lisp-ish languages there WAS > no Common Lisp, while Scheme was already there, although not quite the > same language level as today, I'm sure;-)). Alas, today Scheme is not minimal at all. I mean, the document describing the standard is short, but real implementations are pretty rich. I am also surprised by your claim in this thread that Scheme macros are simpler than Common Lisp macros; perhaps, you are not familiar with syntax-case. BTW, there is still research going on on macros, for instance look at http://srfi.schemers.org/srfi-72/srfi-72.html which is pretty nice. Just to bring some info in yet another useless usenet flamewar. Michele Simionato From jason at tishler.net Thu May 4 11:55:08 2006 From: jason at tishler.net (Jason Tishler) Date: Thu, 4 May 2006 11:55:08 -0400 Subject: Problem building extension under Cygwin (ImportError: Bad address) In-Reply-To: <1146749003.095894.281280@j73g2000cwa.googlegroups.com> References: <1146739813.157265.238320@i39g2000cwa.googlegroups.com> <mailman.5322.1146745099.27775.python-list@python.org> <1146749003.095894.281280@j73g2000cwa.googlegroups.com> Message-ID: <20060504155508.GA2948@tishler.net> On Thu, May 04, 2006 at 06:23:23AM -0700, Lars wrote: > But first compiling hello.c with gcc, then linking it with gnu-ld just > won't work. I only really need to compile one C-file to a shared > library so it doesn't matter so much for me. But bigger projects will > have a problem.. No, it works if you drive it from gcc: $ gcc -I/usr/include/python2.4 -c hello.c $ gcc -shared -o hello.dll hello.o -L/usr/lib/python2.4/config -lpython2.4 $ python hellouse.py Hello, C Hello, module /tmp/examples/PP2E/Integrate/Extend/Hello/hello.dll Hello, 0 Hello, 1 Hello, 2 BTW, if you use Distutils, then it will just work... Jason -- PGP/GPG Key: http://www.tishler.net/jason/pubkey.asc or key servers Fingerprint: 7A73 1405 7F2B E669 C19D 8784 1AFD E4CC ECF4 8EF6 From greg at cosc.canterbury.ac.nz Sat May 6 00:50:01 2006 From: greg at cosc.canterbury.ac.nz (greg) Date: Sat, 06 May 2006 16:50:01 +1200 Subject: ANN: PyGUI 1.7.1 Message-ID: <mailman.5414.1146896794.27775.python-announce-list@python.org> PyGUI 1.7.1 is now available: http://www.cosc.canterbury.ac.nz/~greg/python_gui/ New features: - Slider control. - run() convenience function, equivalent to application().run(). - Geometry.rects_intersect() function. Enhancements: - Files given on the command line opened at application startup. - BlobEdit example extended to demonstrate update_rect usage. Bug fixes: - Disabled a debugging statement that was inadvertently left on in Cursor.__init__. - Changed the package name in setup.py to something more meaningful than 'foo'. What is PyGUI? -------------- PyGUI is an experimental highly-Pythonic cross-platform GUI API. Implementations are currently available for MacOSX and Gtk. For a full description of the project goals, see the PyGUI web page at the above address. From ptmcg at austin.rr._bogus_.com Fri May 19 00:23:04 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 04:23:04 GMT Subject: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> Message-ID: <IKbbg.44583$CH2.28892@tornado.texas.rr.com> "manstey" <manstey at csu.edu.au> wrote in message news:1147992792.038103.151360 at j55g2000cwa.googlegroups.com... > Hi, > > Is there a clever way to see if two strings of the same length vary by > only one character, and what the character is in both strings. > > E.g. str1=yaqtil str2=yaqtel > > they differ at str1[4] and the difference is ('i','e') > >>> def offByNoMoreThanOneCharacter(a,b): ... return len(a)==len(b) and sum(map(lambda (x,y): x==y, zip(a,b))) >= len(a)-1 ... >>> offByNoMoreThanOneCharacter("abc","abd") True >>> offByNoMoreThanOneCharacter("abc","axd") False >>> offByNoMoreThanOneCharacter("yaqtil","yaqtel") True >>> offByNoMoreThanOneCharacter("yiqtol","yaqtel") False This takes advantage of the Python convention that True evaluates to 1 and False evaluates to 0. -- Paul From pjm at spe.com Mon May 8 16:41:39 2006 From: pjm at spe.com (Patrick May) Date: Mon, 08 May 2006 21:41:39 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> Message-ID: <m264kguu4c.fsf@Dagney.local> aleax at mac.com (Alex Martelli) writes: > ...an alleged reply to me, which in fact quotes (and responds to) > only to statements by Brian, without mentioning Brian... > > Mr May, it seems that you're badly confused regarding Usenet's > quoting conventions. It seems that someone pisses in your cornflakes nearly every morning. For the record, I was attempting to respond to your post which I only saw quoted in another message. Please excuse any accidental misquoting. >> Using lambda in an expression communicates the fact that it >> will be used only in the scope of that expression. Another benefit >> is that declaration at the point of use means that all necessary >> context is available without having to look elsewhere. Those are >> two pragmatic benefits. > > You still need to look a little bit upwards to the "point of use", > almost invariably, to see what's bound to which names -- so, you DO > "have to look elsewhere", nullifying this alleged benefit -- looking at > the def statement, immediately before the "point of use", is really no > pragmatic cost when you have to go further up to get the context for all > other names used (are they arguments of this function, variables from a > lexically-containing outer function, assigned somewhere...), which is > almost always. It appears that you write much longer functions than I generally do. Requiring that all functions be named adds even more to the clutter. > And if you think it's an important pragmatic advantage to limit > "potential scope" drastically, nothing stops you from wrapping > functions just for that purpose around your intended scope Or, I could just use a language that supports unnamed functions. > Your "pragmatic benefits", if such they were, would also apply to the > issue of "magic numbers", That claim is, frankly, silly. A function is far more understandable without a name than a value like 1.19 in isolation. The situations aren't remotely comparable. >> >> 3. It adds another construction to the language. >> >> That's a very minimal cost relative to the benefits. > > To my view of thinking, offering multiple semantically equivalent > ways (or, perhaps worse, "nearly equivalent but with subtle > differences" ones) to perform identical tasks is a *HUGE* conceptual > cost: I like languages that are and stay SMALL and SIMPLE. Like Scheme? Regards, Patrick ------------------------------------------------------------------------ S P Engineering, Inc. | The experts in large scale distributed OO | systems design and implementation. pjm at spe.com | (C++, Java, Common Lisp, Jini, CORBA, UML) From bborcic at gmail.com Fri May 19 04:44:03 2006 From: bborcic at gmail.com (Boris Borcic) Date: Fri, 19 May 2006 10:44:03 +0200 Subject: Segmenting a pickle stream without unpickling Message-ID: <446d8566$1_3@news.bluewin.ch> Assuming that the items of my_stream share no content (they are dumps of db cursor fetches), is there a simple way to do the equivalent of def pickles(my_stream) : from cPickle import load,dumps while 1 : yield dumps(load(my_stream)) without the overhead associated with unpickling objects just to pickle them again ? TIA, Boris Borcic From ahaas at airmail.net Thu May 25 17:15:32 2006 From: ahaas at airmail.net (Art Haas) Date: Thu, 25 May 2006 16:15:32 -0500 Subject: [ANNOUNCE] Thirty-second release of PythonCAD now available Message-ID: <20060525211532.GB2132@artsapartment.org> Hi. I'm pleased to announce the thirty-second development release of PythonCAD, a CAD package for open-source software users. As the name implies, PythonCAD is written entirely in Python. The goal of this project is to create a fully scriptable drafting program that will match and eventually exceed features found in commercial CAD software. PythonCAD is released under the GNU Public License (GPL). PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 based, and uses the PyGTK module for interfacing to GTK. The design of PythonCAD is built around the idea of separating the interface from the back end as much as possible. By doing this, it is hoped that both GNOME and KDE interfaces can be added to PythonCAD through usage of the appropriate Python module. Addition of other PythonCAD interfaces will depend on the availability of a Python module for that particular interface and developer interest and action. The thirty-second release fixes a configuration problem where the newly added autosplitting feature would not be activated properly or could disable autosplitting in a Layer. A small bug in the reworked splitting code was also fixed, as well as a few other small errors. A mailing list for the development and use of PythonCAD is available. Visit the following page for information about subscribing and viewing the mailing list archive: http://mail.python.org/mailman/listinfo/pythoncad Visit the PythonCAD web site for more information about what PythonCAD does and aims to be: http://www.pythoncad.org/ Come and join me in developing PythonCAD into a world class drafting program! Art Haas -- Man once surrendering his reason, has no remaining guard against absurdities the most monstrous, and like a ship without rudder, is the sport of every wind. -Thomas Jefferson to James Smith, 1822 From duncan.booth at invalid.invalid Wed May 17 07:57:39 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 17 May 2006 11:57:39 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <Xns97C65986E948Dduncanbooth@127.0.0.1> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> <1147858647.488974.92230@j73g2000cwa.googlegroups.com> <1147862865.142339.117610@j55g2000cwa.googlegroups.com> Message-ID: <Xns97C683D60F53Fduncanbooth@127.0.0.1> achates wrote: > It's horrible but at least it would insulate me from the greater > hideousness of having to hit the spacebar like a madman at the start of > every line of code. I can even see how to get it to work in vi at > least. Hitting the spacebar like a madman? If you have a sensible editor then at the start of a line you press tab once for each additional level of indentation and backspace once for each fewer level and neither if the indentation is guessed correctly by the editor. in another post you suggested to someone else: > Sorry to hear that. You should try using an editor that's easier for > you. From deets at nospam.web.de Fri May 5 09:52:42 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 15:52:42 +0200 Subject: how to remove 50000 elements from a 100000 list? References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> Message-ID: <4c13mdF13esivU1@uni-berlin.de> Ju Hui wrote: > I want to remove about 50000 elements from a list,which has 100000 > elements. > sample code like below: > >>>> a=range(10) >>>> b=range(4) >>>> for x in b: > ... a.remove(x) > ... >>>> a > [4, 5, 6, 7, 8, 9] > > when a and b is small size, it will finished quickly, but when a and b > have many elements. > such as: >>>> a=range(100000) >>>> b=range(50000) >>>> for x in b: > ... a.remove(x) > ... > it will very slowly. Shall I change to another data structure and choos > a better arithmetic? How about a listcomprehension? new_list = [e for e in old_list if predicate(e)] # Possibly you need this, too: old_list[:] = new_list Diez From aleax at mac.com Mon May 8 23:38:14 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 8 May 2006 20:38:14 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> Message-ID: <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> Joe Marshall <eval.apply at gmail.com> wrote: ... > If you language allows unnamed integers, unnamed strings, unnamed > characters, unnamed arrays or aggregates, unnamed floats, unnamed > expressions, unnamed statements, unnamed argument lists, etc. why > *require* a name for trivial functions? I think it's reasonable to make a name a part of functions, classes and modules because they may often be involved in tracebacks (in case of uncaught errors): to me, it makes sense to let an error-diagnosing tracebacks display packages, modules, classes and functions/methods involved in the chain of calls leading to the point of error _by name_. I think it's reasonable to make a name a part of types for a different reason: new types are rarely meant to be used "just once"; but also, if during debugging any object is displayed, it's nice to be able to show, as part of the display, "this object is of type X and ...", with X shown as a name rather than as a complete (thus lengthy) description. (any decent interactive shell/debugger will let you drill down into the details as and when you need to, of course, but a well-chosen name can be often sufficient during such interactive exploration/debugging sessions, and therefore save time and effort). This doesn't stop a programmer from using a meaningless name, of course, but it does nudge things in the right direction. > Wouldn't all the other constructs benefit by having a required name as > well? I believe this is a delicate style call, but I agree with your implication that a language should at least _allow_ any object to have a name (even when such objects are more often constructed on the fly, they could still usefully borrow the first [or, maybe, the latest] name they're bound to, if any). If I was designing a language from scratch, I'd probably have as the first few fields of any object _at least_...: a cell pointing to the type object, a utility cell for GC (reference count or generation-count + markflag) a cell pointing to the name object, ...rest of the object's value/state to follow... Indeed, "given an object, how do I get its NAME" (for inspection and debugging purposes) is the most frequently asked question on comp.lang.python, and I've grown a bit tired of answering "you can't, an object in general intrinsically ``has no name'', it might have many or none at all, blah blah" -- yeah, this is technically true (in today's Python), but there's no real reason why it should stay that way forever (IMHO). If we at least ALLOWED named objects everywhere, this would further promote the use of names as against mysterious "magic numbers", since the programmer would KNOW that after VAT_MULTIPLIER = 1.19 then displaying in a debugger or other interactive session that PARTICULAR instance of the value 1.19 would show the name string 'VAT_MULTIPLIER' as well (or no doubt a more structured name constructed on the fly, identifying package and module-within-package too). As to what good practices should be more or less mandated by the language, and what other good practices instead should be just gently nudged towards, that's an interesting design question in each case; to me, a cornerstone for answering it is generally _language simplicity_. When mandating a certain good practice DETRACTS from language simplicity, make it a matter of convention instead; when so mandating ENHANCES language simplicity (by not needing the addition of some other construct, otherwise unneeded in the language), go for the mandate. Mandating names for _everything_ would complicate the language by forcing it to provide builtin names for a lot of elementary building blocks: so for most types of objects it's best to "gently nudge". For functions, classes, modules, and packages, I think the naming is important enough (as explained above) to warrant a syntax including the name; better, therefore, not to complicate the language by providing another different syntax in each case just to allow the name to be omitted -- why encourage a pratice that's best discouraged, at the price of language simplicity? This DOES imply that some (functions, modules, etc) that are fundamental to the language (and needed to build others) should be provided with a name, but then one tends to do that anyway: what language *DOESN'T* provide (perhaps in some suitable "trigonometry" module) elementary functions named (e.g.) sin, cos, tan, ..., to let the user build richer ones on top of those? Alex From william.boquist at gte.net Tue May 2 21:16:14 2006 From: william.boquist at gte.net (william.boquist at gte.net) Date: Wed, 03 May 2006 01:16:14 GMT Subject: Newbie question on code vetting Message-ID: <yvT5g.132$yh.117@trnddc04> Hi. I have visited the Python web site and read some information on who the commiters are and how to go about submitting code to them, but I have not been able to locate any information regarding the process for vetting the code to identify any possible IP infringement before it is committed. How do the committers ascertain the originality of the code before it becomes part of the base? Is there any use of tools like BlackDuck ProtexIP or the competing Palamida product to scan for matches to code that is already licensed elsewhere? Also, is the same or a different standard of IP assurance practiced for the Cheese Shop? I work for a risk-averse company, and I want to compile a solid case for obtaining and using Python at work. Thanks in advance, Bill From nobody at 127.0.0.1 Wed May 17 14:07:17 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 18:07:17 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> Message-ID: <pDJag.28558$4L1.298@newssvr11.news.prodigy.com> Mirco Wahab wrote: > Maybe somebody would change his style > and had a lot of such statements before: > which can be expressed in one > line: > This has a 1:4 line count then. > > Or, somebody used identifier like: > and later: > and saved ~40% characters. > You got my point? ;-) Hey I completely agree that line counts leave out a lot of information. Measures of the code like complexity, readability, work performed, etc hinge on many more important factors. I don't pretend that lines of code represents any indication of inherent superiority or fitness. But line counts do convey some information. Even if it's only how many lines a particular programmer used to convey his ideas. Real-world and average-case data are more compelling than theoretical limits on how compact code can be. Besides compactness isn't the point, communication is. Maybe line count is a good rough first-cut approximation of that. Maybe it's not. Probably it's both, depending on the case. Talking about the numbers can only shed light on how to interpret them, which as always is 'very carefully'. I'm not saying lines of code necessarily reflects anything else. All I'm saying is, I noticed some properties of my code. I'd like to know what objective properties others have noticed about their code. This is not meant to be a comparison of languages or programming technique, just a sampling of collective wisdom. That always has value, even when it's wrong. By the looks of it, this group is uninterested in the discussion. Which is fine. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From paddy3118 at netscape.net Tue May 16 02:15:04 2006 From: paddy3118 at netscape.net (Paddy) Date: 15 May 2006 23:15:04 -0700 Subject: using target words from arrays in regex, pythons version of perls 'map' References: <44691fc2$0$61162$ae4e5890@news.nationwide.net> <41mi62hih1d3i53nnhdkfi9tpil77bfdp7@4ax.com> Message-ID: <1147760104.401875.177880@j33g2000cwa.googlegroups.com> I don't like string interpolation within REs, it pops me out of 'RE mode' as I scan the line. Maybe creating a dict of matchobjects could be used in the larger context?: dict( [(t, re.search(t+regexp_tail, file2) for t in targets] ) (untested). - Pad. From phddas at yahoo.com Sun May 14 00:09:10 2006 From: phddas at yahoo.com (Gary Wessle) Date: 14 May 2006 14:09:10 +1000 Subject: copying files into one Message-ID: <874pztgsd5.fsf@localhost.localdomain> Hi I am looping through a directory and appending all the files in one huge file, the codes below should give the same end results but are not, I don't understand why the first code is not doing it. thanks combined = open(outputFile, 'wb') for name in flist: if os.path.isdir(file): continue infile = open(os.path.join(file), 'rb') # CODE 1 this does not work tx = infile.read(1000) if tx == "": break combined.write(tx) infile.close() # CODE 2 but this works fine for line in infile: combined.write(line) infile.close() combined.close() From johnzenger at gmail.com Wed May 3 16:03:54 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 3 May 2006 13:03:54 -0700 Subject: Possibly dumb question about dicts and __hash__() In-Reply-To: <e3b0c0$g8o$1@news.lysator.liu.se> References: <e3b0c0$g8o$1@news.lysator.liu.se> Message-ID: <1146686634.117498.313470@j73g2000cwa.googlegroups.com> Use __repr__. Behold: >>> class NamedThing(object): def __init__(self, name): self.name = name def __repr__(self): return self.name >>> a = NamedThing("Delaware") >>> b = NamedThing("Hawaii") >>> d = {} >>> d[a] = 1 >>> d[b] = 50 >>> print d {Delaware: 1, Hawaii: 50} >>> d[a] 1 >>> d[b] 50 Although this is a bit illegal, because repr is not supposed to be used this way. Joel Hedlund wrote: > Hi! > > There's one thing about dictionaries and __hash__() methods that puzzle me. I > have a class with several data members, one of which is 'name' (a str). I would > like to store several of these objects in a dict for quick access > ({name:object} style). Now, I was thinking that given a list of objects I might > do something like > > d = {} > for o in objects: > d[o] = o > > and still be able to retrieve the data like so: > > d[name] > > if I just defined a __hash__ method like so: > > def __hash__(self): > return self.name.__hash__() > > but this fails miserably. Feel free to laugh if you feel like it. I cooked up a > little example with sample output below if you care to take the time. > > Code: > --------------------------------------------------------------- > class NamedThing(object): > def __init__(self, name): > self.name = name > def __hash__(self): > return self.name.__hash__() > def __repr__(self): > return '<foo>' > name = 'moo' > o = NamedThing(name) > print "This output puzzles me:" > d = {} > d[o] = o > d[name] = o > print d > print > print "If I wrap all keys in hash() calls I'm fine:" > d = {} > d[hash(o)] = o > d[hash(name)] = o > print d > print > print "But how come the first method didn't work?" > --------------------------------------------------------------- > > Output: > --------------------------------------------------------------- > This output puzzles me: > {'moo': <foo>, <foo>: <foo>} > > If I wrap all keys in hash() calls I'm fine: > {2038943316: <foo>} > > But how come the first method didn't work? > --------------------------------------------------------------- > > I'd be grateful if anyone can shed a litte light on this, or point me to some > docs I might have missed. > > Also: > Am I in fact abusing the __hash__() method? If so - what's the intended use of > the __hash__() method? > > Is there a better way of implementing this? > > I realise I could just write > > d[o.name] = o > > but this problem seems to pop up every now and then and I'm curious if there's > some neat syntactic trick that I could legally apply here. > > Thanks for your time! > /Joel Hedlund From carlosperezs at alumnos.uvigo.es Mon May 22 04:07:20 2006 From: carlosperezs at alumnos.uvigo.es (carlosperezs at alumnos.uvigo.es) Date: Mon, 22 May 2006 10:07:20 +0200 Subject: Doubt with wx.CallAfter Message-ID: <1148285240.447171382cce8@correoweb.uvigo.es> Hello together:: I have programmed this fuction: def OnNewMovie(self, event): """ Local user receives a new movie event from a user""" #self.log.debug( "Got OnNewMovie, " + `event`) if event.data[0] == self.pubId: fDep.write("New movie equal\n") fDep.flush() #self.log.debug( "Returning, it's my movie") # This lets two users connect at the same time self.lockInitSession.acquire() if self.vInitSession == False: self.vInitSession = True self.lockInitSession.release() else: self.lockInitSession.release() return #self.log.debug( "Doing remote load event id = " + `event.data[0]` + ", myid=" + `self.pubId`) self.lockInitSession.acquire() self.vInitSession = False self.lockInitSession.release() self.sharedAppClient.UpdateDataCache() self.GetState() wx.CallAfter(self.sm.RemoteLoadMovie) This function is a handler that is executed when a event occurs. At the end is wx.CallAfter call. Imagine that two events occur simultaneously. This function takes one event. After executing ax.CallAfter call would tke the second event. Then , my doubt would be, would be there 2 threads simultanously executing: one belongs to self.sm.RemoteLoadMovie and the another one belongs to the handler for the second event? Thank you. As you can see i do not know exactly how wx.CallAfter works. --oOo-----------------------------------------------------------------oOo-- Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo Servicios Inform?ticos [ http://si.uvigo.es ] Universidade de Vigo [ http://www.uvigo.es ] URL: https://correoweb.uvigo.es From gdamjan at gmail.com Thu May 18 00:09:01 2006 From: gdamjan at gmail.com (Damjan) Date: Thu, 18 May 2006 06:09:01 +0200 Subject: MySQLdb - parameterised SQL - how to see resulting SQL ? References: <1147916515.511332.214660@j33g2000cwa.googlegroups.com> Message-ID: <446bf35d$0$15784$14726298@news.sunsite.dk> > ... i would be interested in seeing what the actual SQL used by the > .execute looks like after the replacements have been done. Is there a > way of doing this ? On my development machine I'm using the "--log" argument to MySQL so that it logs all queries and connections. I wouldn't recommend that on a production machine though. The logfile is stored in /var/lib/mysql/<hostname>.log -- damjan From bedouglas at earthlink.net Fri May 5 12:01:05 2006 From: bedouglas at earthlink.net (bruce) Date: Fri, 5 May 2006 09:01:05 -0700 Subject: Drop Down Menus... Message-ID: <288b01c6705d$1df2d200$0301a8c0@Mesa.com> Hi... Never used python, but I have a question regarding Drop Down Menus. Does Python allow me to create a website, that will permit the user to create Drop Down menus that can be initiated with the right mouse click? If it can, is it fairly easy to implement? Thanks -Bruce From aleaxit at yahoo.com Sat May 6 22:23:11 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 19:23:11 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> Message-ID: <1hexigt.h7vk5s1i5fkn3N%aleaxit@yahoo.com> Bill Atkins <NOatkinwSPAM at rpi.edu> wrote: ... > Believe it or not, _you_ got it wrong. Acknowledged: Common Lisp is even MORE insane (note that the quote "INSANELY extensible" is from Tilton) than I believed -- I'm pretty sure that the Lisp dialects I used in 1979-1981 didn't go to such crazy extremes, and neither did Scheme. > Buh? The project doesn't have to be late for Brooks's law to hold; > adding programmers, so goes Brooks reasoning, will always increase the > time required to complete the project because of various communication > issues. And here is where we check if you're as gracious about admitting your errors, as I am about mine. Brooks' law is: """Adding manpower to a late software project makes it later.""" These are Brooks' words, literally. OK so far? Your claim, that adding programmers will ALWAYS increase the time, is not just wrong, but utterly ridiculous. I can't put it better than the wikipedia: """ Misconceptions A commonly understood implication of Brooks' law is that it will be more productive to employ a smaller number of very talented (and highly paid) programmers on a project than to employ a larger number of less talented programmers, since individual programmer productivity can vary greatly between highly talented and efficient programmers and less talented programmers. However, Brooks' law does not mean that starving a project of resources by employing fewer programmers beyond a certain point will get it done faster. """ Moreover, check out the research on Pair Programming: it scientifically, empirically confirms that "two heads are better than one", which should surprise nobody. Does this mean that there aren't "various communication issues"? Of course there are, but there's no implied weighting of these factors wrt the _advantages_ of having that second person on the team (check the Pair Programming literature for long lists of those advantages). Only empirical research can tell us where the boundary is -- when productivity is decreased by going from N to N+1. A lot depends on imponderable issues such as personality meshes or clashes, leadership abilities at hands, methodology used, etc. All of this is pretty obvious, making your assertion that Brooks held otherwise actionable (as libel, by Brooks) in many legislations. As it happens, I also have examples in which adding (a few carefully selected) people to a software project that WAS (slightly) late put that project back on track and made it deliver successfully on schedule. Definitely not the "pointy-haired boss" management style of "throwing warm bodies at the problem" that Brooks was fighting against, but, consider: the project's velocity has suffered because [a] the tech lead has his personal (usually phenomenal) productivity hampered by a painful condition requiring elective surgery to abate, and [b] nobody on the team is really super-experienced in the intricacies of cryptography, yes some very subtle cryptographic work turns out to be necessary. One day, the tech lead calls in -- the pain has gotten just too bad, he's going for surgery, and will be out of the fray for at least one week. I still remember with admiration how my Director reacted to the emergency: he suspended two other projects, deciding that, if THEIR deadlines were broken, that would be a lesser damage to the company than if this one slipped any further; and cherrypicked exactly two people -- one incredibly flexible "jack of all trades" was tasked with getting up to speed on the project and becoming the acting TL for it, and an excellent cryptography specialist was tasked to dig deep into the project's cryptography needs and solve them pronto. So, We Broke Brooks' Law -- the cryptographer did his magic, and meanwhile the JOAT ramped up instantly and took the lead (kudos to the Jack's skills, to the clarity and transparency of the previous TL's work, to the agile methodologies employed throughout, AND to the uniformity of style of one language which will stay unnamed here)... and the project delivered on time and within budget. We had one extra person (two "replacements" for one TL's absence), yet it didn't make the late software project even later -- it brought it back on track perfectly well. I have many other experiences where _I_ was that JOAT (and slightly fewer ones where I was the specialist -- broadly speaking, I'm more of a generalist, but, as needs drive, sometimes I do of necessity become the specialist in some obscure yet necessary technology... must have happened a dozen times over the 30 years of my careers, counting graduate school...). This set of experiences in no way tarnishes the value of Brooks' Law, but it does *put it into perspective*: done JUST RIGHT, by sufficiently brilliant management, adding A FEW people with exactly the right mix of skills and personality to a late software project CAN save the bacon, > Fair enough. But what does Python offer above any garbage-collected > language that makes it so scalable? Uniformity of style, facilitating egoless programming; a strong cultural bias for simplicity and clarity, and against cleverness and obscurity; "just the right constraints" (well, mostly;-), such as immutability at more or less the right spots (FP languages, with _everything_ immutable, have an edge there IN THEORY... but in practice, using them most effectively requires a rare mindset/skillset, making it hard to "scale up" teams due to the extra difficulty of finding the right people). Alex From robert.kern at gmail.com Thu May 11 15:57:17 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 14:57:17 -0500 Subject: segmentation fault in scipy? In-Reply-To: <1147376927.857632.310430@j33g2000cwa.googlegroups.com> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <mailman.5571.1147301063.27775.python-list@python.org> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <mailman.5572.1147304930.27775.python-list@python.org> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> <mailman.5576.1147320706.27775.python-list@python.org> <1147373294.235202.188220@y43g2000cwc.googlegroups.com> <mailman.5604.1147375226.27775.python-list@python.org> <1147376927.857632.310430@j33g2000cwa.googlegroups.com> Message-ID: <e404ut$h8c$1@sea.gmane.org> py_genetic wrote: >>No! matrix objects use matrix multiplication for *. You seem to need elementwise >>multiplication. > > No! when you mult a vector with itself transposed, the diagonal of the > resulting matrix is the squares of each error (albeit you do a lot of > extra calc), then sum the squares, ie trace(). Its a nifty trick, if > you don't have too much data 25000x25000 matrix in mem and youre using > matricies ie. batch learning. The actual equation includes multiply by > 1/2*(sum of the squares), but mean squared error can be more telling > about error and cross entropy is even better, becuase it tells you how > well youre predicting the posterior probabilies... But, again, why bother calculating an enormous matrix just to take its trace when you can use elementwise multiplication and not waste any time or memory calculating values that you don't need? It's not a trick. It's just wrong. -- 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 ishoej at gmail.com Mon May 8 14:53:44 2006 From: ishoej at gmail.com (Holger) Date: 8 May 2006 11:53:44 -0700 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <445b1472$0$16429$626a54ce@news.free.fr> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <pan.2006.05.03.20.57.05.32060@gmx.net> <Sda6g.67189$F_3.50022@newssvr29.news.prodigy.net> <mailman.5289.1146697051.27775.python-list@python.org> <k_a6g.21491$4L1.14831@newssvr11.news.prodigy.com> <4459c050$0$3552$626a54ce@news.free.fr> <HKr6g.81687$dW3.22405@newssvr21.news.prodigy.com> <445b1472$0$16429$626a54ce@news.free.fr> Message-ID: <1147114424.129767.324600@e56g2000cwe.googlegroups.com> And thank you gentlemen for turning my somewhat banale question into a worthwhile discussion. :-) I shall not forget self ever again! From robert.kern at gmail.com Thu May 11 14:31:33 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 13:31:33 -0500 Subject: scientific libraries for python In-Reply-To: <1147355105.972329.115480@y43g2000cwc.googlegroups.com> References: <1147355105.972329.115480@y43g2000cwc.googlegroups.com> Message-ID: <e3vvu6$ujs$1@sea.gmane.org> Harold Fellermann wrote: > Hi all, > > I want to use the current need for a Levenberg-Marquardt least squares > fitting procedure > for my long term desire to dive into scientific libraries for python. Does it have to be Levenberg-Marquardt, or will another non-linear least squares procedure do? > However, I am always > confused by the shear sheer variety of available packages and the fact > that some of them > (Numeric, Numarray) seem to be outdated. Fair enough. > http://wiki.python.org/moin/NumericAndScientific gives a nice overview > of the most > popular packages. According to this listing, ScientificPython and > PyDSTool seem most > appropriate for what I generally work on (simulations of dynamical > systems and data > analysis). I find this page to be a little bit richer: http://www.scipy.org/Topical_Software > Before I start to dive into one of these packages (I would go for > ScientificPython from what > I know so far), I want to ask about your experiences. Is there a good > reason to choose > one instead of the other? They are largely orthogonal to one another in capabilities. You would use the package that solves the problem in front of you. Quite possibly, you will be using both. > Or do they even work together, in the sense > that I can use > PyDSTool to generate data to be later analyzed by ScientifPython > without much timeconsuming > conversion a.s.o. in between? Both of them currently use the old Numeric so there are no real issues converting between the two of them; they both use the same arrays. Install the latest version of old Numeric (24.2), and you can convert to numpy arrays without wasting memory. For nonlinear least squares, I would probably recommend using my wrappers of ODRPACK currently residing in the scipy sandbox. It uses numpy. It is very flexible. http://projects.scipy.org/scipy/scipy/browser/trunk/Lib/sandbox/odr If you need help installing scipy or using odr, come over to one of the scipy lists, and I'll help you out. http://www.scipy.org/Mailing_Lists -- 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 test at test.test Tue May 9 01:41:51 2006 From: test at test.test (test at test.test) Date: Tue, 09 May 2006 00:41:51 -0500 Subject: Problem - Serving web pages on the desktop (SimpleHTTPServer) Message-ID: <7q9062t2oqdesjtl9k2hfvnmdvmb0pau24@4ax.com> Hi there, Perhaps someone can help me. For some reason, when my Python script runs and loads an HTML page in a new browser window at the local host (desktop), the links to my stylesheet and all the images are broken. I did check the HTML file by itself...everything loaded fine ;) Here's my script: -------------------- # File: webbrowser-test.py import webbrowser, SimpleHTTPServer from StringIO import StringIO f=open('testpage.html', 'rb') myPage = f.read() class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def send_head(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() return StringIO(myPage) webbrowser.open("http://127.0.0.1:8000", new=0, autoraise=1) SimpleHTTPServer.test(MyRequestHandler) -------------------- Here's my sample directory: --------------------------------- webbrowser-test.py testpage.html m_files/ |_____stylesheet.css |_____logo.gif -------------------------------- Thanks for having a look. My next step is to process form input using AJAX. I'll post working snippets of code here as I progress. Ben From mtobis at gmail.com Thu May 18 14:38:21 2006 From: mtobis at gmail.com (Michael Tobis) Date: 18 May 2006 11:38:21 -0700 Subject: python vs perl lines of code In-Reply-To: <mailman.5859.1147918811.27775.python-list@python.org> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> Message-ID: <1147977501.554596.149630@i40g2000cwc.googlegroups.com> Sorry, data about reports about X *is* data about X unless you believe the reports are uninfluenced by X. Like any proxy measure, it introduces noise and uncertainty, but it is still data. I can't imagine a motivation for Edward to make this up, so I accept his anecdotes as data. While it is possible to imagine developing a lab experiment to compare the terseness of Python and Perl, it is unlikely that funding is or should be available for the effort. This doesn't make it an uninteresting question. Is the widely held belief that real-world Perl is terser than real-world Python true? So far we have only the two reports from Edward. Still anyone programming in the dynamic languages world would acknowledge that they are quite striking and provocative. I don't see the purpose of this controversy, but it reminds me of some rather cynical attacks on climate science, and I don't like it at all. We don't always have the luxury of vast data of impeccable quality, but we still need to make judgements about the world. mt From apardon at forel.vub.ac.be Tue May 9 06:14:12 2006 From: apardon at forel.vub.ac.be (Antoon Pardon) Date: 9 May 2006 10:14:12 GMT Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> <slrne60jsm.dac.apardon@rcpc42.vub.ac.be> <1147165989.106261.164090@j33g2000cwa.googlegroups.com> Message-ID: <slrne60qrk.dac.apardon@rcpc42.vub.ac.be> Op 2006-05-09, Pisin Bootvong schreef <joesb.coe9 at gmail.com>: > > Antoon Pardon wrote: >> Op 2006-05-09, Pisin Bootvong schreef <joesb.coe9 at gmail.com>: >> > Is this a Slippery Slope fallacious argument? >> > (http://c2.com/cgi/wiki?SlipperySlope) >> >> No it is not. >> >> [...] >> >> So the question I have is: Why is requiring me to give this function >> a name considered a good thing, when it leads to a situation that >> is considered bad practice in case of a number. >> >> -- > > Slippery Slope:: > "Argumentation that A is bad, because A might lead to B, and B > to C, and we all know C is very bad." But I have seen noone here argue that requiring functions to be named leads to requiring all variables to be named. >> Why is requiring me to give this function >> a name considered a good thing, when it leads to a situation that >> is considered bad practice in case of a number. > > A === "requiring me to give function a name" > no B > C === "requiring me to give number a name" > > "Argumentation that requiring one to give function a name is bad, > because that might lead to requiring one to give number a name, and we > all know that that is very bad." That is not the arguement I'm making. The argument is that a particular pratice is considered bad coding, (with an example giving a number) and then showing that requiring a name for a function, almost makes such a practice inevitable (for certain functions used as parameters) -- Antoon Pardon From nobody at 127.0.0.1 Thu May 4 23:26:00 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 05 May 2006 03:26:00 GMT Subject: Newbie question on code vetting References: <yvT5g.132$yh.117@trnddc04> <mailman.5299.1146719004.27775.python-list@python.org> <_%w6g.44217$C63.42016@trnddc06> Message-ID: <cBz6g.67490$F_3.12273@newssvr29.news.prodigy.net> I have no deep connections to any open source projects. I do however know quite a few engineers. Bear that in mind. william.boquist at gte.net wrote: > It seems to me that Open Source generally would be more pervasive if there > was more transparency with respect to the practices observed within the > projects. What possible harm could there be in letting the world know how > decisions to incorporate code are reached? I don't think it's a question of transparency but effort. Documenting the processes takes time which many probably feel is better spent on functional aspects of the project. And for what benefit? Are open source projects more concerned about approval or quality? Besdies, most commercial products have zero transparency in their development processes and it doesn't hinder their market acceptance. > The goal of collaborative > development is to build a body of code with many minds that is better than > the body of code that could be built by any subset of them. The same > principle could be applied to identification of best practices for > committers across projects. If those practices are identifiable and repeatable, then sure, maybe projects could be more productive following a "best practices" approach. OTOH if successful projects function more as little fiefdoms run by benevolent dictators, the reasons for success may be too idiosyncratic and happenstance to translate to other projects. Note I said more productive, as in allow the code to improve quicker. My impression is most engineers don't want to invest time on IP rules and hate when legal shenanigans impinge on their development. They're generally good at providing attribution and avoiding intentional misuses, but won't go out of their way to check sources. Nor should they, as 1) that's not their job and 2) it's a very difficult task (unless you know of some master database containing all the world's code). Hence IP verification "best practices" are likely to be summarily ignored as a foolish waste of time. Closed commercial projects fare no better, indeed they may be even worse since the risk of getting caught is lower. Google for the number of times unlicensed GPLed code turned up in some commercial product. > To me, being unable to reach an understanding > of the practices is analogous to being unable to see and run the JUnit > suites on a bunch of classes - being in the position of assuming that > there is coverage, but not being able to understand how much or how > thorough. Transparency can be valuable to an outsider, but I don't see how most projects would have the time, resources, or inclination to provide it. > I think it is obvious that if every consumer of the code who has an > interest in controlling risk has to reinvent the wheel, there will be a > lot of effort wasted on redundant work. Sure, but this task is better handled by vendors like Red Hat than by individual projects. IP verification is no easy matter to handle, and vendors have a financial incentive to perform the checks. Vendors can also offer indemnity, which individual projects can't. > Why not have the project publish a > document that says "here are the practices by which we manage our code > base - take it or leave it". Just as most licenses are variations on a few > (GPL, LGPL, CPL, etc.), it seems to me that very quickly, a set of common > management practices would evolve if most projects published, perhaps with > a few variations. I suspect part of the reason you have trouble finding answers about IP issues is that there are none to give. I doubt most projects follow anything resembling a formal process for verifying sources. It's more likely left up to individual contributors, and probably runs along the lines of "if it doesn't look obviously ripped-off, then it's ok". > With regard to the issue of trust, how can I either trust or decide not to > trust in an information vacuum? By looking at indirect sources of evidence. How much trust do others put in this project? (Google for one uses python heavily.) How do most open source projects function? How do most engineers handle IP issues? Can I hire an auditor to sample a representative portion of the code base for IP issues? Has anyone else already done so? How often are open source projects accused of IP violations? How serious are they and what are the outcomes? Do closed projects handle things any differently? What assurances do they really provide? Risk analysis means there's risk. Unknowns are inherent. Work around them the best you can. > I may be splitting hairs, but my > understanding is that belief despite absence of evidence is faith, not > trust. Trust is the result of observation, and I want to be able to > observe. Faith is a belief that something is true without evidence. Trust is relying on something/someone to perform a certain way. Blindly believing a project to be free of IP issues is faith. Expecting the committers to take the same reasonable precautions most engineers do is trust. The first is foolhardy, the second is rational, especially when you make your own safeguards against that trust being violated. Faith is binary, trust is by degree. What you're asking isn't unreasonable, but it's also not within the scope of most open source projects. Nor should it be. From martinskou at gmail.com Thu May 18 06:30:51 2006 From: martinskou at gmail.com (martinskou at gmail.com) Date: 18 May 2006 03:30:51 -0700 Subject: Best active community website Message-ID: <1147948251.530565.210690@y43g2000cwc.googlegroups.com> Hi I have been looking for a active Python community website. Something like www.codeproject.com (contains code articles and guide, by developers, for developers) for Python users. Does something like this exist? /Martin From bignose+hates-spam at benfinney.id.au Wed May 3 19:00:59 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 May 2006 09:00:59 +1000 Subject: Gettings subdirectories References: <e3au5u$drm$1@news.in.tum.de> <1146683720.748769.36490@g10g2000cwb.googlegroups.com> <1146695904.623400.128100@y43g2000cwc.googlegroups.com> Message-ID: <87vesmbtn8.fsf@benfinney.id.au> "BartlebyScrivener" <rpdooling at gmail.com> writes: > >> root, dirnames, filenames = os.walk(r"C:\").next() > > Wow. How does that work? Just point me to where I can read about it. I > don't see it under os.walk. We must be reading different Python websites. walk(top[, topdown=True [, onerror=None]]) walk() generates the file names in a directory tree, by walking the tree either top down or bottom up. For each directory in the tree rooted at directory top (including top itself), it yields a 3-tuple (dirpath, dirnames, filenames). <URL:http://docs.python.org/lib/os-file-dir.html#l2h-1638> -- \ "Sittin' on the fence, that's a dangerous course / You can even | `\ catch a bullet from the peace-keeping force" -- Dire Straits, | _o__) _Once Upon A Time In The West_ | Ben Finney From maric at aristote.info Wed May 17 10:11:53 2006 From: maric at aristote.info (Maric Michaud) Date: Wed, 17 May 2006 16:11:53 +0200 Subject: A better way of making subsclassing of built-in types stick for attributes? In-Reply-To: <1147839432.816504.318290@38g2000cwa.googlegroups.com> References: <1147839432.816504.318290@38g2000cwa.googlegroups.com> Message-ID: <200605171611.54399.maric@aristote.info> Le Mercredi 17 Mai 2006 06:17, telesphore4 at gmail.com a ?crit?: > I want the fact that the fields are > not strings to be invisible to the client programmers. You should use properties then. In [12]: class mystr(str) : pass ....: In [13]: class myrow(object) : ....: getX = lambda s : s._x ....: setX = lambda s, v : setattr(s, '_x', mystr(v)) ....: X = property(getX, setX) ....: ....: In [14]: r=myrow() In [15]: r.X = 'toto' In [16]: r.X Out[16]: 'toto' In [17]: type(r.X) Out[17]: <class '__main__.mystr'> -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From robert.kern at gmail.com Sun May 7 16:14:23 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 07 May 2006 15:14:23 -0500 Subject: Numerical Python Tutorial errors In-Reply-To: <87fyjlaht8.fsf@localhost.localdomain> References: <87fyjlaht8.fsf@localhost.localdomain> Message-ID: <e3lkf0$uek$1@sea.gmane.org> Gary Wessle wrote: > Hi > > is the Numerical Python tutorial maintained? > http://www.pfdubois.com/numpy/html2/numpy.html > seams to have some errors and no email to mail them to when found. No, it is not since Numeric itself is no longer maintained. The successor to Numeric is numpy and is being actively developed: http://numeric.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 lance at augustmail.com Tue May 16 14:55:47 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Tue, 16 May 2006 13:55:47 -0500 Subject: round numbers in an array without importing Numeric or Math? - SOLVED, sort of In-Reply-To: <446a1748$0$61168$ae4e5890@news.nationwide.net> References: <446a1748$0$61168$ae4e5890@news.nationwide.net> Message-ID: <446a2032$0$61167$ae4e5890@news.nationwide.net> The array comes out as unicode. This is probably because I am grabbing the numbers from a Word Doc using regex's. So, before rounding I perform the following: # Convert to String Topamax = [str(x) for x in Topamax] # Convert to floating Topamax = [float(x) for x in Topamax] # Finally, round the number Topamax= [(x+0.5) for x in Topamax] Is there a shorter way? Lance Lance Hoffmeyer wrote: > Is there an easy way to round numbers in an array? > > I have > Test = [1.1,2.2,3.7] > > and want to round so the values are > > print Test [1,2,4] > > > Lance From sjmachin at lexicon.net Fri May 19 17:14:10 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 May 2006 14:14:10 -0700 Subject: newb: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <4d4chmF185ohoU1@uni-berlin.de> <1148038726.023455.145900@j73g2000cwa.googlegroups.com> <1148062114.800989.293270@j73g2000cwa.googlegroups.com> <1148062688.445501.30260@y43g2000cwc.googlegroups.com> <7xhd3lvpng.fsf@ruckus.brouhaha.com> Message-ID: <1148073250.524655.108500@j33g2000cwa.googlegroups.com> Paul Rubin wrote: > bearophileH... at lycos.com writes: >>> I have suggested C because if the words are all of the same length then >>> you have 30000^2 = 90 000 000 000 pairs to test. >> Sorry, you have (n*(n-1))/2 pairs to test (~ 45 000 000 000). > Still terrible. Use a better algorithm! To put all this in perspective, here's a very similar real-world problem: You have a customer database with 300,000 records. Some of them are duplicated, because there are differences in recording the customers' names, like a one-keystroke typo. The task is to locate pairs of rows which are likely to be duplicates. 45 billion comaprisons[1] may be ecxessive. And here's a clue for a better algorithm: Knuth's TAOCP vol 3 [1973 edition] chapter 6 (searching) third page "as if the words were spelled backwards". If you find yourself reading about soundex, you've definitely gone too far :-) [1]: "comapring" in the subject: is this a game of 'Spot the deliberate mistake"? Is the OP counting a transposition of adjacent characters as "varying by one character"? Cheers From deets at nospam.web.de Mon May 22 06:38:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 May 2006 12:38:11 +0200 Subject: Includeing Python in text files References: <mailman.6070.1148292392.27775.python-list@python.org> Message-ID: <4ddilkF18fs7bU1@uni-berlin.de> Paolo Pantaleo wrote: > I am working on this: > > I have a text file, containig certain section in the form > <?py > python code here > py?> > > I parse the text file and substitute the python code with its result > [redirecting sys.stdin to a StringIO]. It something like php or > embedded perl. > > So my little toy works not bad, but I was wondering if such a feature > already existed, if yes, can you point me out some links? Its a templating system, and there are a gazillion out there. Some of them are listed here: http://www.cherrypy.org/wiki/ChoosingATemplatingLanguage Diez From pjb at informatimago.com Sun May 21 12:52:25 2006 From: pjb at informatimago.com (Pascal Bourguignon) Date: Sun, 21 May 2006 18:52:25 +0200 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <1148225181.251089.261160@j55g2000cwa.googlegroups.com> Message-ID: <874pzjb9rq.fsf@thalassa.informatimago.com> "SamFeltus" <sam at nuevageorgia.com> writes: > Software needs philosophers is an interesting point, perhaps the most > important function of Philosophers is exposing Sacred Cows as just > Cattle. As I see it philosophers have a big problem: nobody need them, so they're out of job. That's why we see occasional articles "X needs philosophers". I just ask: where are the job offers? -- __Pascal_Bourguignon__ _ Software patents are endangering () ASCII ribbon against html email (o_ the computer industry all around /\ 1962:DO20I=1.100 //\ the world http://lpf.ai.mit.edu/ 2001:my($f)=`fortune`; V_/ http://petition.eurolinux.org/ From theaney at gmail.com Tue May 23 22:34:28 2006 From: theaney at gmail.com (Tim Heaney) Date: Tue, 23 May 2006 22:34:28 -0400 Subject: graphs and charts References: <mailman.6117.1148404831.27775.python-list@python.org> <1276hc8c8uf9870@corp.supernews.com> Message-ID: <m3ac98b16z.fsf@calvin.watterson> Grant Edwards <grante at visi.com> writes: > > On 2006-05-23, Yaron Butterfield <yaronb at telus.net> wrote: > >> What's the best way to on-the-fly graphs and charts using Python? Or is >> Python not really the best way to do this? > > I like Gnuplot-py, but I've been a Gnuplot for 15+ years, so > I'm biased. > > http://gnuplot-py.sourceforge.net/ You might also be interested in matplotlib http://matplotlib.sourceforge.net/ Here is an example of how I've used it http://cablespeed.com/~theaney/mat191/matplotlib.html Tim From stijndesaeger at gmail.com Fri May 5 05:01:02 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 02:01:02 -0700 Subject: Tuple assignment and generators? In-Reply-To: <e-idndayO-NancbZRVn-sQ@speakeasy.net> References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <e-idndayO-NancbZRVn-sQ@speakeasy.net> Message-ID: <1146819662.519528.224530@e56g2000cwe.googlegroups.com> > No. Why should you ever care about whether two integers representing > values are the same object? Your tests should be with `==`, not `is`. Given this though, what other such beauties are lurking in the interpreter, under the name of 'implementation accidents'? One of the things that drew me to python is the claimed consistency and orthogonality of both language and implementation, not sacrificing clarity for performance, minimizing ad-hoc design hacks and weird gotcha's, etc... In fact, I think my code contains things like "if len(arg) is 0:" and so on, and I feel I should be able to do so given the way python treats (claims to treat?) constant objects, even if I don't care whether the values actually represent the same object. s. From meyer.p at gmail.com Wed May 17 12:44:43 2006 From: meyer.p at gmail.com (Pierre) Date: 17 May 2006 09:44:43 -0700 Subject: How to customize getattr(obj, prop) function ? Message-ID: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> Hi, Sorry in advance, english is not my main language :/ I'd like to customize the result obtained by getattr on an object : if the object has the requested property then return it BUT if the object doesn't has actually this property return something else. In my case, I can't use getattr(object, property, default_value). I tried to write a class with a __getattr__ method and even a __getattribute__ method but this doesn't do what I want.... Maybe I didn't correctly understand this : http://docs.python.org/ref/attribute-access.html Here is a piece of my code : ===================================== class myclass: """docstring""" a = 'aa' b = 'bb' def __getattr___(self, ppt): """getattr""" if hasattr(self, ppt): return self.ppt else: return "my custom computed result" def __getattribute__(self, ppt): """getattribute""" if hasattr(self, ppt): return self.ppt else: return "my custom computed result" if __name__ == "__main__": d = myclass() p1 = getattr(d, "a") print p1 p2 = getattr(d, "b") print p2 p3 = getattr(d, "c") print p3 ================================ I get an AttributeError when accessing to the property named "c". Any explanation/solution to my problem ? From onurb at xiludom.gro Wed May 3 11:47:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 17:47:44 +0200 Subject: Need Plone Information In-Reply-To: <mailman.5269.1146669645.27775.python-list@python.org> References: <mailman.5269.1146669645.27775.python-list@python.org> Message-ID: <4458d0fb$0$12855$626a54ce@news.free.fr> bruce wrote: > Hi.... > > I've never used Python/Plone, and am wondering if I can talk with anyone > who's used Plone. I'm trying to determine if Plone could be easily used for > a potential application. Then you'd better post this to the plone and/or zope mailing lists. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mike7411 at gmail.com Wed May 3 15:34:36 2006 From: mike7411 at gmail.com (mike7411 at gmail.com) Date: 3 May 2006 12:34:36 -0700 Subject: python strings Message-ID: <1146684876.311829.297280@i39g2000cwa.googlegroups.com> Is it possible for python strings to contain a zero byte? From roman.bischoff at googlemail.com Tue May 16 02:38:22 2006 From: roman.bischoff at googlemail.com (Roman) Date: 15 May 2006 23:38:22 -0700 Subject: How to guess the language of a given textstring? In-Reply-To: <1147734206.464663.297770@g10g2000cwb.googlegroups.com> References: <1147731412.848833.225910@j55g2000cwa.googlegroups.com> <1147734206.464663.297770@g10g2000cwb.googlegroups.com> Message-ID: <1147761502.688232.43940@i39g2000cwa.googlegroups.com> Hi This is what I'm looking for. Thank you. Roman gene tani schrieb: > Roman wrote: > > Does anybody know an easy way (or tool) to guess the language of a > > given text string? > > > > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/355807 > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/326576 From wuwei23 at gmail.com Thu May 18 06:05:59 2006 From: wuwei23 at gmail.com (alex23) Date: 18 May 2006 03:05:59 -0700 Subject: how to make the program notify me explicitly In-Reply-To: <1147941537.039418.316340@j73g2000cwa.googlegroups.com> References: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> <1147939268.619806.147550@j73g2000cwa.googlegroups.com> <1147941537.039418.316340@j73g2000cwa.googlegroups.com> Message-ID: <1147946759.180928.316090@j33g2000cwa.googlegroups.com> hankssong wrote: > may be message dialog is the best way to let me be informed! EasyGui is possibly the simplest and fastest way to get message dialogue boxes in Python: http://www.ferg.org/easygui/ - alex23 From hgk at et.uni-magdeburg.de Wed May 24 03:26:05 2006 From: hgk at et.uni-magdeburg.de (Hans Georg Krauthaeuser) Date: Wed, 24 May 2006 09:26:05 +0200 Subject: pickling multiple dictionaries In-Reply-To: <1148444653.078683.194750@u72g2000cwu.googlegroups.com> References: <1148444653.078683.194750@u72g2000cwu.googlegroups.com> Message-ID: <e511qd$r2v$1@fuerst.cs.uni-magdeburg.de> manstey wrote: > Hi, > > I am running a script that produces about 450,000 dictionaries. I tried > putting them into a tuple and then pickling the tuple, but the tuple > gets too big. Can I pickle dictionaries one after another into the same > file and then read them out again? > > Cheers, > Matthew > If you don't know, just try it: In [1]:import pickle In [2]:d1={'a':1} In [3]:d2={'b':2} In [4]:pfile=file('test.p','wb') In [5]:pickle.dump(d1,pfile) In [6]:pickle.dump(d2,pfile) In [7]:pfile.close() In [8]:del d1 In [9]:del d2 In [10]:pfile=file('test.p','rb') In [11]:d1=pickle.load(pfile) In [12]:d1 Out[12]:{'a': 1} In [13]:d2=pickle.load(pfile) In [14]:d2 Out[14]:{'b': 2} If your data is *really* large, have a look to PyTables (http://www.pytables.org/moin). Regards, Hans Georg From jordan.taylor2 at gmail.com Tue May 23 15:46:17 2006 From: jordan.taylor2 at gmail.com (jordan.taylor2 at gmail.com) Date: 23 May 2006 12:46:17 -0700 Subject: What's with the @ sign In-Reply-To: <1148405136.743780.46950@i40g2000cwc.googlegroups.com> References: <1148404435.500916.240670@y43g2000cwc.googlegroups.com> <1148405136.743780.46950@i40g2000cwc.googlegroups.com> Message-ID: <1148413576.915894.219930@i39g2000cwa.googlegroups.com> Thanks! I had no clue what that was (and searching for @ in the context of python was returning hundreds of thousands of hits XD) From fredrik at pythonware.com Tue May 2 10:31:51 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 May 2006 16:31:51 +0200 Subject: --version? References: <4bp06lF1276vvU1@individual.net><n2I5g.2683$Vn.323@newsread4.news.pas.earthlink.net> <4bp35kF12517kU1@individual.net> Message-ID: <e37qgp$n44$1@sea.gmane.org> Paul Watson wrote: > I am well aware of -V. Could --version be supported as well? http://www.python.org/dev/ http://sourceforge.net/tracker/?group_id=5470&atid=355470 </F> From bdesth.quelquechose at free.quelquepart.fr Thu May 4 17:49:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 May 2006 23:49:58 +0200 Subject: Subclassing array In-Reply-To: <o5r*BDOfr@news.chiark.greenend.org.uk> References: <1146747096.623101.122510@j73g2000cwa.googlegroups.com> <1heszg6.1q17bgp1jwua35N%aleaxit@yahoo.com> <o5r*BDOfr@news.chiark.greenend.org.uk> Message-ID: <445a4845$0$21665$626a54ce@news.free.fr> Sion Arrowsmith a ?crit : > Alex Martelli <aleaxit at yahoo.com> wrote: > >>TG <girodt at gmail.com> wrote: >> >>>When I call Vector.__init__() in Stimulus, doesn't it also call __new__ >>>? I don't understand the detail of callings to __new__ and __init__ in >>>python inheritance ... >> >>Calling a (new-style) class does __new__ first, THEN calls the class's >>__init__ on the resulting instance -- and the arguments you're passing >>when calling the class go to both __new__ and __init__. > > > ... so you might want something like: > > class Vector(array): > def __new__(cls,*args): > return super(Vector,cls).__new__(cls,'f') > And if you want to support named arguments: class Vector(array): def __new__(cls,*args, **kw): return super(Vector,cls).__new__(cls,'f') From george.sakkis at gmail.com Wed May 31 21:03:59 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 31 May 2006 18:03:59 -0700 Subject: ideas for programs? References: <mailman.6346.1149051733.27775.python-list@python.org> Message-ID: <1149123839.683480.178380@y43g2000cwc.googlegroups.com> Brandon McGinty wrote: > Hi, > I've been learning python for the past couple of months and writing misc > scripts here and there, along with some web apps. > I'm wondering if anyone has ideas of programs I might try my hand at making? > I'd appreciate it if they don't use images, because I'm blind. One ambitious idea would be to implement (a subset of) MDX, the Multi-Dimensional eXpressions language (http://msdn2.microsoft.com/en-us/library/ms145506.aspx). If you have any java experience, there is an open source implementation in it so you don't have to start from scratch: http://mondrian.sourceforge.net. George From bh at intevation.de Wed May 17 08:28:07 2006 From: bh at intevation.de (Bernhard Herzog) Date: Wed, 17 May 2006 14:28:07 +0200 Subject: round numbers in an array without importing Numeric or Math? - SOLVED, sort of References: <446a1748$0$61168$ae4e5890@news.nationwide.net> <446a2032$0$61167$ae4e5890@news.nationwide.net> <cHpag.37880$CH2.22854@tornado.texas.rr.com> Message-ID: <s9zzmhgrg2w.fsf@thetis.intevation.de> "Paul McGuire" <ptmcg at austin.rr._bogus_.com> writes: > ... or if you prefer the functional approach (using map)... > > roundToInt = lambda z : int(z+0.5) > Topamax = map( roundToInt, map( float, map(str, Topamax) ) ) > > (Python also has a built-in round() function, but this returns floats, not > ints - if that is okay, then just delete the lambda definition, and replace > roundToInt with round.) Your roundToInt behaves differently from round for negative numbers: >>> roundToInt(-0.6) 0 >>> int(round(-0.6)) -1 Bernhard -- Intevation GmbH http://intevation.de/ Skencil http://skencil.org/ Thuban http://thuban.intevation.org/ From me+python at modelnine.org Tue May 2 17:27:57 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 23:27:57 +0200 Subject: data regex match In-Reply-To: <87r73cdtmk.fsf@localhost.localdomain> References: <87r73cdtmk.fsf@localhost.localdomain> Message-ID: <200605022327.57422.me+python@modelnine.org> Am Dienstag 02 Mai 2006 23:06 schrieb Gary Wessle: > Hi > > I am having an issue with this match > > tx = "now 04/30/2006 then" > data = re.compile('(\d{2})/\1/\1\1', re.IGNORECASE) As always, use a raw string for regular expressions. \d is being interpreted to mean an ascii character, and not to mean the character class you're trying to reference here. Second: \1 (if properly quoted in the string) matches the first group exactly. Your regex would only match 20/20/2020 or strings of such format. Third: IGNORECASE is irrelevant here, you're not trying to match letters, are you? Anyway, the following works: dateregex = re.compile(r"(\d{2})/(\d{2})/(\d{4})") m = dateregex.search(tx) if m: print m.groups() else: print "No match." --- Heiko. From charl.loubser at gmail.com Sat May 13 06:13:33 2006 From: charl.loubser at gmail.com (Merrigan) Date: 13 May 2006 03:13:33 -0700 Subject: Sending mail with attachment... In-Reply-To: <1147508571.532690.292650@v46g2000cwv.googlegroups.com> References: <1147508571.532690.292650@v46g2000cwv.googlegroups.com> Message-ID: <1147515213.695066.5740@u72g2000cwu.googlegroups.com> Hi Guys, I just wanted to post the error, and then also the coda that causes it....I get this no matter what I do to this, and I don't understand it. Any help would be welcome. Thank you Error :: Traceback (most recent call last): File "/home/merrigan/projects/Backup Script/hobbitarchive.py", line 113, in ? mailSender() File "/home/merrigan/projects/Backup Script/hobbitarchive.py", line 74, in mailSender s.sendmail(fromaddy, recievelist, mesg.as_string()) File "/usr/lib/python2.4/email/Message.py", line 129, in as_string g.flatten(self, unixfrom=unixfrom) File "/usr/lib/python2.4/email/Generator.py", line 82, in flatten self._write(msg) File "/usr/lib/python2.4/email/Generator.py", line 120, in _write self._write_headers(msg) File "/usr/lib/python2.4/email/Generator.py", line 166, in _write_headers header_name=h, continuation_ws='\t').encode() File "/usr/lib/python2.4/email/Header.py", line 395, in encode return self._encode_chunks(newchunks, maxlinelen) File "/usr/lib/python2.4/email/Header.py", line 355, in _encode_chunks _max_append(chunks, s, maxlinelen, extra) File "/usr/lib/python2.4/email/quopriMIME.py", line 79, in _max_append L.append(s.lstrip()) AttributeError: 'list' object has no attribute 'lstrip' :: Code :: def mailSender(): openlogmsg = open(completelog, 'rb') mesg = MIMEText(openlogmsg.read()) openlogmsg.close() mesg['Subject'] = subject mesg['From'] = fromaddy mesg['To'] = recievelist s = smtplib.SMTP(smtpserver) # s.connect(smtpserver) s.sendmail(fromaddy, recievelist, mesg.as_string()) s.quit() :: Thanks a lot :) From andy at neotitans.com Wed May 17 06:27:58 2006 From: andy at neotitans.com (Andy Sy) Date: Wed, 17 May 2006 18:27:58 +0800 Subject: Tabs are *EVIL*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <e4etkv$vk6$1@sea.gmane.org> Please... just stop this senseless defense of a Rube-Goldberg feature. There will NEVER be a universal agreement on whether tabs should be 2, 3, 4 or 8 spaces in width, and this causes endless tweaking of editor settings (a *humongous* waste of time) to handle source code made by other programmers with different settings. And I, for the life of me, have never remembered getting any source code to display properly by fiddling with my text editor's (the very popular SciTE) tab settings. 4, 8, 3, 2, it doesn't matter. *Nothing* has ever made someone's tab-infested source code display completely cleanly. Nearly a third of my coding time seems to have been spent (read:wasted) trying to reformat some unenlightened tab user's source code to read comprehensibly. 1. Tabs as 8 spaces just take up too much horizontal area 2. But you can't use any other value because if you do, you will screw up display using cat/less/more !! DOES ANYONE NEED ANY REASON MORE COMPLICATED THAN THE ABOVE TO JUST *NOT* USE TABS??!???!??!!!?? Don't be evil - always configure your editor to convert tabs to true spaces. -- It's called DOM+XHR and it's *NOT* a detergent! From ntamas at gmail.com Mon May 8 21:08:29 2006 From: ntamas at gmail.com (Tamas Nepusz) Date: 8 May 2006 18:08:29 -0700 Subject: __dict__ in class inherited from C extension module Message-ID: <1147136909.428632.8880@j73g2000cwa.googlegroups.com> Dear Python experts, I have a strange problem - or more precisely, I'm not even sure if it's a problem or not. I'm developing a Python extension module in C which creates a new type with methods, mapping support and stuff like that :) Everything's working fine, but if I inherit a new class from this type in Python, I start getting strange warning messages in valgrind. Just a simple example: import mymodule class InheritedType(mymodule.MyType): def a_new_method(self): print "test" x=InheritedType() x.a_new_method() ("mymodule" is the C extension module I developed) The error message I see in valgrind is the following: ==6579== Conditional jump or move depends on uninitialized value(s) ==6579== at 0x807CFF9: PyObject_GenericGetAttr (object.c:1283) ==6579== by 0x80B2EA3: PyEval_EvalFrame (ceval.c:1957) [...] I'm using Python 2.4.3, and by taking a look at the source of object.c (line 1283), it looks like the tp_dict member of the type object of my subclass is not initialized. The code snippet from line 1281-1285 looks like this: dictptr = (PyObject **) ((char *)obj + dictoffset); dict = *dictptr; if (dict != NULL) { res = PyDict_GetItem(dict, name); if (res != NULL) { [...] Should I worry about Valgrind's warning or is it just a false alarm? It does not occur if I try to inherit my class from a built-in class (like string or module or whatever), only if I use my extension's class, so I suspect that I'm doing something wrong. Is there anything I should watch out for when I create inheritable classes in a C extension? Thanks a lot in advance. -- Tamas <ntamas at gmail.com> From grante at visi.com Sat May 6 17:04:20 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 06 May 2006 21:04:20 -0000 Subject: NaN handling References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> <mailman.5402.1146867973.27775.python-list@python.org> <125nlbgm8l1fi17@corp.supernews.com> <DE87348C-5BE0-4D55-B041-516FB72E7B04@mcmaster.ca> <mailman.5409.1146880569.27775.python-list@python.org> <yfsy7xfxr1x.fsf@oc.ex.ac.uk> <mailman.5428.1146943512.27775.python-list@python.org> Message-ID: <125q3qk6tk9go4a@corp.supernews.com> On 2006-05-06, Robert Kern <robert.kern at gmail.com> wrote: >>>>Since numpy seems to be working on a variety of platforms/hardware, >>>>how hard would it be to extract this functionality from it to add to >>>>Python proper? >>> >>>Harder than just enabling fpectl. >> >> Last thing I heard fpectl was considered to be completely broken -- it's >> likely not disabled by default for no reason. > > Fair enough. If you want to go through numpy's code to rip out its floating > point error handling, knock yourself out. It's not going to be trivial, though. > It's heavily embedded in the ufunc machinery. Does numpy's NaN handling only work within numpy functions, or does it enable HW FP signals and then catch them for "normal" floating point operations that take place outside of numpy code? -- Grant Edwards grante Yow! I'm in direct contact at with many advanced fun visi.com CONCEPTS. From me at modelnine.org Wed May 17 15:34:39 2006 From: me at modelnine.org (Heiko Wundram) Date: Wed, 17 May 2006 21:34:39 +0200 Subject: creating a new database with mysqldb In-Reply-To: <wKKag.2114$No6.46328@news.tufts.edu> References: <gcKag.2113$No6.46302@news.tufts.edu> <1147893204.503850.225770@j73g2000cwa.googlegroups.com> <wKKag.2114$No6.46328@news.tufts.edu> Message-ID: <200605172134.39401.me@modelnine.org> Am Mittwoch 17 Mai 2006 21:23 schrieb John Salerno: > Well, the thing about it is that all the guides I find online seem to > begin with using a command prompt or a unix shell, neither of which will > work in my case. I'm trying to find a way to access my database server > using just a python script. Perhaps that isn't even possible for me to > do without shell access. I might just have to use the msqladministrator > in my server control panel, instead of using python. Creating a database is just another SQL command in MySQL (which you can easily send to the MySQL server you're using with Python and MySQLdb): "CREATE DATABASE <dbname>" Of course, you need to log on with a user who is allowed to create databases. See the MySQL documentation for more info on the available CREATE commands. --- Heiko. From Toyagaines at aol.com Sat May 27 14:26:43 2006 From: Toyagaines at aol.com (Toyagaines at aol.com) Date: Sat, 27 May 2006 14:26:43 EDT Subject: CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS! Message-ID: <4ad.18e670.31a9f3e3@aol.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060527/c7b87350/attachment.html> From thomas at eforms.co.nz Wed May 24 23:59:08 2006 From: thomas at eforms.co.nz (Thomas Thomas) Date: Thu, 25 May 2006 15:59:08 +1200 Subject: os listdir access denied when run as a service References: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz><1146620207.56.7672@mint-julep.mondoinfo.com><002901c66e57$05a69090$346ea8c0@tintz.co.nz><1146624295.41.7841@mint-julep.mondoinfo.com><003501c66e64$316deb30$346ea8c0@tintz.co.nz><1146677203.2.7870@mint-julep.mondoinfo.com><00f701c673e5$a3af0860$346ea8c0@tintz.co.nz><1147292340.91.3040@mint-julep.mondoinfo.com><012d01c67473$09fc0450$346ea8c0@tintz.co.nz><1147305886.06.3304@mint-julep.mondoinfo.com><016201c67497$22a91d70$346ea8c0@tintz.co.nz> <1147311218.22.3304@mint-julep.mondoinfo.com> Message-ID: <03cf01c67faf$97f94d20$346ea8c0@tintz.co.nz> Hi All, I am trying to access a mapped network drive folder. everything works fine normally. But when i run the application as service I am getting the error Traceback (most recent call last): File "docBoxApp.py", line 129, in ? File "core\PollFiles.pyc", line 332, in doPoll File "core\PollFiles.pyc", line 47, in createFileList File "core\PollFiles.pyc", line 25, in addFolderFiles WindowsError: [Errno 5] Access is denied: 'G:\\DT Hot Folder test/*.*' below is my code def addFolderFiles(folder,filelist=[]): logger=ServerInterface.getErrorLogger() folder = folder.encode('ascii') #convert path to ascii for File Method for filename in os.listdir(folder):#line 25 file=os.path.join(folder,filename) logger.error("loop file :"+file); if os.path.isfile(file): logger.error("is file :"+file); if ((not (file.find(".tmp")>=0)) and (not (file.find("~")>=0))): filelist.append(file) elif os.path.isdir(file): logger.error("file is a directory :"+file); addFolderFiles(file,filelist) def createFileList(files,folders,filelist=[]): logger=ServerInterface.getErrorLogger() for file in files: file = file.encode('ascii') #convert path to ascii for File Method if os.path.isfile(file): if ((not (file.find(".tmp")>=0)) and (not (file.find("~")>=0))): filelist.append(file) for folder in folders: logger.error("got a folder :"+folder); logger.error("it was in the list :"+folders.__str__()); addFolderFiles(folder,filelist) return (1,filelist) anything I can do about this.. ----------------------------------------------------- Thomas Thomas From 123 at 321.com Mon May 8 17:58:10 2006 From: 123 at 321.com (DeepBlue) Date: Tue, 09 May 2006 05:58:10 +0800 Subject: Econometrics in Panel data? Message-ID: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi all, I am new to Python. Just wondering can Python able to do econometric regression in either Time-series or pooled (panel) data? As well as test for hetero, autocorrelation, or endogeneity? Thank you! From diffuser78 at gmail.com Wed May 10 19:10:33 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 10 May 2006 16:10:33 -0700 Subject: Memory leak in Python In-Reply-To: <1147230403.415674.72580@e56g2000cwe.googlegroups.com> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <44605dd1$0$2056$626a54ce@news.free.fr> <1147225282.478996.134910@i39g2000cwa.googlegroups.com> <1147230403.415674.72580@e56g2000cwe.googlegroups.com> Message-ID: <1147302632.946485.184730@u72g2000cwu.googlegroups.com> With 1024 nodes it runs fine...but takes around4 hours to run on AMD 3100. From sjmachin at lexicon.net Mon May 8 09:24:45 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 08 May 2006 23:24:45 +1000 Subject: A better way to split up a list In-Reply-To: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> References: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> Message-ID: <445F469D.60007@lexicon.net> On 8/05/2006 10:45 PM, fidtz at clara.co.uk wrote: > The code below works fine, but it is less than nice to look at and > somewhat long winded. Is there a better way to do the docstring task? > This is the first working version, and can proabably be "compacted" a > bit (list comprehensions etc) but I am looking for a better basic > approach. Any help much appreciated :) > > from itertools import islice > def chopupmoves(movelist): > '''creates a list of 3 lists from one list, that should all have > (length of movelist)/3 length, with any remainder getting added to the > third list''' > outputlist = [[],[],[]] > > parlen = int(len(movelist)/3) > if parlen < 3: > parlen = 3 What's this for? It causes weird things to happen with short lists. > > stoplist=[0];exit = 0 > while exit < len(movelist): > stoplist.append(exit+parlen) > exit = exit + parlen > while len(stoplist) > 4: > stoplist.pop(len(stoplist)-1) > stoplist[-1]=len(movelist) > > for x in range(len(stoplist)-1): > for i in islice(movelist,stoplist[x],stoplist[x+1],1): > outputlist[x].append(i) > return outputlist > movelist = [1,2,3,4,5,6,7,8,9,10,11] > print chopupmoves(movelist) > Unless I've totally misunderstood your spec, you don't need all that islice and stoplist stuff. def chopupmoves2(movelist): parlen = len(movelist) // 3 return [movelist[:parlen], movelist[parlen:parlen*2], movelist[parlen*2:]] for k in range(13): mlist = range(k) print print "v1", chopupmoves(mlist) print "v2", chopupmoves2(mlist) From joesb.coe9 at gmail.com Tue May 9 05:04:54 2006 From: joesb.coe9 at gmail.com (Pisin Bootvong) Date: 9 May 2006 02:04:54 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <DN-dnRfxYOiFzv3ZnZ2dnUVZ_v6dnZ2d@speakeasy.net> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <pan.2006.05.06.03.54.17.404055@hastings.org> <1147123648.914726.212680@i39g2000cwa.googlegroups.com> <1147156556.952331.29450@i39g2000cwa.googlegroups.com> <DN-dnRfxYOiFzv3ZnZ2dnUVZ_v6dnZ2d@speakeasy.net> Message-ID: <1147165494.822938.27590@e56g2000cwe.googlegroups.com> Rob Warnock wrote: > Pisin Bootvong <joesb.coe9 at gmail.com> wrote: > +--------------- > | No matter how scalable your language is, you cannot make a 100MHz/128MB > | server serve 100,000 client a second over the internet. > +--------------- > > Sure you can! That's ~1000 CPU cycles/request, which [assuming at least > a 100BASE-TX NIC] is plenty to service 100K *small* requests/s... ;-} > > Of course, you might have to write it in assembler on bare metal, > but the good news is that with only a 1000 cycle budget, at least > the code won't be very large! ;-} > Well, I was really asking for a service that really service something complicate and useful though :-D And donot forget to account for OS CPU time (well may be you can write your own OS for it too :-D ) > > -Rob [someone who remembers 0.5 MIPS DEC PDP-10s being used > for >100 simultaneous commercial timesharing users] > > ----- > Rob Warnock <rpw3 at rpw3.org> > 627 26th Avenue <URL:http://rpw3.org/> > San Mateo, CA 94403 (650)572-2607 From ag at mirada-solutions.com Sat May 13 20:32:00 2006 From: ag at mirada-solutions.com (Alexandre Guimond) Date: 13 May 2006 17:32:00 -0700 Subject: distutils and binding a script to a file extension on windows Message-ID: <1147566720.618224.150810@j73g2000cwa.googlegroups.com> Hi. I built a little installer on windows XP using distutils for my package. In there i add a few files to the python script directory. I would like one of these scripts to be the default program to be used by files with a given extention (e.g. i have an image viewer and would like it to be used when ever i click on a .gif file). I can do this manually (through Tools->Folder Options->File Types), but it would be nicer if the installer could configure this. It seems this may be possible through the "postinstallation" script of distutils, but i have no clue how to do this. does any have experience with this? i assume i need to edit the registry entries, but i dont know how or which ones. thx for any help alex. From rupole at hotmail.com Wed May 31 23:35:50 2006 From: rupole at hotmail.com (Roger Upole) Date: Wed, 31 May 2006 23:35:50 -0400 Subject: Try/Except for ADSI GetObject References: <al5fg.9877$ho6.1459@trnddc07> Message-ID: <1149132664_5885@sp6iad.superfeed.net> "LittlePython" <LittlePython at lost.com> wrote in message news:al5fg.9877$ho6.1459 at trnddc07... >I am a little confused on why I can not detect an object that does not exist > with a try and except. If I understand ADSI correctly from what I have read > you do not create these objects but rather get them. They already exist. I > believe if I do the equivalent in VB I would generate an error when I try to > get an object that does not exist (can not find). I don't get an error when doing a GetObject in VBS for a nonexistent domain. What have I done wrong? > I have included the function below that works in ever respect but detecting > incorrect NT Domain Names (objects that do not exist) . Any tips, insight or > comments would be welcome by this newbie. You should be able to use win32net.NetValidateName to verify that the domain exists before doing any more operations. hth 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 luismgz at gmail.com Sat May 20 15:36:41 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 20 May 2006 12:36:41 -0700 Subject: combining a C# GUI with Python code? In-Reply-To: <446f4058$0$1987$c3e8da3@news.astraweb.com> References: <3Dnbg.2135$No6.46516@news.tufts.edu> <mn.a2757d657d031da4.43626@yahoo.fr.invalid> <446f4058$0$1987$c3e8da3@news.astraweb.com> Message-ID: <1148153801.219968.291840@i39g2000cwa.googlegroups.com> PythonCard is based on wxpython and it's free: http://pythoncard.sourceforge.net/ From robert.kern at gmail.com Thu May 11 23:04:30 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 22:04:30 -0500 Subject: which windows python to use? In-Reply-To: <e40t7m$ull$1@daisy.noc.ucla.edu> References: <mailman.5589.1147359382.27775.python-list@python.org> <e406rp$dvt$1@daisy.noc.ucla.edu> <mailman.5608.1147380021.27775.python-list@python.org> <e40t7m$ull$1@daisy.noc.ucla.edu> Message-ID: <e40tvu$jm1$1@sea.gmane.org> James Stroud wrote: > Robert Kern wrote: > >>James Stroud wrote: >> >>>Enthought does not play well with cygwin, I've noticed. >> >>In what way? Does the mingw gcc that we distribute interfere with Cygwin's gcc? > > One can not run the enthought python interactive interpreter from a > cygwin x-window session, it locks up. Interesting. I've seen the same thing with MSYS's rxvt ("native", not X). I presumed it was a strange interaction between bash and (any) Python. Looks like it may just be our Python, then. I'll enter a ticket on our Trac. Thank you! -- 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 rocky at panix.com Tue May 23 23:09:29 2006 From: rocky at panix.com (R. Bernstein) Date: 23 May 2006 23:09:29 -0400 Subject: continue out of a loop in pdb References: <87mzdkwke3.fsf@localhost.localdomain> <PIK9g.28632$CH2.27494@tornado.texas.rr.com> <87ac9kwdl8.fsf@localhost.localdomain> <4cpqtcF16e1gaU1@uni-berlin.de> Message-ID: <wih7j4cw23a.fsf@panix3.panix.com> "Diez B. Roggisch" <deets at nospam.web.de> writes: > > the code works with no problem, I am playing around with the pdb, i.e > > **************** > > from pdb import * > > set_trace() for i in range(1,500000): > > print i > > print "tired of this" > > print "I am out" > > **************** > > fred at debian:~/python/practic$ python practic.py > >> /home/fred/python/practic/practic.py(4)?() > > -> for i in range(1,500000): > > (Pdb) n > >> /home/fred/python/practic/practic.py(5)?() > > -> print i > > (Pdb) n > > 1 > >> /home/fred/python/practic/practic.py(4)?() > > -> for i in range(1,500000): > > (Pdb) b 6 > > Breakpoint 1 at /home/fred/python/practic/practic.py:6 > > (Pdb) c > >> /home/fred/python/practic/practic.py(5)?() > > -> print i <<<< I expected (print "tired of this") > > (Pdb) > > > In TFM it says that set_trace() puts a breakpoint to the current > frame. I admit that I also wouldn't read that as "each and every > instruction in this very frame", but that is what essentially > happens. I think the docs could need some enhancement here. Try > debugging a called function, there things will work as expected. Let me try to explain my understanding here. set_trace() merely tells the Python interpreter to call the debugger dispatcher after the call to set_trace() finishes. In effect this is at the next statement of your program because the caller frame here is always the "set_trace()" call you put in your program. Okay, so now we've called this "debugger dispatcher" thing and what does that do? Well, it accepts commands from you, like "next" or "step" or "continue". . In the case above, Python was told to make that set-trace call 500000 times. But yes, I agree the wording in in the pdb (and pydb) manuals are written too much from view of someone writing a debugger rather than someone using it. If you or someone else wantsto make a suggestion as to how to make the description of set_trace() more user friendly (and I don't think the above explanation succeeds), I'll put it in the next release of pydb (http://bashdb.sourceforge.net/pydb) which probably will be in the not-too distant future. From nospam at foo.com Fri May 12 19:10:34 2006 From: nospam at foo.com (jayessay) Date: 12 May 2006 19:10:34 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> <m38xp7p7el.fsf@rigel.goldenthreadtech.com> <yfs3bffuqj7.fsf@oc.ex.ac.uk> <r559g.16$Id.14@fe10.lga> <yfsk68rt3cq.fsf@oc.ex.ac.uk> Message-ID: <m3vesaon4l.fsf@rigel.goldenthreadtech.com> Alexander Schmolck <a.schmolck at gmail.com> writes: > Ken Tilton <kentilton at gmail.com> writes: > > > Alexander Schmolck wrote: > > > jayessay <nospam at foo.com> writes: > > > > > > > >>"Michele Simionato" <michele.simionato at gmail.com> writes: > > >> > > >> > > >>>I was interested in a proof of concept, to show that Python can > > >>>emulate Lisp special variables with no big effort. > > >> > > >>OK, but the sort of "proof of concept" given here is something you can > > >> hack up in pretty much anything. > > > > > Care to provide e.g. a java equivalent? > > > > > > I think the point is that, with the variable actually being just a string and > > with dedicated new explicit functions required as "accessors", well, you could > > hack that up in any language with dictionaries. > > Great -- so can I see some code? Can't be that difficult, it takes about 10-15 > lines in python (and less in scheme). Do you actually need the code to understand this relatively simple concept??? /Jon -- 'j' - a n t h o n y at romeo/charley/november com From jstroud at ucla.edu Thu May 11 16:29:45 2006 From: jstroud at ucla.edu (James Stroud) Date: Thu, 11 May 2006 13:29:45 -0700 Subject: which windows python to use? In-Reply-To: <mailman.5589.1147359382.27775.python-list@python.org> References: <mailman.5589.1147359382.27775.python-list@python.org> Message-ID: <e406rp$dvt$1@daisy.noc.ucla.edu> Brian Blais wrote: > Hello, > > Are there any recommendations for which Windows python version to use? > I'd like to see a pros-and-cons description of each, given that > different uses might dictate different versions. The versions I know > (and there are surely more) are: > > 1) download from www.python.org > 2) enthought > 3) activepython > > Are there advantages/disadvantages? I have used enthought before, but > it seems as if they are not at 2.4, and may lag behind in versions > (which may not be a bad thing). > > Any other recommendations? > > > thanks, > > Brian Blais > > Enthought does not play well with cygwin, I've noticed. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From robert.kern at gmail.com Thu May 11 02:35:10 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 01:35:10 -0500 Subject: problem with array and for loop In-Reply-To: <slrne65lt7.53j.f.braennstroem@node1.ut.TU-Berlin.DE> References: <slrne65jfh.53j.f.braennstroem@node1.ut.TU-Berlin.DE> <e3uje4$vf3$1@sea.gmane.org> <slrne65lt7.53j.f.braennstroem@node1.ut.TU-Berlin.DE> Message-ID: <e3uluu$5mq$1@sea.gmane.org> Fabian Braennstroem wrote: > Hi Robert, > > * Robert Kern <robert.kern at gmail.com> wrote: >>Are you aware that numpy array indices start with 0, not 1? >> >>You will probably want to ask numpy questions on the numpy-discussion mailing list: >> >> http://www.scipy.org/Mailing_Lists > > I thought a simple for loop-array-declaration question would > fit in this group ... it actually help for this simple > problem. Thanks! When you have an issue with a certain package, and that package has a dedicated mailing list, you will usually a get a much better response on that list instead of a general one. While I usually read comp.lang.python every day and try to answer all numpy and scipy questions that come by, I really prefer to see these questions on the appropriate lists. -- 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 tsaar2003 at yahoo.com Wed May 3 04:28:24 2006 From: tsaar2003 at yahoo.com (tsaar2003 at yahoo.com) Date: 3 May 2006 01:28:24 -0700 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> <mailman.5253.1146643043.27775.python-list@python.org> Message-ID: <1146644904.906523.255970@j73g2000cwa.googlegroups.com> > are you sure you know how Python's object model work ? if you do, please > explain your proposal in terms of what needs to be changed, rather than in > terms of wishful thinking. No, I do not know. As stated in my first post, I am quite newbie in Python and miss a simple and intuitive mechanism that would allow to declare something as constant and that would protect these "constant" objects from accidental modifications. T.S. From harry.g.george at boeing.com Tue May 16 01:59:00 2006 From: harry.g.george at boeing.com (Harry George) Date: Tue, 16 May 2006 05:59:00 GMT Subject: Using python for a CAD program References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Message-ID: <xqxpsietsrf.fsf@cola3.ca.boeing.com> 63q2o4i02 at sneakemail.com writes: > Hi, I'm interested in using python to start writing a CAD program for > electrical design. I just got done reading Steven Rubin's book, I've > used "real" EDA tools, and I have an MSEE, so I know what I *want* at > the end of this; I just have never taken on a programming task of this > magnitude. I've seen that some are using python as a utility language > for existing CAD environments, and I've also found some guy who's > writing a 2d drafting tool with python, which is cool. I've been > playing with python recently and so far have a SPICE parser > half-written (it'll do production rules, but no syntax trees yet...) > I'm wondering if the python experts can provide some opinion on > python's efficiency/utility in the following areas, and perhaps where > some things will need to be in C++ and/or pyrex: > > 1. Databases. I don't mean sql type database, but design databases, > which contain all the components for any given design, including > schematics, layout, simulation parameters, etc. I'm not concerned > about python's ability to do fancy data structures, but I'm wondering > how it'll go in terms of efficiency when things get really big. If the > alternative is home-brewed C++ linked-lists, attributes, arrays, binary > trees, memory management, etc., it looks like python's ability to do > all this neatly without all the bugs waiting to happen if I did this > myself are well worth the efficiency loss that may result from its > uber-generality. > > 2. GUI. Yes, I know you can do guis with qt, gtk, tkinter, etc. I'm > talking of fancy guis that do alpha blending, animations, nice > shading/gradients, etc. in a quick, smooth, and slick way, such that > moving a scroll bar or jiggling the mouse yields fast game-like > response time, and which gives this program the feeling that you're > actually in the 21st century... ie this is an *interactive* > environment, and I f***king hate crass-hatching, so real colors is a > must. Can this be portable between linux and windows? Is it possible > to "do the whole thing" in opengl, even the 2d stuff? I guess I dont > know enough about guis here. My fear is that my app will turn into > x-hell if I try to do more than 8-bit colors in linux, with flashing > background windows and complaints from the server about bit planes. > Maybe I need to play with linux a bit more from the development side > before commenting on this, since I get the feeling I'm working on old > information here... > > 3. Computational stuff. I imagine the really heavy computing needs to > be done in c++, especially if I'm stupid enough to write my own > simulator, which my brain seems to want to do (I'm imagining a small > homer simpson brain with a mind of its own telling me what to do...). > But what about other things like rules and constraints about layout, > routing, compaction, undo/redo, etc? These aren't really > computationally expensive, I don't think, but do munge about quite a > bit with the database. Is it likely I'll write something faster in > C++? (answer: no). > > 4. Programmability. I imagine this is a slam-dunk, relatively > speaking, to have a python interpreter as part-and-parcel of the design > system. But how do I customize the command window to do custom things > like adding special shortcuts (eg '?' brings up help, or help on > commands a la Matlab), or making an API into the CAD program? I'm not > sure conceptually how to merge an embedded python interpreter into the > rest of the CAD program in an intelligent way, so some stuff is > exposed, but not all, and which interacts dynamically with the > graphical portion so that, for instance, context-sensitive help is > available in the console window, or so you can access information about > the currently selected object, or so you can do stuff from the command > line that is based on your current graphical context. > > 5. Threads and parallelism. One of the things about this is that I'd > like there to be some real-time simulator running so when you change > the values of parts, the output changes, and I'd like to be able to > take advantage of mulitple processors, or dual-core, or whatever. I've > seen fake multi-threading in python (read about it, but I haven't done > it), but that doesn't really use any extra cycles from a separate > processor. > > So why am I thinking about this? I've used a few "real" CAD systems, > and from using them, it's obvious the modus is to kludge shit together > over 20 years and screw the user experience. So basically I'd like to > take over the world with my nifty new python-based cad system because > it's so beautiful and fun to use, and so flexible that my time to > market for any given new idea is 5x shorter than the existing tools. > > Any comments on the above from people who've actually written stuff > would be greatly appreciated! :) > > thanks > ms > As a BSEE, MSCS, and developer using Lisp and Prolog for Knowledge-Based Engineering (KBE) of structures and systems, I'm interested in where you are going. Nothing wrong with reinventing a few wheels, but I always like to start with a literature search. It wasn't clear if you had done so. At a minimum, take a look at: 1. OSS EE suites: http://www.opencollector.org/ http://www.geda.seul.org/ I don't see rewriting ngspice or Icarus Verilog -- people of people doing that. Putting a good DBMS behind gscheme on the other hand makes sense. Also, I write Python scripts around geda and there has been discussion of embedding Python. 2. Databases: Locally, we have struggled with various DBMSs. It seems OO is mandatory, so I look to Postgresql with inheritance, or (smaller scale) ZODB. I really wouldn't want to grow one from B+ trees. http://www.postgresql.org/ http://www.zope.org/Products/StandaloneZODB 3. 2D CAD and game engines: http://directory.fsf.org/PythonCAD.html http://pygame.seul.org/news.html 4. 3D CAD Locally we write Python code against several commercial CAD packages (I agree with your assessment). For an OSS effort, the only game in town seems to be: http://www.opencascade.org/ http://free-cad.sourceforge.net/ 5. Knowledge Based Engineering (KBE) inference engines: Python already gives you lazy evaluation and memoizing, but a prolog-based backward chaining engine helps too. We wrote CAD-engine-calls-python-and-prolog and python-and-prolog-calls-CAD-engine scripts. http://sourceforge.net/projects/pyprolog/ http://christophe.delord.free.fr/en/pylog/ http://arts.anu.edu.au/linguistics/People/AveryAndrews/Software/AmziPy/Doc/manual.pyfrompro.html http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/303057 6. Simulation http://simpy.sourceforge.net/ Also need FEM for electromagnetic analysis, and CFD for heat dissapation. -- Harry George PLM Engineering Architecture From mwilson-to at sympatico.ca Fri May 26 12:21:56 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Fri, 26 May 2006 12:21:56 -0400 Subject: how to clear up a List in python? In-Reply-To: <1148653059.381151.113360@j73g2000cwa.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <e54gtn$grs$1@ulysses.news.tiscali.de> <1148653059.381151.113360@j73g2000cwa.googlegroups.com> Message-ID: <FWFdg.2226$ho5.171990@news20.bellglobal.com> linnorm at gmail.com wrote: > The original post only mentions deleting the values in the list, not > the list itself. Given that you want to keep the list and just ditch > the values it contains I'd go with: > > list1 = [] Depends what you mean by "keep the list". Consider class C (object): def __init__ (self, things): self.things = things a = range (5) b = C (a) a = [] print b.things d = range (5) e = C (d) d[:] = [] print e.things These are very different. Mel. From rganesan at myrealbox.com Fri May 19 08:25:01 2006 From: rganesan at myrealbox.com (Ganesan Rajagopal) Date: Fri, 19 May 2006 17:55:01 +0530 Subject: memory error with zipfile module References: <446DADFD.1040705@gmail.com> Message-ID: <xkvhejyq6w2q.fsf@grajagop-lnx.cisco.com> >>>>> Hari Sekhon <sekhon.hari at googlemail.com> writes: > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "D:\u\Python24\lib\zipfile.py", line 357, in read > bytes = dc.decompress(bytes) > MemoryError Looks like the .iso file is huge. Even if it's only a CD image (approx 650MB), reading it all into memory in a single string is not a good idea. > The python zipfile module is obviously broken... Indeed. I am surprised that there is no API that returns a file object. Ganesan -- Ganesan Rajagopal From bucodi at yahoo.fr.invalid Mon May 8 10:48:24 2006 From: bucodi at yahoo.fr.invalid (Rony Steelandt) Date: Mon, 08 May 2006 16:48:24 +0200 Subject: Job opportunity in France References: <mn.2a417d6545f2820b.43626@yahoo.fr.invalid> <cG37g.53396$eR6.17008@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <mn.43f07d6555ae6099.43626@yahoo.fr.invalid> Well that would be one less, and countng.... > Rony Steelandt wrote: > >> We have a vacancy for a python programmer for a 6 months assignement. >> >> If interested, please visit www.bucodi.com >> >> And don't worry we speak english :) >> >> R_ >> > seriously, a job opportunity in France?? I heard that the unemployment rate > is not doing too well. -- --- Rony Steelandt BuCodi rony dot steelandt (at) bucodi dot com Visit the python blog at http://360.yahoo.com/bucodi From shree.ksn at gmail.com Mon May 29 15:48:08 2006 From: shree.ksn at gmail.com (nataraj) Date: 29 May 2006 12:48:08 -0700 Subject: Very good Python Book. Free download : Beginning Python: From Novice to Professional In-Reply-To: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> References: <1148925133.715216.12020@i39g2000cwa.googlegroups.com> Message-ID: <1148932088.908285.160250@u72g2000cwu.googlegroups.com> i won't have a free and guileless mind to code if i do this. From m.yanowitz at kearfott.com Tue May 9 16:14:30 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Tue, 9 May 2006 16:14:30 -0400 Subject: Shadow Detection? In-Reply-To: <U-WdnQTfLKUebf3ZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <HGEOKIAPAMCIFPPBDALKMEINCAAA.m.yanowitz@kearfott.com> Hello: Many times, people are warning things like "Don't use 'str' as a variable name as it will shadow the built in str function." Is there some way to determine if a string is already defined in some higher scope? Maybe something like <code> if isdefined ('str'): print 'str is already defined, please choose another name' </code> If not, would it be easy to write this? Thanks in advance: From bencvt at gmail.com Sun May 7 01:05:08 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 6 May 2006 22:05:08 -0700 Subject: Splice two lists In-Reply-To: <1146973630.629933.323210@y43g2000cwc.googlegroups.com> References: <1146961724.195038.18680@u72g2000cwu.googlegroups.com> <1146965920.842441.168920@i40g2000cwc.googlegroups.com> <1146973630.629933.323210@y43g2000cwc.googlegroups.com> Message-ID: <1146978308.297369.319930@j73g2000cwa.googlegroups.com> danmcleran at yahoo.com wrote: > Thanks, this worked great. Welcome. :-) > Can you explain the syntax of the '*' on the > return value of izip? I've only ever seen this syntax with respect to > variable number of args. When used in a function call (as opposed to a function definition), * is the "unpacking" operator. Basically, it "flattens" an iterable into arguments. The docs mention it... http://www.python.org/doc/2.4.2/tut/node6.html#SECTION006740000000000000000 http://www.python.org/doc/faq/programming/#how-can-i-pass-optional-or-keyword-parameters-from-one-function-to-another ...but not in great detail. You can apply * to an arbitrary expression, e.g.: >>> def f3(a, b, c): pass >>> f3(1, 2, 3) >>> f3(*range(3)) >>> f3(*[1, 2, 3]) --Ben From fccoelho at gmail.com Fri May 12 21:07:47 2006 From: fccoelho at gmail.com (Flavio) Date: 12 May 2006 18:07:47 -0700 Subject: distributing a app frozen by cx_freeze Message-ID: <1147482467.404798.187530@y43g2000cwc.googlegroups.com> Hi, After a good deal of tunig I managed to freeze my application. I ended up with an executable, and a Bunch of .so files in the install-dir. It runs fine in the original machine. I copied the install folder to another machine but the executable wont run. Here's the traceback: Traceback (most recent call last): File "/home/fccoelho/Downloads/cx_Freeze-3.0.2/initscripts/Console.py", line 26, in ? File "epigrass.py", line 4, in ? ImportError: /home/flavio/freeze/qt.so: undefined symbol: _ZNK9QSGIStyle9classNameEv It is looking for the Original cx_freeze installation!! Do I have to distribute cxFreeze with my app? I don't think so. But in that case, how do I remove this dependency? any help is appreciated Fl?vio From nkanthikiran at gmail.com Sun May 28 03:43:12 2006 From: nkanthikiran at gmail.com (k.i.n.g.) Date: 28 May 2006 00:43:12 -0700 Subject: generating random passwords ... for a csv file with user details Message-ID: <1148802192.793574.209720@i40g2000cwc.googlegroups.com> Hi, I have a csv file which in taken as the input file for adding users in my linux mail server with the format userid,fullname,passwword,dateofbith Now I have to write a script to generate random password in the password field for each user. A simple algorithm is sufficient for passwords I being new to scripting would seek all your help in doing so Thanks In advance kanthi From cfc at shell01.TheWorld.com Wed May 10 15:58:58 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 10 May 2006 15:58:58 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> <NUP7g.17$G22.12@fe11.lga> <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> <ubn362tg2ft4la26hq4so0ron8lsj7fvqe@4ax.com> <sddwtcuc4wo.fsf@shell01.TheWorld.com> <Fio8g.7$CQ6.0@fe11.lga> Message-ID: <sddwtctfy7x.fsf@shell01.TheWorld.com> Kenny replied to me saying: > Yep. But with Cells the dependency graph is just a shifting record of > who asked who, shifting because all of a sudden some outlier data will > enter the system and a rule will branch to code for the first time, > and suddenly "depend on" on some new other cell (new as in never > before used by this cell). This is not subject to static analysis > because, in fact, lexically everyone can get to everything else, what > with closures, first-class functions, runtime branching we cannot > predict... fuggedaboutit. > > So we cannot say, OK, here is "the graph" of our application > model. All we can do is let her rip and cross our fingers. :) Yes, if you have Turing completeness in your dependency graph, the problem is unsolvable. However, it's like the static v. dynamic typing debate, you can pick how much you want to allow your graph to be dynamic versus how much "safety" you want. In particular, I suspect that in many applications, one can compute the set of potentially problematic dependencies (and that set will be empty). It's just a matter of structuring and annotating them correctly. Just like one can create type systems that work for ML and Haskell. Of course, if you treat your cell references like C pointers, then you get what you deserve. Note that you can even run the analysis dynamically, recomputing whether the graph is cycle free as each dependency changes. Most updates have local effect. Moreover, if you have used topological sort to compute an ordering as well as proving cycle-free-ness, the edge is only pontentially problemantic when it goes from a later vertex in the order to an earlier one. I wouldn't be surprised to find efficient algorithms for calculating and updating a topological sort already in the literature. It is worth noting that in typical chip circuitry there are constructions, generally called "busses" where the flow of information is sometimes "in" via an edge and sometimes "out" via the same edge and we can model them in a cycle-free manner. If you want to throw up your hands and say the problem is intractable in general, you can. However, in my opinion one doesn't have to give up quite that easily. -Chris From fabiofz at gmail.com Mon May 22 16:42:19 2006 From: fabiofz at gmail.com (Fabio Zadrozny) Date: Mon, 22 May 2006 17:42:19 -0300 Subject: Pydev release 1.0.7 Message-ID: <cfb578b20605221342kebedb18ga2bf8d1347e70c56@mail.gmail.com> Hi All, Pydev and Pydev Extensions 1.0.7 have been released Check http://www.fabioz.com/pydev for details on Pydev Extensions and http://pydev.sf.net for details on Pydev Release Highlights in Pydev Extensions: ----------------------------------------------------------------- - Mark Occurrences is able to highlight all the occurrences of some token in a file (and is python-aware) - Rename Occurrences is able to rename all the occurrences of some token in a file (Ctrl+2+R) - Hierarchy view is final (can now find children classes in referencing modules) - Remote debugger - Can redirect the output to the client (the signature for starting the remote debugger became settrace(host='localhost', stdoutToServer = False, stderrToServer = False)) - Maps the locations from the server to the client even if they are not in the same exact paths - Force code-analysis in the current editor (Ctrl+2+C) Release Highlights in Pydev: ---------------------------------------------- - Assign variables to attributes (Ctrl+2+a): Contributed by Joel Hedlund (this is the first contribution using the new jython scripting engine). - 3 minor 'quirks' were fixed in the indentation engine - The debugger had some changes (so, if you had halts with it, please try it again). - Allow changing the keybinding for activating the Find next problem (Ctrl+.) - The debugger step-return had its behaviour changed. - Additional scripts location added to pythonpath in the jython scripting engine - Transversal of nested references improved - Fixed problems with compiled modules when they had 'nested' module structures (e.g.: wx.glcanvas) 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: <http://mail.python.org/pipermail/python-list/attachments/20060522/9d22bf8b/attachment.html> From thomasbartkus at comcast.net Wed May 31 13:25:57 2006 From: thomasbartkus at comcast.net (Thomas Bartkus) Date: Wed, 31 May 2006 12:25:57 -0500 Subject: ideas for programs? References: <mailman.6346.1149051733.27775.python-list@python.org> Message-ID: <sq2dnRA2-JURTODZRVn-sg@telcove.net> "Brandon McGinty" <brandon.mcginty at gmail.com> wrote in message news:mailman.6346.1149051733.27775.python-list at python.org... > Hi, > I've been learning python for the past couple of months and writing misc > scripts here and there, along with some web apps. > I'm wondering if anyone has ideas of programs I might try my hand at making? > I'd appreciate it if they don't use images, because I'm blind. > > Also, I'm thinking of hiring myself out as a free-lance programmer. Python is your tool to put your expertise on a computer. Skill with Python, or any computer language for that matter, counts for little. Expertise that you can code into a computer program however, counts for much. No matter what the language you use to accomplish computer automation. > Are there many individuals/companies which would aprove programs written > in python? Don't even ask that question. It's irrelevant. Companies approve programs that solve company problems! Does anyone care what Excel, Quickbooks, Autocad, Turbo Tax, MySQL, whatever, are written in? No! Automate something useful! A bookeeping problem. Or a computer networking problem. OR a chemistry, cooking, gardening, truck routing, record keeping, music problem. What about new ways a computer might make life easier for the handicapped? Or old ways done better. How do the blind communicate with a computer? I see nothing but software opportunites yet undone. Python plus expertise in something else. It's the something else that hangs people up. You need to have or acquire that something else. I can't write a bookeeping program if I don't understand bookeeping and my Python abilities offer no relief from that particular deficiency. > Most adds I've seen require the programmer have a strong grasp of c++ or > java. Those ads are worthless! They are put forth by people with meaningless jobs in human resources and no understanding of what one might do with computer software. Hobbies? Interests? Expertise? What inspires you that might be put into computer code? You can't sell a program because it's written in Python. But you can sell a Python program that solves a problem. Find a problem and beat it with software. The particular language you choose to use has nothing to do with it! But we do like Python ;-) Thomas Bartkus From luismgz at gmail.com Thu May 25 00:40:03 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 24 May 2006 21:40:03 -0700 Subject: IronPython 1.0 Beta 7 Released References: <1148490561.705681.206470@u72g2000cwu.googlegroups.com> <1148518396.856710.173810@g10g2000cwb.googlegroups.com> Message-ID: <1148532003.624344.88030@38g2000cwa.googlegroups.com> Well, basically, ironpython is to .NET what jython is to JAVA. It is a faithful implementation of the python language, written in c#, created to run on and take full advantage of the .NET framework. That means that you have access to all the available libraries of the .NET framework and you can use your favorite language. It is 100% compliant with cpython. If you want to take advantage of ironpython, all you have to do is learn more about the .NET framework and its libraries. You don't need to learn anything new regarding language features. It's just plain and regular python. You have to bear in mind something very important though: Ironpython is not a first class .NET language. That means that although you can write programs that run on .NET and you have access to all its libraries, you can't write libraries that could be consumed by other languages. This is because ironpython is still a dynamic language, while all the other .NET languages are static. So it cannot be compiled like c# or VB, for example. It is not a problem if all you want is to create end user programs, but if you want to write reusable libraries, you're better off using any other statically typed language. In this case, a good alternative is Boo, which is very similar to python (syntax wise), but statically typed. From aleaxit at yahoo.com Sat May 6 22:23:12 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 19:23:12 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <7xac9uhcf0.fsf@ruckus.brouhaha.com> Message-ID: <1hexjzk.moa0r817mi3bbN%aleaxit@yahoo.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> wrote: ... > > Yes, we are, because the debate about why it's better for Python (as a > > language used in real-world production systems, *SCALABLE* to extremely > > large-scale ones) to *NOT* be insanely extensible and mutable is a > > separate one -- Python's uniformity of style allows SCALABILITY of > > teams, and teams-of-teams, which is as crucial in the real world ... > > My current take on Lisp vs Python is pretty close to Peter Norvig's > (http://www.norvig.com/python-lisp.html): > > Python has the philosophy of making sensible compromises that make > the easy things very easy, and don't preclude too many hard > things. In my opinion it does a very good job. The easy things are > easy, the harder things are progressively harder, and you tend not > to notice the inconsistencies. Lisp has the philosophy of making > fewer compromises: of providing a very powerful and totally > consistent core. This can make Lisp harder to learn because you > operate at a higher level of abstraction right from the start and > because you need to understand what you're doing, rather than just > relying on what feels or looks nice. But it also means that in > Lisp it is easier to add levels of abstraction and complexity; > Lisp makes the very hard things not too hard. Sure -- however, Python makes them not all that hard either. Peter and I have uncannily similar tastes -- just last month we happened to meet at the same Arizona Pueblo-ancestral-people ruins-cum-museum (we both independently chose to take vacation during spring break week to take the kids along, we both love the Grand Canyon region, we both love dwelling on ancient cultures, etc -- so I guess the coincidence wasn't TOO crazy -- but it still WAS a shock to see Peter walk into the museum at the same time I was walking out of it!-). Yes, it IS easier to add complexity in Lisp; that's a good summary of why I prefer Python. > I've heard many times that your current employer uses Python for all > kinds of internal tools; I hadn't heard that it was used in Very Large > projects over there. I'd be interested to hear how that's been > working out, since the biggest Python projects I'd heard of before > (e.g. Zope) are, as you say, toy-sized throwaways compared to the > stuff done regularly over there at G. Sorry, but I'm not authorized to speak for my employer nor to reveal details of our internal systems -- hey, I cannot even say how many servers we have; the "corporate approved metrics" is ``several thousands''...;-). The most that managed to get approved for external communication you'll find in the "Python at Google" presentation that Chris di Bona and Greg Stein hold at times in various venues, and that's not saying much -- good thing I'm not the one giving those presentations, as I might find hard to stick to the approved line;-) Alex From ptmcg at austin.rr._bogus_.com Fri May 19 13:44:45 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 17:44:45 GMT Subject: Python sqlite and regex. References: <mailman.5942.1148042842.27775.python-list@python.org><1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> Message-ID: <hunbg.46845$CH2.29994@tornado.texas.rr.com> "Gerhard H?ring" <gh at ghaering.de> wrote in message news:mailman.5966.1148057291.27775.python-list at python.org... > -----BEGIN PGP SIGNED MESSAGE----- > Hash: SHA1 > > Matt Good wrote: > > SQLite3 already has a REGEXP function, so you don't need to create your > > own. [...] > > Yes, but SQLite does not include a regular expression engine, and thus > according to the SQLite docs you need to register a REGEXP function in > order to make the REGEXP operator work: > > """ > The REGEXP operator is a special syntax for the regexp() user function. No > regexp() user function is defined by default and so use of the REGEXP > operator will normally result in an error message. If a user-defined > function named "regexp" is defined at run-time, that function will be > called in order to implement the REGEXP operator. > """ > This is very interesting. So I *could* define my own regexp function that processes not regular expressions, but say, glob-like strings, which are usually much easier for end users to work with (very basic wild-carding where '*' matches one or more characters, and '?' matches any single character - maybe add '#' to match any single digit and '@' to match any single alpha character). -- Paul From jzgoda at o2.usun.pl Tue May 23 06:28:50 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 23 May 2006 12:28:50 +0200 Subject: freeze tool like perl2exe? In-Reply-To: <1148329713.916486.68410@i40g2000cwc.googlegroups.com> References: <1148329713.916486.68410@i40g2000cwc.googlegroups.com> Message-ID: <e4uo5r$7lc$1@atlantis.news.tpi.pl> Jerry napisal: > I am looking for a freeze tool for Python that is similar to perl2exe > in that I can "compile" a script on one platform that is built for > another. Basically, I would like to be able to build a Python script > for Solaris using my Windows workstation. Is there any tool that fits > the bill? AFAIK Python tools like py2exe tend to bundle together whole VM (interpreter + all needed library modules) along with your code. Anyway, I didn't use (nor even find) anything similar. -- Jarek Zgoda http://jpa.berlios.de/ From rmuschall at tecont.de Sat May 20 20:38:18 2006 From: rmuschall at tecont.de (Ralf Muschall) Date: Sun, 21 May 2006 02:38:18 +0200 Subject: Name conflict in class hierarchy In-Reply-To: <mailman.6014.1148158078.27775.python-list@python.org> References: <mailman.6014.1148158078.27775.python-list@python.org> Message-ID: <rcp4k3-1c5.ln1@prcm.tecont.de> Jeffrey Barish wrote: [overriding of base class member functions by subclass] > but then B does not inherit other functions of A that I would like to use. > It struck me that this must be a common problem in OOP, so I'm wondering > whether there is a simple solution that I am missing. In C++, one has virtual member functions (which behave like python's), and their purpose is to be overriden (o.g. a print method, whose subclass version will print more attributes than the base knows about). Such functions usually are documented - otherwise their being virtual would make no sense. In Python, a function not intended to be overriden should be either have a name starting with an underscore or be documented. So the person who should change something is the author of the library, not you. In your current situation, the following options seem to remain: 1. Use funny names ("foobar239847562384756" instead of "func") and hope that the library update will not use them 2. Call dir(classname) at hacking time and avoid names listed therein. This breaks if the library update may happen at the user's site without you being able to change your code. 3. Call dir(classname) at runtime and raise an exception if it contains a name used by you. Ralf From phaylon at dunkelheit.at Fri May 26 07:20:24 2006 From: phaylon at dunkelheit.at (Robert Sedlacek) Date: 26 May 2006 11:20:24 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> <447479A1.8050809@hotORgooMAIL.invalid> <Xns97CD6AB19B4F3castleamber@130.133.1.4> <447485B6.4070507@hotORgooMAIL.invalid> <Xns97CD733A1B9ABcastleamber@130.133.1.4> <44748E79.9010208@hotORgooMAIL.invalid> Message-ID: <4476e478$0$4510$9b4e6d93@newsread2.arcor-online.net> In comp.lang.perl.misc Mitch <spudtheimpaler at hotorgoomail.invalid> wrote > All that I snipped is your opinion, which is yours to do with as you > please. "I like it just the way it is." is *MY* opinion, so please > don't try to change it. I think I know my opinion best. Wrong. You don't like it how it is. Because as it is now, if someone acts irresponsible for his own actions, his ISP might get an abuse message and might act on that. You want it to follow you own personal moral standards that you feel are being hurt by the usenet as it is. > And as for setting it to reply to only you, I changed that back. I > don't think you censoring (redirecting) other peoples replies/opinions > serves the purpose of this thread well. It's certanily not speaking for you that you compare that and abuse messages to "censorship." It mostly seems like you try to make an argument by acting emtionally. Won't do. p -- The eternal mistake of mankind is to set up an attainable ideal. -- Aleister Crowley From johnjsal at NOSPAMgmail.com Thu May 18 11:38:44 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 18 May 2006 15:38:44 GMT Subject: Python - Web Display Technology In-Reply-To: <1147961355.652526.230610@i39g2000cwa.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5872.1147945818.27775.python-list@python.org> <1147961355.652526.230610@i39g2000cwa.googlegroups.com> Message-ID: <8y0bg.2120$No6.46449@news.tufts.edu> SamFeltus wrote: > I guess there isn't much to understand. If you are satisfied with a > text based, static image web, that is light on artistic possabilities, > all that HTML stuff is acceptable. Personally, I always heave a big sigh of resignation when I'm on a site that uses Flash, because I just feel so locked in to that technology when it's running. It makes me feel very out of control when navigating the site. From tbrkic at yahoo.com Thu May 18 06:14:42 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 03:14:42 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147944268.262819.13450@u72g2000cwu.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147944268.262819.13450@u72g2000cwu.googlegroups.com> Message-ID: <1147947282.359681.126080@38g2000cwa.googlegroups.com> > Here's a nice stan example, taken from Kieran Holland's tutorial > http://www.kieranholland.com/code/documentation/nevow-stan/ I took a quick look and it looks nice as long as your page is static. But I couldnt se how you could mix in python code seamlessy when creating your tree. But I might be wrong if you could write: tags.body[ for i in range(10): tags.h1[ "Heading %s." %(i) ], tags.p[ "This text is inside a paragraph tag." ], ] I think that this is close enough to my syntax. But I dont think you can do it. From bdesth.quelquechose at free.quelquepart.fr Mon May 22 21:15:39 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 May 2006 03:15:39 +0200 Subject: Running script in __main__ shows no output in IDLE In-Reply-To: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> References: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> Message-ID: <447232fc$0$7046$636a55ce@news.free.fr> heidi.hunter at fantasy-interactive.com a ?crit : > I just downloaded the most recent (2.4.3) Python and IDLE (1.1.3) to > Windows XP Professional. I'm new to the IDLE environment, so hopefully > someone can tell me what I'm missing here! Below is the code, which I'm > editing within IDLE, and attempting to test with the Run commands. > > I was expecting to see at least see the prints to stdout from the if > __name__ ... statement and main() function, but when I use F5 Run > module I don't see any output or errors. Any suggestions? Does IDLE > still need the executable file statement at the top even if I run it > explicity? I can't tell you about IDLE related stuff (I don't use it myself), but FWIW, you have a problem with main()'s 'arg' param : you use it like this: > parser.parse(args[0]) but pass it like this: > main("\\Iceman\propod\flash\xml\webService\XmlData\Authors\Heidi") The first problem is that: "\\Iceman\propod\flash\xml\webService\XmlData\Authors\Heidi" already raises an exception ('ValueError: invalid \x escape'). The second problem is that somestring[0] returns the first characted of somestring. First correct your code, then see what happens. And eventually, find a better tool than IDLE... From mhodkin at comcast.net Tue May 16 10:37:06 2006 From: mhodkin at comcast.net (mhodkin at comcast.net) Date: 16 May 2006 07:37:06 -0700 Subject: constucting a lookup table Message-ID: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> I'm new to Python and want to contruct a "lookup table" which would be similar to a spreadsheet in that a value is read along the first column, then along the top row, and the intersection of the two gives a value that is hard-coded, i.e. not mathmatically related. An example would be a table with HEIGHT in the first column, WEIGHT in the first row, and estimated SUITSIZE with the body of the table. Which Python type would be most appropriate and/or efficient? thanks From hapaboy2059 at gmail.com Tue May 2 00:12:03 2006 From: hapaboy2059 at gmail.com (hapaboy2059 at gmail.com) Date: 1 May 2006 21:12:03 -0700 Subject: SGML parsing tags and leeping track Message-ID: <1146543123.663415.48640@g10g2000cwb.googlegroups.com> Hello, I need help in using sgmlparser to parse a html file and keep track of the number of times each tag is being used. In the end of this program I need to print out the number of times each tag was seen(presumably any type of tag can be used) and the linked text. I need help in getting past the first steps. I already have this basic program to return hyperlinks. I cant seem to understand how to parse any tag and keep track of it to print it out at a later time.... very frustrated and help is appreciated!!!!! -------------------------------------------------------------------------- import sgmllib, urllib class HtmParser(sgmllib.SGMLParser): def __init__(self, verbose=0): "Initialise an object, passing 'verbose' to the superclass." sgmllib.SGMLParser.__init__(self, verbose) self.hyperlinks = [] self.descriptions = [] self.inside_a_element = 0 def start_a(self, attributes): "Process a hyperlink and its 'attributes'." for name, value in attributes: if name == "href": self.hyperlinks.append(value) def get_hyperlinks(self): "Return the list of hyperlinks." return self.hyperlinks parser = HtmParser() inptAdrs = raw_input('Please input the absolute path to the url\n') print 'you entered: ', inptAdrs content = urllib.urlopen(inptAdrs) bufff = content.read() print 'Statistics for ', inptAdrs print 'There is', len(bufff), 'characters in the web page' parser.feed(bufff) print parser.get_hyperlinks() parser.close() --------------------------------------------------------------------------------- any help is much appreciated From benji at benjiyork.com Fri May 19 16:26:42 2006 From: benji at benjiyork.com (Benji York) Date: Fri, 19 May 2006 16:26:42 -0400 Subject: Process forking on Windows - or what is MQSeries In-Reply-To: <126n8g6669ml2b6@corp.supernews.com> References: <126mgi2j7fl4b4b@corp.supernews.com> <446b45b1$0$7132$636a55ce@news.free.fr> <126mi8q1t31r9e0@corp.supernews.com> <mailman.5823.1147885546.27775.python-list@python.org> <126n8g6669ml2b6@corp.supernews.com> Message-ID: <446E2A02.3040601@benjiyork.com> Andrew Robert wrote: > In this situation, it is possible for a process(my python program) to > monopolize and block other processes from being triggered. > > Ideally, this needs to be avoided through the use of a fork. Another option would be to write the incoming messages to your own queue (an on-disk directory perhaps) and have the triggered program return after doing that. Then you can have a separate, long-running program process the messages. -- Benji York From marcoacarvalho at gmail.com Wed May 3 23:47:44 2006 From: marcoacarvalho at gmail.com (Marco Carvalho) Date: Thu, 4 May 2006 00:47:44 -0300 Subject: Fwd: what is the 'host' for SMTP? In-Reply-To: <9c9ec91c0605032045h111b61c4ueddafa7652f59d8e@mail.gmail.com> References: <44581205$0$25583$c3e8da3@news.astraweb.com> <pan.2006.05.03.03.42.28.745634@hastings.org> <IB46g.2043$No6.43969@news.tufts.edu> <9c9ec91c0605032045h111b61c4ueddafa7652f59d8e@mail.gmail.com> Message-ID: <9c9ec91c0605032047g15fcf81aw69b6437da3cd23a3@mail.gmail.com> Uh, I don't sent to list :P ---------- Forwarded message ---------- From: Marco Carvalho <marcoacarvalho at gmail.com> Date: May 4, 2006 12:45 AM Subject: Re: what is the 'host' for SMTP? To: John Salerno <johnjsal at nospamgmail.com> On 5/3/06, John Salerno <johnjsal at nospamgmail.com> wrote: > Steve R. Hastings wrote: > > Thanks for all the information. Very helpful. But I'm still a little > confused, because it seems like that's not enough information. If all I > put in is, for example, smtp.gmail.com, how is that directed to my own > email address? Do I still need to include other, more specific (i.e. > personal) information elsewhere? You need a little more than a smtp server address to send an e-mail. If you are using smtplib: import smtplib sender = "your_email at gmail.com" to = "destination_email at example.com" message = "blablabla" smtplogin = "your_login_on_gmail" smtppasswd = "your_password_on_gmail" smtpserver = "smtp.gmail.com" smtp = smtplib.SMTP(smtpserver) smtp.login(smtplogin,smtppasswd) smtp.sendmail(sender, to, message) smtp.quit() I don't put the correct construction of the message's headers and body, it's another story :-) -- Marco Carvalho (macs) | marcoacarvalho(a)gmail.com http://arrakis.no-ip.info | http://cdd.debian-br.org Maceio - Alagoas - Brazil Debian GNU/Linux unstable (Sid) GNU-PG ID:08D82127 - Linux Registered User #141545 Not?cias Semanais do Debian em Portugu?s: http://www.debian.org/News/weekly Alertas de Seguran?a Debian (DSA): http://www.debian.org/security -- Marco Carvalho (macs) | marcoacarvalho(a)gmail.com http://arrakis.no-ip.info | http://cdd.debian-br.org Maceio - Alagoas - Brazil Debian GNU/Linux unstable (Sid) GNU-PG ID:08D82127 - Linux Registered User #141545 Not?cias Semanais do Debian em Portugu?s: http://www.debian.org/News/weekly Alertas de Seguran?a Debian (DSA): http://www.debian.org/security From ivoras at __yahoo__.com_ Sat May 13 16:10:33 2006 From: ivoras at __yahoo__.com_ (Ivan Voras) Date: Sat, 13 May 2006 22:10:33 +0200 Subject: [ANN] PanDAV on SourceForge.net Message-ID: <e45efp$loe$1@news2.carnet.hr> Around three weeks ago there was a thread about Python WebDAV servers, and I mentioned my "PanDAV" work (old homepage: http://ivoras.sharanet.org/projects/pandav.html). There was some interest in continuing the development and merging patches made by its users, so I requested a SourceForge project for it. Due to some internal delay in SourceForget it took a while until the project was created, but now it's there! The project's home is http://sourceforge.net/projects/pandav/. If any of the thread's original posters (or anyone else) are interested, please create a SourceForge.net account and contact me. The current version in CVS contains code and patches (for better compatibility with Windows XP) which is not present in the original package. From pod at internode.on.net Fri May 19 02:34:08 2006 From: pod at internode.on.net (PoD) Date: Fri, 19 May 2006 15:34:08 +0900 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <mailman.5801.1147872851.27775.python-list@python.org> <pan.2006.05.18.07.37.44.126396@internode.on.net> <446c319d$0$5298$626a54ce@news.free.fr> Message-ID: <pan.2006.05.19.06.34.08.555908@internode.on.net> On Thu, 18 May 2006 10:33:58 +0200, Christophe wrote: > PoD a ?crit : >> On Wed, 17 May 2006 21:37:14 +0800, Andy Sy wrote: >> >> >>>If tabs are easily misunderstood, then they are a MISfeature >>>and they need to be removed. >>> >>>>From the Zen of Python: >>> >>>"Explicit is better than implicit..." >>>"In the face of ambiguity, refuse the temptation to guess..." >>>"Special cases aren't special enough to break the rules..." >> >> >> Exactly. >> How many levels of indentation does 12 spaces indicate? >> It could be 1,2,3,4,6 or 12. If you say it's 3 then you are _implying_ >> that each level is represented by 4 spaces. > > Actually, who said you had to always use the same number of spaces to > indent ? 12 = 6 + 6 = 4 + 4 + 4 but also 12 = 2 + 10 = 1 + 1 + 3 + 3 + 4 :D Thus supporting my assertion that space indenting is implicit not explicit. Spaces are evil. > >> How many levels of indentation is 3 tabs? 3 levels in any code that >> you will find in the wild. > > No, it could be 3 levels or 3 tabs per level or 2 tabs for the first > level and 1 tab for the second ... Could be but wouldn't be. Maybe what Python should do (but never will given the obsession with using spaces) is only allow one level of indentation increase per block so that def foo(): <TAB><TAB>return 'bar' would return a syntax error From g.brandl-nospam at gmx.net Fri May 26 05:56:57 2006 From: g.brandl-nospam at gmx.net (Georg Brandl) Date: Fri, 26 May 2006 09:56:57 +0000 Subject: how to clear up a List in python? In-Reply-To: <1148636521.026385.171410@y43g2000cwc.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <mailman.6221.1148634413.27775.python-list@python.org> <1148636521.026385.171410@y43g2000cwc.googlegroups.com> Message-ID: <e56jdg$gn7$2@news.albasani.net> vbgunz wrote: > Fredrik_Lundh = 'wah' > > I bet you enjoy stealing candy from babies and dunging on the little > guy every chance you get. You're suppose to be a role model in this > community? Your temper tantrum and unrelenting 'look at me look at me > i'm bigger and better' machismo attitude is nothing more than a decoyed > ploy set out by a deluded megalomaniac. Personally speaking, Fredrik's just sitting here next to me, and I can assure you that he's not screaming "I'm bigger and better than you all" every few minutes. He may be screaming "I made it faster!", but that's why we're here ;) > You're promoting Python or the > fact that you're the son of Zeus and Hera? You're the worse sore losing > cry baby I've ever witnessed on the net in my ten years here... > pathetic for sure... You perhaps shouldn't become so excited. Next time, if you're not sure of the correctness of your solution, try to wait a bit before posting it, and see if someone other comes up with the same thing you would have posted. Georg From skip at pobox.com Wed May 24 21:18:20 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 24 May 2006 20:18:20 -0500 Subject: Python mentioned in context of $100 laptop... Message-ID: <17525.1500.55062.838318@montanaro.dyndns.org> >From Google alerts: MIT's US$100 laptop prototype completed Ars Technica - Boston,MA,USA ... and interactivity. Called Sugar, the OLPC interface is built with Python, GTK, and Mozilla's Gecko HTML rendering engine. Tom Hoffman ... <http://arstechnica.com/news.ars/post/20060524-6903.html> Skip From sybrenUSE at YOURthirdtower.com.imagination Tue May 9 03:08:59 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 9 May 2006 09:08:59 +0200 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> Message-ID: <slrne60g0b.7vs.sybrenUSE@schuimige.stuvel.eu> Kaz Kylheku enlightened us with: > I've been reading the recent cross-posted flamewar, and read Guido's > article where he posits that embedding multi-line lambdas in > expressions is an unsolvable puzzle. > [...] > a = lambda(x, y), lambda(s, t), lambda(u, w): u + w > statement1 > statement2 > lambda: > statement3 > statement4 I think it's a very ugly solution. If you need multiple lines in your lambda, use an inner function. If you need a couple of single-line lambdas and use them in a multi-line expression, assign them to a name and use that name in their stead. > a = lambda(x, y): > return x + y And what's the advantage of that above this? def a(x, y): return x + y > More examples: lambda defined in a function call argument > > a = foo(lambda (x, y)): > return x + y > > Confusing? Not if you read it properly. "A lambda function is > constructed with arguments x, y and passed to foo, and the result is > assigned to a. Oh, and by the way, the body of the > lambda is: return x + y." I think it's very, very ugly. Use inner functions for that. They are a much cleaner solution than this. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From alanalan at newsgroup.nospam Wed May 31 12:24:26 2006 From: alanalan at newsgroup.nospam (A.M) Date: Wed, 31 May 2006 12:24:26 -0400 Subject: Are ActivePython scripts compatible with Linux? Message-ID: <Knjfg.1106$Su3.100610@news20.bellglobal.com> Hi, I am planning to develop python applications on windows and run them on Linux. Are ActivePython scripts compatible with Linux? Is there any guideline that explains the compatibility issues between python in different platforms? What would be the best approach for what I am trying to do? Any help would be appreciated, Alan From siona at chiark.greenend.org.uk Thu May 4 11:01:33 2006 From: siona at chiark.greenend.org.uk (Sion Arrowsmith) Date: 04 May 2006 16:01:33 +0100 (BST) Subject: Python function returns: References: <mailman.5316.1146744053.27775.python-list@python.org> Message-ID: <HoB*txOfr@news.chiark.greenend.org.uk> Michael Yanowitz <m.yanowitz at kearfott.com> wrote: > In Python, there does not seem to be an easy way to have functions return >multiple values except it can return a list such as: >strHostname, nPortNumber, status = get_network_info (strIpAddress, >strHostname, > nPortNumber) > Am I missing something obvious? Is there a better, or more standard way >to return values from functions? I'm kind of repeating what other people have said, but there isn't a better way. Not just in Python, but in any language. If your function is returning multiple values, why should you have to split them into one privileged "return value" plus a bunch of Out (or InOut) parameters? That's a historical mis- feature of older languages, and one which more newer languages would do well to fix. -- \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 elw000 at verizonz.net Sat May 6 19:35:56 2006 From: elw000 at verizonz.net (Eric) Date: Sat, 06 May 2006 23:35:56 GMT Subject: Replace References: <R40975357.427.5217.1@mx-extra.net> <mailman.5419.1146921316.27775.python-list@python.org> <u757g.202$NB6.173@trndny03> <jssp529kre6g83fso3clj3ndf1s6t2dua2@4ax.com> <ng1q52hgo2bjkp471d1jkbd52u7odfep47@4ax.com> Message-ID: <wpa7g.3081$923.1771@trndny02> On 2006-05-06, Dennis Lee Bieber wrote: > On Sat, 06 May 2006 19:55:35 GMT, Dennis Lee Bieber ><wlfraed at ix.netcom.com> declaimed the following in comp.lang.python: > > >> splits = encData.split("#", 1) > > Whoops.... # => = > > Since there are only what, five, escaped characters, the use of a > translate table seems somewhat overkill... A simple dictionary can be > used... > > # pseudo-yENC decoder > # ignores all of the protocol except for the > # data portion decode > > d42 = "".join([chr((x - 42) % 256) for x in range(256)]) > d64 = { "@" : "\0", > "I" : "\t", > "J" : "\n", > "M" : "\r", > "}" : "=" } > e42 = "".join([chr((x + 42) % 256) for x in range(256)]) > e64 = { "\0" : "=@", > "\t" : "=I", > "\n" : "=J", > "\r" : "=M", > "=" : "=}" } > > def decode(encData): > segments = [] > while True: > splits = encData.split("=", 1) > segments.append(splits[0]) > if len(splits) == 1: break > segments.append(d64[splits[1][0]]) > encData = splits[1][1:] > > decData = "".join(segments).translate(d42) > return decData > > def encode(decData): > segments = [] > encData = decData.translate(e42) > while encData: > pos = len(encData) > > nl = encData.find("\0") > tb = encData.find("\t") > lf = encData.find("\n") > cr = encData.find("\r") > eq = encData.find("=") > > if nl != -1: > pos = min(pos, nl) > if tb != -1: > pos = min(pos, tb) > if lf != -1: > pos = min(pos, lf) > if cr != -1: > pos = min(pos, cr) > if eq != -1: > pos = min(pos, eq) > > segments.append(encData[:pos]) > > if pos < len(encData): > segments.append(e64[encData[pos]]) > encData = encData[pos+1:] > > return "".join(segments) > > > if __name__ == "__main__": > junk = """This is not > the end of the silliness > being inflicted upon the world of 183743ljf8734jflu807ur32""" > > morejunk = encode(junk) > print morejunk > > print decode(morejunk) > print > > tbl = "".join([chr(x) for x in range(256)]) > > print repr(tbl) > print > yetmore = encode(tbl) > print repr(yetmore) > print > print repr(decode(yetmore)) I think you right about the d64 translation thing, it does seem like overkill. I've been playin with sting.split(), came up with... def decode(encData): segments = [] splits = encData.split("=") for i in range(len(splits)): if i == 0: segments.append(splits[0].translate(d42)) else: segments.append(splits[i][0].translate(d64) + splits[i][1:].translate(d42 )) decoded = ''.join(segments) return decoded string.split might be the way to go, this function almost decodes the test file from the ydec site correctly. From ryanf at cs.uoregon.edu Sat May 6 12:59:15 2006 From: ryanf at cs.uoregon.edu (Ryan Forsythe) Date: Sat, 06 May 2006 09:59:15 -0700 Subject: NaN handling In-Reply-To: <e3ikb0$vl3$1@sea.gmane.org> References: <mailman.5272.1146675632.27775.python-list@python.org><125hplqmppfeq29@corp.supernews.com><01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> <1146929327.30335.5.camel@kenshin.CASA> <e3ikb0$vl3$1@sea.gmane.org> Message-ID: <445CD5E3.1070600@cs.uoregon.edu> Terry Reedy wrote: > "Felipe Almeida Lessa" <felipe.lessa at gmail.com> wrote in message > news:1146929327.30335.5.camel at kenshin.CASA... >> This works everywhere: >> >> nan = float('nan') > > Not. > >>>> nan = float('nan') > > Traceback (most recent call last): > File "<pyshell#4>", line 1, in -toplevel- > nan = float('nan') > ValueError: invalid literal for float(): nan > > Above is Windows, which requires something else. I think he meant: >>> float("NaN") nan That's Python 2.4.1 on Mac OS X. From noway at sorry.com Tue May 30 20:41:22 2006 From: noway at sorry.com (Giovanni Bajo) Date: Wed, 31 May 2006 00:41:22 GMT Subject: genexp performance problem? Message-ID: <SC5fg.18764$jP5.469405@twister1.libero.it> Hello, I found this strange: python -mtimeit "sum(int(L) for L in xrange(3000))" 100 loops, best of 3: 5.04 msec per loop python -mtimeit "import itertools; sum(itertools.imap(int, xrange(3000)))" 100 loops, best of 3: 3.6 msec per loop I thought the two constructs could achieve the same speed. -- Giovanni Bajo From sjmachin at lexicon.net Mon May 15 23:26:37 2006 From: sjmachin at lexicon.net (John Machin) Date: 15 May 2006 20:26:37 -0700 Subject: C API: getting sys.argv References: <1147748640.699770.285430@g10g2000cwb.googlegroups.com> Message-ID: <1147749997.535248.71490@g10g2000cwb.googlegroups.com> > PyObject *_argv = PyImport_ImportModule("sys.argv"); What does the name of the function tell you? You can't do that in one hit. Start with PyObject *_sys = PyImport_ImportModule("sys"); then you need to get the module's argv attribute. However a better design might be have your extension module have an arg which can be *any* list of strings. That makes it more flexible, at the expense of making the caller pass sys.argv. But it would save you having to muck about with importing "sys", then plucking out the module's argv attribute. From jUrner at arcor.de Sat May 6 06:50:04 2006 From: jUrner at arcor.de (jUrner at arcor.de) Date: 6 May 2006 03:50:04 -0700 Subject: ANN: Eric3-IDE documentation and wiki Message-ID: <1146912604.439250.319740@i40g2000cwc.googlegroups.com> Happy to announce that the Eric3 python IDE has found a home for its documentation and wiki! Currently effords are taken to document the user interface of the Eric3-IDE. The documentation and wiki project is hosted at http://ericide.python-hosting.com/ . Everyone interested in Eric is heartly invited to take part in the ongoing effords, drop comments or whatever to help to improve usability of the IDE for the python comunity. What is Eric ? Eric is an advanced open source Python and Ruby IDE based on the pyQt GUI toolkit written and maintained mainly by Detlev Offenbachs. Currenlty usage on windows oses is quite limited due to Qt3 licence issues . This is going to change as soon as Eric is ported to pyQt4 with full GPL licence support for open source developers. See http://www.die-offenbachs.de/detlev/eric3 or http://ericide.python-hosting.com/ or for a more detailed description. Juergen Urner From grante at visi.com Tue May 30 09:46:41 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 30 May 2006 13:46:41 -0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> Message-ID: <127oj612scnl8a0@corp.supernews.com> On 2006-05-30, xkenneth <xkenneth at gmail.com> wrote: > I'm using linux. [It's generally considered good practice to quote enough context so that your post makes sense to people without access to older postings.] Under Linux there isn't really anything. IIRC, many years ago, somebody had written a kernel module that inserted itself between application and serial port and logged operations, but the last time I tried to find it, I was unsuccessful. If you feel like building a kernel, adding a few printk() calls to either the low-level serial driver or the tty line-discipline layer might do what you want. -- Grant Edwards grante Yow! YOW!! Everybody out at of the GENETIC POOL! visi.com From kent at kentsjohnson.com Wed May 10 15:47:27 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 10 May 2006 15:47:27 -0400 Subject: reusing parts of a string in RE matches? In-Reply-To: <YMm8g.2077$No6.45935@news.tufts.edu> References: <YMm8g.2077$No6.45935@news.tufts.edu> Message-ID: <446242c8$1_1@newspeer2.tds.net> John Salerno wrote: > I probably should find an RE group to post to, but my news server at > work doesn't seem to have one, so I apologize. But this is in Python > anyway :) > > So my question is, how can find all occurrences of a pattern in a > string, including overlapping matches? You can specify a start location to re.search(), and get the location of a match from a match object. This allows you to loop, searching the string following the last match: import re string = 'abababababababab' pattern = re.compile(r'ab(?=a)') ans = [] start = 0 while True: m = pattern.search(string, start) if not m: break ans.append( (m.start(), m.end()) ) start = m.start() + 1 print ans # => [(0, 2), (2, 4), (4, 6), (6, 8), (8, 10), (10, 12), (12, 14)] Kent From buzzard at urubu.freeserve.co.uk Mon May 29 11:36:40 2006 From: buzzard at urubu.freeserve.co.uk (Duncan Smith) Date: Mon, 29 May 2006 16:36:40 +0100 Subject: itertools.count() as built-in In-Reply-To: <1148893017.099404.39750@38g2000cwa.googlegroups.com> References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> <1148860241.048549.269330@j73g2000cwa.googlegroups.com> <1hg24o2.18odi4uzoiraoN%aleax@mac.com> <1148893017.099404.39750@38g2000cwa.googlegroups.com> Message-ID: <447b1721.0@entanet> jantod at gmail.com wrote: > Zipping an xrange? I'm having trouble visualizing how you do that to > avoid x*i+y. > > -Janto > Something like, >>> lis = ['a', 'b', 'c', 'd'] >>> y = 3 >>> i = 7 >>> for n, item in zip(xrange(y, len(lis)*i+y, i), lis): print n, item 3 a 10 b 17 c 24 d >>> Duncan From dacut at kanga.org Thu May 18 04:11:01 2006 From: dacut at kanga.org (David Cuthbert) Date: Thu, 18 May 2006 01:11:01 -0700 Subject: Using python for a CAD program In-Reply-To: <1147808333.652756.5180@u72g2000cwu.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <1147808333.652756.5180@u72g2000cwu.googlegroups.com> Message-ID: <e4ha6m$df$1@sea.gmane.org> Paddy wrote: > Unfortunately, Cadence got their first with their DFII environment for > Schematic based design and their Lisp based language SKILL Well, SKILL (a Franz Lisp derivative) is very old and has some peculiar design quirks. Interfacing with anything not written by Cadence or not written in SKILL is painful, at best. Interestingly, Python is being used as an extension language for the OpenAccess database. LSI Logic had a Python wrapper for 2.0 (it looked like they used SWIG). I had written one for 2.1, but never was able to release it before my company was acquired by Cadence (and that project quashed). There is some interest... just not quite critical mass. From jbellis at gmail.com Wed May 10 12:09:30 2006 From: jbellis at gmail.com (Jonathan Ellis) Date: 10 May 2006 09:09:30 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <86fyjjl0lz.fsf@blue.stonehenge.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1147106666.402541.114270@g10g2000cwb.googlegroups.com> <1hf1iq2.o3lae1fgte55N%aleax@mac.com> <86fyjjl0lz.fsf@blue.stonehenge.com> Message-ID: <1147277370.447790.319790@i39g2000cwa.googlegroups.com> Randal L. Schwartz wrote: > >>>>> "Alex" == Alex Martelli <aleax at mac.com> writes: > > Alex> The difference, if any, is that gurus of Java, C++ and Python get to > Alex> practice and/or keep developing their respectively favorite languages > Alex> (since those three are the "blessed" general purpose languages for > Alex> Google - I say "general purpose" to avoid listing javascript for > Alex> within-browser interactivity, SQL for databases, XML for data > Alex> interchange, HTML for web output, &c, &c), while the gurus of Lisp, > Alex> Limbo, Dylan and Smalltalk don't (Rob Pike, for example, is one of the > Alex> architects of sawzall -- I already pointed to the whitepaper on that > Alex> special-purpose language, and he co-authored that paper, too). > > That's crazy. Some of the key developers of Smalltalk continue to work > on the Squeak project (Alan Kay, Dan Ingalls, and I'm leaving someone > out, I know it...). So please remove Smalltalk from that list. I thought it was clear that Alex was talking about "smalltalk gurus who work for Google." -Jonathan From bdesth.quelquechose at free.quelquepart.fr Wed May 3 19:53:17 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 May 2006 01:53:17 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <LI76g.72436$H71.6915@newssvr13.news.prodigy.com> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <4457fc52$0$31159$636a55ce@news.free.fr> <yE56g.72397$H71.4757@newssvr13.news.prodigy.com> <4458ef17$0$24993$636a55ce@news.free.fr> <LI76g.72436$H71.6915@newssvr13.news.prodigy.com> Message-ID: <445913b4$0$2654$636a55ce@news.free.fr> Edward Elliott a ?crit : > bruno at modulix wrote: > >>Technically, they are still function objects. They are later wrapped >>into method descriptor objects (at lookup time IIRC, but ask a guru or >>read the doc to know for sure). And don't forget the case of nested >>functions... > > > I don't see how nested functions change anything. If they're nested in a > method, they can access self, but the name mapping is done at runtime. > Unless you mean a nested fucntion which is dynamically added as a method, > but that's the same case as the next one. > Nope. I just wanted to point out that just checking for def statements in the scope of a class statement is not enough to decide if it has to be treated as a method. (snip) > >>>Well I'm assuming the rules for when to put 'self' in the parameter list >>>are simple enough to be automated. >> >>They are still complex enough to require a real parser. And anyway, >>since this is a syntax change, this should be handled by the parser IMHO. > > I agree, but it's good to keep options in mind. regexp are not an option !-) > >>Honestly, I don't think it has much chance. I barely even notice typing >>'self' or 'cls', and I guess it's the same for most Python programmers >>- those who can't stand it probably use another language... And FWIW, I >>still prefer to keep consistency in functions definitions. > > I have no doubt that's true for a lot of people. Hell I probably prefer the > current approach because 1) it's not a big deal in practice, and 2) I can > use the shorter 'me' or 's' in place of self in my own code, which I > couldn't do under the change Now *this* would be a +1 !-) > (well, I could add 'me = self' as the first > statement of any method, but that's clumsy). My objections stem more from > an elegance standpoint. Of course elegance is in the eye of the beholder. Indeed... From jjl at pobox.com Fri May 5 16:38:20 2006 From: jjl at pobox.com (John J. Lee) Date: 05 May 2006 20:38:20 +0000 Subject: HTMLParseError: EOF in middle of construct error References: <1146745753.568267.166130@v46g2000cwv.googlegroups.com> <4buai4F12pcheU1@uni-berlin.de> Message-ID: <874q041a2r.fsf@pobox.com> "Diez B. Roggisch" <deets at nospam.web.de> writes: [...] > google:BeatifulSoup Even better, google for BeautifulSoup ^ John From rbsharp at gmx.de Fri May 26 03:53:19 2006 From: rbsharp at gmx.de (rbsharp at gmx.de) Date: 26 May 2006 00:53:19 -0700 Subject: Anyone compiling Python 2.3 on an SCO OpenServer 5 box? In-Reply-To: <1148577884.528595.157910@j33g2000cwa.googlegroups.com> References: <1148577884.528595.157910@j33g2000cwa.googlegroups.com> Message-ID: <1148629999.915890.228800@j73g2000cwa.googlegroups.com> I have a lot to do with Python and SCO but I never got above Python2.2 but that probably relates to the fact that I need to statically link some libraries into python. My notes on this subject are that if you need dynamic linking configure has a problem finding libdl.so, and that therefore you have to use the compiler flag "-b elf", before you do ./configure. I do it with: CC=cc CFLAGS="'-b elf"' If you already have done a configure, you might need to do "make clean" and possibly delete config.cache to make sure configure starts from scratch. Regards, Richard Sharp From phpbird at gmail.com Tue May 23 11:45:03 2006 From: phpbird at gmail.com (Ju Hui) Date: 23 May 2006 08:45:03 -0700 Subject: how to change sys.path? In-Reply-To: <4472c6b7$0$26894$626a54ce@news.free.fr> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> Message-ID: <1148399102.963320.129230@u72g2000cwu.googlegroups.com> yes, I mean I want change the sys.path value and save it for next using. I can change the value of sys.path, but I can't "save" it permanently. There is no python_path environment on my pc, what the relationship between it and the sys.path? From webraviteja at gmail.com Thu May 11 23:27:58 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 11 May 2006 20:27:58 -0700 Subject: Calling C/C++ functions in a python script In-Reply-To: <1147339012.474084.327540@q12g2000cwa.googlegroups.com> References: <1147299778.630583.83380@q12g2000cwa.googlegroups.com> <1147300511.673435.72630@i39g2000cwa.googlegroups.com> <1147339012.474084.327540@q12g2000cwa.googlegroups.com> Message-ID: <1147404478.550707.197690@j33g2000cwa.googlegroups.com> You are working with the debug configuration, use release instead and python24.lib will suffice. http://news.hping.org/comp.lang.python.archive/6741.html From softwindow at gmail.com Wed May 24 05:57:48 2006 From: softwindow at gmail.com (softwindow) Date: 24 May 2006 02:57:48 -0700 Subject: hi,every body. a problem with PyQt. In-Reply-To: <1148464336.960828.199950@j55g2000cwa.googlegroups.com> References: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> <1148463003.324183.279350@y43g2000cwc.googlegroups.com> <1148463700.936915.279470@i40g2000cwc.googlegroups.com> <1148464336.960828.199950@j55g2000cwa.googlegroups.com> Message-ID: <1148464668.151235.35220@38g2000cwa.googlegroups.com> i find it now thanks ! From luismgz at gmail.com Sun May 21 19:19:28 2006 From: luismgz at gmail.com (=?iso-8859-1?q?Luis_M._Gonz=E1lez?=) Date: 21 May 2006 16:19:28 -0700 Subject: Python - Web Display Technology In-Reply-To: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> Message-ID: <1148253568.925307.221830@y43g2000cwc.googlegroups.com> IMHO, there's nothing more annoying that a website showing me a progression bar, indicating how much time it will get to provide the information I'm looking for... And when the progression bar ends, I have to wait until the flashy graphics and stupid presentation shows me the "go to html site"... I use the web for working. I work in international trade and I'm all the time looking for new products, searching for information, technical specifications, etc, etc... Flash, when using sparingly, could give an elegant touch to a web site. But when abussed, it is very annoying. It makes me waist my time and my patience.... And finding a website that uses Flash apropiately, is very unusual. Most of the times, they are loaded with heavy animations (most of them boring). The more I see it, the more I like the old fashioned html style... And now with "Vista", "Avalon", and all those new buzzwords coming soon, I don't know where we are going...all I know is that we will need 1 GB of ram just to keep on seeing the same stupid animations that get on my way when I'm working... From johnjsal at NOSPAMgmail.com Wed May 31 15:50:31 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 31 May 2006 19:50:31 GMT Subject: using import * with GUIs? In-Reply-To: <mailman.6381.1149104575.27775.python-list@python.org> References: <R2mfg.2200$No6.47332@news.tufts.edu> <mailman.6381.1149104575.27775.python-list@python.org> Message-ID: <bsmfg.2202$No6.47400@news.tufts.edu> Terry Reedy wrote: > If I were to use Tkinter, I would 'import Tkinter as tk'. Good idea! I was kind of excited about Tkinter for a little while...seems very easy, and it has an event delegation system that I understand! But then I saw that for a toolbar you use a Frame? And for a status bar you use a Label? Ick! I guess if I'm going to learn a GUI, I might as well jump right into wxPython from the beginning. From grante at visi.com Tue May 9 15:35:18 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 09 May 2006 19:35:18 -0000 Subject: How to recast integer to a string References: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> Message-ID: <1261rnm87mt5k4b@corp.supernews.com> On 2006-05-09, James <hslee911 at yahoo.com> wrote: > How to recast an integer to a string? > something like > n = 5 > str = str + char(n) str = str + chr(5) -- Grant Edwards grante Yow! I want EARS! I at want two ROUND BLACK visi.com EARS to make me feel warm 'n secure!! From nobody at 127.0.0.1 Wed May 3 13:21:34 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 17:21:34 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <4457fc52$0$31159$636a55ce@news.free.fr> Message-ID: <yE56g.72397$H71.4757@newssvr13.news.prodigy.com> Bruno Desthuilliers wrote: > But then, constructs like: > > class Obj(object): > def method(...): ... > method = staticmethod(method) > > or it's newer syntactic-sugar-version would become somewhat more > difficult to parse properly - but I admit that this is beyond my > knowledge. Hmm, that'll take some thought. I assume if you're making method static, you don't declare a self parameter for it? If so, it shouldn't be hard, just have the parser mark the method as static or no as it parses, and when it reaches the end of the class insert 'self' for non-static methods. If a normal method can be converted to a static method outside the class definition, that case should work just as it does now. >> e.g. when it sees "def method (a,b)" > > This has to be in a class statement - else it's shouldn't be touched. Exactly, that's why I called it method and not func. If you're declaring methods outside the class and adding them dynamically, I think you would need to declare 'self' explicitly. I'm ok with this because 1) when you're going that route, an explicit signal that something "different" is happening is a good thing, and 2) I have no problem with optimizing for the common case. Not everyone will agree on these points, obviously. >> I can prove that assertion too: make a simple text processor that reads >> Python source code and outputs the same source code with only one change: >> insert the string 'self" as the first parameter of every "def >> somemethod". > > Not so simple: you have plain functions (outside class statements), and > inner functions (inside def statements), and classmethods, and statict > methods, and some other corner cases (like __new__()) to take into > acccount... Well I'm assuming the rules for when to put 'self' in the parameter list are simple enough to be automated. In cases where they're not (e.g. dynamic methods outside a class), I have no problem with an explicit self to signal what's going on. That's the price you pay for dynamism. > As I said, this requires more than a simple pre-processor > and so would have to be done at parsing time since it requires parsing > anyway. I think you could make a go of it with regular expressions, but yes parsing is the better approach. > - but note that there may as well be something obviously wrong that I > fail to spot ditto > (it's very late here and I had a hard day !-). I of course > don't take into account the fact that this would break all existing > Python code, which is unavoidable for such a syntactic change. of course, which I'm sure means it will never happen, Python 3 notwithstanding. > Well, I must admit that done this way (which is quite different from > what I understood from your previous posts), That's my fault, I did a lot of hand-waving at first and probably contradicted myself a couple times as I was describing the idea. > Now is this something good is another point. I was about to argue that I > don't like the implicitness of it, but 1/ this is how most OOPLs do (at > least from a syntactic POV) and 2/ the fact is that the instance is > implicitely passed at call time, so I guess I'm just way too intoxicated > by so many years of Python programming to feel at ease with this !-) I'm sure much ink will be (and has been) spilled on the subject. > Since Python 3K is supposed to be the 'clean the warts and don't bother > breaking compat' rewrite of Python, you may as well propose a PEP on > this. Maybe that will be my summer project. We'll see, I was really hoping to write fewer briefs and more code. > You'll have to really prove it doesn't break anything else in the > object model, have strong and articulate arguments to support your point > (like proving this is really a common source of confusion for newbies), > and I really doubt it'll be accepted anyway. But what... It's definitely an uphill battle and I wonder if it's really worth the effort. We'll see. From bdesth.quelquechose at free.quelquepart.fr Mon May 22 21:00:01 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 23 May 2006 03:00:01 +0200 Subject: problem with my regex? In-Reply-To: <1148332545.563949.102290@38g2000cwa.googlegroups.com> References: <1148332545.563949.102290@38g2000cwa.googlegroups.com> Message-ID: <44722f53$0$2546$636a55ce@news.free.fr> Brian a ?crit : > I have a simple script below that is causing me some problems and I am > having a hard time tracking them down. Here is the code: > > import urllib > import re > > def getPicLinks(): > found = [] > try: > page = > urllib.urlopen("http://continuouswave.com/whaler/cetacea/") > except: Do everyone a favor: don't use bare expect clause > print "ERROR RREADING PAGE." > sys.exit() stdout is for normal program outputs. Error messages should go to stderr. And FWIW, your exception handling here is more than useless. You'd better let the exception propagate - at worse, it will also exit the program, but with the right return value for the system and a meaningful traceback. > page1 = page.read() > cetLinks = re.compile("cetaceaPage..\.html", page1) Are you sure you've carefully read the doc for re.compile() ?-) You want something like this (NB : regexp not tested): html = page.read() page.close() # dont forget to free resources cetLinks = re.compile(r"cetaceaPage[0-9]{2}\.html") found = cetLinks.findall(html) print "\n".join(found) > This is the error message: > "/Library/Frameworks/Python.framework/Versions/2.4/lib/python2.4/sre_parse.py", > line 396, in _parse > if state.flags & SRE_FLAG_VERBOSE: > TypeError: unsupported operand type(s) for &: 'str' and 'int' This is not the *full* traceback. (snip) > My problem is that I can't seem to be able to figure out what is going > wrong here. What's going wrong is that you are passing the html page content as the second argument for re.compile(), (instead of an integer value representing a combination of various flags, cf the doc for the re module). > Mostly because I am a bit confused by the error message as > it points to a file (presumable part of re) It is. The last parts of the traceback are the file and line where the exception has been raised and the exception's message. But before, you had all the call stack, including the line where you called re.compile() with the wrong arguments. Exception tracebacks are usually really useful once you know how to read them. HTH From scott.daniels at acm.org Tue May 9 19:10:49 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 09 May 2006 16:10:49 -0700 Subject: Dictionaries -- ahh the fun.. (newbie help) In-Reply-To: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> References: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> Message-ID: <44611db8$1@nntp0.pdx.net> rh0dium wrote: > Hi all, > > Can someone help me out. I am trying to determing for each run whether > or not the test should pass or fail but I can't seem to access the > results .. > > Alternatively can someone suggest a better structure ( and a lesson as > to the reasoning ) that would be great too!! Here's a little less convoluted version: cells = dict(NOR3X1=dict(lvs='pass', drc='fail'), OR3X=dict(lvs='pass'), AND3X1=dict(drc='fail')) for cell in cells: print cell for run, expect in cells[cell].items(): print cell, run, "should", expect Or even: for cell, expectations in cells.items(): print cell for run, expect in expectations.items(): print cell, run, "should", expect You might prefer .iteritems rather than .items if the lists get huge. * I use the dict(name=val [, name=val)*) form if the keys are symbols. * Don't get any more indirect than you need to. * A list of single-entry dictionaries is almost never a good idea; if you mean a list of pairs, use that. if you mean a dictionary with a number of keys, use that. -- -Scott David Daniels scott.daniels at acm.org From bearophileHUGS at lycos.com Wed May 3 08:36:08 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 May 2006 05:36:08 -0700 Subject: ANN: ShedSkin 0.0.8 In-Reply-To: <1146659573.611592.104150@i39g2000cwa.googlegroups.com> References: <1146659573.611592.104150@i39g2000cwa.googlegroups.com> Message-ID: <1146659768.184015.36820@u72g2000cwu.googlegroups.com> Sorry, the correct link to the thesis: http://kascade.org/shedskin.pdf bearophile From scott.daniels at acm.org Fri May 26 18:22:46 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Fri, 26 May 2006 15:22:46 -0700 Subject: Modify one character in a string In-Reply-To: <pan.2006.05.26.22.21.58.181622@gmx.net> References: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> <roy-F85321.10044225052006@reader1.panix.com> <pan.2006.05.26.22.21.58.181622@gmx.net> Message-ID: <44777b79$1@nntp0.pdx.net> Marc 'BlackJack' Rintsch wrote: > In <roy-F85321.10044225052006 at reader1.panix.com>, Roy Smith wrote: > >>> Also, how do I do this when dealing with a file ; which file mode >>> should I use and what function should I use to modify a single >>> character once in that file mode? >> This is a much more complicated question, because it depends on the details >> of the operating system you're using. On Unix, you can seek to a specific >> place in a file, write a single character, seek to EOF, and you've done an >> in-place single character edit of the file. > > Why seeking to EOF after writing the byte? Because some operating systems may create an EOF (thus truncating the file) after a write, close sequence. --Scott David Daniels scott.daniels at acm.org From DirkHagemann at gmail.com Mon May 22 07:10:37 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 22 May 2006 04:10:37 -0700 Subject: string.count issue (i'm stupid?) In-Reply-To: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> References: <1148295555.557057.222650@i40g2000cwc.googlegroups.com> Message-ID: <1148296237.506185.41860@y43g2000cwc.googlegroups.com> I think I can tell you WHY this happens, but I don't know a work-around at the moment. It seems as if only the following "_a_" (A) are counted: a_A_a_A_ regards Dirk From Florian.Lindner at xgm.de Wed May 3 14:52:32 2006 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Wed, 03 May 2006 20:52:32 +0200 Subject: Gettings subdirectories Message-ID: <e3au5u$drm$1@news.in.tum.de> Hello, how can I get all subdirectories of a given directories? os.listdir() gives me all entries and I've found no way to tell if an object is a file or a directory. Thanks, Florian From ark at acm.org Tue May 2 11:44:50 2006 From: ark at acm.org (Andrew Koenig) Date: Tue, 02 May 2006 15:44:50 GMT Subject: bug in modulus? References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> <4450928c$0$21107$626a54ce@news.free.fr> <j3L5g.18187$Fs1.621@bgtnsc05-news.ops.worldnet.att.net> Message-ID: <S7L5g.30013$eR6.27390@bgtnsc04-news.ops.worldnet.att.net> "Andrew Koenig" <ark at acm.org> wrote in message news:j3L5g.18187$Fs1.621 at bgtnsc05-news.ops.worldnet.att.net... > I disagree. For any two floating-point numbers a and b, with b != 0, it > is always possible to represent the exact value of a mod b as a > floating-point number--at least on every floating-point system I have ever > encountered. The implementation is not even that difficult. Oops... This statement is true for the Fortran definition of modulus (result has the sign of the dividend) but not the Python definition (result has the sign of the divisor). In the Python world, it's true only when the dividend and divisor have the same sign. From akameswaran at gmail.com Fri May 19 17:26:30 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 19 May 2006 14:26:30 -0700 Subject: python vs perl lines of code In-Reply-To: <Xns97C8A4628E0EBcastleamber@130.133.1.4> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> Message-ID: <1148073990.938267.320410@38g2000cwa.googlegroups.com> > Yes, like the shorter version might be overlooking many real world > situations and is naive code. As for generalization, if you bet that the > shorter one is later written, that's to me a generalization. I agree that > there is a change that after reexamining the code, and algorithm can be > written shorter, but I have also seen algorithms refactored for better > readability. All very good points - I need to be more specific. I've been working on some data analysis stuff etc, lately - so I'm often time just reimplementing a specific algo or library I've written. The actual program as a whole generaly does get larger. But I was really thinking about a handful of data manipulation or aggregation algo's that were functionaly fine - but I realized could be done better. > > Two points here. I have since the beginning stating a HYPOTHESIS - a > > theory. One which my experince leads me think MIGHT be true. > > Enough to bet on it ;-) > I'm a gambling man, what can I say? > >> Yup, and this is exactly what frightens me the whole time in this > >> thread. People looking for quality rules based on line count. It's > >> wrong. > > > > Please note my original hypothesis was maintainability - not quality! > > Aren't those closely related? > Yep, but not the same thing. Maintainability is a subset of quality. > > important important distinction - and one I may have muddles myself as > > I got drawn into the conversation. > > And what frightens me are people who are so dogmatically convinced > > becasue of their long 10 years of experience - that they know exactly > > what does and doesn't matter, and have no intellectual curiosity > > anymore. There are no objective tests for maintainability that I am > > aware of. > > Because it depends a lot on the skill level of the maintainer. By just > counting lines and characters you can't measure quality IMO. It's a naive > way of measuring and it reminds me of the early days of search engines. > > And if you mistake understanding that it's not a good way to measure > things as having no intellectual curiosity, you're again mistaken. > All I would ask is what objective evidence does either of actually have? How can you know? What is a fair way to even count line numbers? From there how do we begin to objectively measure software quality? That's why this discussion interests me, and why I don't understand why you are so adamant it doesn't work. I'll agree that I have never seen line count/char count type data used for anything other than marketing swill and kitty litter. Doesn't mean it can't be used. But first things first... and this one I think is solvable - their has got to be an equitable way to count how much code was written - maybe it isn't lines maybe it is. In truth, since you are so opposed to the idea, I'd be curious if you can think of a way to measure the quantity of code objectively? ANd that's it - not can we make a qualitative statement beyond that. But simply can we quanitfy the amount of code in some fashion that allows a reasonable comparison? From andy at neotitans.com Wed May 17 10:13:41 2006 From: andy at neotitans.com (Andy Sy) Date: Wed, 17 May 2006 22:13:41 +0800 Subject: Tabs are *MISUNDERSTOOD*, *EVIL* AND *STUPID*, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <ca55a9900605170639re1ad32co4164913a78d8f228@mail.gmail.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <OsEag.7446$mU6.4353@trnddc07> <e4f8nr$8q9$1@sea.gmane.org> <ca55a9900605170639re1ad32co4164913a78d8f228@mail.gmail.com> Message-ID: <e4fas7$hlk$1@sea.gmane.org> Peter Decker wrote: > On 5/17/06, Andy Sy <andy at neotitans.com> wrote: > >> If tabs are easily misunderstood, then they are a MISfeature >> and they need to be removed. > > I don't seem to understand your point in acting as a dictator. > Therefore, you are a MISfeature and need to be removed. Is the above an example of how a tab-user exercises 'logic'...? Besides, I'm not the only dictator here... there are also the: 4-space tabs dictators... 8-space tabs dictators... etc... -- It's called DOM+XHR and it's *NOT* a detergent! From yogesh28577 at yahoo.co.in Sat May 20 03:09:53 2006 From: yogesh28577 at yahoo.co.in (yogesh shrikhande) Date: Sat, 20 May 2006 08:09:53 +0100 (BST) Subject: mysql Message-ID: <20060520070953.93372.qmail@web8715.mail.in.yahoo.com> hello sir i want to aceess database at any location i know my.ini config. setting but my problem is suppose my i have two database ie. abc & xyz abc database is stored at path c:\apache\mysql\data this path is also in my.ini . & xyz database at path c:\mydocument i want to access both database at a time i use vb front end & mysql backend i want both database in connetion string plz ans me as early as possible thanks yogesh yogesh28577 at yahoo.co.in --------------------------------- Do you have a question on a topic you cant find an Answer to. Try Yahoo! Answers India Get the all new Yahoo! Messenger Beta Now -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060520/94c8650c/attachment.html> From bdesth.quelquechose at free.quelquepart.fr Thu May 11 20:28:33 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 May 2006 02:28:33 +0200 Subject: Reg Ex help In-Reply-To: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> Message-ID: <4463a7be$0$290$626a54ce@news.free.fr> don a ?crit : > I have a string from a clearcase cleartool ls command. > > /main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT > from /main/parallel_branch_1/release_branch_1.0/4 > > I want to write a regex that gives me the branch the file was > checkedout on ,in this case - 'dbg_for_python' > > Also if there is a better way than using regex, please let me know. s ="/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/parallel_branch_1/release_branch_1.0/4" parts = s.replace(' ', '/').strip('/').split('/') branch = parts[parts.index('CHECKEDOUT') - 1] From phddas at yahoo.com Tue May 2 18:36:31 2006 From: phddas at yahoo.com (Gary Wessle) Date: 03 May 2006 08:36:31 +1000 Subject: string.find first before location References: <87hd49m0xc.fsf@localhost.localdomain> <e370ro$415$02$2@news.t-online.com> <87zmi0emhd.fsf@localhost.localdomain> <e37ff0$km9$00$1@news.t-online.com> <1146571862.234132.8670@u72g2000cwu.googlegroups.com> Message-ID: <87mze0dpg0.fsf@localhost.localdomain> "Serge Orlov" <Serge.Orlov at gmail.com> writes: > Peter Otten wrote: > > Gary Wessle wrote: > > > > >> These days str methods are preferred over the string module's functions. > > >> > > >> >>> text = "abc abc and Here and there" > > >> >>> here_pos = text.find("Here") > > >> >>> text.rfind("abc", 0, here_pos) > > >> 4 > > >> > > >> Peter > > > > > > and what about when python 3.0 is released and those depreciated > > > functions like find and rfind are not supported. is there another > > > solution which is more permanent? > > > > I think the functions may go away, the methods will stay; so I'm confident > > the above will continue to work. > > find and rfind methods are in danger too. AFAIR they are to be replaced > by partion and rpartition methods. People who are worried about future > can continue to use index and rindex except with index and rindex, if the search string is not present, they return a [ Traceback (most recent call last): ValueError: substring not found ] ps. is there a online doc or web page where one enters a method and it returns the related docs? From rmuschall at tecont.de Fri May 19 15:18:32 2006 From: rmuschall at tecont.de (Ralf Muschall) Date: Fri, 19 May 2006 21:18:32 +0200 Subject: [silly] Does the python mascot have a name ? In-Reply-To: <Xns97C8B0412BD14BaldHeadedJohn@216.196.109.145> References: <mailman.5890.1147966982.27775.python-list@python.org> <e4i9hb$f1r$1@emma.aioe.org> <_s2bg.8867$aa4.296233@news20.bellglobal.com> <Xns97C8B0412BD14BaldHeadedJohn@216.196.109.145> Message-ID: <89i1k3-17m.ln1@prcm.tecont.de> John D Salt wrote: > I'll believe you if you can give me a list of ten things that don't have > names. [ sub{$_}, sub{$_+1}, sub{$_+2}, sub{$_+3}, sub{$_+4}, sub{$_+5}, sub{$_+6}, sub{$_+7}, sub{$_+8}, sub{$_+9}] That was easy. Ralf From kent at kentsjohnson.com Mon May 22 08:50:55 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Mon, 22 May 2006 08:50:55 -0400 Subject: grabbing portions of a file to output files In-Reply-To: <1148297296.330413.68540@j73g2000cwa.googlegroups.com> References: <1148297296.330413.68540@j73g2000cwa.googlegroups.com> Message-ID: <4471b2ed$1_2@newspeer2.tds.net> s99999999s2003 at yahoo.com wrote: > hi. > I have a file with this kind of structure: > > Hxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx > ......... > ..... > ..... > xxxxx > Hxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx > ... > .... > ... > xxxxx > Hxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx > ..... > .... > and so on....lines starting with 'H' are headers. I wish to get the > parts of the file > where line start with 'H' all the way till before the next 'H' and save > to files of different names...how is the best way to do it ? > thanks Something like this? out = None for line in open(...): if line.startswith('H'): if out: out.close() out = open(..., 'w') if out: out.write(line) out.close() Kent From wrongbad at gmail.com Sun May 7 04:35:07 2006 From: wrongbad at gmail.com (I V) Date: Sun, 07 May 2006 01:35:07 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> Message-ID: <pan.2006.05.07.08.35.04.362248@gmail.com> On Sat, 06 May 2006 23:05:59 -0700, Alex Martelli wrote: > Tomasz Zielonka <tomasz.zielonka at gmail.com> wrote: > ... >> higher level languages. There are useful programming techniques, like >> monadic programming, that are infeasible without anonymous functions. >> Anonymous functions really add some power to the language. > > Can you give me one example that would be feasible with anonymous > functions, but is made infeasible by the need to give names to > functions? In Python, specifically, extended with whatever fake syntax > you favour for producing unnamed functions? Monads are one of those parts of functional programming I've never really got my head around, but as I understand them, they're a way of transforming what looks like a sequence of imperative programming statements that operate on a global state into a sequence of function calls that pass the state between them. So, what would be a statement in an imperative language is an anonymous function that gets added to the monad, and then, when the monad is run, these functions get executed. The point being, that you have a lot of small functions (one for each statement) which are likely not to be used anywhere else, so defining them as named functions would be a bit of a pain in the arse. Actually, defining them as unnamed functions via lambdas would be annoying too, although not as annoying as using named functions - what you really want is macros, so that what looks like a statement can be interpreted is a piece of code to be executed later. Here, for instance, is an article about using scheme (and, in particular, macros), to produce a fairly elegant monad implementation: http://okmij.org/ftp/Scheme/monad-in-Scheme.html From ilitzroth at gmail.com Wed May 24 05:39:48 2006 From: ilitzroth at gmail.com (ilitzroth at gmail.com) Date: 24 May 2006 02:39:48 -0700 Subject: John Bokma harassment In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <1148463588.566212.36300@i39g2000cwa.googlegroups.com> Xah Lee schreef: > I'm sorry to trouble everyone. But as you might know, due to my > controversial writings and style, recently John Bokma lobbied people to > complaint to my web hosting provider. After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. > > I'm not sure I will be able to keep using their service, but I do hope > so. I do not like to post off-topic messages, but this is newsgroup > incidence is getting out of hand, and I wish people to know about it. > > I wrote some full detail here: > http://xahlee.org/Periodic_dosage_dir/t2/harassment.html > > If you believe this lobbying to my webhosting provider is unjust, > please write to my web hosting provider abuse at dreamhost.com > > Your help is appreciated. Thank you. > > Xah > xah at xahlee.org > ? http://xahlee.org/ We seem to have strayed a long way from Voltaire's "I do not agree with what you say, but I will defend to the death your right to say it.", but that was of course the age of enlightenment. Immanuel From sybrenUSE at YOURthirdtower.com.imagination Wed May 17 15:44:52 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 17 May 2006 21:44:52 +0200 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> Message-ID: <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> Dave Hansen enlightened us with: > Assume the code was written by someone using 4-space tabs. To them, > the code is: > > def sqlcall(): > --->cursor.execute('select id, item, amount, field4, <etc> > --->--->--->--->...'from table1 where amount>100') > > (where -------> represents an 4-space tab and . represents a space) That would be stupid indeed. It would indeed fix the tabstops at every 4 characters to keep the layout. But generally, I don't do layout like that. I'd do: --->cursor.execute( --->--->--->'select id, item, amount, field4, <etc> --->--->--->'from table1 where amount>100' --->) Which keeps looking fine, no matter what tab size, and without mixing tabs and spaces. Just because people can use tabs to make things suck, doesn't mean the tabs are evil. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From bdesth.quelquechose at free.quelquepart.fr Thu May 11 20:07:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 12 May 2006 02:07:58 +0200 Subject: Python memory deallocate In-Reply-To: <1147366843.222919.199700@q12g2000cwa.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <-yy*V4mgr@news.chiark.greenend.org.uk> <1147355266.189030.131420@y43g2000cwc.googlegroups.com> <4463462a$0$297$626a54ce@news.free.fr> <1147358549.473182.89950@i40g2000cwc.googlegroups.com> <44636843$0$278$626a54ce@news.free.fr> <1147366843.222919.199700@q12g2000cwa.googlegroups.com> Message-ID: <4463a2eb$0$297$636a55ce@news.free.fr> mardif a ?crit : > OK! i will test my app with python 2.5a2 Please let us know the result. From nobody at 127.0.0.1 Fri May 19 19:29:51 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 19 May 2006 23:29:51 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> Message-ID: <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> John Bokma wrote: > Edward Elliott <nobody at 127.0.0.1> wrote: > >> The question is how to count explicit names like module.class.func; >> should that be 1 identifier or 3? Counting as 3 would reward things >> like "from X import *" which are generally frowned on in python while >> 'use MOD qw(id)' is encouraged in perl. > > Not by me, and I doubt it is in general. Well it's all over the Perl Cookbook. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From manojk at sasken.com Wed May 31 06:03:29 2006 From: manojk at sasken.com (Manoj Kumar P) Date: Wed, 31 May 2006 15:33:29 +0530 Subject: Best Python Editor In-Reply-To: <mailman.24508.1149069603.27774.python-list@python.org> Message-ID: <BHEEKBFODALGBHHKCOFFOECKCGAA.manojk@sasken.com> Hi, Can anyone tell me a good python editor/IDE? It would be great if you can provide the download link also. Thank You, -Manoj- "SASKEN RATED Among THE Top 3 BEST COMPANIES TO WORK FOR IN INDIA - SURVEY 2005 conducted by the BUSINESS TODAY - Mercer - TNS India" SASKEN BUSINESS DISCLAIMER This message may contain confidential, proprietary or legally Privileged information. In case you are not the original intended Recipient of the message, you must not, directly or indirectly, use, Disclose, distribute, print, or copy any part of this message and you are requested to delete it and inform the sender. Any views expressed in this message are those of the individual sender unless otherwise stated. Nothing contained in this message shall be construed as an offer or acceptance of any offer by Sasken Communication Technologies Limited ("Sasken") unless sent with that express intent and with due authority of Sasken. Sasken has taken enough precautions to prevent the spread of viruses. However the company accepts no liability for any damage caused by any virus transmitted by this email From Serge.Orlov at gmail.com Fri May 19 04:57:54 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 May 2006 01:57:54 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> <1147998139.268318.315250@y43g2000cwc.googlegroups.com> <rNOSPAMon-AC0C9B.18040918052006@news.gha.chartermi.net> <1148001708.183506.296240@g10g2000cwb.googlegroups.com> <rNOSPAMon-96A79F.00032619052006@news.gha.chartermi.net> Message-ID: <1148029074.083644.112370@i40g2000cwc.googlegroups.com> Ron Garret wrote: > In article <1148001708.183506.296240 at g10g2000cwb.googlegroups.com>, > "Serge Orlov" <Serge.Orlov at gmail.com> wrote: > > > Ron Garret wrote: > > > > > I'm using an OS X terminal to ssh to a Linux machine. > > > > > > > > In theory it should work out of the box. OS X terminal should set > > > > enviromental variable LANG=en_US.utf-8, then ssh should transfer this > > > > variable to Linux and python will know that your terminal is utf-8. > > > > Unfortunately AFAIK OS X terminal doesn't set that variable and most > > > > (all?) ssh clients don't transfer it between machines. As a workaround > > > > you can set that variable on linux yourself . This should work in the > > > > command line right away: > > > > > > > > LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > > > > > > Or put the following line in ~/.bashrc and logout/login > > > > > > > > export LANG=en_US.utf-8 > > > > > > No joy. > > > > > > ron at www01:~$ LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > > Traceback (most recent call last): > > > File "<string>", line 1, in ? > > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in > > > position 0: ordinal not in range(128) > > > ron at www01:~$ > > > > What version of python and what shell do you run? What the following > > commands print: > > > > python -V > > echo $SHELL > > $SHELL --version > > ron at www01:~$ python -V > Python 2.3.4 > ron at www01:~$ echo $SHELL > /bin/bash > ron at www01:~$ $SHELL --version > GNU bash, version 2.05b.0(1)-release (i386-pc-linux-gnu) > Copyright (C) 2002 Free Software Foundation, Inc. > ron at www01:~$ That's recent enough. I guess the distribution you're using set LC_* variables for no good reason. Either unset all enviromental variables starting with LC_ and set LANG variable or overide LC_CTYPE variable: LC_CTYPE=en_US.utf-8 python -c "print unichr(0xbd)" Should be working now :) From __peter__ at web.de Tue May 16 03:55:23 2006 From: __peter__ at web.de (Peter Otten) Date: Tue, 16 May 2006 09:55:23 +0200 Subject: Python and Combinatorics References: <44697b5c$0$14794$4fafbaef@reader4.news.tin.it> Message-ID: <e4c0dh$197$03$1@news.t-online.com> Nic wrote: [Algorithm that I may have misunderstood] > 12a 13a 23a > 12a 13b 23a > 12a 13b 23b > 12b 13a 23a > 12b 13b 23a > 12b 13b 23b What about 12a 13a 23b and 12b 13a 23b? Peter PS: Please don't top-post. From robert.kern at gmail.com Mon May 8 20:25:13 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 May 2006 19:25:13 -0500 Subject: ascii to latin1 In-Reply-To: <445fdc6c$0$15793$14726298@news.sunsite.dk> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> Message-ID: <e3onha$56t$1@sea.gmane.org> Luis P. Mendes wrote: > example: > if the word searched is 'televis?o', I want that a search by either > 'televisao', 'televis?o' or even 't?l?visao' (this last one doesn't > exist in Portuguese) is successful. The ICU library has the capability to transliterate strings via certain rulesets. One such ruleset would transliterate all of the above to 'televisao'. That transliteration could act as a normalization step akin to stemming. There are one or two Python bindings out there. Google for PyICU. I don't recall if it exposes the transliteration API or not. -- 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 dcrosta at sccs.swarthmore.edu Tue May 9 10:40:16 2006 From: dcrosta at sccs.swarthmore.edu (Dan Crosta) Date: Tue, 09 May 2006 10:40:16 -0400 Subject: distutils In-Reply-To: <loom.20060509T161902-311@post.gmane.org> References: <loom.20060509T161902-311@post.gmane.org> Message-ID: <4460A9D0.50503@sccs.swarthmore.edu> David S. wrote: > I have a what I a typical source tree, something like: > fsi\ > - common\ # some modules > - db\ # some modules > - someutility\ # my script > > I would like to create a setup script to install my script as a script as well > as the modules that is depends on, but where should the setup.py file live? If > I put it in ./someutility/ it can not find fsi.common or fsi.db. David Your setup.py should live in fsi/setup.py. try: --- from distutils.core import setup setup( packages=['common', 'db'], scripts=['someutility/script1.py', 'someutility/script2.py']) --- dsc From onurb at xiludom.gro Thu May 4 09:20:01 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 15:20:01 +0200 Subject: Swaying A Coder Away From Python In-Reply-To: <1146745480.260929.55940@y43g2000cwc.googlegroups.com> References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <W40839200.311.1532.1@mx-extra.net> <mailman.5315.1146743831.27775.python-list@python.org> <1146745480.260929.55940@y43g2000cwc.googlegroups.com> Message-ID: <4459ffdd$0$21105$626a54ce@news.free.fr> BartlebyScrivener wrote: > I'm picking this up via clp on Google Groups. I can't tell what Mr. > Lundh is referring to. The first line of his post is: "Tim Williams > wrote" but there's nothing that comes before. I had seen the article on > Django on Digg I think, but what is article Tim Williams is referring > to? Google for "David A. Utter" -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From python-url at phaseit.net Mon May 22 11:45:09 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 22 May 2006 15:45:09 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 22) Message-ID: <e4sma5$msm$1@lairds.us> QOTW: "It's hard to make a mistake by having too many short and simple functions. And much too easy to make them when you have too few ;-)" - Thomas Bartkus "Argh, the following is valid Python syntax: assert a is not b - XXX in-progress" - Armin Rigo (found on Michael Hudson's blog) A GREAT Python event is taking place right now: http://wiki.python.org/moin/NeedForSpeed/ Python does not encourage one-liners, but when they work they are often beautiful and efficient, like this one for counting distinct lines in a file. http://groups.google.com/group/comp.lang.python/msg/332003a1a24205d3 Starting with Python 2.4 you may have to explicitly mask away the bits that used to fall off the edge of the world in previous versions. http://groups.google.com/group/comp.lang.python/browse_frm/thread/54b60719b4b1f960/0c5f1afebf8ec0c3?tvc=1 Paul Cannon is working on Noodle, a lisp flavour targeting Python bytecode. http://noodler.blogspot.com/2006/05/release.html Modules lack a __getattr__ method. However, that is not a limitation in practice: http://groups.google.com/group/comp.lang.python/msg/68e0c33b843a8a64 Mike Foord and John J. Lee have teamed to improve the "Missing urllib2 Manual" slated to become an official Howto. http://www.voidspace.org.uk/python/weblog/arch_d7_2006_05_20.shtml#e335 When Python balks at printing non-ascii characters to stdout, the shell is likely to be the culprit, as Serge Orlov and others work out. http://groups.google.com/group/comp.lang.python/browse_frm/thread/7a5ce0d2f48ac9ec/74b0c561f3e87288?tvc=1 Dave Kuhlman has updated his FAQ concerning XML handling with Python. http://www.rexx.com/~dkuhlman/pyxmlfaq.html Among the folks Bruce Eckel has interviewed are Guido van Rossum and Jim Fulton. http://www.mindviewinc.com/mediacast/interviews/Index.php Still undecided whether you need "wxPython in Action", the new book written by Noel Rappin and Robin Dunn (the latter also the main developer of the wxPython GUI framework)? Get a feel for what to expect from this excerpt: http://www.pythonthreads.com/articles/python/incorporating-into-wxpython-part-1.html If you want to access only part of a pickle file cPickle has a fast-forward that avoids loading stuff you are not interested in. http://groups.google.com/group/comp.lang.python/msg/d55b2e987563422a ======================================================================== 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, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python 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 <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From george.sakkis at gmail.com Fri May 19 11:27:13 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 19 May 2006 08:27:13 -0700 Subject: the tostring and XML methods in ElementTree References: <1147035307.937895.151870@g10g2000cwb.googlegroups.com> <mailman.5467.1147077842.27775.python-list@python.org> <1147853382.250160.270530@i39g2000cwa.googlegroups.com> <446dd405$0$4512$9b4e6d93@newsread2.arcor-online.net> Message-ID: <1148052433.497179.148240@u72g2000cwu.googlegroups.com> Stefan Behnel wrote: > George Sakkis wrote: > > Fredrik Lundh wrote: > > > >> mirandacascade at yahoo.com wrote: > >> > >>> I wanted to see what would happen if one used the results of a tostring > >>> method as input into the XML method. What I observed is this: > >>> a) beforeCtag.text is of type <type 'str'> > >>> b) beforeCtag.text when printed displays: I'm confused > >>> c) afterCtag.text is of type <type 'unicode'> > >>> d) afterCtag.text when printed displays: I?m confused > >> the XML file format isn't a Python string serialization format, it's an XML infoset > >> serialization format. > >> > >> as stated in the documentation, ET always uses Unicode strings for text that > >> contain non-ASCII characters. for text that *only* contains ASCII, it may use > >> either Unicode strings or 8-bit strings, depending on the implementation. > >> > >> the behaviour if you're passing in non-ASCII text as 8-bit strings is undefined > >> (which means that you shouldn't do that; it's not portable). > > > > I was about to post a similar question when I found this thread. > > Fredrik, can you explain why this is not portable ? > > Because there is no such things as a default encoding for 8-bit strings. > > > > I'm currently using > > (a variation of) the workaround below instead of ET.tostring and it > > works fine for me: > > > > def tostring(element, encoding=None): > > text = element.text > > if text: > > if not isinstance(text, basestring): > > text2 = str(text) > > elif isinstance(text, str) and encoding: > > text2 = text.decode(encoding) > > element.text = text2 > > s = ET.tostring(element, encoding) > > element.text = text > > return s > > > > > > Why isn't this the standard behaviour ? > > > Because it wouldn't work. What if you wanted to serialize a different encoding > than that of the strings you put into the .text fields? How is ET supposed to > know what encoding your strings have? And how should it know that you didn't > happily mix various different byte encodings in your strings? If you're mixing different encodings, no tool can help you clean up the mess, you're on your own. This is very different though from having nice utf-8 strings everywhere, asking ET.tostring explicitly to print them in utf-8 and getting back garbage. Isn't the most reasonable assumption that the input's encoding is the same with the output, or does this fall under the "refuse the temptation to guess" motto ? If this is the case, ET could at least accept an optional input encoding parameter and convert everything to unicode internally. > Use unicode, that works *and* is portable. *and* it's not supported by all the 3rd party packages, databases, middleware, etc. you have to or want to use. > Stefan George From doomsAinfoDuclDacDbe at AisATandDisDOT.com Wed May 10 08:29:50 2006 From: doomsAinfoDuclDacDbe at AisATandDisDOT.com (=?ISO-8859-1?Q?Gr=E9goire_Dooms?=) Date: Wed, 10 May 2006 14:29:50 +0200 Subject: clear memory? how? In-Reply-To: <slrne61nlc.e9e.spamspam@bowser.marioworld> References: <e3pjop$rqd$1@enyo.uwa.edu.au> <4cb49uF15811rU1@uni-berlin.de> <slrne61dve.e9e.spamspam@bowser.marioworld> <slrne61nlc.e9e.spamspam@bowser.marioworld> Message-ID: <2p-dnQQrLYq8QPzZRVnyjg@scarlet.biz> Ben C wrote: > On 2006-05-09, Ben C <spamspam at spam.eggs> wrote: >> def clearall(): >> all = [var for var in globals() if "__" not in (var[:2], var[-2:])] >> for var in all: >> del globals()[var] >> >> since I think magic things always start and end with __. > > Oops, got that wrong anyway: > > should be: > > all = [var for var in globals() if (var[:2], var[-2:]) != ("__", "__")] You can also add and var != "clearall" :-) -- Gr?goire From bdesth.quelquechose at free.quelquepart.fr Thu May 18 22:09:41 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 19 May 2006 04:09:41 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147991330.560422.145560@38g2000cwa.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147980462.464427.323030@u72g2000cwu.googlegroups.com> <446cdd6b$0$7043$636a55ce@news.free.fr> <mailman.5903.1147987032.27775.python-list@python.org> <446ceb96$0$7024$636a55ce@news.free.fr> <1147991330.560422.145560@38g2000cwa.googlegroups.com> Message-ID: <446cf9c0$0$24981$626a54ce@news.free.fr> glomde a ?crit : > So I read trough all of the make PEP and make would support the syntax > i propose.. > and more generic and better in many ways. Since it was rejected I have > to ... bug the BDFL until he reconsiders its position. From skip at pobox.com Wed May 17 07:34:28 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 17 May 2006 06:34:28 -0500 Subject: CFLAGS are not taken into account properly In-Reply-To: <446ad377$0$438$6c56d894@reader0.news.be.easynet.net> References: <446ad377$0$438$6c56d894@reader0.news.be.easynet.net> Message-ID: <17515.2628.410214.828758@montanaro.dyndns.org> Toon> To configure python on a Solaris 9 box with sunstudio11 installed Toon> and to compile it in 64bit, I execute following: Toon> <code> Toon> export CC=cc Toon> export CFLAGS="-xarch=v9" Toon> export CXX=CC Toon> export CXXFLAGS="-xarch=v9" Toon> export F77=f77 Toon> export FFLAGS="-xarch=v9" Toon> export LDFLAGS="-xarch=v9" Toon> ./configure Toon> </code> Toon> When doing 'make' afterwards, the '-xarch=v9' option is not on the Toon> command-line however? Should'nt the CFLAGS be propagated to the Toon> Makefile that is generated by configure? Or is there any other way Toon> to do this? I agree, the Python configure/Makefile combination doesn't conform very well to current GNU style in this regard. Try setting EXTRA_CFLAGS instead of CFLAGS. Skip From grflanagan at yahoo.co.uk Sat May 27 07:22:20 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 27 May 2006 04:22:20 -0700 Subject: starting some Python script from C# References: <e58ta7$jns$1@fegnews.vip.hr> Message-ID: <1148728940.440692.166330@i39g2000cwa.googlegroups.com> tatamata wrote: > Hello. > > How can I run some Python script within C# program? > --------------------------------------------------------------------------------- ProcessStartInfo startInfo; Process process; string directory; string pyArgs; string script; startInfo = new ProcessStartInfo("python"); startInfo.WorkingDirectory = directory; startInfo.Arguments = script + " " + pyArgs; startInfo.UseShellExecute = false; startInfo.CreateNoWindow = true; startInfo.RedirectStandardOutput = true; startInfo.RedirectStandardError = true; process = new Process(); process.StartInfo = startInfo; process.Start(); string s; while ((s = process.StandardOutput.ReadLine()) != null) { //do something with s } --------------------------------------------------------------------------------- HTH Gerard From brian at sweetapp.com Mon May 15 13:11:36 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Mon, 15 May 2006 19:11:36 +0200 Subject: ANN: Vancouver Python Workshop Message-ID: <4468B648.5080609@sweetapp.com> Vancouver Python Workshop ========================= Building on the huge success of the 2004 Vancouver Python Workshop, the Vancouver Python and Zope User Group is pleased to announce the 2006 Vancouver Python Workshop. The conference will begin with keynote addresses on August 4st. Further talks (and tutorials for beginners) will take place on August 5th and 6th. The Vancouver Python Workshop is a community organized conference designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers * tracks on multimedia, Web development, education and more More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Talk proposals accepted: May 15th to June 15th Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th (1) http://news.bbc.co.uk/2/hi/business/2299119.stm Cheers, Brian From robert.kern at gmail.com Thu May 18 17:55:59 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 18 May 2006 16:55:59 -0500 Subject: WTF? Printing unicode strings In-Reply-To: <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> Message-ID: <e4iqhf$mi7$1@sea.gmane.org> Ron Garret wrote: > I forgot to mention: > >>>>sys.getdefaultencoding() > > 'utf-8' A) You shouldn't be able to do that. B) Don't do that. C) It's not relevant to the encoding of stdout which determines how unicode strings get converted to bytes when printing them: >>> import sys >>> sys.stdout.encoding 'UTF-8' >>> sys.getdefaultencoding() 'ascii' >>> print u'\xbd' ? -- 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 george.sakkis at gmail.com Fri May 26 10:55:13 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 26 May 2006 07:55:13 -0700 Subject: dict literals vs dict(**kwds) In-Reply-To: <Xns97CF9CDFFB09Cduncanbooth@127.0.0.1> References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> <1148646327.998387.294310@y43g2000cwc.googlegroups.com> <1148650269.190130.209840@i39g2000cwa.googlegroups.com> <Xns97CF9CDFFB09Cduncanbooth@127.0.0.1> Message-ID: <1148655313.422226.297700@i40g2000cwc.googlegroups.com> Duncan Booth wrote: > George Sakkis wrote: > > > 2) restricting in a more serious sense: the future addition of optional > > keyword arguments that affect the dict's behaviour. Google for "default > > dict" or "dictionary accumulator". > > There is nothing to stop dictionaries being created using factory functions > (e.g. see dict.fromkeys). So one possible way to implement defaults would > be to extend the dict class with a new classmethod 'withdefault' which > takes a default value as an argument. > > However, given that the default argument isn't actually needed during > construction, it doesn't seem to me that it fits either as a constructor > parameter nor a factory method. I don't see why it shouldn't just be set on > an existing dictionary (or dictionary subclass) when you need it. Because I would find d = dict(default=0) d['x'] += 3 more elegant than d = {} d.withdefault(0) d['x'] += 3 YMMV, George From thorsten at thorstenkampe.de Sun May 7 10:18:46 2006 From: thorsten at thorstenkampe.de (Thorsten Kampe) Date: Sun, 7 May 2006 15:18:46 +0100 Subject: Job opportunity in France References: <mn.2a417d6545f2820b.43626@yahoo.fr.invalid> <cG37g.53396$eR6.17008@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <6x2rk0tjoj05$.ayv6dpl6ipfk$.dlg@40tude.net> * Butternut squash (2006-05-06 16:55 +0000) > Rony Steelandt wrote: >> We have a vacancy for a python programmer for a 6 months assignement. >> >> If interested, please visit www.bucodi.com >> >> And don't worry we speak english :) >> > seriously, a job opportunity in France?? I heard that the unemployment rate > is not doing too well. Funny. And I heard that the /employment rate/ is not doing too well :-)... From mrmakent at cox.net Mon May 1 15:53:51 2006 From: mrmakent at cox.net (Mike Kent) Date: 1 May 2006 12:53:51 -0700 Subject: How do I take a directory name from a given dir? In-Reply-To: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> References: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> Message-ID: <1146513231.511442.220020@v46g2000cwv.googlegroups.com> Python 2.4.2 (#1, Nov 29 2005, 14:04:55) [GCC 3.2.2 20030222 (Red Hat Linux 3.2.2-5)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> d = "/home/testuser/projects" >>> os.path.basename(d) 'projects' >>> os.path.dirname(d) '/home/testuser' >>> From johnjsal at NOSPAMgmail.com Wed May 24 11:04:58 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 24 May 2006 15:04:58 GMT Subject: Python keywords vs. English grammar In-Reply-To: <roy-CEC3E3.08573224052006@reader1.panix.com> References: <roy-CEC3E3.08573224052006@reader1.panix.com> Message-ID: <uC_cg.2166$No6.46848@news.tufts.edu> Roy Smith wrote: > try { > throw foo; > } catch { > } > try: > raise foo > except: But which one is prettier? ;) From bdesth.quelquechose at free.quelquepart.fr Mon May 15 21:19:56 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 16 May 2006 03:19:56 +0200 Subject: my cryptogram program In-Reply-To: <7xfyjbrmzl.fsf@ruckus.brouhaha.com> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <gh5ag.2100$No6.46182@news.tufts.edu> <4468f2c4$0$7135$626a54ce@news.free.fr> <7xfyjbrmzl.fsf@ruckus.brouhaha.com> Message-ID: <4468f9af$0$12816$636a55ce@news.free.fr> Paul Rubin a ?crit : > Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> writes: > >>def convert_quote(quote): >> return make_code(quote).split('|', 1) > > > I thought about suggesting that, but it's semantically different than > the original since it fails to raise an error if no vertical bar is > present. Yeps, true. > I don't know if that's good or bad. At least someone reading this may learn about the max_split param of str.split() !-) From johnjsal at NOSPAMgmail.com Sun May 7 23:23:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 07 May 2006 23:23:21 -0400 Subject: utility functions within a class? In-Reply-To: <445eb995$0$9381$c3e8da3@news.astraweb.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> Message-ID: <445ebacc$0$5345$c3e8da3@news.astraweb.com> John Salerno wrote: > jeffshannon at gmail.com wrote: > >> Even if you don't end up referring to self or any instance >> attributes within the method > > Hmm, follow-up: I *do* plan to refer to instance attributes inside these > methods (self.something), but does that require that they be instance > methods, or can they still reference 'self' since they are inside the class? > > They won't be called directly from an instance, which is why I wondered > about making them static or class methods, but can static or class > methods use self, or does it have to be an instance method in that case? Ugh, sorry about another post, but let me clarify: In these utility functions, I need to refer to an attribute of an instance, but these functions will be called from another method in the class, not from the instance itself. Is this even possible, or would 'self' have no meaning when used this way? From iainking at gmail.com Mon May 8 07:51:12 2006 From: iainking at gmail.com (Iain King) Date: 8 May 2006 04:51:12 -0700 Subject: Web framework comparison video Message-ID: <1147089072.416705.17810@j73g2000cwa.googlegroups.com> http://compoundthinking.com/blog/index.php/2006/03/10/framework-comparison-video/ Thought this might be interesting to y'all. (I can't watch it 'cos I'm at work, so any comments about it would be appreciated :) Iain From michele.simionato at gmail.com Thu May 4 05:09:29 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 4 May 2006 02:09:29 -0700 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <aL56g.72399$H71.17629@newssvr13.news.prodigy.com> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> <mailman.5253.1146643043.27775.python-list@python.org> <1146644904.906523.255970@j73g2000cwa.googlegroups.com> <1146651877.687428.294320@v46g2000cwv.googlegroups.com> <aL56g.72399$H71.17629@newssvr13.news.prodigy.com> Message-ID: <1146733769.619181.268050@j33g2000cwa.googlegroups.com> Edward Elliott wrote: > Michele Simionato wrote: > > Python solution is to rely on the intelligence of programmers. If they > > see an all caps name and then they try to change it without knowing what > > they are doing, then they are stupid. If you have stupid programmers there > > is no way the language can stop them for making disasters. > > Which doesn't apply here, one of the OP's examples further up this thread > doesn't modify any ALL CAPS vars directly: > > >>> A = [] # let's declare a "constant" here > >>> b = A # and let's assign the constant here > >>> b.append('1') # OOPS! But it makes no sense to use a mutable object for a constant! The user should use a tuple, or a custom list-like type where all methods with side effects are removed, so it effectively acts as a tuple. Michele Simionato From larry.bates at websafe.com Sat May 6 11:51:44 2006 From: larry.bates at websafe.com (Larry Bates) Date: Sat, 06 May 2006 10:51:44 -0500 Subject: Replace In-Reply-To: <IsS6g.711$re6.599@trndny04> References: <IsS6g.711$re6.599@trndny04> Message-ID: <wtKdnTz9TP6eW8HZnZ2dnUVZ_sydnZ2d@comcast.com> Eric wrote: > I have a string... > > str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" > > I want to replace the characters after each '=', what I ended up doing is > somthing like this... > > buf = list(str) > newchr = '#' > > count = 0 > for i in range(len(buf)): > if buf[count] == '=': > buf[count + 1] = newchr > count = count + 1 > else: > count = count + 1 > > newstr = ''.join(buf) > > Is there a better, faster way of doing it? Using somthing like > str.index() dosn't work because... > > str = "hello world" > for i in str: > print str.index(i) > > 0 > 1 > 2 > 2 > 4 > 5 > 6 > 4 > 8 > 2 > 10 > > Every 'e' in "hello world" has the same index value. Am i missing somthing? Split the string on '=', and join it back with '=#'. s='=#'.join(s.split('=')) -Larry Bates From python.list at tim.thechases.com Fri May 12 10:28:28 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 12 May 2006 09:28:28 -0500 Subject: NEWBIE: Tokenize command output In-Reply-To: <44648ed3$0$12812$636a55ce@news.free.fr> References: <lorenzo-58D5E4.10282511052006@hedley.thethurmans.com> <mailman.5590.1147362357.27775.python-list@python.org> <446478eb$0$287$626a54ce@news.free.fr> <mailman.5627.1147439411.27775.python-list@python.org> <44648ed3$0$12812$636a55ce@news.free.fr> Message-ID: <44649B8C.2020102@tim.thechases.com> > I reeducated my fingers after having troubles with huge files !-) I'll keep it in mind...the prospect of future trouble with large files is a good kick-in-the-pants to remember. >>Otherwise, just to be informed, what advantage does rstrip() have over >>[:-1] (if the two cases are considered uneventfully the same)? > > 1/ if your line doesn't end with a newline, line[:-1] will still remove > the last caracter. Good catch. Most *nix editors are smart about having a trailing NL character at the end of the file, but some Windows text-editors aren't so kind. > 2/ IIRC, if you don't use universal newline and the file uses the > DOS/Windows newline convention, line[:-1] will not remove the CR - only > the LF (please someone correct me if I'm wrong here). To get this behavior, I think you have to open the file in binary mode. To me, opening as binary is a signal that I should be using read() rather than readlines() (or xreadlines, or the iterator, or whatever). If you've opened in binary mode, you might have to use rstrip("\r\n") to get both possible line-ending characters. > I know this may not be a real issue in the actual case, but using > rstrip() is still a safer way to go IMHO - think about using this same > code to iterate over a list of strings without newlines... Makes sense. Using rstrip("\r\n") has all the benefits, plus more gracefully handles cases where a newline might not be present or comprised of two (or more) characters. Got it! Thanks for the explanation. -tkc From tbrkic at yahoo.com Sat May 13 14:58:52 2006 From: tbrkic at yahoo.com (glomde) Date: 13 May 2006 11:58:52 -0700 Subject: compiling module from string and put into namespace In-Reply-To: <446599de$0$5314$626a54ce@news.free.fr> References: <1147429689.533221.316110@i39g2000cwa.googlegroups.com> <4464754a$0$306$626a54ce@news.free.fr> <1147474282.618115.60590@u72g2000cwu.googlegroups.com> <446599de$0$5314$626a54ce@news.free.fr> Message-ID: <1147546732.243157.174810@i40g2000cwc.googlegroups.com> Ok, now I think I know what I need to do. I need to create a variable in the calling functions locals. So how do I get access to the calles locals dictionary? Is it possible? From deets at nospam.web.de Mon May 15 03:43:05 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 09:43:05 +0200 Subject: Problem with Tkinter on Mac OS X In-Reply-To: <mailman.5694.1147662391.27775.python-list@python.org> References: <mailman.5694.1147662391.27775.python-list@python.org> Message-ID: <4cqpo4F17a2otU1@uni-berlin.de> Jean Richelle schrieb: > Hello, > > I installed version 2.4.1 (and I tried also with 2.4.3) of Python under > 10.3.9 (and 10.4.6), and I trying to use Tkinter. For simplicity I'm > testing the "hello world" that I found in the documentation. > I first launch IDLE, write (cut and paste from the web) the program in > an editing window, save it, and then run it. The window with two buttons > is displayed in the back of the IDLE window (and I cannot bring it to > the front), and there nothing happening when I click either button. > Did anybody do a fresh install recently and can run program using Tkinter ? MacOs is somewhat peculiar when it comes to running GUI-apps. What you ususally want to (or better have to do) is to cretae a so-called application bungle. There are several ways to do so - I frequenmtly code PyObjc-Applications and use xcode + the distutils py2app-extension. The latter one should work for Tkinter, too. Then with my MacPython distro, there came a mac-specific IDE that also allowed to save a script as application. I sugegst you read up on the whole subject here: http://pythonmac.org/wiki/FAQ and here http://pythonmac.org/wiki/py2app Diez From joesb.coe9 at gmail.com Tue May 9 00:13:56 2006 From: joesb.coe9 at gmail.com (Pisin Bootvong) Date: 8 May 2006 21:13:56 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147108421.090707.226700@i40g2000cwc.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> Message-ID: <1147148036.512676.288190@i39g2000cwa.googlegroups.com> Joe Marshall wrote: > Alex Martelli wrote: > Most languages allow `unnamed numbers'. The `VAT_MULTIPLIER' argument > is a > strawman. Would you want to have to use a special syntax to name the > increment > in loop? > > defnumber zero 0 > defnumber one { successor (zero); } > > for (int i = zero; i < limit; i += one) { ...} > > If you language allows unnamed integers, unnamed strings, unnamed > characters, unnamed arrays or aggregates, unnamed floats, unnamed > expressions, unnamed statements, unnamed argument lists, etc. why > *require* a name for trivial functions? > Wouldn't all the other constructs benefit by having a required name as > well? > Is this a Slippery Slope fallacious argument? (http://c2.com/cgi/wiki?SlipperySlope) "if python required you to name every function then soon it will require you to name every number, every string, every immediate result, etc. And we know that is bad. Therefore requiring you to name your function is bad!!!! So Python is bad!!!!" How about: If Common Lisp lets you use unnamed function, then soon everyone will start not naming their function. Then soon they will start not naming their variable, not naming their magic number, not naming any of their class, not naming any function, and then all Common Lisp program will become one big mess. And we know that is bad. So allowing unnamed function is bad!!!! So Common Lisp is bad!!!!! From oscartheduck at gmail.com Sun May 21 12:17:44 2006 From: oscartheduck at gmail.com (oscartheduck) Date: 21 May 2006 09:17:44 -0700 Subject: newbie: windows xp scripting Message-ID: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> I've been having trouble with the following style of script. It's simple stuff, I know, but it's stumping me: import os dirfrom = 'C:\\test' dirto = 'C:\\test1\\' copy_command = 'copy "%s" "%s"' % (dirfrom, dirto) if os.system(copy_command) == 0: print "yay" else: print "boo" What's going wrong is with the %s substitution part. I've tried more complex scipts and kept running against an error where my script just wouldn't work. So I stripped back and back and back to this point, where I'm just trying to run a simple copy command. But for some reason, it fails. If I don't use the %s substitution but use the full pathnames explicitly in the copy command, it works fine. So that's where my issue seems to be. Help! From "reverse[nepank.noot]" at fft.be Wed May 17 03:11:36 2006 From: "reverse[nepank.noot]" at fft.be (Toon Knapen) Date: Wed, 17 May 2006 09:11:36 +0200 Subject: build now requires Python exist before the build starts In-Reply-To: <1147840440.217866.314750@u72g2000cwu.googlegroups.com> References: <4469df8d$0$442$6c56d894@reader0.news.be.easynet.net> <1147840440.217866.314750@u72g2000cwu.googlegroups.com> Message-ID: <446acca7$0$443$6c56d894@reader0.news.be.easynet.net> nnorwitz at gmail.com wrote: > > It shouldn't actually be required. I'm assuming the problem is while > trying to run asdlgen.py. The generated files are checked in, but the > timestamps are wrong and the Makefile is trying to be helpful. > > Try: > touch Include/Python-ast.h Python/Python-ast.c > make > Thanks, indeed it is a timestamp problem. However I copied the error message 'build now requires Python exists before the build starts' directly from the Makefile. It might be instructive that the Makefile also mentions that this is not strictly necessary and documents that python is needed if one wants to regenerated Python-ast.[hc]. Thanks a lot, toon From onurb at xiludom.gro Thu May 18 04:58:05 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 10:58:05 +0200 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> Message-ID: <446c3785$0$6981$626a54ce@news.free.fr> Pierre wrote: > Hi, > > Sorry in advance, english is not my main language :/ > > I'd like to customize the result obtained by getattr on an object : if > the object has the requested property then return it BUT if the object > doesn't has actually this property return something else. So implement __getattr__(self, name). > In my case, I can't use getattr(object, property, default_value). Why so ? > > I tried to write a class with a __getattr__ method and even a > __getattribute__ method but this doesn't do what I want.... Warning: __getattribute__ will take over normal attribute lookup. It can be really tricky. Anyway, you don't need it for your use case - just stick with __getattr__() and you'll be ok. > Maybe I didn't correctly understand this : > http://docs.python.org/ref/attribute-access.html > > Here is a piece of my code : > ===================================== > class myclass: Make this : class MyClass(object): > """docstring""" > > a = 'aa' > b = 'bb' a and b are class attributes, not instance attributes. If you want per-instance attributes (which is the most usual case...), you need to define them in a method - usually the __init__() method: def __init__(self): self.a = 'aa' self.b = 'bb' > def __getattr___(self, ppt): > """getattr""" > if hasattr(self, ppt): > return self.ppt __getattr__() will be called only if the normal attribute lookup fails. So calling hasattr(self, ...) in __getattr__ is useless. More than this: the fact that __getattr__() has benn called means that normal lookup has already failed, so hasattr() will end up calling __getattr__()... > else: > return "my custom computed result" (snip) > > if __name__ == "__main__": > > d = myclass() > p1 = getattr(d, "a") You do understand that getattr(d, "a") is the same as d.a, don't you ? > print p1 > p2 = getattr(d, "b") > print p2 > p3 = getattr(d, "c") > print p3 > ================================ > > I get an AttributeError when accessing to the property named "c". > > Any explanation/solution to my problem ? 1/ use new-style classes 2/ only implement __getattr__() here's a minimal working example: class MyClass(object): def __init__(self, default='default'): self.a = 'aa' self.b = 'bb' self._default = default def __getattr__(self, name): return self._default m = MyClass() m.a m.b m.toto HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From darshan.purandare at gmail.com Thu May 11 12:05:23 2006 From: darshan.purandare at gmail.com (darshan.purandare at gmail.com) Date: 11 May 2006 09:05:23 -0700 Subject: Memory leak in Python In-Reply-To: <slrne65tdr.8pb.sybrenUSE@schuimige.stuvel.eu> References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <ccl062h5tc24b4qe3d66b7hvh7ujgrklcp@4ax.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> <slrne63ae3.96g.sybrenUSE@schuimige.stuvel.eu> <1147302164.557634.177170@v46g2000cwv.googlegroups.com> <slrne65tdr.8pb.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1147363523.635677.267640@y43g2000cwc.googlegroups.com> Either of it would do, I am creating a discrete time simulator. From mensanator at aol.com Wed May 24 21:18:57 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 May 2006 18:18:57 -0700 Subject: GMPY: divm() still broken (was: module conflict? gmpy and operator) References: <1148346626.184199.125740@38g2000cwa.googlegroups.com> <mailman.6095.1148354349.27775.python-list@python.org> <1148370675.969310.41660@38g2000cwa.googlegroups.com> Message-ID: <1148519937.935514.188630@y43g2000cwc.googlegroups.com> Drat, gmpy is still broken. Prior to ver 1.01, divm(4,8,20) would produce a 'not invertible' error even though this is a valid linear congruence (because gcd(8,20)=4 divides 4). The issue was that the modular inverse function invert() requires that 8 & 20 be co-prime (have gcd=1). Linear congruence doesn't require that, only that the gcd divides 4. But if the gcd divides 4, then all three parameters are divisible by 4, so we can convert the non-invertible (4,8,20) into the invertible (1,2,5). That feature was added to the 1.01 version of divm() in addition to fixing the memory leak. And although it works, it has an "interesting" side effect: completely corrupting the gmpy module. IDLE 1.1a3 >>> from gmpy import * >>> x = mpz('8') >>> y = mpz('20') >>> z = mpz('4') >>> x,y,z (mpz(8), mpz(20), mpz(4)) >>> divm(z,x,y) mpz(3) Correct answer... >>> x,y,z (mpz(2), mpz(5), mpz(1)) ...but variables have changed (that's not supposed to happen). 2,5,1 results from dividing x,y,z by gcd(8,20) in order to obtain a valid modular inverse. Invoking divm(z,x,y) again still produces the correct answer. >>> divm(z,x,y) mpz(3) But if x,y,z are actually 2,5,1, this should fail with a 'not invertible' error. So even though it is being called with x,y,z, the original values are still being used somehow. Calling divm() with literals... >>> divm(4,8,20) mpz(3) ...also produces the correct answer, but the literals had to be coerced to mpzs. Earlier, we saw that x,y,z somehow have two different values simultaneously. With the literals coerced to mpzs, we have corrupted gmpy so that it cannot do any further coercion on 8: >>> mpz(8) mpz(2) 8 is now stuck with value 2 when coerced to mpz. So even though divm(4,8,20) should work, it can't any more since failure to coerce 4 & 8 means divm() is actually trying to evaluate (1,2,20). >>> divm(4,8,20) Traceback (most recent call last): File "<pyshell#21>", line 1, in -toplevel- divm(4,8,20) ZeroDivisionError: not invertible My speculation is that the three mpz_divexact functions shown below must be doing some kind of bizarre pointer magic that permits x,y,z to have two different values simultaneously while also corrupting the coercion of literals. It's legal in the gmp program to have a result overwrite an operand, but my guess is that shouldn't be done. static char doc_divm[]="\ divm(a,b,m): returns x such that b*x==a modulo m, or else raises\n\ a ZeroDivisionError exception if no such value x exists\n\ (a, b and m must be mpz objects, or else get coerced to mpz)\n\ "; static PyObject * Pygmpy_divm(PyObject *self, PyObject *args) { PympzObject *num, *den, *mod, *res; int ok; if(!PyArg_ParseTuple(args, "O&O&O&", Pympz_convert_arg, &num, Pympz_convert_arg, &den, Pympz_convert_arg, &mod)) { return last_try("divm", 3, 3, args); } if(!(res = Pympz_new())) return NULL; if(mpz_invert(res->z, den->z, mod->z)) { /* inverse exists */ ok = 1; } else { /* last-ditch attempt: do num, den AND mod have a gcd>1 ? */ PympzObject *gcd; if(!(gcd = Pympz_new())) return NULL; mpz_gcd(gcd->z, num->z, den->z); mpz_gcd(gcd->z, gcd->z, mod->z); mpz_divexact(num->z, num->z, gcd->z); mpz_divexact(den->z, den->z, gcd->z); mpz_divexact(mod->z, mod->z, gcd->z); Py_DECREF((PyObject*)gcd); ok = mpz_invert(res->z, den->z, mod->z); } if (ok) { mpz_mul(res->z, res->z, num->z); mpz_mod(res->z, res->z, mod->z); if(options.ZM_cb && mpz_sgn(res->z)==0) { PyObject* result; if(options.debug) fprintf(stderr, "calling %p from %s for %p %p %p %p\n", options.ZM_cb, "divm", res, num, den, mod); result = PyObject_CallFunction(options.ZM_cb, "sOOOO", "divm", res, num, den, mod); if(result != Py_None) { Py_DECREF((PyObject*)res); return result; } } Py_DECREF((PyObject*)num); Py_DECREF((PyObject*)den); Py_DECREF((PyObject*)mod); return (PyObject*)res; } else { PyObject* result = 0; if(options.ZD_cb) { result = PyObject_CallFunction(options.ZD_cb, "sOOO", "divm", num, den, mod); } else { PyErr_SetString(PyExc_ZeroDivisionError, "not invertible"); } Py_DECREF((PyObject*)num); Py_DECREF((PyObject*)den); Py_DECREF((PyObject*)mod); Py_DECREF((PyObject*)res); return result; } } And despite using gmpy 1.01 for six months, I've never encountered this problem before because in the algorithm where I use it, my operands are guaranteed to be invertible by construction, so I have never provoked the corrupting influence of divm(). From grante at visi.com Tue May 2 15:05:23 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 02 May 2006 19:05:23 -0000 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> Message-ID: <125fbbj4rfeah20@corp.supernews.com> On 2006-05-02, John Salerno <johnjsal at NOSPAMgmail.com> wrote: > Yeah, after trying some crazy things, I just wrote it this way: > > def truth_test(seq): > truth = 0 > for item in seq: > if item: > truth += 1 > if truth == 1: > return True > else: > return False > > Not sure I like having to keep a counter though, but the other stuff I > did was really convoluted, like checking to see if the first item was > True, and if it was, popping it from the list and iterating over the > rest of the items (needless to say, the in-place change wasn't helpful). Python knows how to count. :) def countFalse(seq): return len([v for v in seq if not v]) def countTrue(seq): return len([v for v in seq if v]) def truth_test(seq): return countTrue(seq) == 1 -- Grant Edwards grante Yow! I FORGOT to do the at DISHES!! visi.com From gdamjan at gmail.com Wed May 31 18:33:54 2006 From: gdamjan at gmail.com (Damjan) Date: Thu, 01 Jun 2006 00:33:54 +0200 Subject: is a wiki engine based on a cvs/svn a good idea? References: <mailman.6384.1149113085.27775.python-list@python.org> Message-ID: <447e19d2$0$15788$14726298@news.sunsite.dk> > I'm planning to wite a fully featured wiki in Python in one of > frameworks. I've seen some notes about wiki/documentation management > scripts that use SVN as a data storage/versioning. Cool > I've been using SVN a bit but I don't know if it's a good idea to use > it in a wiki engine. Pro: versioning / diffs, Cons: you need your own > svn/cvs repository, can pyLucene or Xapwrap index this? You can certanly index the svn checkout if nothing else. -- damjan From rupole at hotmail.com Thu May 4 05:01:09 2006 From: rupole at hotmail.com (Roger Upole) Date: Thu, 4 May 2006 05:01:09 -0400 Subject: Customize IE to make a toolbar visible References: <1146667058.286119.27920@j33g2000cwa.googlegroups.com> Message-ID: <1146733059_1283@sp6iad.superfeed.net> This does the trick for Google toolbar: import win32com.client ie=win32com.client.Dispatch('internetexplorer.application') ie.Visible=1 ie.ShowBrowserBar('{2318C2B1-4965-11d4-9B18-009027A5CD4F}',True,0) You should be able to just substitute the GUID for the Yahoo toolbar. Roger <brochu121 at gmail.com> wrote in message news:1146667058.286119.27920 at j33g2000cwa.googlegroups.com... > Does anyone know of a way to make a toolbar visible in IE through > automation? I am not speaking about the InternetExplorer.ToolBar that I > have run into on MSDN, but rather want to make a toolbar such as > Yahoo's visibilbe through running my script. > > How would I do this. > > Thanks, > Dave > From john at castleamber.com Thu May 18 19:31:56 2006 From: john at castleamber.com (John Bokma) Date: 18 May 2006 23:31:56 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> Message-ID: <Xns97C7BC8549BA0castleamber@130.133.1.4> "Michael Tobis" <mtobis at gmail.com> wrote: > The relevant corrolary is, "he programs best who programs least". I > would have thought this was conventional wisdom among all dynamic > language communities. Isn't that the whole point? By all means go back > to C++ if you like to have three lines for each idea instead of the > other way around. You disagree: go back. A true zealot. Programming is about writing down ideas in a *clear* and *consistent way*, so that not only the original author is able to read and understand it after 3 months, but also peers. According to your silly rule the shortest book on a subject would be the best. Now why is that false? Why are Perl golf scripts so hard to understand? -- 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 bj_666 at gmx.net Sat May 20 16:48:52 2006 From: bj_666 at gmx.net (Marc 'BlackJack' Rintsch) Date: Sat, 20 May 2006 22:48:52 +0200 Subject: Question about exausted iterators References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <mailman.5914.1147992246.27775.python-list@python.org> <446d8971$0$6053$626a54ce@news.free.fr> Message-ID: <pan.2006.05.20.20.48.50.300489@gmx.net> In <446d8971$0$6053$626a54ce at news.free.fr>, Christophe wrote: > Well, the main reason for such change is and will always be to catch > bugs. The fact is, using duct typing is something very common with the > Python language. Duct typing? I guess you mean duct taping, or duck taping [1] or maybe duck typing. :-) SCNR, Marc 'BlackJack' Rintsch [1] http://www.cybersalt.org/cleanlaugh/images/03/ducktape.htm From larry.bates at websafe.com Thu May 25 13:15:07 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 25 May 2006 12:15:07 -0500 Subject: access to TimesTen using python In-Reply-To: <mailman.6189.1148555050.27775.python-list@python.org> References: <mailman.6189.1148555050.27775.python-list@python.org> Message-ID: <qY6dnbSU_eiGe-jZnZ2dnUVZ_tmdnZ2d@comcast.com> gunsupancar wrote: > is there any module to access > TimesTen in-memory database using python? > I didn't find native one, but TimesTen has ODBC interface that you could use. http://www.compwisdom.com/topics/ODBC From me+python at modelnine.org Sun May 21 16:51:04 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Sun, 21 May 2006 22:51:04 +0200 Subject: proposal: disambiguating type In-Reply-To: <1148238801.796827.56560@j33g2000cwa.googlegroups.com> References: <1148238801.796827.56560@j33g2000cwa.googlegroups.com> Message-ID: <200605212251.05037.me+python@modelnine.org> Am Sonntag 21 Mai 2006 21:13 schrieb gangesmaster: > i suggest splitting this overloaded meaning into two separate builtins: > * type(name, bases, dict) - a factory for types > * typeof(obj) - returns the type of the object While I personally don't find this proposal to be bad, this is something that should only be considered for Python 3000, because it breaks old code in very unnecessary ways (because it's only for "beauty", not for function), considering that most scripts written for Python 1.5.2 still work under current Python without modification, and people expect them to. --- Heiko. From fredrik at pythonware.com Thu May 25 15:39:03 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 25 May 2006 21:39:03 +0200 Subject: how to clear up a List in python? In-Reply-To: <1148567178.295878.305080@u72g2000cwu.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> Message-ID: <e5514h$7uh$1@sea.gmane.org> vbgunz wrote: >> I have new a list , when it hava large number of values, I wonna to >> delete all the values in it,how to do? > > something like this will probably help. > > x = [1,2,3,4,5,6,7,8,9] > y = x > > list([x.pop() for z in xrange(len(x))]) > > print x, y # [] [] if you don't know how to do things, you don't need to post. if you know why this is about the dumbest way to do what you're doing, and you're posted this on purpose, you really need to grow up. </F> From 3dbernard at gmail.com Mon May 29 09:23:10 2006 From: 3dbernard at gmail.com (Bernard Lebel) Date: Mon, 29 May 2006 09:23:10 -0400 Subject: Running Python scripts under a different user In-Reply-To: <447AE2A7.60800@designaproduct.biz> References: <mailman.6246.1148657024.27775.python-list@python.org> <4dolv4F1b8m87U1@uni-berlin.de> <447725C3.2000901@designaproduct.biz> <61d0e2b40605261017l367b4642i5bd0e2208ea502eb@mail.gmail.com> <447AE2A7.60800@designaproduct.biz> Message-ID: <61d0e2b40605290623y28aa586dj1873d0ef87037d24@mail.gmail.com> Thanks Laszlo, I'll check it out. Bernard On 5/29/06, Laszlo Nagy <gandalf at designaproduct.biz> wrote: > > >> > >> From what you wrote, I think that you need to change architecture. You > >> should write your own service rather than write tricky programs. This > >> way you can develop your own security system, and restrict access to > >> specific files/programs. You can write tools that can connect to your > >> service. The service program can be ran on the background, with > >> sufficient privileges. How does it sound? > > > > [Bermard] Any ressource you could point me to as to write services? > > I'm totally unexperienced with that. > I'm sorry, I was out of town in the weekend. You can try to write a > multi-threaded application server that provides services through TCP/IP. > Probably, the easiest to start with an existing framework: > > http://twistedmatrix.com/projects/core/ > http://www.webwareforpython.org/ > > There are many other libraries, you can look for them in the cheeseshop. > > http://cheeseshop.python.org/pypi > > You can also develop your own protocol with SocketServer or xmlrpc: > > http://docs.python.org/lib/module-SocketServer.html > http://docs.python.org/lib/module-xmlrpclib.html > > > Best, > > Laszlo > > From alf at merlin.fayauffre.org Fri May 5 05:47:19 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Fri, 5 May 2006 09:47:19 +0000 (UTC) Subject: Tuple assignment and generators? References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <e-idndayO-NancbZRVn-sQ@speakeasy.net> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> <4c0ke7F13i82oU1@uni-berlin.de> Message-ID: <slrne5m7os.4l1.alf@merlin.fayauffre.org> Le 05-05-2006, Diez <deets at nospam.web.de> nous disait: > The thing you observe as accident is that sometimes "0 is 0" is true just > because of an optimization of number objects allocation. Such things happen > in the "real" world - other examples are string-interning in e.g. the JVM > (and I bet they have a similar scheme to boxed number object allocation as > python has). String interning is available in Python too, by using the intern() builtin function. -- Alexandre Fayolle 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 piet at cs.uu.nl Fri May 12 06:48:12 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Fri, 12 May 2006 12:48:12 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> Message-ID: <m2irobbjtf.fsf@ordesa.lan> >>>>> tsaar2003 at yahoo.com (T) wrote: >T> As you can see, the "constant" A can be modified this easily. But if >T> there were an intuitive mechanism to declare a symbol to be immutable, >T> then there won't be this problem. Mutability is not a property of symbols but of values. So it doesn't make sense to declare an identifier to be immutable. And mutability is tied to the object's type, not to individual instances. What you want can only be obtained if Python would have an immutable variant for each type or would add an immutable attribute to each object. -- Piet van Oostrum <piet at cs.uu.nl> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From ask at me Thu May 11 20:00:41 2006 From: ask at me (AndyL) Date: Thu, 11 May 2006 20:00:41 -0400 Subject: python equivalent of the following program In-Reply-To: <OOQ8g.25220$4L1.15804@newssvr11.news.prodigy.com> References: <FbWdnZazBY8Aqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> <J-CdnRbdnJzNBP7ZnZ2dnUVZ_s-dnZ2d@comcast.com> <t1O8g.85795$dW3.66367@newssvr21.news.prodigy.com> <24-dnWcg5IQETf7ZnZ2dnUVZ_tKdnZ2d@comcast.com> <OOQ8g.25220$4L1.15804@newssvr11.news.prodigy.com> Message-ID: <UtudneBd8PmiQf7ZnZ2dnUVZ_uWdnZ2d@comcast.com> Edward Elliott wrote: > AndyL wrote: > >>Edward Elliott wrote: >> >>>And if the script runs somewhere that stderr is likely to disappear: >>> >>>prog1 = subprocess.Popen(['prog1'], stdout=file1, >>>stderr=subprocess.STDOUT) >> >>Forgot to mention before that the main motivation is to have the same >>code on bot Linux and M$ platforms. >> >>Does subprocess work well on both? > > > yes > > > >>Also how to find out that the 'prog1' e.g. has exited and it is done? > > > prog1.wait() or prog1.poll(). look at the subprocess docs. thx a lot. From philipasmith at blueyonder.co.uk Tue May 30 12:47:10 2006 From: philipasmith at blueyonder.co.uk (Philip Smith) Date: Tue, 30 May 2006 16:47:10 GMT Subject: Multiple Polynomial Quadratic Sieve Message-ID: <iG_eg.242782$xt.233497@fe3.news.blueyonder.co.uk> Just to announce that I have posted an experimental version of MPQS which I am hoping those of a mathematical turn of mind would care to test, comment on and maybe contribute to. There is work to do but it performs very well. The package is available via FTP at http://www.pythonstuff.pwp.blueyonder.co.uk/ account: python password: guest Thanks From reply.in.the.newsgroup at my.address.is.invalid Mon May 29 05:45:01 2006 From: reply.in.the.newsgroup at my.address.is.invalid (Rene Pijlman) Date: Mon, 29 May 2006 11:45:01 +0200 Subject: HTMLParser chokes on bad end tag in comment References: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> <1148891651.141309.263190@38g2000cwa.googlegroups.com> Message-ID: <1hgl725ng2q35vnlltvob42a69ltusai04@4ax.com> Miki: >You can also check out BeautifulSoup >(http://www.crummy.com/software/BeautifulSoup/) which is less strict >than the regular HTML parser. Yes, thanks. Ik this case it was my sitechecker which checks for syntax and broken links, so it was supposed to find the syntax error. BeautifulSoup is not very well suited for validators :-) -- Ren? Pijlman From johnjsal at NOSPAMgmail.com Tue May 23 11:33:40 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 15:33:40 GMT Subject: New beginner to python for advice In-Reply-To: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> References: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> Message-ID: <oXFcg.2147$No6.46785@news.tufts.edu> Minlar Ginger wrote: > HIi all: > I am a new beginner to python, would you like give me some advice on > studying it? > Welcome to list some book on python for me. > Thanks a lot. > I'd say read "Learning Python" (2nd ed.) From johnjsal at NOSPAMgmail.com Thu May 11 11:39:29 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 11 May 2006 15:39:29 GMT Subject: which windows python to use? In-Reply-To: <mailman.5589.1147359382.27775.python-list@python.org> References: <mailman.5589.1147359382.27775.python-list@python.org> Message-ID: <RUI8g.2089$No6.46052@news.tufts.edu> Brian Blais wrote: > Hello, > > Are there any recommendations for which Windows python version to use? > I'd like to see a pros-and-cons description of each, given that > different uses might dictate different versions. The versions I know > (and there are surely more) are: > > 1) download from www.python.org > 2) enthought > 3) activepython FWIW, I would stick to the 'authentic' version of Python (i.e. the first choice). Not that the others are much different, I don't think, but like you said you'll have the newest version from python.org. Also, as a newcomer to Python, I find it more helpful to have to do some things manually, such as installing extra packages/modules that might already come with the other distributions. This way, you learn how to do these things, and you also get a better idea of what really comes with Python and what is bundled on by the other companies. ActivePython is also touted because it comes with an IDE for Windows, but again, it's better to write your code by hand at first and really learn what you're doing. From chris.cavalaria at free.fr Tue May 16 04:47:43 2006 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 16 May 2006 10:47:43 +0200 Subject: IDLE confusion In-Reply-To: <e4c34c$5l6$1@newsreader3.netcologne.de> References: <1147767977.928350.261650@i39g2000cwa.googlegroups.com> <e4c34c$5l6$1@newsreader3.netcologne.de> Message-ID: <446991de$0$7690$626a54ce@news.free.fr> Claudio Grondi a ?crit : > MrBlueSky wrote: > >> Hi, I'm trying to use IDLE to develop My First Python App and my head >> hurts... >> >> I've a file called spalvi.py with this in it: >> from Test import * >> firstTest("Mike") >> >> And a file called Test.py with this in it: >> def firstTest(name): >> print "Yo",name >> >> I open spalvi.py with IDLE and Run it. It says "Yo Mike". >> I use the File menu to open Test.py and change the message from "Yo" to >> "Hi". >> I Run it again.... it still says "Yo Mike" :-( >> I close everything down, open spalvi.py with IDLE and Run it again. It >> says "Hi Mike". >> >> So I'm obviously not using IDLE in the "right" way. But what *is* the >> "right" way, when you're trying to develop using several source files? >> >> John >> > You need some deeper understanding of what import does and what happens > when you import again (after the library files have changed). > Try in the IDLE menu [Shell] "Restart Shell" (Ctrl+F6) each time you > have changed something in your files - this "resets" anything previously > imported, which stays the same way otherwise. > > Claudio And I though that "bug" was fixed already :) Try to use something else than IDLE for your code editing. Use Scite for example. http://www.scintilla.org/SciTE.html From sybrenUSE at YOURthirdtower.com.imagination Wed May 17 12:47:33 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 17 May 2006 18:47:33 +0200 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> Message-ID: <slrne6mkt5.hoa.sybrenUSE@schuimige.stuvel.eu> Andy Sy enlightened us with: > Like I said, you'll *NEVER* get that fancy shmancy 'semantic > indentation' idea to work properly in the most basic utilities which > have the 8-space tabs assumption hardcoded in them. Fair enough. How much code is viewed with less and cat, and how much is viewed using smart viewers/editors? I think the majority is viewed using the latter. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From ibr at radix50.net Mon May 22 17:54:27 2006 From: ibr at radix50.net (Baurzhan Ismagulov) Date: Mon, 22 May 2006 23:54:27 +0200 Subject: logging Message-ID: <20060522215427.GD5603@radix50.net> Hello all, I want that each module has its own logger. I've defined the following config file: [formatters] keys=f01 [handlers] keys=console [loggers] keys=root,l01 [formatter_f01] format=%(name)s: %(message)s [handler_console] class=StreamHandler args=[] formatter=f01 [logger_root] level=CRITICAL handlers=console [logger_l01] level=DEBUG qualname=l01 handlers=console I use it like this: import logging import logging.config logging.config.fileConfig('a.conf') log = logging.getLogger('l01') log.debug('zzz') I want logger_root to go to /dev/null, so I've configured it with level CRITICAL. My understanding is that in this way debug messages are not printed on logger_root's handler. However, running the program results in the message being printed twice. What is the problem? Thanks in advance, Baurzhan. From nd51 at le.ac.uk Wed May 3 12:19:25 2006 From: nd51 at le.ac.uk (N.Davis) Date: Wed, 03 May 2006 17:19:25 +0100 Subject: Need Plone Information In-Reply-To: <mailman.5269.1146669645.27775.python-list@python.org> References: <mailman.5269.1146669645.27775.python-list@python.org> Message-ID: <e3al6e$36g$1@south.jnrs.ja.net> bruce wrote: > I've never used Python/Plone, and am wondering if I can talk with anyone > who's used Plone. I'm trying to determine if Plone could be easily used for > a potential application. > this might help (where to start): http://plone.org/documentation/how-to/read-documentation Nick From mrmakent at cox.net Thu May 25 20:13:57 2006 From: mrmakent at cox.net (Mike Kent) Date: 25 May 2006 17:13:57 -0700 Subject: Anyone compiling Python 2.3 on an SCO OpenServer 5 box? In-Reply-To: <4Brdg.278$%U1.166@nntpserver.swip.net> References: <1148577884.528595.157910@j33g2000cwa.googlegroups.com> <4Brdg.278$%U1.166@nntpserver.swip.net> Message-ID: <1148602437.460709.114830@u72g2000cwu.googlegroups.com> I need to compile Python on OpenServer 5 because I need to 'freeze' our Python app, and running 'freeze' requires a working, compilable source installation of Python. From claird at lairds.us Mon May 15 11:25:34 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 15 May 2006 15:25:34 +0000 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> <tj2kj3-82b.ln1@lairds.us> <1hfc2sb.8hxfcv13c5v6nN%aleax@mac.com> Message-ID: <e4jmj3-apg.ln1@lairds.us> In article <1hfc2sb.8hxfcv13c5v6nN%aleax at mac.com>, Alex Martelli <aleax at mac.com> wrote: . . . >I'd be a bit worried about having len(x) change x's state into an >unusable one. Yes, it happens in other cases (if y in x:), but adding >more such problematic cases doesn't seem advisable to me anyway -- I'd >evaluate this proposal as a -0, even taking into account the potential >optimizations to be garnered by having some iterables expose __len__ >(e.g., a genexp such as (f(x) fox x in foo), without an if-clause, might >be optimized to delegate __len__ to foo -- again, there may be semantic >alterations lurking that make this optimization a bit iffy). > > >Alex Quite so. My proposal isn't at all serious; I'm doing this largely for practice in thinking about functionalism and its complement in Python. However, maybe I should take this one step farther: while I think your caution about "attractive nuisance" is perfect, what is the precise nuisance here? Is there ever a time when a developer would be tempted to evaluate len() on an iterable even though there's another approach that does NOT impact the iterable's state? On the other hand, maybe all we're doing is observing that expanding the domain of len() means we give up guarantees on its finiteness, and that's simply not worth doing. From johnjsal at NOSPAMgmail.com Tue May 16 10:15:43 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 14:15:43 GMT Subject: my cryptogram program In-Reply-To: <4468f2c4$0$7135$626a54ce@news.free.fr> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <gh5ag.2100$No6.46182@news.tufts.edu> <4468f2c4$0$7135$626a54ce@news.free.fr> Message-ID: <j8lag.2103$No6.46276@news.tufts.edu> Bruno Desthuilliers wrote: > Too late ! You asked for it, you get it !-) Good, I desperately need it! :) > PUNCT_SPACE_SET = set(string.punctuation + string.whitespace) > def make_set(original): > return ''.join(set(original) - PUNCT_SPACE_SET) Interesting! Always learning new, weird ways to do things! > <splitting-hairs> Nope, I was actually wondering about what to name some of my functions and variables. From phddas at yahoo.com Tue May 9 16:32:16 2006 From: phddas at yahoo.com (Gary Wessle) Date: 10 May 2006 06:32:16 +1000 Subject: installing numpy References: <877j4v5ukc.fsf@localhost.localdomain> <6Y%7g.11622$EC.10694@tornado.rdc-kc.rr.com> Message-ID: <8764kfkkhb.fsf@localhost.localdomain> "Raymond L. Buvel" <levub137 at wi.rr.com> writes: > Gary Wessle wrote: > > Hi > > > > I am trying to install NumPy in my debian/testing linux > > 2.6.15-1-686. > > > <snip> > > When installing from source on a Debian system, you want the installed > package to wind up in /usr/local/lib/python2.x/site-packages (where x > represents the version of Python you are running the installer from). > This allows you to keep it separate from the apt managed directories and > allows for easy removal/upgrade. So the command you want to execute > from root is > > python setup.py install --prefix=/usr/local sorry if this is boring since I am not a seasoned Linux user. setup.py isn't located at the root, do you mean, execute the command above from root, as to do this :~$ cd / :/$ python setup.py install --prefix=/usr/local or :/$ python home/fred/numpy-0.9.6/setup.py install --pref... or AS root :/# python setup.py install --prefix=/usr/local or :/# python home/fred/numpy-0.9.6/setup.py install --pref... > > By the way, to get NymPy to use the high-performance libraries, you must > install these libraries and the associated -dev packages before running > the Python install. I wish to know the debian names for those packages, my first guess would be refblas3 under testing since blas is not available for debian/testing, there is also refblas3-dev Basic Linear Algebra Subroutines 3, static library which I don't have installed. would refblas3 be all what NymPy need to the high-performance? thanks From cvanarsdall at mvista.com Fri May 19 14:53:07 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 19 May 2006 11:53:07 -0700 Subject: Request for comments on python distributed technologies Message-ID: <446E1413.70807@mvista.com> Hey everyone, another question for the list. In particular i'm looking for comments on some of the distributed technologies supported in python. Specifically, I'm looking at XML-RPC, RPyC, CORBA, and Twisted. Before you offer any comments let me talk about what i'm doing a little bit. Right now I'm creating an execution framework. The framework aims to allow users to create a modular system by which engineers can mitigate some of the issues seen in large complex systems. By using modules the system hopes to allow the system to change but allow engineers to re-use as much code as possible. By using the modules in a framework we hope to encapsulate the entire system to that it is controllable in the sense that we can generate and catch errors anywhere in the system and exit gracefully, things like that. There's a lot more to it but the motivation spawn from our system where the system kept needing to adapt to support changes in our company. These changes over time have resulted in a large number of "hacks". The hope of the modules is to make the code a lot cleaner and organized so that the system can operate in whatever way it needs to without having so many hacks. This system I use also operates in a primitive distributed environment. Currently, these are ssh calls to other nodes that then execute other python scripts and shell commands. This is the next piece I'm interested in moving away from. With all that being said, I've come across those four technologies so far and I've been looking into them. I was wondering if anyone had any comments, pros/cons, or suggestions of other distributed technologies to take a look at. I intend to integrate the distributed technology directly into the framework making it easy for developers to distribute tasks. Anyhow, any comments would be greatly appreciated! I also hope to release this framework as an open-source project when its finished, so again I community input is important. Thanks! .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From cvanarsdall at mvista.com Wed May 17 15:02:46 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 17 May 2006 12:02:46 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <e4fqga$ep3$1@sea.gmane.org> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> Message-ID: <446B7356.4050202@mvista.com> Andy Sy wrote: > Carl J. Van Arsdall wrote: > > >>> Next major objection then, how can one practically use 'tabs as >>> semantic indentation' without screwing up formatting of code like >>> the below?? >>> >>> >>> def sqlcall(): >>> cursor.execute('select id, item, amount, field4, field5, field6'+ >>> 'from table1 where amount>100') >>> >>> >>> >> Why couldn't you tab your third line over as close as possible to the >> start of the quote then use a couple spaces? Then the tabs would work >> just fine and you could still have your pretty line. >> > > > This will break if someone tries to view my code using different > tab settings from the one I'm using > Uh, no it won't. It should be read in as "one tab and two spaces" regardless of the tabstop setting. .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From onurb at xiludom.gro Fri May 19 06:42:32 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 12:42:32 +0200 Subject: calling python functions using variables In-Reply-To: <mailman.5934.1148032680.27775.python-list@python.org> References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <e4k443$el5$02$1@news.t-online.com> <mailman.5934.1148032680.27775.python-list@python.org> Message-ID: <446da180$0$10184$636a55ce@news.free.fr> Ben Finney wrote: > Peter Otten <__peter__ at web.de> writes: (snip) >> >>You want >>getattr(commands, VARIABLE)() > > You'll also need to anticipate the situation where the value bound to > VARIABLE is not the name of an attribute in 'commands'. > > Either deal with the resulting NameError exception (EAFP[0]) try: getattr(commands, VARIABLE)() except NameError: print >> sys.stderr, "Unknown command", VARIABLE > or test > first whether the attribute exists (LBYL[1]). command = getattr(commands, VARIABLE, None) if command is None: print >> sys.stderr, "Unknown command", VARIABLE else: command() I'd go for the first solution. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jim.lewis at miclog.com Sat May 27 06:16:28 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 27 May 2006 03:16:28 -0700 Subject: Pyrex speed Message-ID: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> Has anyone found a good link on exactly how to speed up code using pyrex? I found various info but the focus is usually not on code speedup. From robert.kern at gmail.com Mon May 8 02:41:44 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 08 May 2006 01:41:44 -0500 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> Message-ID: <e3mp79$icb$1@sea.gmane.org> ankyhe at gmail.com wrote: > L = [4,3,2,1] > L=L.sort() > L will refer to None, why L.sort() don't return the L? > I want to ask why the designer of Python do so? http://www.python.org/doc/faq/general/#why-doesn-t-list-sort-return-the-sorted-list -- 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 molasses0 at gmail.com Wed May 24 07:34:14 2006 From: molasses0 at gmail.com (molasses) Date: Wed, 24 May 2006 21:34:14 +1000 Subject: PEP 3102 for review and comment Message-ID: <5384bedc0605240434l645281e8ub40daa730457559d@mail.gmail.com> I don't mind the naked star and will be happy if thats what we end up with. Though how about using *None? I think that makes the intention of the function clearer. eg. def compare(a, b, *None, key=None): Which to me reads as "no further positional arguments". Or alternatively: def compare(a, b, *0, key=None): -- Mark From gene.tani at gmail.com Mon May 29 10:52:33 2006 From: gene.tani at gmail.com (gene tani) Date: 29 May 2006 07:52:33 -0700 Subject: summarize text In-Reply-To: <1148903386.095226.249270@38g2000cwa.googlegroups.com> References: <1148903386.095226.249270@38g2000cwa.googlegroups.com> Message-ID: <1148914353.156936.309040@g10g2000cwb.googlegroups.com> robin wrote: > hello list, > > does anyone know of a library which permits to summarise text? i've > been looking at nltk but haven't found anything yet. any help would be unclear what you're asking, maybe look at: http://www.cs.waikato.ac.nz/~ml/weka/index.html http://www.kdnuggets.com/software/suites.html http://www.ailab.si/orange http://mallet.cs.umass.edu/index.php/Main_Page http://minorthird.sourceforge.net/ http://www.dia.uniroma3.it/db/roadRunner/ http://www.lemurproject.org/ From vbgunz at gmail.com Tue May 23 07:10:09 2006 From: vbgunz at gmail.com (vbgunz) Date: 23 May 2006 04:10:09 -0700 Subject: Don't wish to give up on a Tkinter GUI Builder :( In-Reply-To: <1148371674.932205.83160@j55g2000cwa.googlegroups.com> References: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> <1148371674.932205.83160@j55g2000cwa.googlegroups.com> Message-ID: <1148382609.644438.267020@j55g2000cwa.googlegroups.com> Thank you very much for the link and info. It looks promising but I am still on the lookout for a drag-n-drop Gui builder like vltc so if anyone has more links to new projects I am definitely interested! PS. I do love the code generated from rapyd! From ilias at lazaridis.com Sat May 20 14:51:03 2006 From: ilias at lazaridis.com (Ilias Lazaridis) Date: Sat, 20 May 2006 21:51:03 +0300 Subject: [OT] - Requesting Comments for "Open Source Rework" Business Concept Message-ID: <e4noep$b0h$1@mouse.otenet.gr> You may remember the request for comments at the start of this year: http://groups.google.com/group/comp.lang.python/msg/b0e3487ef8b13eed http://groups.google.com/group/comp.lang.ruby/msg/b0e3487ef8b13eed - The services of "Lazaridis System Design" have reached pre-release state and will be soon released to the public: http://lazaridis.com/services/index.html You can find the overall picture of how the services interconnect with other company activities here: http://lazaridis.com/pj/index.html The target groups for the services are mainly: * Open Source Projects * Individuals and Vendors (intrested in open source projects) * Commercial Vendors (proprietary systems) I would like to ask for feedback subjecting the business concept especialy in the context of Open Source Projects. You can reply publically or with private email. - The initial plan is the following: The "Initial Analysis" week has a low rate (trial rate). This is to allow Vendors & Projects to try the services for a lower investment: http://lazaridis.com/efficiency/graph/analysis.html Small Scale Open Source Projects can benefit from very special prices, which can reach 1/5th of the current rates (80% off). If the product category is currently under review, an open source project will be charged only a-day-for-a-week: http://case.lazaridis.com/multi/wiki Actual Subsystems is for following: * persistency systems (python, ruby) * complete frameworks, which contain persistency (python, ruby) * project hosts and collaboration tools (python, ruby) As an example, python persistence candidates for the reduced rates would be "Axiom", "Django" and "SQLObject": http://case.lazaridis.com/multi/wiki/Persist - Audits of other listed Subsystems will be charged with 2/5th of the current rates. Large Scale Open Source Projects and/or fully commercialized Open Source Projects will be charged with 3/5th (actual subsystems) or 4/5th (scheduled subsystems). Commercial Entities and Open Source Projects not within the Subsystem listing will be charged with 5/5ths of the rates. - Another possibility would be to make the audits freely and to ask for a small fee from the end-users which use the results (e.g. paypal link within the section). - This is a draft version and the facts and interconnections are most possibly not demonstrated very clearly. You feedback will assist to clarify / adjust the concept. Thank you very much for your time. . -- http://lazaridis.com From jparlar at cogeco.ca Thu May 4 00:52:44 2006 From: jparlar at cogeco.ca (Jay Parlar) Date: Thu, 4 May 2006 00:52:44 -0400 Subject: pythonic way to sort In-Reply-To: <1146715940.923869.91730@u72g2000cwu.googlegroups.com> References: <1146715940.923869.91730@u72g2000cwu.googlegroups.com> Message-ID: <f2079f01059e1bcc1cfd41a7b9d4b0ec@cogeco.ca> On May 4, 2006, at 12:12 AM, micklee74 at hotmail.com wrote: > hi > I have a file with columns delimited by '~' like this: > > 1SOME STRING ~ABC~12311232432D~20060401~00000000 > 2SOME STRING ~DEF~13534534543C~20060401~00000000 > 3SOME STRING ~ACD~14353453554G~20060401~00000000 > > ..... > > What is the pythonic way to sort this type of structured text file? > Say i want to sort by 2nd column , ie ABC, ACD,DEF ? so that it becomes > > 1SOME STRING ~ABC~12311232432D~20060401~00000000 > 3SOME STRING ~ACD~14353453554G~20060401~00000000 > 2SOME STRING ~DEF~13534534543C~20060401~00000000 > ? > I know for a start, that i have to split on '~', then append all the > second columns into a list, then sort the list using sort(), but i am > stuck with how to get the rest of the corresponding columns after the > sort.... > > thanks... > A couple ways. Assume that you have the lines in a list called 'lines', as follows: lines = [ "1SOME STRING ~ABC~12311232432D~20060401~00000000", "3SOME STRING ~ACD~14353453554G~20060401~00000000", "2SOME STRING ~DEF~13534534543C~20060401~00000000"] The more traditional way would be to define your own comparison function: def my_cmp(x,y): return cmp( x.split("~")[1], y.split("~")[1]) lines.sort(cmp=my_cmp) The newer, faster way, would be to define your own key function: def my_key(x): return x.split("~")[1] lines.sort(key=my_key) The key function is faster because you only have to do the split("~")[1] once for each line, whereas it will be done many times for each line if you use a comparison function. Jay P. From johnjsal at NOSPAMgmail.com Mon May 8 11:49:26 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 15:49:26 GMT Subject: which is better, string concatentation or substitution? In-Reply-To: <e3nnv0$jbm$1@reader1.panix.com> References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <roy-A5FC8E.09284008052006@reader1.panix.com> <IWH7g.2053$No6.45672@news.tufts.edu> <e3nnv0$jbm$1@reader1.panix.com> Message-ID: <aMJ7g.2058$No6.45704@news.tufts.edu> Roy Smith wrote: > OK, here's a quick tutorial to "big-oh" notation. Wow, that was fantastic (and interesting)! Did you just write that? That should be saved somewhere! Mind if I post it on my website? (don't worry, no one goes there anyway) :) From john at castleamber.com Fri May 19 21:51:11 2006 From: john at castleamber.com (John Bokma) Date: 20 May 2006 01:51:11 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> Message-ID: <Xns97C8D420E22castleamber@130.133.1.4> Edward Elliott <nobody at 127.0.0.1> wrote: > John Bokma wrote: > >> Edward Elliott <nobody at 127.0.0.1> wrote: >> >>> The question is how to count explicit names like module.class.func; >>> should that be 1 identifier or 3? Counting as 3 would reward things >>> like "from X import *" which are generally frowned on in python while >>> 'use MOD qw(id)' is encouraged in perl. >> >> Not by me, and I doubt it is in general. > > Well it's all over the Perl Cookbook. Yeah, sure, all over. Maybe check the book again. It is used in some examples, sure. And it even explains how it works. Don't forget that most of the book was written around 1998. Yes, 8 years ago. You can even find examples on my site that use imported functions (which I will fix, because I frown upon it :-) ). But I doubt you can find a majority in the perl community that *encourages* the use of imported functionality. -- 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 micklee74 at hotmail.com Mon May 8 03:44:39 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 8 May 2006 00:44:39 -0700 Subject: printing out elements in list Message-ID: <1147074279.391832.158350@y43g2000cwc.googlegroups.com> hi i have a list with contents like this alist = ['>QWER' , 'askfhs', '>REWR' ,'sfsdf' , '>FGDG', 'sdfsdgffdgfdg' ] how can i "convert" this list into a dictionary such that dictionary = { '>QWER':'askfhs' , '>REWR' : 'sfsdf' , '>FGDG', 'sdfsdgffdgfdg' } thanks From ullrich at math.okstate.edu Tue May 9 06:35:47 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Tue, 09 May 2006 05:35:47 -0500 Subject: A critic of Guido's blog on Python's lambda References: <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> <NUP7g.17$G22.12@fe11.lga> Message-ID: <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> On Mon, 08 May 2006 18:46:57 -0400, Ken Tilton <kentilton at gmail.com> wrote: > > >David C. Ullrich wrote: >> On 08 May 2006 12:53:09 -0700, tfb at conquest.OCF.Berkeley.EDU (Thomas >> F. Burdick) wrote: >> >> >>>Ken Tilton <kentilton at gmail.com> writes: >>> >>> >>>>No, you do not want on-change handlers propagating data to other >>>>slots, though that is a sound albeit primitive way of improving >>>>self-consistency of data in big apps. The productivity win with >>>>VisiCalc was that one simply writes rules that use other cells, and >>>>the system keeps track of what to update as any cell changes for >>>>you. You have that exactly backwards: every slot has to know what >>>>other slots to update. Ick. >>> >>>No no, that's fine and the way it should be: when you change a slot, >>>it should know who to update. And that's also the way it works in >>>Cells. The trick is that Cells takes care of that part for you: >> >> >> I'm glad you said that - this may be what he meant, but it seems >> more plausible than what he actually said. > >There may be some confusion here because there are two places for code >being discussed at the same time, and two sense of propagation. > >the two places for code are (1) the rule attached to A which is >responsible for computing a value for A and (2) a callback for A to be >invoked whenever A changes. Why the difference? > >In Cells, A is a slot such as 'background-color'. Whenever that changes, >we have to do something more. On Mac OS9 it was "InvalidateRect" of the >widget. In Cells-Tk, it is: > (Tcl_interp "mywidget configure -background <new color>") > >In my OpenGL GUI, it is to rebuild the display-list for the widget. > >That is the same no matter what rule some instance has for the slot >background-color, and different instances will have different rules. > >As for propagating, yes, Cells propagates automatically. More below on >that. What I saw in the example offered was a hardcoded on-change >callback that was doing /user/ propagation form B to A (and B to A! ... >doesn't that loop, btw? No, there's no looping in the example. Yes, the code determining what b returns should be attached to b instead of to a, but the code I gave does work as advertised. (I mean give me a break - I provided a sample use so you could simply run it. Installing Python is not hard.) If you, um, look at the code you see that "cells.a = 42" triggers cells.__setattr__, which fires a's callback; the callback then reaches inside and sets the value of b _without_ going through __setattr__, hence without triggering b's callback. In Cells you can't have A depend on B and also B depend on A? That seems like an unfortunate restriction - I'd want to be able to have Celsius and Farenheit, so that setting either one sets the other. Of course if there are no loops it's easier to see how you managed to do the stuff you were talking about elsewhere, (at least sometimes) delaying execution until needed. >Anyway...) > >> >> >>>all >>>the *programmer* has to care about is what values a slot depends on -- >>>Cells takes care of inverting that for you, which is important because >>>that's a job that a computer is much better at than a human. >> >> >> Fine. I suppose that is better; if b is going to return a + 1 >> the fact that this is what b returns should belong to b, not >> to a. So a has an update list including b, so when a's value >> is set a tells b it needs to update itself. >> >> If we're allowed to pass (at some point, to some constructor >> or other) something like (b, a + 1, [a]), which sets up a >> cell b that shall return a + 1, and where the [a] is used >> in the constructor to tell a to add b to a's update list >> then this seems like no big deal. >> >> And doing that doesn't seem so bad - now when the programmer >> is writing b he has to decide that it should return a + 1 >> and also explicitly state that b shall depend on a; this >> is all nice and localized, it's still _b_ telling _a_ to >> add b to a's update list, and the programmer only has >> to figure out what _b_ depends on when he's writing _b_. >> Doesn't seem so bad. >> >> But of course it would be better to be able to pass just >> something morally equivalent to (b, a + 1) to whatever >> constructor and have the system figure out automatically >> that since b returns a + 1 it has to add a to b's update >> list. There must be some simple trick to accomplish that >> (using Python, without parsing code). > >Right, you do not want to parse code. It really would not work as >powerfully as Cells, which notice any dynamic access to another cell >while a rule is running. So my rule can call a function on "self" (the >instance that wons the slot being calculated, and since self can have >pointers to other instances, the algorithm can navigate high and low >calling other functions before finally reading another ruled slot. You >want to track those. > >> Exactly what the trick is I >> don't see immediately. > >To compute a value for a slot that happens to have a rule associated >with it, have a little cell datastructure that implements all this and >associate the cell with the slot and store a pointer to the rule in the >cell. Then have a global variable called *dependent* and locally: > > currentdependent = *dependent* > oldvalue = cell.value > newvalue = call cell.rule, passing it the self instance > *dependent* = currentvalue > > if newvalue not = oldvalue > call on-change on the slot name, self, newvalue and oldvalue > (the on-chnage needs to dispatch on as many arguments as > the language allows. Lisp does it on them all) > >In the reader on a slot (in your getattr) you need code that notices if >the value being read is mediated by a ruled cell, and if the global >*dependent* is non empty. If so, both cells get a record of the other >(for varying demands of the implementation). > >> >> In Cells do we just pass a rule using other cells to >> determine this cell's value, or do we also include >> an explicit list of cells that this cell depends on? > >Again, the former. Just write the rule, the above scheme dynamically >figures out the dependencies. Note then that dependencies vary over time >because of different branches a rule might take. > >I want to reassure the community that this (nor the spreadsheet analogy ><g>) is not just my crazy idea. In 1992: > > http://www.cs.utk.edu/~bvz/active-value-spreadsheet.html > >"It is becoming increasingly evident that imperative languages are >unsuitable for supporting the complicated flow-of-control that arises in >interactive applications. This paper describes a declarative paradigm >for specifying interactive applications that is based on the spreadsheet >model of programing. This model includes multi-way constraints and >action procedures that can be triggered when constraints change the >values of variables." > >Cells do not do multi-way constraints, btw. My _guess_ is that a "multi-way constraint" is something like what's above, where A depends on B and B depends on A? >Nor partial constraints. To >hard to program, because the system gets non-deterministic. That kinda >killed (well, left to a small niche) the whole research programme. I >have citations on that as well. :) > >kenny ************************ David C. Ullrich From danmcleran at yahoo.com Fri May 26 15:12:34 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 26 May 2006 12:12:34 -0700 Subject: PIL problem with biprocessor hardware In-Reply-To: <1148665221.735821.211520@y43g2000cwc.googlegroups.com> References: <1148661656.407762.147020@j73g2000cwa.googlegroups.com> <1148663531.254814.301790@i40g2000cwc.googlegroups.com> <1148665221.735821.211520@y43g2000cwc.googlegroups.com> Message-ID: <1148670754.148116.23950@y43g2000cwc.googlegroups.com> I wonder if there are other threads accessing image? Maybe image isn't fully initialized by some other thread before this code accesses it? It's hard to say what's going wrong. I don't believe that an SMP system would have any bearing on an application unless it uses multiple threads of execution. I wonder if From nospam at nospam.net Thu May 11 00:53:45 2006 From: nospam at nospam.net (Matthew Graham) Date: Thu, 11 May 2006 05:53:45 +0100 Subject: Nested loops confusion In-Reply-To: <W8GdnaVYdtMnX__ZRVny1A@giganews.com> References: <W8GdnaVYdtMnX__ZRVny1A@giganews.com> Message-ID: <J9-dnY5PeKHEXv_ZRVnytA@giganews.com> Oops, I forget to reset the j after the inner loop. Always manage to work these things out just after asking for help! ;-) Matthew Graham wrote: > Hi, > > I expect this is very obvious for anyone who knows what they're doing - > but I don't understand what's the problem with the following code. I > was intending that the program cycle through all i and j (ie. all > possible (i,j) coordinates, but the output when I run the program shows > me up to > > "1 > 99 > plot 3 > 1 > 100 > plot 2 > done j" > > and doesn't perform the print functions for any i > 1. > > Help much appreciated! :) > > Matt > > > corna = int(raw_input("CornA? ")) > cornb = int(raw_input("CornB? ")) > side = int(raw_input("Side? ")) > i = 0 > j = 0 > for i in range(100): > for j in range(100): > x = corna + i * side / 100 > y = cornb + j * side / 100 > c = int(x^2 + y^2) > if c%3 == 1: > print i > print j > print "plot 1" > elif c%3 == 2: > print i > print j > print "plot 2" > elif c%3 == 0: > print i > print j > print "plot 3" > print "done j" > print "Done i" > > From dsuch at gefira.pl Sun May 7 10:41:39 2006 From: dsuch at gefira.pl (Dariusz Suchojad) Date: Sun, 07 May 2006 16:41:39 +0200 Subject: MQSeries based file transfers using the pymqi module In-Reply-To: <125mvj5pmi2au7e@corp.supernews.com> References: <125mvj5pmi2au7e@corp.supernews.com> Message-ID: <e3l0vt$45q$1@atlantis.news.tpi.pl> Andrew Robert wrote: > Hi everyone, Hello, > Has anyone developed a pymqi module based file transfer method for use > with WebSphere MQSeries v5.3? > > If so, would it be possible to point me towards examples of how this > was done? I'm not sure I understand your question. Webshpere MQ expects your code to give it a stream of bytes, there's nothing file-specific in using base WMQ so it's your application's job to read a file, put its contents onto the desired queue, and to get it off the queue some time later. If the code below is not what you need then feel free to ask a more specific question :-) import pymqi as mq # Queue manager name qm_name = "M01" # Listener host and port listener = "127.0.0.1(1414)" # Channel to transfer data through channel = "SYSTEM.DEF.SVRCONN" # Input/output queue name queue_name = "Q01" # Make some data file_name = "C:\\sample.txt" sample_data = "Hello from PyMQI." open(file_name,"w").write(sample_data) # Connect to queue manager qm = mq.QueueManager(None) qm.connectTCPClient(qm_name, mq.cd(), channel, listener) # Put a message onto the queue queue = mq.Queue(qm, queue_name) data = open(file_name).read() queue.put(data) # Close the queue, queue.put has implicitly opened the queue for output # so we can't use the same pymqi.Queue object for getting the messages # off the queue queue.close() # Now get the message, queue.get will implicitly open the queue for # input queue = mq.Queue(qm, queue_name) msg = queue.get() queue.close() # Here's the message contents print msg -- Dariusz Suchojad From sjmachin at lexicon.net Fri May 19 17:33:26 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 May 2006 14:33:26 -0700 Subject: Encode exception for chinese text References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> <1148037335.595690.49030@g10g2000cwb.googlegroups.com> <1148039249.873491.234770@38g2000cwa.googlegroups.com> <1148042447.460782.156990@j73g2000cwa.googlegroups.com> <446DD95E.4080802@v.loewis.de> Message-ID: <1148074406.445310.278570@j73g2000cwa.googlegroups.com> MvL wrote: > Also, *by definition*, though :-) Ah yes, indeed; and thanks for reminding me. Aside: Similar definition, but not similar design: IMHO utf-8 sits on top of ASCII like a rose on a stalk, whereas gb18030 sits on top of gb2312 like a rhinoceros on a unicycle :-) Cheers, John From ullrich at math.okstate.edu Thu May 4 11:10:42 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Thu, 04 May 2006 10:10:42 -0500 Subject: Multiple Version Install? References: <gbtj52l54trlhekcht3mgdb8s60aa4k83d@4ax.com> <mailman.5333.1146752332.27775.python-list@python.org> Message-ID: <3b6k52dp4l4grl985dv26jjmt2uvs7mqpl@4ax.com> On Thu, 4 May 2006 16:17:57 +0200, "Fredrik Lundh" <fredrik at pythonware.com> wrote: >David C.Ullrich wrote: > >> Would there be issues (registry settings, environment >> variables, whatever) if a person tried to install >> versions 1.x and 2.x simultaneously on one Windows >> system? Windows 98, if it matters. >> >> (I can handle the file associations with no problem.) > >in general, no. Excellent. Thanks. >(I usually have about a dozen Python's, or more, on most of my >windows boxes) > >however, applications that look in the registry may only find the >last one you've installed. > ></F> > > ************************ David C. Ullrich From samschul at pacbell.net Fri May 19 12:57:22 2006 From: samschul at pacbell.net (sam) Date: 19 May 2006 09:57:22 -0700 Subject: The use of PyW32_BEGIN_ALLOW_THREADS and PyW32_END_ALLOW_THREADS Message-ID: <1148057842.384971.132910@j55g2000cwa.googlegroups.com> The follllowing code lifted from Mark Hammond Pywin32 code shows and example of calling the Windows Kernel32 GetTickCount(),using PyW32_BEGIN_ALLOW_THREADS and PYW32_END_ALLOW_THREADS. My Code does not use this,but uses SetThreadAffinityMask(GetCurrentThread(),1). My questions are: 1) What is the difference? 2) What happens after I leave my function, to the previous threads that I may have had running? 3) Should I be using the BEGIN/END ALLOW_THREADS? / @pymethod string|win32api|GetTickCount|Returns the number of milliseconds since windows started. static PyObject * PyGetTickCount(PyObject * self, PyObject * args) { if (!PyArg_ParseTuple (args, ":PyGetTickCount")) return NULL; PyW32_BEGIN_ALLOW_THREADS DWORD count = GetTickCount(); PyW32_END_ALLOW_THREADS return Py_BuildValue("l",(long)count); } Now my code uses the Microsoft "SetThreadAffinityMask(GetCurrentThread(),1)" // // PROGRAMMER: Samuel W. Schulenburg // DATE: May 18,2006 // // FUNCTION: double dMyClock() // // DESCRIPTION: This function will return the seconds since the system was started // as a double. If a call to QueryPerformanceFrequency() returns a true // then QueryPerformanceCounter() will be used else the standard 'C' // dMyClock() function will be used. // // PARAMETERS: None // // RETURN: double The seconds passed sense the system was started // double dMyClock() { double dLow; double dHigh; if(iPerformanceClocks == 1) // if the hardware supports the high performance clock { SetThreadAffinityMask(GetCurrentThread(),1); QueryPerformanceCounter(&liPerformanceCount); dLow = (double)liPerformanceCount.LowPart; dHigh = (double)(liPerformanceCount.HighPart)*(4294967296.0); return((dLow+dHigh)/dTicksPerSecond); } else // use the standard C clock function return((double) (clock()/dTicksPerSecond)); } From saint.infidel at gmail.com Tue May 16 11:00:54 2006 From: saint.infidel at gmail.com (infidel) Date: 16 May 2006 08:00:54 -0700 Subject: what is the difference between tuple and list? In-Reply-To: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> References: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> Message-ID: <1147791654.513678.309360@i39g2000cwa.googlegroups.com> > is there any typical usage that shows their difference? I think the general idea is to use lists for homogenous collections and tuples for heterogenous structures. I think the database API provides a good usage that shows their differences. When you do cursor.fetchall() after executing a query, you get back a list of tuples. Each tuple is one "record" from the cursor. "tuple" is even the term used in relational database theory when talking about a table row. You shouldn't be able to add or remove fields from a query result, so using a tuple is a perfect match for this. On the other hand, you can certainly add, delete, or replace entire tuples in the result set, so it makes sense to use a list to hold the set of tuples. From nomail at nixmail.com Thu May 4 07:34:16 2006 From: nomail at nixmail.com (DarkBlue) Date: Thu, 04 May 2006 19:34:16 +0800 Subject: Pythoncard question Message-ID: <4459e6b8@127.0.0.1> I am trying to port a Delphi database application to python on linux with a firebird database backend and I am using pythoncard to recreate the gui. I will have about 25 delphi forms to be recreated and I would like to know what is the best way to call them up from within each other . There is a main screen where I must be able to call up any of the subscreens and on any given subscreen there would be buttons to call up 1-5 of the other subscreens or go back to the mainscreen. The database is connected on the mainscreen and relevant connections/cursors shall be accessible from any of the subscreens. While I am able to connect to the database and create the different screens I am stumped at how to efficiently call them up and pass the cursors between them as needed. Sorry for the long post. Thanks for any hint Db From heidi.hunter at fantasy-interactive.com Mon May 22 08:26:41 2006 From: heidi.hunter at fantasy-interactive.com (heidi.hunter at fantasy-interactive.com) Date: 22 May 2006 05:26:41 -0700 Subject: Running script in __main__ shows no output in IDLE Message-ID: <1148300801.759984.102100@j55g2000cwa.googlegroups.com> I just downloaded the most recent (2.4.3) Python and IDLE (1.1.3) to Windows XP Professional. I'm new to the IDLE environment, so hopefully someone can tell me what I'm missing here! Below is the code, which I'm editing within IDLE, and attempting to test with the Run commands. I was expecting to see at least see the prints to stdout from the if __name__ ... statement and main() function, but when I use F5 Run module I don't see any output or errors. Any suggestions? Does IDLE still need the executable file statement at the top even if I run it explicity? --------------------------------------------------------------------------------------- import sys from xml.sax import ContentHandler, make_parser from xml.sax.handler import feature_namespaces class AuthorHandler(ContentHandler): # """Converts an author file""" def __init__(self,outfilename): # """Constructor. Takes output file name.""" self.outfile = "" self.insertCmd = "INSERT Authors SET " def startElement(self,name,attrs): # """Overridden. Creates SQL statements from author nodes.""" if name != "root": self.insertCmd += "%s = '" % self.convertColumnName(name) def characters(self,chars): # """Overridden. Add tag values as column values.""" self.insertCmd += chars def endElement(self,name): # """Overridden. Close column value and add separator.""" if name == "root": self.insertCmd += "';" else: self.insertCmd += "'," def convertColumnName(self,name): return name def main(args): print "In main" # Create an instance of the handler classes ah = AuthorHandler() # Create an XML parser parser = make_parser() # Tell the parser to use your handler instance parser.setContentHandler(ah) # Parse the file; your handler's methods will get called parser.parse(args[0]) print ah.insertCmd if __name__ == "__main__": print "to main" main("\\Iceman\propod\flash\xml\webService\XmlData\Authors\Heidi") From grante at visi.com Mon May 8 16:11:52 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 08 May 2006 20:11:52 -0000 Subject: python rounding problem. References: <mailman.5443.1146987087.27775.python-list@python.org> <-s6dnaR5BO5UOcDZRVn-tw@speakeasy.net> <87ody9amsd.fsf@localhost.localdomain> <fPednfg-wOsvDcLZRVn-vQ@telcove.net> Message-ID: <125v9g8q00o1d52@corp.supernews.com> On 2006-05-08, Thomas Bartkus <thomasbartkus at comcast.net> wrote: >> does python support true rations, which means that 1/3 is a >> true one-third and not 0.333333333 rounded off at some >> arbitrary precision? > > At risk of being boring ;-) > > - Python supports both rational and irrational numbers as > floating point numbers the way any language on any digital > computer does - imprecisely. > > A "true" (1/3) can only be expressed as a fraction. At the risk of being both boring and overly pedantic, that's not true. In base 3, the value in question is precisely representable in floating point: 0.1 > As soon as you express it as a floating point - you are in a > bit of trouble because that's impossible. It's not possible in base 2 or base 10. It's perfectly possible in base 9 (used by the Nenets of Northern Russia) base 12 (popular on planets where everybody has twelve toes) or base 60 (used by th Sumerians). [I don't know if any of those peoples used floating point in those bases -- I'm just pointing out that your prejudice towards base 10 notation is showing.] > You can not express (1/3) as a floating point in Python any > more than you can do it with pencil and paper. That's true assuming base 2 in Python and base 10 on paper. The base used by Python is pretty much etched in stone (silicon, to be precise). There used to be articles about people working on base-3 logic gates, but base-3 logic never made it out of the lab. However, you can pick any base you want when using paper and pencil. > You can be precise and write "1/3" or you can surrender to > arithmetic convenience and settle for the imprecise by writing > "0.333333333", chopping it off at some arbitrary precision. Or you can write 0.1 3 :) -- Grant Edwards grante Yow! Yes, Private at DOBERMAN!! visi.com From phddas at yahoo.com Sat May 6 17:41:21 2006 From: phddas at yahoo.com (Gary Wessle) Date: 07 May 2006 07:41:21 +1000 Subject: os.isfile() error Message-ID: <87ac9uygou.fsf@localhost.localdomain> Hi could someone help me to find out whats wrong with this code? **************** code **************** import os, sys if len(sys.argv) < 2: sys.exit("please enter a suitable directory.") dpath = sys.argv[1] for name in os.listdir(dpath): if os.isfile(dpath+name): infile = open(os.path.join(dpath,name), 'rb') print type(infile) **************** error **************** Traceback (most recent call last): File "python/useful/cat2all.py", line 13, in ? if os.isfile(dpath+name): AttributeError: 'module' object has no attribute 'isfile' thank you From duncan.booth at invalid.invalid Fri May 12 04:29:09 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 12 May 2006 08:29:09 GMT Subject: deleting texts between patterns References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> Message-ID: <Xns97C1607A4A01Cduncanbooth@127.0.0.1> wrote: > hi > say i have a text file > > line1 > line2 > line3 > line4 > line5 > line6 > abc > line8 <---to be delete > line9 <---to be delete > line10 <---to be delete > line11 <---to be delete > line12 <---to be delete > line13 <---to be delete > xyz > line15 > line16 > line17 > line18 > > I wish to delete lines that are in between 'abc' and 'xyz' and print > the rest of the lines. Which is the best way to do it? Should i get > everything into a list, get the index of abc and xyz, then pop the > elements out? or any other better methods? > thanks > Something like this (untested code): def filtered(f, stop, restart): f = iter(f) for line in f: yield line if line==stop: break for line in f: if line==restart: yield line break for line in f: yield line for line in filtered(open('thefile'), "abc\n", "xyz\n"): print line From kentilton at gmail.com Tue May 16 12:30:02 2006 From: kentilton at gmail.com (Ken Tilton) Date: Tue, 16 May 2006 12:30:02 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147767671.450912.152140@u72g2000cwu.googlegroups.com> References: <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> <d6lu07r7u0u.fsf@vipunen.hut.fi> <44681F95.9040400@gmail.com> <1147689991.541829.129550@u72g2000cwu.googlegroups.com> <MD2ag.777$8K5.396@fe09.lga> <1147767671.450912.152140@u72g2000cwu.googlegroups.com> Message-ID: <W4nag.20$UI3.14@fe09.lga> Ben wrote: > This kind of discussions between two groups of people, > neither of who know the other person's language very well just wind me > up something chronic! I must say, it is pretty funny how a flamewar turned into a pretty interesting SoC project. > Anything that makes programming more fun is good, and I hope the Lisp > true way explodes into my head at some point. Here is an excerpt of an excerpt from famous Gears demo. I notice it really makes concrete what Lispniks are talking about in re macros and multi-line lambda (pity about the formatting): (defmodel gears-demo (window) ((gear-ct :initform (c-in 1) :accessor gear-ct :initarg :gear-ct)) (:default-initargs :title$ "Rotating Gear Widget Test" :kids (c? (the-kids (mk-stack (:packing (c?pack-self)) (mk-row () (mk-button-ex (" Add " (incf (gear-ct .tkw)))) (mk-button-ex ("Remove" (when (plusp (gear-ct .tkw)) (decf (gear-ct .tkw))))) (mk-entry :id :vtime :md-value (c-in "10"))) (make-instance 'gears :fm-parent *parent* :width 400 :height 400 :timer-interval (max 1 (or (parse-integer (fm^v :vtime)) :junk-allowed t) 0))))))) Don't worry, Lispniks cannot read that either. It is a delarative construction of a hierarchical GUI. That is such a common task, that I have rolled up a bunch of GUI-building macrology so that just the stuff specific to this GUI gets typed in. Since the Gears widget is a custom widget I have no macrology for that, and the wiring shows in the expression ":fm-parent *parent*" (which itself leverages Lisp special variables). And no, I cannot remember all my macrology. I can certainly read it and easily modify my GUI, because all the wiring is hidden, but if I have to build a new GUI I cut and paste from other GUIs. Let's look at just one form, which I believe destroys Alex's whole case for naming every lambda: (mk-button-ex ("Remove" (when (plusp (gear-ct .tkw)) (decf (gear-ct .tkw))))) "mk-button-ex" (a) makes fun of MS$ naming standards and (b) expands to: (make-instance 'button :fm-parent *parent* :text "remove" :on-command (c? (lambda (self) (when (plusp (gear-ct .tkw)) (decf (gear-ct .tkw)))))) The above is what one really needs to write to stick something in my GUI framework, but who wants to look at all of that when most of it is boilerplate? I need ":fm-parent *parent*" on every label and widget because of some internals requirements, I just do not want to look at it or have to remember to code it all the time (the latter not being a huge problem because I really am cutting/pasting when I build a new GUI). Is mk-button-ex some mysterious new language construct that will make multi-programmer projects collapse in a heap of programmer-specific constructs inscrutable to anyone else on the team? (a) mk-button-ex kinda tells you (1) it makes a button and (2) no, this is not part of Common Lisp, so where is the confusion? (b) control-alt-. in my IDE shows me: (defmacro mk-button-ex ((text command) &rest initargs) `(make-instance 'button :fm-parent *parent* :text ,text :on-command (c? (lambda (self) (declare (ignorable self)) ,command)) , at initargs)) Looks a lot like the expansion, right? That is really important in making macrology easy. Once one has mastered the syntax (` , @), writing a macro gets as natural as writing out the code. (In case you are wondering, in my little example I did not need any other customizations on the button, so it is hard to make out what the initargs are doign up there. here is how they would work (also getting a little fancier by actually disabling the "Remove" button, not just making it do nothing when pressed, if the gear count is zero): (mk-button-ex ("Remove" (decf (gear-ct .tkw))) :fore-color 'red ;; Tcl/Tk will understand :enabled (c? (plusp (gear-ct .tkw)))) becomes: (make-instance 'button :fm-parent *parent* :text "remove" :on-command (c? (lambda (self) (decf (gear-ct .tkw)))) :fore-color 'red :enabled (c? (plusp (gear-ct .tkw)))) [ps. Do not try that at home, i invented the enabled thing. It really should be the Tk syntax, which I forget.] ie, I created mk-button-ex because, jeez, every button I put in a GUI I /know/ needs its own label and its own command (and the parent thing), but there are other options, too. They have to be supported if the macro is to get used all the time (we want that), but I do not want to make them positional arguments without identifying keywords, because then the code would be unreadable as well as unwritable (from memory). Needless to say, there is more macrology in the expansion. One bit of fun is .tkw. Background: in the GUIs I roll, a widget always knows its parent. I guess you noticed. Anyway, because of that, a rule can kick off code to navigate to any other widget and get information, ie, it pretty much has global scope and that means power. Now one place a rule will often look is up the hierarchy, say to a containing radio group for a radio button. So the first thing I wrote was: (upper self radio-group) -> (container-typed self 'radio-group) Hmmph. I am /always/ upper-ing off self, I am surprised I have not written a macro so I can just do (^upper radio-group). Soon. But since I often look to the containing window in rules, I was looking for something insanely short, shorter than even parentheses would allow, like ".tkw": (define-symbol-macro .tkw (nearest self window)) Nearest is like "upper" except that it is inclusive of the starting point of the search (and, no, I am not happy with the name <g>). And so it goes with Lisp macros. All the tedious boilerplate is hiiden, in ways that cannot be done with functions. Oh, I skipped that point. Look again at how the command (decf (gear-ct .tkw)) gets spliced into the lambda form as so much source code: From: (mk-button-ex ("Remove" (decf (gear-ct .tkw)))) To: (make-instance 'button :fm-parent *parent* :text "remove" :on-command (c? (lambda (self) (decf (gear-ct .tkw)))))) If mk-button-ex were a function, Lisp would try to evaluate (decf (gear-ct .tkw)) which would be pretty sad because the "self" in there would not even exist yet (the form is an /input/ to make-instance of what will become "self" by the time the macro expansion code runs. Which brings us to the idea of every multi-line lambda needing a name. Does this: (lambda (self) (when (plusp (gear-ct .tkw)) (decf (gear-ct .tkw))) Not sure what the Python would be, but maybe: lambda (self): if nearest(self,'window').gear_ct > 0: nearest(self,'window').gear_ct = \ nearest(self,'window').gear_ct - 1 Does that need a name? kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From kruhft at gmail.com Sun May 21 15:17:55 2006 From: kruhft at gmail.com (Burton Samograd) Date: Sun, 21 May 2006 13:17:55 -0600 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <1148225181.251089.261160@j55g2000cwa.googlegroups.com> <874pzjb9rq.fsf@thalassa.informatimago.com> Message-ID: <87verz9ogs.fsf@gmail.com> Pascal Bourguignon <pjb at informatimago.com> writes: > "SamFeltus" <sam at nuevageorgia.com> writes: >> Software needs philosophers is an interesting point, perhaps the most >> important function of Philosophers is exposing Sacred Cows as just >> Cattle. > > As I see it philosophers have a big problem: nobody need them, so > they're out of job. That's why we see occasional articles "X needs > philosophers". I just ask: where are the job offers? Some might think that Aristotle's categorization and type theories might have created a few jobs in our current hobby/profession. There are many types of philosophy, but from what I've read, the most interesting the the mental deconstructionism of reality on a humanistic linguistic level, similar to mathematics without all the abbreviations. No, there aren't any jobs for philosophers, and their works are generally very underappreciated during thier lives, but it's quite difficult to say that it's useless, just often misunderstood by the less forward thinking people of their time. -- burton samograd kruhft .at. gmail kruhft.blogspot.com www.myspace.com/kruhft metashell.blogspot.com From nobody at 127.0.0.1 Fri May 12 14:09:59 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 18:09:59 GMT Subject: [OT] Unix Tools (was: deleting texts between patterns) References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <mailman.5625.1147437032.27775.python-list@python.org> <m2irobtjyh.fsf_-_@unique.fqdn> Message-ID: <Xb49g.16162$Lm5.426@newssvr12.news.prodigy.com> Dan Sommers wrote: > Or even > > awk '/abc/,/xyz/' file.txt > > Excluding the abc and xyz lines is left as an exercise to the > interested reader. Once again, us completely disinterested readers get the short end of the stick. :) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From grante at visi.com Fri May 26 19:15:47 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 26 May 2006 23:15:47 -0000 Subject: Looking for triangulator/interpolator Message-ID: <127f313dbhl7gf4@corp.supernews.com> I need to interpolate an irregularly spaced set of sampled points: Given a set of x,y,z points, I need to interpolate z values for a much finer x,y grid. I tried using the scipy sandbox delaunay module, but the interpolators don't work: the natural neighbor interpolator produces a surface with "holes" in it: the interpolator returns NaNs for no reason for certain regions within the convex hull (the convex hull looks right, and the input Z values in that region don't look any different that regions that work). The linear interpolator just segfualts no matter what data I try with it. In the past i've used the Delny/libqhull module, but it doesn't do interpolation, so I had to write the interpolator in Python (which works but is very slow). Is there any "off the shelf" module that does interpolation of irregularly spaced data? -- Grant Edwards grante Yow! LOOK!! Sullen at American teens wearing visi.com MADRAS shorts and "Flock of Seagulls" HAIRCUTS! From duncan.booth at invalid.invalid Fri May 5 13:40:08 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 May 2006 17:40:08 GMT Subject: to thine own SELF be true... References: <cEL6g.73268$H71.7968@newssvr13.news.prodigy.com> Message-ID: <Xns97BABC3EE77F3duncanbooth@127.0.0.1> Mark Harrison wrote: > For example, in my brain I'm thinking: > > optc,args=getopt.getopt(args,cmdopts[cmd][0], cmdopts[cmd][1]) > > but I'm having to type: > > self.optc,self.args=getopt.getopt(self.args,self.cmdopts[self.c > md][0], > > self.cmdopts[self.cmd][1]) > > > Is there a way to get rid of those the "self." references, or is this > just something I need to get my brain to accept? > I would wonder why it is that all of those need to be attributes on self. Are you sure you aren't storing too many things as attributes? Trying to guess some context around that code, I would expect something like: def docommand(self, cmd, args): opts, longopts = self.cmdopts[cmd] optc, args = getopt.getopt(args, opts, longopts) return self.getAction(cmd)(optc, args) or in other words a lot fewer uses of self. From tbrkic at yahoo.com Thu May 18 18:28:50 2006 From: tbrkic at yahoo.com (glomde) Date: 18 May 2006 15:28:50 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <446ceb96$0$7024$636a55ce@news.free.fr> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147980462.464427.323030@u72g2000cwu.googlegroups.com> <446cdd6b$0$7043$636a55ce@news.free.fr> <mailman.5903.1147987032.27775.python-list@python.org> <446ceb96$0$7024$636a55ce@news.free.fr> Message-ID: <1147991330.560422.145560@38g2000cwa.googlegroups.com> So I read trough all of the make PEP and make would support the syntax i propose.. and more generic and better in many ways. Since it was rejected I have to continue live with my preprocessor... >From the make PEP ..... Allowing this sort of customization could allow XML to be written without repeating element names, and with nesting of make-statements corresponding to nesting of XML elements: make Element html: make Element body: text('before first h1') make Element h1: attrib(style='first') text('first h1') tail('after first h1') make Element h1: attrib(style='second') text('second h1') tail('after second h1') From cm012b5105 at blueyonder.co.uk Tue May 30 16:57:25 2006 From: cm012b5105 at blueyonder.co.uk (nigel) Date: Tue, 30 May 2006 21:57:25 +0100 Subject: interactive programme (voice) Message-ID: <200605302157.26110.cm012b5105@blueyonder.co.uk> hi i have wrote an interactive programme,this is a small section of it. #This is my first programme writing in python s = raw_input ("hello what's your name? ") if s=='carmel': print "Ahh the boss's wife" if s=='melvyn': print "your the boss's dad" if s=='rebecca': print "you must be the wreath woman" if s=='gareth ': print "You must be the trucker" if s=='carol': print "you must be my boss's mom" What i was wandering is there a way i can get sound,i mean instead of getting it to just print text on my screen i would like my computer to say it. Thanks nige From federico.pelloni at gmail.com Wed May 3 12:32:03 2006 From: federico.pelloni at gmail.com (Fredp) Date: 3 May 2006 09:32:03 -0700 Subject: __getattr__ on non-instantiated class In-Reply-To: <4458D4F9.8010900@websafe.com> References: <1146671588.529743.249570@v46g2000cwv.googlegroups.com> <4458D4F9.8010900@websafe.com> Message-ID: <1146673922.994217.241620@j33g2000cwa.googlegroups.com> Larry Bates ha scritto: > Fredp wrote: > > Hi > > I was wondering if it is possible to have the various magic methods, > > mainly __getattr__ and __setattr__, and @property attributes called > > when accessing the attribute of a non-intantiated class. > > > > Imagin something like this: > > ##### > > class MyClass: > > @property > > def prop(self): > > print "Accessed" > > return "ABCD" > > > > print MyClass.prop > > ##### > > having it printing: > > ##### > > Accessed > > ABCD > > ##### > > > > Thanks very much > > > Looks like you want Python to execute a method on an uninstantiated > class. I can't imagine how you would use such a thing. Can you > give us a real-life "use case"? > > This produces the output you want: > > m=MyClass() > print m.prop() > > -Larry Bates I have something like a simple ORM which objects haven't a fixed number of fields, and I need to have properties (or methods) for each of them, but currently it is more comfortable for me to use uninstantiaded classes (as someway SQLObject does). I guess I'd better taking another approach to him, maybe using something from ASPN cookbook :-\ From olsongt at verizon.net Sun May 7 15:40:35 2006 From: olsongt at verizon.net (olsongt at verizon.net) Date: 7 May 2006 12:40:35 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1hew3d4.1x2eems1pb7o5N%aleaxit@yahoo.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> <1hew3d4.1x2eems1pb7o5N%aleaxit@yahoo.com> Message-ID: <1147030835.498512.314110@u72g2000cwu.googlegroups.com> Alex Martelli wrote: > Steve R. Hastings <steve at hastings.org> wrote: > ... > > > But the key in the whole thread is simply that indentation will not > > > scale. Nor will Python. > > > > This is a curious statement, given that Python is famous for scaling well. > > I think "ridiculous" is a better characterization than "curious", even > if you're seriously into understatement. > When you consider that there was just a big flamewar on comp.lang.lisp about the lack of standard mechanisms for both threading and sockets in Common Lisp (with the lispers arguing that it wasn't needed) I find it "curious" that someone can say Common Lisp scales well. From ilias at lazaridis.com Fri May 5 09:39:50 2006 From: ilias at lazaridis.com (lazaridis_com) Date: 5 May 2006 06:39:50 -0700 Subject: PUDGE - Colored Code Blocks / Mailing List Access Message-ID: <1146836390.251422.286650@y43g2000cwc.googlegroups.com> Colored Code Blocks Pudge generated documentation can contain colored code blocks, using the rst directive "..code-block:: Python" (an other languages supported by SilverCity). http://pudge.lesscode.org/trac/ticket/21 http://pudge.lesscode.org/trac/changeset/126 - Mailing List The Pudge Mailing List seems to be down since the change of the server: http://news.gmane.org/gmane.comp.python.pudge.general Possibly someone can notify some of the project admins. -- http://lazaridis.com From fredrik at pythonware.com Wed May 3 13:26:18 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 19:26:18 +0200 Subject: A python problem about int to long promotion just see the idle session References: <1146676227.349286.280250@v46g2000cwv.googlegroups.com> Message-ID: <e3ap3s$i63$1@sea.gmane.org> "gen_tricomi" <ogahejini at yahoo.com> wrote: > IDLE 1.1.2 > >>> import sys > >>> save_maxint = sys.maxint > >>> save_maxint > 2147483647 > >>> save_maxint += 1 > >>> save_maxint > 2147483648L > >>> save_maxint - 1 > 2147483647L > >>> save_maxint + 1 > 2147483649L > >>> save_maxint - 1 > 2147483647L > >>> save_maxint + 1 > 2147483649L > >>> save_maxint - 1 > 2147483647L > >>> save_maxint + 1 > 2147483649L > > > from the above you can see what int to long promotion is causing > i dont need to say much please see for yourself. ? </F> From lance at augustmail.com Mon May 15 16:23:49 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Mon, 15 May 2006 15:23:49 -0500 Subject: regular expression error ? Message-ID: <4468e354$0$61167$ae4e5890@news.nationwide.net> why isn't re.search recognizing "file"? I can print the contents of "file". import win32com.client import re D=MSWord.Documents.Open('C:/test/Test.doc') file=D.Content print file match = re.search('(Table ?)', file) if match: print "Table Number is: ", match.group(1) Traceback (most recent call last): File "test.py", line 21, in ? match = re.search('(Table ?)', file) File "C:\Python24\Lib\sre.py", line 134, in search return _compile(pattern, flags).search(string) TypeError: expected string or buffer From rory.brandybuck at gmail.com Sat May 13 09:52:16 2006 From: rory.brandybuck at gmail.com (rory.brandybuck at gmail.com) Date: 13 May 2006 06:52:16 -0700 Subject: Sending mail with attachment... References: <1147508571.532690.292650@v46g2000cwv.googlegroups.com> <1147515213.695066.5740@u72g2000cwu.googlegroups.com> Message-ID: <1147528336.852387.179840@j73g2000cwa.googlegroups.com> Replace: mesg['To'] = recievelist By: mesg['To'] = ', '.join(recievelist) From aleaxit at yahoo.com Sun May 7 02:05:59 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 23:05:59 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <slrne5qsun.9lp.tomasz.zielonka@tomekz.gem.lan> Message-ID: <1hexuhy.1s2wd54hhev3mN%aleaxit@yahoo.com> Tomasz Zielonka <tomasz.zielonka at gmail.com> wrote: ... > higher level languages. There are useful programming techniques, like > monadic programming, that are infeasible without anonymous functions. > Anonymous functions really add some power to the language. Can you give me one example that would be feasible with anonymous functions, but is made infeasible by the need to give names to functions? In Python, specifically, extended with whatever fake syntax you favour for producing unnamed functions? I cannot conceive of one. Wherever within a statement I could write the expression lambda <args>: body I can *ALWAYS* obtain the identical effect by picking an otherwise locally unused identifier X, writing the statement def X(<args>): body and using, as the expression, identifier X instead of the lambda. > On the other hand, what do you get by allowing ( as an indentifier? Nothing useful -- the parallel is exact. > Significant whitespace is a good thing, but the way it is designed in > Python it has some costs. Can't you simply acknowledge that? I would have no problem "acknowledging" problems if I agreed that any exist, but I do not agree that any exist. Please put your coding where your mouth is, and show me ONE example that would be feasible in a Python enriched by unlimited unnamed functions but is not feasible just because Python requires naming such "unlimited" functions. Alex From Serge.Orlov at gmail.com Thu May 11 10:01:33 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 May 2006 07:01:33 -0700 Subject: Python memory deallocate References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <1147347601.597292.15220@j73g2000cwa.googlegroups.com> <1147353348.028544.143470@u72g2000cwu.googlegroups.com> <mailman.5587.1147355642.27775.python-list@python.org> Message-ID: <1147356093.328235.22450@j33g2000cwa.googlegroups.com> Heiko Wundram wrote: > Am Donnerstag 11 Mai 2006 15:15 schrieb mariano.difelice at gmail.com: > > I MUST find a system which deallocate memory... > > Otherwise, my application crashes not hardly it's arrived to > > break-point system > > As was said before: as long as you keep a reference to an object, the object's > storage _will not be_ reused by Python for any other objects (which is > sensible, or would you like your object to be overwritten by other objects > before you're done with them?). Besides, even if Python did free the memory > that was used, the operating system wouldn't pick it up (in the general case) > anyway (because of fragmentation issues), so Python keeping the memory in an > internal free-list for new objects is a sensible choice the Python developers > took here. BTW python 2.5 now returns free memory to OS, but if a program keeps allocating more memory with each new iteration in python 2.4, it will not help. From sebastien.martini at gmail.com Fri May 19 12:03:10 2006 From: sebastien.martini at gmail.com (=?iso-8859-1?B?c+liYXN0aWVu?=) Date: 19 May 2006 09:03:10 -0700 Subject: Any pointers/advice to help learn CPython source? References: <1147886150.819254.158880@i40g2000cwc.googlegroups.com> <1147936062.293223.233820@y43g2000cwc.googlegroups.com> Message-ID: <1148054590.546979.189710@j33g2000cwa.googlegroups.com> There is also an interesting pep which describe the front-end http://www.python.org/dev/peps/pep-0339/ It doesn't explain the whole things, but it gives few hints where to start to read the code. BTW, the main difficulty is that there are fat C files and you should ask yourself what do you want to learn, because instead it can be interesting to read the compiler module or to look at pypy source code. Obviously if your motivations are to understand some internals of CPython you want to study CPython ! lol -- s?bastien http://seb.dbzteam.com From bearophileHUGS at lycos.com Mon May 15 16:59:16 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 15 May 2006 13:59:16 -0700 Subject: Large Dictionaries In-Reply-To: <e4adgk$196$1@reader1.panix.com> References: <1147699064.107490@teuthos> <roy-765731.09112115052006@reader1.panix.com> <e4abj6$p6a$1@panix1.panix.com> <e4adgk$196$1@reader1.panix.com> Message-ID: <1147726756.778578.45090@v46g2000cwv.googlegroups.com> Roy Smith: > I am befuddled as to why > people thought creating a dict by keyword would be a useful thing to > do, but left out (and, indeed, eliminated the chance to add the syntax > later) the obviously useful ability to hint at the size. Adding the keyword syntax doesn't require much memory to a Python programmer because it's the same syntax used elsewhere. While adding another different method to dicts increases their API. Python is usually designed to have smaller APIs, to help programmers remember most things. I agree that a reserve method to Python dicts/sets can be a little useful, but Python programmers are usually more concerned about doing things in a short programmer time and short code space, than telling the computer how to do such things in the faster way (C++ is more for speed so the reserve of the STL hashes can be more useful). Bye, bearophile From shearichard at gmail.com Wed May 17 21:41:55 2006 From: shearichard at gmail.com (shearichard at gmail.com) Date: 17 May 2006 18:41:55 -0700 Subject: MySQLdb - parameterised SQL - how to see resulting SQL ? Message-ID: <1147916515.511332.214660@j33g2000cwa.googlegroups.com> Hi - I've got SQL that looks like this ... cursor = self.MySQLDb_conn.cursor(cursorclass=MySQLdb.cursors.DictCursor) sqlQuery = "SELECT * FROM T1 WHERE C1 = %s and C2 = %s" sql = cursor.execute(sqlQuery,(strURLAlias,strSessionID)) rows = cursor.fetchall() cursor.close ... i would be interested in seeing what the actual SQL used by the .execute looks like after the replacements have been done. Is there a way of doing this ? thanks richard. From jarrod.roberson at gmail.com Tue May 16 14:10:42 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 16 May 2006 11:10:42 -0700 Subject: How to log only one level to a FileHandler using python logging module. Message-ID: <1147803042.198679.236260@j73g2000cwa.googlegroups.com> I want a FileHandler to only log a single level say for example logging.INFO, and nothing else. do I need to create a custom Handler for this or is this doable with some magic that is not documeneted somewhere? From sjmachin at lexicon.net Sun May 28 17:47:49 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 May 2006 07:47:49 +1000 Subject: Serializing / Unserializing datetime In-Reply-To: <1148844232.605364.192760@i40g2000cwc.googlegroups.com> References: <1148751427.204676.238100@g10g2000cwb.googlegroups.com> <4478E634.8060001@lexicon.net> <1148844232.605364.192760@i40g2000cwc.googlegroups.com> Message-ID: <447a1a86$1@news.eftel.com> On 29/05/2006 5:23 AM, Brendan wrote: > Thanks John. I've discovered that datetime.strptime will be available > in 2.5, (http://docs.python.org/dev/whatsnew/modules.html) but your > example will work in the meantime. > Only in the meantime? I would thought there was a good chance it would continue to work in 2.5 -- especially as I tested it with 2.5a2 :-) Hmmm ... now you've got me thinking, maybe there's an anti-DIY enforced-use-of-official-functionality gadget in 2.5. Just because I'm paranoid doesn't mean the PSU isn't out to ~;{[]=]|\ <no connection> From johnjsal at NOSPAMgmail.com Tue May 23 11:49:21 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 15:49:21 GMT Subject: how to change sys.path? In-Reply-To: <1148399102.963320.129230@u72g2000cwu.googlegroups.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> Message-ID: <5aGcg.2150$No6.46806@news.tufts.edu> Ju Hui wrote: > yes, I mean I want change the sys.path value and save it for next > using. > I can change the value of sys.path, but I can't "save" it permanently. > There is no python_path environment on my pc, what the relationship > between it and the sys.path? > In Windows, at least, you can create the PYTHONPATH variable and assign to it the paths of the directories you want Python to check for when running a script. From OlafMeding at gmail.com Tue May 9 10:44:44 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 9 May 2006 07:44:44 -0700 Subject: Using time.sleep() in 2 threads causes lockup whenhyper-threading is enabled In-Reply-To: <mailman.5487.1147125430.27775.python-list@python.org> References: <mailman.5487.1147125430.27775.python-list@python.org> Message-ID: <1147185883.943026.192730@i39g2000cwa.googlegroups.com> Tim, Serge, Dennis Yes it happens every time. The PC does not run any other programs. We have tried multiple PC but they all have an identical configuration. We usually start the test leave the PC alone. The best way to test my posted .py program is to start the test before going to lunch or before going home for the day. Olaf From nobody at 127.0.0.1 Sun May 14 01:12:38 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 14 May 2006 05:12:38 GMT Subject: copying files into one References: <874pztgsd5.fsf@localhost.localdomain> Message-ID: <a%y9g.5951$fb2.3222@newssvr27.news.prodigy.net> Gary Wessle wrote: > I am looping through a directory and appending all the files in one > huge file, the codes below should give the same end results but are > not, I don't understand why the first code is not doing it. another bit of friendly advice (for others as well): learn to use pdb before posting your code for the group to debug. this type of error is easily catchable with a little effort. you'll learn more by investigating your problems yourself before feeding them to the great distributed debugger known as comp.lang.python. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From grante at visi.com Fri May 19 09:58:35 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 19 May 2006 13:58:35 -0000 Subject: Script to make Windows XP-readable ZIP file References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> <Xns97C7E851F9CC2castleamber@130.133.1.4> <1148011001.613000.294750@g10g2000cwb.googlegroups.com> <Xns97C7ED9E857DEcastleamber@130.133.1.4> <1148014650.844340.212540@38g2000cwa.googlegroups.com> Message-ID: <126rjobnstfrc68@corp.supernews.com> On 2006-05-19, softwindow <softwindow at gmail.com> wrote: > Carl Banks is right That would be valuable information if we know what he was right about. -- Grant Edwards grante Yow! Bo Derek ruined at my life! visi.com From mateus.justino at gmail.com Wed May 31 09:30:36 2006 From: mateus.justino at gmail.com (mateus) Date: 31 May 2006 06:30:36 -0700 Subject: Variable name has a typo, but code still works. Why? Message-ID: <1149082236.151844.99600@u72g2000cwu.googlegroups.com> print "hello world" I have a nested loop where the outer loop iterates over key value pairs of a dictionary and the inner loop iterates over a list each list of which is a mapped value from the dictionary def showReport(self): for dev, sessions in self.logger.items(): for tree in session: self.addTestItem(self, tree) What I don't understand is why this executes w/o any problems when "sessions" was spelled as plural (sessionS) while later being spelled in the singular (session). Is there some type of name resolution of local variables where Python makes assumptions? From johnjsal at NOSPAMgmail.com Mon May 15 16:13:00 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 20:13:00 GMT Subject: my cryptogram program In-Reply-To: <ZI3ag.2095$No6.46239@news.tufts.edu> References: <ZI3ag.2095$No6.46239@news.tufts.edu> Message-ID: <gh5ag.2100$No6.46182@news.tufts.edu> Alrighty, here is what I've come up with. Any suggestions for tweaks or speed-boosting efficiency? Just kidding. :) Maybe the weakest part is how the code is determined (just shuffling the letters in the alphabet). Perhaps there's a better way? Although it seems effective to me.... import string import random import itertools def convert_quote(quote): coded_quote = make_code(quote) author = coded_quote.split('|')[1] quote = coded_quote.split('|')[0] return quote, author def make_code(original): original_letters = make_set(original) new_letters = list(string.ascii_uppercase) while True: random.shuffle(new_letters) trans_letters = ''.join(new_letters)[:len(original_letters)] if test_code(original_letters, trans_letters): trans_table = string.maketrans(original_letters, trans_letters) break return original.translate(trans_table) def make_set(original): original_set = set(original) punc_space = string.punctuation + string.whitespace for char in punc_space: if char in original_set: original_set.remove(char) return ''.join(original_set) def test_code(original_letters, trans_letters): for pair in itertools.izip(original_letters, trans_letters): if pair[0] == pair[1]: return False return True if __name__ == '__main__': print convert_quote("The past is not dead. In fact, it's not even past.|William Faulkner") From john at castleamber.com Tue May 30 13:59:49 2006 From: john at castleamber.com (John Bokma) Date: 30 May 2006 17:59:49 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> <Xns97D294C4D81FCcastleamber@130.133.1.4> <447bff02$0$38691$edfadb0f@dread12.news.tele.dk> Message-ID: <Xns97D3843577541castleamber@130.133.1.4> Max M <maxm at mxm.dk> wrote: > John Bokma wrote: >> ilitzroth at gmail.com wrote: > >> Your first question should be: Is it alright that Xah harasses 5 >> newsgroups? Or maybe work on your spelling, harass is with one r, but >> maybe you didn't read the subject, which wouldn't amaze me, since you >> sound like you should be spending time on MySpace OMG!. > > I assume that the single l in alright is the courteous misspelling that > should allways be in a posting, when correcting other peoples speling? http://www.answers.com/alright http://www.answers.com/main/ntquery?tname=all-right :-D -- 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 ishoej at gmail.com Mon May 1 07:10:59 2006 From: ishoej at gmail.com (Holger) Date: 1 May 2006 04:10:59 -0700 Subject: noob question: "TypeError" wrong number of args Message-ID: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> Hi guys Tried searching for a solution to this, but the error message is so generic, that I could not get any meaningfull results. Anyways - errormessage: ---------------------------------------------------- TypeError: addFile() takes exactly 1 argument (2 given) ---------------------------------------------------- The script is run with two args "arg1" and "arg2": ---------------------------------------------------- import sys class KeyBase: def addFile(file): print "initialize the base with lines from this file" print "These are the args" print "Number of args %d" % len(sys.argv) print sys.argv print sys.version_info print sys.version f = sys.argv[1] print "f = '%s'" % f b = KeyBase() b.addFile(f) ---------------------------------------------------- The output - including error message (looks like stdout and stderr are a bit out of sync...): ---------------------------------------------------- These are the args Traceback (most recent call last): Number of args 3 ['C:\\home\\<.. bla bla snip ...>\\bin\\test.py', 'arg1', 'arg2'] (2, 4, 2, 'final', 0) 2.4.2 (#67, Oct 30 2005, 16:11:18) [MSC v.1310 32 bit (Intel)] f = 'arg1' File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 1806, in runMain self.dbg.runfile(debug_args[0], debug_args) File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 1529, in runfile h_execfile(file, args, module=main, tracer=self) File "C:\Program Files\ActiveState Komodo 3.5\lib\support\dbgp\pythonlib\dbgp\client.py", line 590, in __init__ execfile(file, globals, locals) File "C:\home\hbille\projects\bc4rom\bin\test.py", line 20, in __main__ b.addFile(f) TypeError: addFile() takes exactly 1 argument (2 given) ---------------------------------------------------- I'm running this inside ActiveState Komodo on WinXP. Hope one you wizards can give me pointers to either what I'm doing wrong or maybe advise me what to modify in my setup. Thank you! Regards, Holger From johnjsal at NOSPAMgmail.com Tue May 16 22:48:16 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 22:48:16 -0400 Subject: help with this simple DB script In-Reply-To: <1147830679.941943.310290@i40g2000cwc.googlegroups.com> References: <446a7849$0$1901$c3e8da3@news.astraweb.com> <1147830679.941943.310290@i40g2000cwc.googlegroups.com> Message-ID: <446a8f7d$0$1907$c3e8da3@news.astraweb.com> trebucket at gmail.com wrote: > This is probably causing a problem: > !#/usr/bin/python > > It should be "#!", not "!#". Ugh! So stupid! Thanks for correcting that, but it wasn't the only problem. > If that doesnt' work, add this line at the top of your script, to check > that the script is begin executed: > > print "Content-Type: text/html\n\n" > print "Hello, World!" Yes, this part gets executed. > If you still get an Internal Server Error put the following before you > import MySQLdb: > > import cgitb; cgitb.enable() This produces a page with a ProgrammingError (http://www.johnjsalerno.com/server_db_test.py), but the main part I guess is this: ProgrammingError: (1064, "You have an error in your SQL syntax. Check the manual that corresponds to your MySQL server version for the right syntax to use near 'number(2))' at line 1") I'm not sure what I'm doing wrong with the syntax though. I don't think I need semicolons (a sample I saw didn't use them). From richie at entrian.com Tue May 9 06:41:34 2006 From: richie at entrian.com (Richie Hindle) Date: Tue, 09 May 2006 11:41:34 +0100 Subject: ascii to latin1 In-Reply-To: <1147136835.481913.323510@v46g2000cwv.googlegroups.com> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> Message-ID: <ntr062d3akki3jsj9gg30b9sq1smstfvt0@4ax.com> [Serge] > def search_key(s): > de_str = unicodedata.normalize("NFD", s) > return ''.join(cp for cp in de_str if not > unicodedata.category(cp).startswith('M')) Lovely bit of code - thanks for posting it! You might want to use "NFKD" to normalize things like LATIN SMALL LIGATURE FI and subscript/superscript characters as well as diacritics. -- Richie Hindle richie at entrian.com From etu.suku at iki.fi.invalid Mon May 15 07:35:13 2006 From: etu.suku at iki.fi.invalid (Ilkka Poutanen) Date: Mon, 15 May 2006 11:35:13 +0000 (UTC) Subject: How to organise classes and modules References: <mailman.5703.1147691931.27775.python-list@python.org> Message-ID: <slrne6gpri.7r4.etu.suku@korppi.cs.tut.fi> On 2006-05-15, Alex <mizipzor at gmail.com> wrote: >>>> import Foo >>>> Foo.Foo.bar() > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: unbound method bar() must be called with Foo instance as > first argument (got nothing instead) > > ... > > One thing that I tried that worked ok was this: > >>>> import Foo >>>> instance=Foo.Foo() >>>> instance.bar() > hello world > > But in my opinion, this is very ugly. Especially if the class names Are you sure you understand object-oriented programming? Reading the Python tutorial[1] and re-reading the above error messages should clue you in to what you're doing wrong. To put it simply, the whole point of classes is that you create instances of them, each having their own internal state, and then invoke their methods to accomplish whatever it is that you want your program to accomplish. 1. http://docs.python.org/tut/ -- Ilkka Poutanen [http://ipo.iki.fi/] And unto this, Conan; From __peter__ at web.de Mon May 15 12:36:00 2006 From: __peter__ at web.de (Peter Otten) Date: Mon, 15 May 2006 18:36:00 +0200 Subject: List and order References: <446842f7$0$14785$4fafbaef@reader4.news.tin.it> <1147691967.998184.285120@u72g2000cwu.googlegroups.com> <446872cb$0$18288$4fafbaef@reader1.news.tin.it> <e49u2k$3i2$02$1@news.t-online.com> <4468a8b7$0$29719$4fafbaef@reader2.news.tin.it> Message-ID: <e4aahn$l16$01$1@news.t-online.com> Nic wrote: > The only problem is that from: > 12 > 22 > 21 > In spite of writing > 12 12 22 > it writes > 12 21 22 > Do you know how is it possible to delete also this last trouble? I thought that the two 12 were a typo, but it seems you want to reorder the nodes inside an edge, too. Here's a fix that normalizes the edge before sorting the list of edges: edges = [sorted((ddeg[u], ddeg[v])) for u, v in G.edges()] edges.sort() for a, b in edges: ????print?a,?b, print Peter From enleverlesX.XmcX at XmclaveauX.com Wed May 31 07:54:03 2006 From: enleverlesX.XmcX at XmclaveauX.com (Méta-MCI) Date: Wed, 31 May 2006 13:54:03 +0200 Subject: Best Python Editor References: <mailman.6359.1149069835.27775.python-list@python.org> Message-ID: <447d83fd$0$6689$8fcfb975@news.wanadoo.fr> Hi! Komodo (http://www.activestate.com/Products/Komodo) is great, for me. @-salutations -- Michel Claveau From grante at visi.com Tue May 16 16:23:48 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 16 May 2006 20:23:48 -0000 Subject: Using python for a CAD program References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <1147808333.652756.5180@u72g2000cwu.googlegroups.com> <1147809833.650020.142570@j33g2000cwa.googlegroups.com> Message-ID: <126kd6k7tqor34f@corp.supernews.com> On 2006-05-16, 63q2o4i02 at sneakemail.com <63q2o4i02 at sneakemail.com> wrote: > Yes, I figured I should be pretty expert at what's out there > first before redoing something and making in inferior to the > existing solution. Eagle from Cadsoft.de is a pretty decent (and free for educational/hobby use) integrated schematic capture and board layout package (including a quite usable auto-router). It doesn't have integrated simulation, but after messing about with both gEDA and Eagle for an hour or two the you get a good feel for the difference between an integrated tool-set and something cobbled together from disparate utilities. -- Grant Edwards grante Yow! Of course, you at UNDERSTAND about the PLAIDS visi.com in the SPIN CYCLE -- From iamsidd at gmail.com Fri May 26 02:24:59 2006 From: iamsidd at gmail.com (Sidd) Date: 25 May 2006 23:24:59 -0700 Subject: Can any body help me References: <1148621554.184942.155430@38g2000cwa.googlegroups.com> Message-ID: <1148624698.985455.57480@38g2000cwa.googlegroups.com> 1.Given a test file containing lines of words such as (abc, abb, abd,abb, etc), write a script that prints, in order of frequency, how many times each word appears in the file. Use dictionary datastructure in python and simple if-else statement. Its simple give it a try. From cvanarsdall at mvista.com Fri May 19 17:15:17 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 19 May 2006 14:15:17 -0700 Subject: Request for comments on python distributed technologies In-Reply-To: <ZIobg.46857$CH2.39191@tornado.texas.rr.com> References: <mailman.5972.1148064796.27775.python-list@python.org> <ZIobg.46857$CH2.39191@tornado.texas.rr.com> Message-ID: <446E3565.40908@mvista.com> Paul McGuire wrote: >> > > What you describe sounds very much like pyro, which should probably be added > to your list. > Pyro looks nothing short of amazing. I will definitely spend some time studying this technology as well. Does anyone here use pyro or any of the other technologies enough to comment on them? .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From dongdonglove8 at hotmail.com Sun May 28 10:47:37 2006 From: dongdonglove8 at hotmail.com (python) Date: 28 May 2006 07:47:37 -0700 Subject: iteration over non-sequence ,how can I resolve it? In-Reply-To: <mailman.6293.1148825990.27775.python-list@python.org> References: <1148822420.452617.79720@u72g2000cwu.googlegroups.com> <mailman.6293.1148825990.27775.python-list@python.org> Message-ID: <1148827657.065311.256470@38g2000cwa.googlegroups.com> To BJ?rn Lindqvist : thank you . how to write the code specifically ?Could you give an example? From http Mon May 22 11:21:50 2006 From: http (Paul Rubin) Date: 22 May 2006 08:21:50 -0700 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <bhv172hbu1i37nqi3kp1rhnuaujj1qo208@4ax.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> Message-ID: <7xk68eytip.fsf@ruckus.brouhaha.com> "SamFeltus" <sam at nuevageorgia.com> writes: > I do find it interesting that Flash folks readily will acknowledge that > Flash has shortcomings, yet anti-Flash folks seem to have great > difficulty acknowledging Flash's positive features over HTML. Such > situations always make me suspicious Ludditism is at work. Nobody doubts that Flash has positive features. The question is whether the positives are worth the negatives. For many of us, the answer is no. From me+python at modelnine.org Thu May 18 18:51:45 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Fri, 19 May 2006 00:51:45 +0200 Subject: Feature request: sorting a list slice In-Reply-To: <1147983236.869617.222970@u72g2000cwu.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147983236.869617.222970@u72g2000cwu.googlegroups.com> Message-ID: <200605190051.45307.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 22:13 schrieb Raymond Hettinger: > This is a false optimization. The slicing steps are O(n) and the sort > step is O(n log n) unless the data has some internal structure that > Timsort can use to get closer to O(n). > > If you implemented this and timed in it real apps, I would be surprised > to find that the slice extraction and assignments were the performance > bottleneck. IMO, a worthwhile performance gain is unlikely. I personally wouldn't find this to be a false optimization, at least not memory-wise. If you sort really large lists, and only want to sort part of the list, the memory gains of not having to do a slice should be enormous, and there should be some time-gains too. And, additionally, implementing this (if I understand timsort correctly, just had a look at the sources) isn't hard. Rather, I'd pose the usage question: why are you only sorting a part of a list? lists are basically meant for homogenous data. And sorting only a part of that should be a pretty meaningless operation, mostly... Anyway, I've just written up a patch to extend sort() with a start/stop parameter (which behaves just like the default slice notation). Generally, this will make sort() setup slightly slower in the "standard" case (because there's some more pointer arithmetic involved, but this should be negligible, and is O(1)), but for the actual use case, the following numbers can be seen: modelnine at phoenix ~/mercurial/python-modelnine $ ./python test.py New average time: 13.7254650593 ms per loop Old average time: 14.839854002 ms per loop [10198 refs] modelnine at phoenix ~/mercurial/python-modelnine $ This is just a very, very simple test (testing the case of a list with one million entries, where 99000 are sorted): >>> from random import randrange from time import time x = [randrange(256) for x in xrange(1000000)] timesnew, timesold = [], [] for reps in range(1000): y = x[:] timesnew.append(time()) y.sort(start=1000,stop=10000) timesnew[-1] = time() - timesnew[-1] for reps in range(1000): y = x[:] timesold.append(time()) y[1000:10000] = sorted(y[1000:10000]) timesold[-1] = time() - timesold[-1] print "New average time:", sum(timesnew), "ms per loop" print "Old average time:", sum(timesold), "ms per loop" >>> I'll post the patch to the SF bugtracker tomorrow, it's too late today for me to review it, but generally, I wouldn't find it to be a bad addition, if there's actually a general use case to only sort parts of a list. --- Heiko. From sam at nuevageorgia.com Tue May 23 12:13:24 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 23 May 2006 09:13:24 -0700 Subject: Python - Web Display Technology In-Reply-To: <44732c19$0$21103$626a54ce@news.free.fr> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <mailman.6050.1148253641.27775.python-list@python.org> <44732c19$0$21103$626a54ce@news.free.fr> Message-ID: <1148400804.164224.244680@y43g2000cwc.googlegroups.com> """"I would. Most people would, once they realize that shiny/flashy is information too. High "production values" affect value-determining centers of the brain, bypassing the linguistic and logical centers. They make you understand that the thing you're being presented is "worth something". Most of the time, it's only worth a fat cash profit to the person doing the presenting, who is giving you a piece of junk at an inflated price. But your brain doesn't care. It's got a shortcut to your wallet, and the information on the screen is accessing that. --Blair """" This was the most useful comment for me. I never fully considered that Flash was aiming at a different part of the brain. HTML is resonant with the mindset of Python, Flash is not. Perceptual match vs perceptual mismatch. From trebucket at gmail.com Wed May 17 19:16:38 2006 From: trebucket at gmail.com (trebucket at gmail.com) Date: 17 May 2006 16:16:38 -0700 Subject: How to tell if function was passed a list or a string? In-Reply-To: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> References: <1147900957.466840.192390@i40g2000cwc.googlegroups.com> Message-ID: <1147907798.819913.146580@i40g2000cwc.googlegroups.com> >>> import types >>> type("") is types.ListType False >>> type("") is types.StringType True >>> type([]) is types.StringType False >>> type([]) is types.ListType True From jeremy+complangpython at jeremysanders.net Tue May 9 04:43:06 2006 From: jeremy+complangpython at jeremysanders.net (Jeremy Sanders) Date: Tue, 09 May 2006 09:43:06 +0100 Subject: Why 3.0/5.0 = 0.59999... References: <1147159404.498386.58860@g10g2000cwb.googlegroups.com> Message-ID: <e3pkmq$202$1@gemini.csx.cam.ac.uk> Davy wrote: > Is there some precision loss? And how to overcome it? See http://docs.python.org/tut/node16.html for some useful information. -- Jeremy Sanders http://www.jeremysanders.net/ From aleax at mac.com Tue May 9 11:14:03 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 9 May 2006 08:14:03 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> <1147123648.914726.212680@i39g2000cwa.googlegroups.com> <1147156556.952331.29450@i39g2000cwa.googlegroups.com> <DN-dnRfxYOiFzv3ZnZ2dnUVZ_v6dnZ2d@speakeasy.net> <1147165494.822938.27590@e56g2000cwe.googlegroups.com> <lv-dnXZEUq9Mwf3ZRVn-jg@speakeasy.net> Message-ID: <1hf2987.bz1yak12k45qaN%aleax@mac.com> Rob Warnock <rpw3 at rpw3.org> wrote: ... > If "only" being useful is enough, 100 cycles is enough for a DNS server, > or an NTP server, or even a stub HTTP server that delivers some small > piece of real-time data, like a few realtime environmental sensors > [temperature, voltages, etc.]. Reminds me of Stuart Cheshire's description of how they managed to shoehorn zeroconf (aka bonjour, the artist formerly known as rendezvous) into a risible amount of ROM (less than 1K byte, if I recall correctly) left in an embedded microcontroller (for a video camera, I think). Zeroconf is at heart a few clever tricks on top of DNS (plus 169.254.* IPs), and in the end they managed by one more clever trick (the thingy ignores WHAT the request is for, and just spits out the same response each and every time -- pushing the boundaries of DNS but, it seems, still technically staying within those boundaries;-). Not directly relevant to the scaling debate (the camera's expected to be on a LAN, serving a few requests per second at most), but the limit being on bits rather than cycles somehow "tastes" similar to me. Alex From python-url at phaseit.net Mon May 8 19:01:00 2006 From: python-url at phaseit.net (Peter Otten) Date: Mon, 8 May 2006 23:01:00 +0000 (UTC) Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 8) Message-ID: <e3oijc$5l1$1@lairds.us> QOTW: "If you can find a workable solution not involving metaclasses and decorators, don't use them" - Michele Simionato "Newest Beautiful Soup beta solves everyone's problems that I know of." - Leonard Richardson Jeff Croft gives a good introduction to the Django web framework. Don't let the "for non-programmers" tag deter you. http://www2.jeffcroft.com/2006/may/02/django-non-programmers/ The recording of a presentation given by Django developer Jacob Kaplan-Moss takes little more time to download and consume, but requires only basic Python knowledge, too. http://video.google.com/videoplay?docid=-70449010942275062 [290 MB, 75 min] Debian now provides Python OpenCV bindings. http://www.intel.com/technology/computing/opencv/ If you know some C it may be interesting to learn how to translate error handling and passing of multiple result values into idiomatic Python. http://groups.google.com/group/comp.lang.python/msg/95c4918d139c0089 The basics of Python and SSL are discussed here: http://groups.google.com/group/comp.lang.python/browse_frm/thread/4f6386b597b43a78/bb424ccaedf42ee4?tvc=1 You have to be careful when you test a Queue's state, but that is business as usual in a multithreaded environment. http://groups.google.com/group/comp.lang.python/msg/7379ddaffb4d5fad The best way to pass a verbosity option around in your programm is using the logging package instead. http://groups.google.com/group/comp.lang.python/browse_frm/thread/75e65baa1a51b3a6/f2fe1ada4c3a07ea?tvc=1 While most Python users don't compete with the effbot by putting more than a dozen Python versions on their computer, having a few around for compatibility tests doesn't pose big problems, either. http://groups.google.com/group/comp.lang.python/msg/9c8ca8bd9a6e5105 Voicecode promises to make the keyboard superfluous for writing Python, C, and C++ code. http://www.p2pnet.net/story/8681 ======================================================================== 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, Tim Lesher, and Tony Meyer continue the marvelous tradition early borne by Andrew Kuchling, Michael Hudson and Brett Cannon of intelligently summarizing action on the python-dev mailing list once every other week. http://www.python.org/dev/summary/ The Python Package Index catalogues packages. http://www.python.org/pypi/ The somewhat older Vaults of Parnassus ambitiously collects references to all sorts of Python resources. http://www.vex.net/~x/parnassus/ Much of Python's real work takes place on Special-Interest Group mailing lists http://www.python.org/sigs/ Python Success Stories--from air-traffic control to on-line match-making--can inspire you or decision-makers to whom you're subject with a vision of what the language makes practical. http://www.pythonology.com/success The Python Software Foundation (PSF) has replaced the Python Consortium as an independent nexus of activity. It has official responsibility for Python's development and maintenance. http://www.python.org/psf/ Among the ways you can support PSF is with a donation. http://www.python.org/psf/donate.html Kurt B. Kaiser publishes a weekly report on faults and patches. http://www.google.com/groups?as_usubject=weekly%20python%20patch Although unmaintained since 2002, the Cetus collection of Python hyperlinks retains a few gems. http://www.cetus-links.org/oo_python.html Python FAQTS http://python.faqts.com/ The Cookbook is a collaborative effort to capture useful and interesting recipes. http://aspn.activestate.com/ASPN/Cookbook/Python 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 <Python-URL at phaseit.net> should get through. To receive a new issue of this posting in e-mail each Monday morning (approximately), ask <claird at phaseit.net> to subscribe. Mention "Python-URL!". -- The Python-URL! Team-- Dr. Dobb's Journal (http://www.ddj.com) is pleased to participate in and sponsor the "Python-URL!" project. From roy at panix.com Tue May 2 19:41:24 2006 From: roy at panix.com (Roy Smith) Date: Tue, 02 May 2006 19:41:24 -0400 Subject: assignment in if References: <87iroodnqz.fsf@localhost.localdomain> Message-ID: <roy-746AEB.19412402052006@reader1.panix.com> In article <87iroodnqz.fsf at localhost.localdomain>, Gary Wessle <phddas at yahoo.com> wrote: > Hi > > is there a way to make an assignment in the condition of "if" and use > it later, e.g. > > nx = re.compile('regex') > if nx.search(text): > funCall(text, nx.search(text)) > > nx.search(text) is evaluated twice, I was hoping for something like > > nx = re.compile('regex') > if x = nx.search(text): > funCall(text, x)) Personally, I find the C-style idiom you long for to be convenient and useful. That being said, it does not exist in Python, by deliberate design decision. In Python, assignment is not an operator with side effects like in C or Java, but a statement. What you need to do is: nx = re.compile('regex') x = nx.search(text) if x: funCall(text, x)) The lack of embedded assignments leads to slightly more verbose code in situations like this, but on the other hand, it avoids the typical C disaster of writing a whole function as a one liner. From sekhon.hari at googlemail.com Fri May 26 06:50:09 2006 From: sekhon.hari at googlemail.com (Hari Sekhon) Date: Fri, 26 May 2006 11:50:09 +0100 Subject: WinPops Message-ID: <4476DD61.7050201@gmail.com> Hi, Is there a way of sending winpops (Windows Pop-Up / Net Send messages) in python? Perhaps some library or something that I can use under both Windows and Linux? Hari From rick446 at usa.net Wed May 17 12:56:33 2006 From: rick446 at usa.net (Richard Copeland) Date: Wed, 17 May 2006 12:56:33 -0400 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> Message-ID: <KN-dnQHuvPtYyPbZRVn-ig@comcast.com> Try this: class Class: a='aa' b='bb' def __getattr__(self, ppt): return 'custom computed result' __getattr__ is only called when "normal" attribute lookup fails, so there's no need for the "hasattr" test. Also, I believe that __getattribute__ only applies to new-style classes (classes derived from "object"), and it will override *all* attribute accesses, anyway (meaning you'd have infinite recursion if you used it since you look up "self.ppt") Pierre wrote: > Hi, > > Sorry in advance, english is not my main language :/ > > I'd like to customize the result obtained by getattr on an object : if > the object has the requested property then return it BUT if the object > doesn't has actually this property return something else. > > In my case, I can't use getattr(object, property, default_value). > > I tried to write a class with a __getattr__ method and even a > __getattribute__ method but this doesn't do what I want.... > > Maybe I didn't correctly understand this : > http://docs.python.org/ref/attribute-access.html > > Here is a piece of my code : > ===================================== > class myclass: > """docstring""" > > a = 'aa' > b = 'bb' > > def __getattr___(self, ppt): > """getattr""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" > > def __getattribute__(self, ppt): > """getattribute""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" > > if __name__ == "__main__": > > d = myclass() > p1 = getattr(d, "a") > print p1 > p2 = getattr(d, "b") > print p2 > p3 = getattr(d, "c") > print p3 > ================================ > > I get an AttributeError when accessing to the property named "c". > > Any explanation/solution to my problem ? > From micklee74 at hotmail.com Tue May 2 02:31:03 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 1 May 2006 23:31:03 -0700 Subject: strip newlines and blanks Message-ID: <1146551463.451811.266960@j73g2000cwa.googlegroups.com> hi i have a file test.dat eg abcdefgh ijklmn <-----newline opqrs tuvwxyz I wish to print the contents of the file such that it appears: abcdefgh ijklmn opqrs tuvwxyz here is what i did: f = open("test.dat") while 1: line = f.readline().rstrip("\n") if line == '': break print line but it always give me first 2 lines, ie abcdefgh ijklmn What can i do to make it print all w/o the newlines..? and what is the proper way to skip printing blank lines while iterating file contents? thanks From tomerfiliba at gmail.com Sun May 21 15:13:21 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 21 May 2006 12:13:21 -0700 Subject: proposal: disambiguating type Message-ID: <1148238801.796827.56560@j33g2000cwa.googlegroups.com> typing "help(type)" gives the following documentation: >>> help(type) Help on class type in module __builtin__: class type(object) | type(object) -> the object's type | type(name, bases, dict) -> a new type "type" behaves both as a function, that reports the type of an object, and as a factory type for creating types, as used mainly with metaclasses. calling the constructor of types, like lists, etc., is expected to create a new instance of that type -- list() is a factory for lists, dict() is a factory for dicts, etc. but type() breaks this assumption. it behaves like a factory when called with 3 params, but as a function when called with one param. i find this overloading quite ugly and unnecessary. more over, it can cause abominations like >>> class x(type): ... pass ... >>> x(1) <type 'int'> or >>> list.__class__(1) <type 'int'> i suggest splitting this overloaded meaning into two separate builtins: * type(name, bases, dict) - a factory for types * typeof(obj) - returns the type of the object this way, "type" retains it meaning as the base-class for all types, and as a factory for types, while typeof() reports the object's type. it's also more intuitive that typeof(1) returns, well, the *type of* the object 1. no new keywords are needed, and code is always allowed to override builtin functions, so i don't expect backward- compatibility issues. proposed schedule: * 2.6 introduces typeof(), but type() with one argument retains its old meaning * 2.7 deprecates the usage of type() with a single argument * 2.8 type is only a factory, while typeof replaces type() with a single argument comments are welcome. -tomer From roman.zeyde at gmail.com Fri May 5 09:56:50 2006 From: roman.zeyde at gmail.com (roman.zeyde at gmail.com) Date: 5 May 2006 06:56:50 -0700 Subject: how to remove 50000 elements from a 100000 list? In-Reply-To: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> Message-ID: <1146837410.064061.84700@j73g2000cwa.googlegroups.com> Try to use set objects: >>> a=set(range(100000)) >>> b=set(range(50000)) >>> a = a - b From steven.bethard at gmail.com Mon May 22 13:12:06 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Mon, 22 May 2006 11:12:06 -0600 Subject: Using metaclasses to inherit class variables In-Reply-To: <1148315581.385405.204750@i40g2000cwc.googlegroups.com> References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> <1148315581.385405.204750@i40g2000cwc.googlegroups.com> Message-ID: <KvCdncoHsJN4bezZnZ2dnUVZ_sydnZ2d@comcast.com> telesphore4 at gmail.com wrote: > OK no question. I'm only posting b/c it may be something another newbie > will want to google in the future. Now that I've worked thru the > process this turns out to be fairly easy. > > However, if there are better ways please let me know. > > Module = ClassVars.py > > import copy > > class ClassVars(type): > classVars = {} > def __init__(cls, name, bases, dict): > for name, value in type(cls).classVars.iteritems(): > if name not in dict: > setattr(cls, name, copy.copy(value)) > > count = 0 # Not really needed but it semed nice to name the new types > def are(dict): > global count > count += 1 > return type('ClassVars%d' % count, (ClassVars,), > {'classVars':dict}) > > > To use in another module: > > import ClassVars > > class MyClass(str): > __metaclass__ = ClassVars.are(dict(name=None, desc=None, > myList=[])) > > # Rest of class definition ... Hmm... That still seems more complicated than you need. I think you really want to be able to write something like: class C(object): __metaclass__ = set_classvars(name=None, desc=None, myList=[]) Which is actually quite easily done with nested functions: >>> def set_classvars(**kwargs): ... def __metaclass__(name, bases, classdict): ... for name, value in kwargs.iteritems(): ... if name not in classdict: ... classdict[name] = value ... return type(name, bases, classdict) ... return __metaclass__ ... >>> class C(object): ... __metaclass__ = set_classvars(name='foo', desc='bar', list=[]) ... name = 'not foo' ... >>> C.name, C.desc, C.list ('not foo', 'bar', []) >>> class D(C): ... __metaclass__ = set_classvars(name='foo', list=[]) ... >>> D.name, D.desc, D.list, D.list is C.list ('foo', 'bar', [], False) STeVe From vinayakchitre at gmail.com Fri May 19 09:07:48 2006 From: vinayakchitre at gmail.com (Vinayakc) Date: 19 May 2006 06:07:48 -0700 Subject: Encode exception for chinese text In-Reply-To: <1148043734.554660.152120@j55g2000cwa.googlegroups.com> References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> <1148039929.462581.51770@i40g2000cwc.googlegroups.com> <1148042230.341700.151410@y43g2000cwc.googlegroups.com> <1148043734.554660.152120@j55g2000cwa.googlegroups.com> Message-ID: <1148044068.082279.3270@38g2000cwa.googlegroups.com> Hey Serge, john, Thank you very much. I was really not aware of these facts. Anyways this is happening only for one in millions so I can ignore this for now. Thanks again, Vinayakc From timr at probo.com Sat May 6 20:09:06 2006 From: timr at probo.com (Tim Roberts) Date: Sun, 07 May 2006 00:09:06 GMT Subject: the print statement References: <1146950481.610645.39710@j33g2000cwa.googlegroups.com> Message-ID: <n1eq52tv6r6uarag1394j8ejil2e4pom44@4ax.com> mirandacascade at yahoo.com wrote: > >O/S: Win2K >Vsn of Python: 2.4 > >Here is copy/paste from interactive window of pythonwin: >... >My questions are: >1) is the 'x' character within the variable y a signal that what >follows is a hex value? Sort of; it is the \x pair that signals this. This is in the Python documentation; the convention was borrowed from C. >2) is it more than just a coincidence that 146 (the result of >ord(y[3])) is the decimal equivalent of the hex number 92? Did you really have to ask that question? The 4th character of Y is a byte containing 0x92, which is 146 in decimal. >3) is there any character set in which 146 represents the >single-quote/apostrophe character? if so, which character set? Certainly. The default Windows code page, CP 1252, is an extension to ISO-8859-1 which includes this. It defines 0x91 as a "left single quote" and 0x92 as a "right single quote". In typography, you often want to use different quotes for something like 'this' than you do for something like isn't. 0x91 and 0x92 are used for 'this', and 0x27 is used for isn't. Your VGA font happens to display "left single quote" and "right single quote" with the same glyph as "apostrophe". >4) what is the role/function of the backslash character in the variable >y? See above. \x introduces a hex character. \047 is another special sequence; this is the octal code for apostrophe. >5) how did the print statement know to transform the contents of y >('Joe\x92s desk') to something that gets displayed as: > >Joe's desk >? The print statement didn't know that. It sent the 0x92 character. It's just that your VGA font happens to display them as the same glyph. >6) Would it be correct to infer that the print statement is aware of >characters beyond the 128 characters in the ascii character set? Certainly. It knows about whatever the current character set is. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From onurb at xiludom.gro Wed May 3 13:56:11 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 19:56:11 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: <yE56g.72397$H71.4757@newssvr13.news.prodigy.com> References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <4457fc52$0$31159$636a55ce@news.free.fr> <yE56g.72397$H71.4757@newssvr13.news.prodigy.com> Message-ID: <4458ef17$0$24993$636a55ce@news.free.fr> Edward Elliott wrote: > Bruno Desthuilliers wrote: > >>But then, constructs like: >> >>class Obj(object): >> def method(...): ... >> method = staticmethod(method) >> >>or it's newer syntactic-sugar-version would become somewhat more >>difficult to parse properly - but I admit that this is beyond my >>knowledge. > > > Hmm, that'll take some thought. I assume if you're making method static, > you don't declare a self parameter for it? Nope. But classmethods takes the class object as the first param (usually named 'cls'). > >>>e.g. when it sees "def method (a,b)" >> >>This has to be in a class statement - else it's shouldn't be touched. > > Exactly, that's why I called it method and not func. Technically, they are still function objects. They are later wrapped into method descriptor objects (at lookup time IIRC, but ask a guru or read the doc to know for sure). And don't forget the case of nested functions... > If you're declaring > methods outside the class and adding them dynamically, I think you would > need to declare 'self' explicitly. Of course. Virtually *any* function can be set as a method[1] outside the class statement scope, either directly on the class object or - with manual wrapping - on an individual instance. And it's important to keep this feature. (snip) >>>I can prove that assertion too: make a simple text processor that reads >>>Python source code and outputs the same source code with only one change: >>>insert the string 'self" as the first parameter of every "def >>>somemethod". >> >>Not so simple: you have plain functions (outside class statements), and >>inner functions (inside def statements), and classmethods, and statict >>methods, and some other corner cases (like __new__()) to take into >>acccount... > > > Well I'm assuming the rules for when to put 'self' in the parameter list are > simple enough to be automated. They are still complex enough to require a real parser. And anyway, since this is a syntax change, this should be handled by the parser IMHO. (snip) > >>You'll have to really prove it doesn't break anything else in the >>object model, have strong and articulate arguments to support your point >>(like proving this is really a common source of confusion for newbies), >>and I really doubt it'll be accepted anyway. But what... > > > It's definitely an uphill battle and I wonder if it's really worth the > effort. Honestly, I don't think it has much chance. I barely even notice typing 'self' or 'cls', and I guess it's the same for most Python programmers - those who can't stand it probably use another language... And FWIW, I still prefer to keep consistency in functions definitions. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From noemail at junk.com Sat May 13 14:09:19 2006 From: noemail at junk.com (The Shaffer s) Date: Sat, 13 May 2006 14:09:19 -0400 Subject: Setting up InformixDb Message-ID: <C08B990E.5807%noemail@junk.com> I have an informix database on a unix machine which I want to access. I downloaded InformixDb-2.2 and managed to get it built and installed and it works fine with python. My problem is I want to access the same database from a PC remotely. Yes, I already have informix setup and configured on the unix machine to accept connections remotely. And, I can connect to it fine from an ODBC interface to Excel and Access. But, to build the informix module requires the INFORMIXDIR environment variable set to it which I don't believe I can set to a remote machine. So, how can I get this module built without having an informix installed on my PC? Thanks. Ken From jarrod.roberson at gmail.com Sat May 20 15:43:12 2006 From: jarrod.roberson at gmail.com (fuzzylollipop) Date: 20 May 2006 12:43:12 -0700 Subject: Simple DAV server? In-Reply-To: <10ddj3-qhb.ln1@snout.lairds.com> References: <e22ngm$ipq$1@ulysses.news.tiscali.de> <e23v7e$4uq$1@news1.carnet.hr> <e25ib0$12hc$1@ulysses.news.tiscali.de> <e26hrl$dfc$1@news1.carnet.hr> <e27p5p$1ehi$1@ulysses.news.tiscali.de> <e285ur$obt$1@news1.carnet.hr> <e2isqu$ckm$1@ulysses.news.tiscali.de> <1fg0i3-7pc.ln1@snout.lairds.com> <e2rkq0$g7s$1@news1.carnet.hr> <10ddj3-qhb.ln1@snout.lairds.com> Message-ID: <1148154192.576503.29480@38g2000cwa.googlegroups.com> webfolders is broken, I have worked on webdav support at the isp level ( for millions of customers to use ) webfolders is NOT something you should base compliancey on. It is broken so badly that we decided to just not even test against it. We provide our customers with our own application with which to map drive letters to mount webdav our webdav store so we don't have to even worry about Web Folders not working. From fccoelho at gmail.com Sat May 13 18:16:35 2006 From: fccoelho at gmail.com (Flavio) Date: 13 May 2006 15:16:35 -0700 Subject: distributing a app frozen by cx_freeze In-Reply-To: <1147549615.716786.240560@d71g2000cwd.googlegroups.com> References: <1147482467.404798.187530@y43g2000cwc.googlegroups.com> <1147501391.800070.265860@g10g2000cwb.googlegroups.com> <1147536825.158172.73480@i40g2000cwc.googlegroups.com> <1147549615.716786.240560@d71g2000cwd.googlegroups.com> Message-ID: <1147558595.026963.250380@d71g2000cwd.googlegroups.com> I know, but the whole point of cx_freeze is to generate standalone executables, so asking for an installation of an specific version of Qt is just a little better than asking the end user to install from source... From ptmcg at austin.rr._bogus_.com Wed May 3 09:10:27 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 03 May 2006 13:10:27 GMT Subject: Recommended data structure for newbie References: <1146626916.066395.206540@y43g2000cwc.googlegroups.com> Message-ID: <7Z16g.1536$CH2.1053@tornado.texas.rr.com> "manstey" <manstey at csu.edu.au> wrote in message news:1146626916.066395.206540 at y43g2000cwc.googlegroups.com... > Hi, > > I have a text file with about 450,000 lines. Each line has 4-5 fields, > separated by various delimiters (spaces, @, etc). > > I want to load in the text file and then run routines on it to produce > 2-3 additional fields. > <snip> Matthew - If you find re's to be a bit cryptic, here is a pyparsing version that may be a bit more readable, and will easily scan through your input file: ================ from pyparsing import OneOrMore, Word, alphas, oneOf, restOfLine, lineno data = """gee fre asd[234 ger dsf asd[243 gwer af as.:^25a""" # define format of input line, that is: # - one or more words, composed of alphabetic characters, periods, and colons # - one of the characters '[' or '^' # - the rest of the line entry = OneOrMore( Word(alphas+".:") ) + oneOf("[ ^") + restOfLine # scan for matches in input data - for each match, scanString will # report the matching tokens, and start and end locations for toks,start,end in entry.scanString(data): print toks print # scan again, this time generating additional fields for toks,start,end in entry.scanString(data): tokens = list(toks) # change these lines to implement your # desired generation code - couldn't guess # what you wanted from your example tokens.append( toks[0]+toks[1] ) tokens.append( toks[-1] + toks[-1][-1] ) tokens.append( str( lineno(start, data) ) ) print tokens ================ prints: ['gee', 'fre', 'asd', '[', '234'] ['ger', 'dsf', 'asd', '[', '243'] ['gwer', 'af', 'as.:', '^', '25a'] ['gee', 'fre', 'asd', '[', '234', 'geefre', '2344', '1'] ['ger', 'dsf', 'asd', '[', '243', 'gerdsf', '2433', '2'] ['gwer', 'af', 'as.:', '^', '25a', 'gweraf', '25aa', '3'] You asked about data structures specifically. The core collections in python are lists, dicts, and more recently, sets. Pyparsing returns tokens from its matching process using a pyparsing-defined class called ParseResults. Fortunately, using Python's "duck-typing" model, you can treat ParseResults objects just like a list, or like a dict if you have assigned names to the fields in the parsing expression. Download pyparsing at http://pyparsing.sourceforge.net. -- Paul From nobody at 127.0.0.1 Wed May 17 22:08:15 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 02:08:15 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> Message-ID: <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> Ben Finney wrote: > I responded to a post that seemed to claim that anecdotes about events > can be treated as data about events. They can't; that's what I'm > arguing. And conveniently ignoring the key part of my post. Here it is again for those who missed it: "Before the days of cheap video, lots of scientific data was gathered by lone observers recording unrepeatable events.??You?build?statistics?by accumulating a vast number of such observations over time." Sounds like anecdotes can become data to me. It's a stupid argument anyway. Anecdotes *are* data. Some data is repeatable, some is not. All data has an associated confidence level. Single anecdotes are relatively low, as you gather more the confidence level rises (for the aggregate). Eventually you reach the maximal level by definition: the sum of all anecdotes is the universe of available data. No one's saying anecdotes are 100% reliable. But they aren't 0% reliable either. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From rpdooling at gmail.com Mon May 15 10:13:00 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 May 2006 07:13:00 -0700 Subject: keyword help in Pythonwin interpreter Message-ID: <1147702380.665861.106540@g10g2000cwb.googlegroups.com> Using ActivePython 2.4.3 on Windows XP While in the Pythonwin IDE, if I seek keyword help by issuing the following command: >>>help ('while') I get: Sorry, topic and keyword documentation is not available because the Python HTML documentation files could not be found. If you have installed them, please set the environment variable PYTHONDOCS to indicate their location. My PYTHONDOCS variable is set to: c:\python24\Doc\Python-Docs-2.4.2\ref which appears to be correct (ie the help html files are installed there). Searching this group, I found someone else complaining about the same behavior with no clear resolution. http://tinyurl.com/pblev Any advice? rick From gregory.petrosyan at gmail.com Fri May 26 14:44:15 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 26 May 2006 11:44:15 -0700 Subject: write() vs. writelines() References: <1148667630.902170.310930@i40g2000cwc.googlegroups.com> <mailman.6257.1148668587.27775.python-list@python.org> Message-ID: <1148669055.390737.57050@j33g2000cwa.googlegroups.com> Thanks for your reply. I understand this fact, but I wonder why writelines() works slowly -- I think C code can be optimised to work faster than Python one. Is it correct that writelines(...) is just a shorthand for for ch in ...: file.write(ch) ? From seberino at spawar.navy.mil Sun May 7 22:48:38 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 7 May 2006 19:48:38 -0700 Subject: Python Eggs Just install in *ONE* place? Easy to uninstall? In-Reply-To: <mailman.5437.1146962605.27775.python-list@python.org> References: <1146936395.028140.15640@i39g2000cwa.googlegroups.com> <mailman.5437.1146962605.27775.python-list@python.org> Message-ID: <1147056518.652933.27270@i39g2000cwa.googlegroups.com> But not matter where eggs are installed they are never spread across multiple places on hard drive right? An egg is all under one node of tree right? From perlefar at gmail.com Wed May 24 06:13:26 2006 From: perlefar at gmail.com (Zameer) Date: 24 May 2006 03:13:26 -0700 Subject: Best way to handle exceptions with try/finally In-Reply-To: <mailman.6122.1148413632.27775.python-list@python.org> References: <mailman.6122.1148413632.27775.python-list@python.org> Message-ID: <1148465606.079283.184470@y43g2000cwc.googlegroups.com> Unindent your first return statement. The return statement in putVar is not needed. From sdcook55 at sbcglobal.net Mon May 29 16:08:30 2006 From: sdcook55 at sbcglobal.net (Stan Cook) Date: Mon, 29 May 2006 20:08:30 GMT Subject: create a text file Message-ID: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> I'm writing a script to list all of my music files' id3 tags to a comma delimited file. The only part I'm missing seems like it should be the simplest. I haven't used Python for the last couple of years. My question is this: When I use os.open(<file_variable>,"w"), I get an error message, TypeError: an integer is required. Has something changed? Did I miss something??? Thanks, -------------------> S Cook From DirkHagemann at gmail.com Thu May 18 11:00:15 2006 From: DirkHagemann at gmail.com (Dirk Hagemann) Date: 18 May 2006 08:00:15 -0700 Subject: Windows Registry Dump Message-ID: <1147964415.540190.47480@i40g2000cwc.googlegroups.com> Hi! Does someone know how I can make a Text-Dump-File of a remote Windows-Computer's Registry (not the whole registry - only a part of it)? Thanks a lot for some code or a helpful link! regards Dirk From chris.uppal at metagnostic.REMOVE-THIS.org Sun May 7 05:35:15 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Sun, 7 May 2006 10:35:15 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <87wtcyy5i0.fsf@rpi.edu> Message-ID: <445dc17a$1$25449$bed64819@news.gradwell.net> Bill Atkins wrote: > But why should I have to worry about any of this? Why can't I do: > > (with-indentation (pdf (+ (indentation pdf) 4)) > (out-header) > (out-facts)) > > and then within, say out-facts: > > (with-indentation (pdf (+ (indentation pdf) 4)) > (write pdf "some text")) > > More readable, and no bookkeeping to worry about. This is great! And > here's the macro: . [...] Can you explain to a non-Lisper why macros are needed for this ? I'm a Smalltalker, and Smalltalk has no macros, nor anything like 'em, but the equivalent of the above in Smalltalk is perfectly feasible, and does not require a separate layer of semantics (which is how I think of true macros). aPdf withAdditionalIndent: 4 do: [ aPdf writeHeader; writeFacts ]. and aPdf withAdditionalIndent: 4 do: [ aPdf write: '... some text...' ]. Readers unfamiliar with Smalltalk may not find this any easier to read that your Lisp code, but I can assure them that to any Smalltalker that code would be both completely idiomatic and completely transparent. (Although I think a fair number of Smalltalkers would choose to use a slightly different way of expressing this -- which I've avoided here only in order to keep things simple). > Macros rock. I have yet to be persuaded of this ;-) -- chris From google at spiceaid.com Wed May 10 13:44:09 2006 From: google at spiceaid.com (Dr. Who) Date: 10 May 2006 10:44:09 -0700 Subject: Is Welfare Part of Capitalism? In-Reply-To: <s097j3-3u3.ln1@eskimo.tundraware.com> References: <1147200065.889769.76050@v46g2000cwv.googlegroups.com> <s097j3-3u3.ln1@eskimo.tundraware.com> Message-ID: <1147283049.602226.74730@y43g2000cwc.googlegroups.com> Technically, I would call it a manfesto. The manifesto module is probably the most facinating module in Python since it's the only one whose functions consist entirely of doc strings followed by a pass and do no useful work. Jeff Tim Daneliuk wrote: > envyisevil at yahoo.com wrote: > > This article is dedicated to: > > > <SNIP> > > > But I am still confused: Is this a statement or an expression? From LittlePython at lost.com Sun May 28 10:27:08 2006 From: LittlePython at lost.com (LittlePython) Date: Sun, 28 May 2006 14:27:08 GMT Subject: Using a package like PyInstaller References: <FyYdg.2216$As2.860@trnddc02> <e5ab5l$tkm$1@daisy.noc.ucla.edu> <DD4eg.2432$As2.2216@trnddc02> <e5amec$64m$1@daisy.noc.ucla.edu> <ZX5eg.287$xO5.197@trnddc03> <e5bf4k$of9$1@daisy.noc.ucla.edu> Message-ID: <0rieg.1829$hv1.972@trnddc01> "Im 99.999% confident that this will not happen from the .exe file generated by pyinstaller (unless you specify--see link above)." Well I guess that's about as close as any one can get in this business. I have been trying to introduce py into our environment, and have opened a few eyes, however I have been given one restriction. I can not install anything, leave behind anything or alter anything on a systems ...... period, and as the saying goes "To error is human but to forgive is not company policy!" thx for your comments! "James Stroud" <jstroud at ucla.edu> wrote in message news:e5bf4k$of9$1 at daisy.noc.ucla.edu... > LittlePython wrote: > > That is very close to what I have being doing, however I was unable to > > enclose a bmp or another file for that matter in the exe. I used both DATA > > and BINARY key words with no luck. I checked what was in the package and > > there were there. I guess for some reason it could not locate then when > > executed. I used snap 274 if I remember correctly. > > You can include files with innosetup under the [FILES] section. The docs > show how. You can then code absolute paths to these resources in your > code according to the results of 'sys.platform'. If you use the > "--onedir" option, then you may want to look here: > > http://pyinstaller.hpcf.upr.edu/docs/Manual_v1.1.html#accessing-data-files > > > > I am worrying that > > when the py script is run I am leaving behind files. That the components of > > my stand-alone exe is somehow coming out of the exe (PyInstaller) and being > > installed. > > Im 99.999% confident that this will not happen from the .exe file > generated by pyinstaller (unless you specify--see link above). > > However, innosetup will put files in the 'Program Files' directory or > wherever you specify. This would be similar to just about every other > application out there for windows. > > James > > -- > James Stroud > UCLA-DOE Institute for Genomics and Proteomics > Box 951570 > Los Angeles, CA 90095 > > http://www.jamesstroud.com/ From nospamjynyl at yahoo.co.nz Wed May 10 04:30:16 2006 From: nospamjynyl at yahoo.co.nz (Peter) Date: Wed, 10 May 2006 20:30:16 +1200 Subject: data entry tool References: <445f038f@news.maxnet.co.nz> <4c8gkoF14mu9cU1@uni-berlin.de> Message-ID: <4461a499@news.maxnet.co.nz> Diez B. Roggisch wrote: > Make it a webapp. That will guarantee to make it runnable on the list of > OSses you gave. Use Django/TurboGears/ZOPE for the application itself- > whichever suits you best. A webapp isn't feasible as most of the users are on dial up (this is in New Zealand and broadband isn't available for lots of people). I was hoping for a simple tool. Even if it only worked on Windows, it would be a start. It just needs to present a form of text entry fields to the user, and place the data in a plain text file. If python can't do this, can anyone suggest another language or approach? TIA Peter From jens.goepfert at tracetronic.de Tue May 16 05:05:12 2006 From: jens.goepfert at tracetronic.de (Jens) Date: 16 May 2006 02:05:12 -0700 Subject: problem with namespaces using eval and exec Message-ID: <1147770312.756392.147920@i39g2000cwa.googlegroups.com> Hi, has anyone an idea why the following code does not work. s = """ def a(n): return n*n def b(t): return a(t) """ ns = {} exec(s, {}, ns) eval("b(2)", ns, {}) executing this script raises an exception (NameError: global name 'a' is not defined) in the last line. Hope for your help. From jim.lewis at miclog.com Mon May 22 20:38:40 2006 From: jim.lewis at miclog.com (Jim Lewis) Date: 22 May 2006 17:38:40 -0700 Subject: Pyrex installation on windows XP: step-by-step guide References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146164100.552822.280630@j33g2000cwa.googlegroups.com> <1148251275.211468.221460@g10g2000cwb.googlegroups.com> <mailman.6055.1148262320.27775.python-list@python.org> Message-ID: <1148344720.139905.282630@y43g2000cwc.googlegroups.com> Still problems :-( I have a directory c:\data\code\test\pyrex containing: build_and_install.bat: "C:\program files\Python\python.exe" setup.py build_ext --compiler=mingw32 pause setup.py: from distutils.core import setup from distutils.extension import Extension from Pyrex.Distutils import build_ext setup( name = "PyrexGuide", ext_modules=[ Extension("worldimport", ["world.pyx"]) ], cmdclass = {'build_ext': build_ext} ) world.pyx - pyrex code run.py: import worldimport ... ======================== The batch file creates a build folder with subfolders containing: world.pyd, world.def, world.o, worldimport.def But running run.py gives: "ImportError: No module named worldimport" Should worldimport.def be going to C:\program files\python\Lib\site-packages? Why isn't it? From onurb at xiludom.gro Mon May 22 04:23:04 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 22 May 2006 10:23:04 +0200 Subject: Name conflict in class hierarchy In-Reply-To: <rcp4k3-1c5.ln1@prcm.tecont.de> References: <mailman.6014.1148158078.27775.python-list@python.org> <rcp4k3-1c5.ln1@prcm.tecont.de> Message-ID: <44717552$0$10541$636a55ce@news.free.fr> Ralf Muschall wrote: > Jeffrey Barish wrote: > > [overriding of base class member functions by subclass] > (snip) > > In Python, a function not intended to be overriden should be either > have a name starting with an underscore actually with *two* underscores. The single-leading-underscore naming scheme is the convention for 'protected' (read: 'implementation, not API') attributes. > or be documented. s/or/and/ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jiba at tuxfamily.org Thu May 25 18:41:44 2006 From: jiba at tuxfamily.org (jiba at tuxfamily.org) Date: 25 May 2006 15:41:44 -0700 Subject: Secure Pickle-like module References: <1148588541.444993.115600@u72g2000cwu.googlegroups.com> <mailman.6207.1148590975.27775.python-list@python.org> Message-ID: <1148596904.420626.96550@i40g2000cwc.googlegroups.com> > There are a couple factual inaccuracies on the site that I'd like to clear up first: > Trivial benchmarks put cerealizer and banana/jelly on the same level as far as performance goes: > $ python -m timeit -s 'from cereal import dumps; L = ["Hello", " ", ("w", "o", "r", "l", "d", ".")]' 'dumps(L)' > 10000 loops, best of 3: 84.1 usec per loop > $ python -m timeit -s 'from twisted.spread import banana, jelly; dumps = lambda o: banana.encode(jelly.jelly(o)); L = ["Hello", " ", ("w", "o", "r", "l", "d", ".")]' 'dumps(L)' > 10000 loops, best of 3: 89.7 usec per loop > > This is with cBanana though, which has to be explicitly enabled and, of course, is written in C. So Cerealizer looks like it has the potential to do pretty well, performance-wise. My personal benchmark was different; it was using a list with 2000 objects defined as following: class O(object): def __init__(self): self.x = 1 self.s = "jiba" self.o = None with self.o referring to another O object. I think my benchmark, although still very limited, is more representative since it involves object, string, number and list. See it there: http://svn.gna.org/viewcvs/*checkout*/soya/trunk/cerealizer/test/test1.py?content-type=text%2Fplain&rev=31 The results are (using Psyco): With old-style classes: cerealizer dumps in 0.0619530677795 s, 114914 bytes length loads in 0.0313038825989 s cPickle dumps in 0.0301840305328 s, 116356 bytes length loads in 0.023097038269 s jelly + banana dumps in 0.168012142181 s 169729 bytes length loads in 1.82081913948 s jelly + cBanana dumps in 0.082946062088 s 169729 bytes length loads in 0.156159877777 s With new-style classes: cerealizer dumps in 0.0575239658356 s, 114914 bytes length loads in 0.028165102005 s cPickle dumps in 0.07634806633 s, 116428 bytes length loads in 0.0278959274292 s jelly + banana dumps in 0.156242132187 s 169729 bytes length (TypeError; I didn't investigate this problem yet although it is surely solvable) jelly + cBanana dumps in 0.10772895813 s 169729 bytes length (TypeError; I didn't investigate this problem yet although it is surely solvable) As you see, cPickle is about 2 times faster than cerealizer for old-style classes, but cerealizer beats cPickle for new-style classes (which makes sense since I have optimized it for new-style classes). However, Jelly is far behind, even using cBanana, especially for loading. > You talked about _Tuple and _Dereference on the website as well. These are internal implementation details. jelly also supports extension types, by way of setUnjellyableForClass and similar functions. The problem arises only when the extension type expects an attribute of a specific class, e.g. (in Pyrex): cdef class MyClass: cdef MyClass other The other attribute of MyClass can only contains a reference to an instance of MyClass (or None). Thus it cannot be set to an instance of _Dereference or _Tuple, even temporarily; doing other = _Dereference(...) raises an exception. I solve this problem in Cerealizer by doing a 2-pass object creation: step 1, create all the objects; step 2, set all objects' states. > As far as security goes, no obvious problems jump out at me, either > from the API for from skimming the code. I think early-binding > __new__, __getstate__, and __setstate__ may be going further than > is necessary. If someone can find code to set attributes on classes > in your process space, they can probably already do anything they > want to your program and don't need to exploit security problems in > your serializer. I agree on that; however I prefer to be "over-secure" than "just as secure as necessary" :-) Thank you for your opinion! I'm going to update my website. Jiba From robert.kern at gmail.com Sat May 6 18:19:28 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 06 May 2006 17:19:28 -0500 Subject: NaN handling In-Reply-To: <125q3qk6tk9go4a@corp.supernews.com> References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> <mailman.5402.1146867973.27775.python-list@python.org> <125nlbgm8l1fi17@corp.supernews.com> <DE87348C-5BE0-4D55-B041-516FB72E7B04@mcmaster.ca> <mailman.5409.1146880569.27775.python-list@python.org> <yfsy7xfxr1x.fsf@oc.ex.ac.uk> <mailman.5428.1146943512.27775.python-list@python.org> <125q3qk6tk9go4a@corp.supernews.com> Message-ID: <e3j7dh$hd6$1@sea.gmane.org> Grant Edwards wrote: > On 2006-05-06, Robert Kern <robert.kern at gmail.com> wrote: > >>>>>Since numpy seems to be working on a variety of platforms/hardware, >>>>>how hard would it be to extract this functionality from it to add to >>>>>Python proper? >>>> >>>>Harder than just enabling fpectl. >>> >>>Last thing I heard fpectl was considered to be completely broken -- it's >>>likely not disabled by default for no reason. >> >>Fair enough. If you want to go through numpy's code to rip out its floating >>point error handling, knock yourself out. It's not going to be trivial, though. >>It's heavily embedded in the ufunc machinery. > > Does numpy's NaN handling only work within numpy functions, or > does it enable HW FP signals and then catch them for "normal" > floating point operations that take place outside of numpy code? Just in numpy code, it seems. In [1]: import numpy i In [2]: import math In [3]: numpy.seterr(invalid='raise') Out[3]: {'over': 'ignore', 'divide': 'ignore', 'invalid': 'ignore', 'under': 'ignore'} In [4]: numpy.log(-1.0) --------------------------------------------------------------------------- exceptions.FloatingPointError Traceback (most recent call last) /Users/kern/<ipython console> FloatingPointError: invalid encountered in log In [5]: math.log(-1.0) Out[5]: nan -- 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 fwgnyelt at fufmxels.com Sat May 27 00:22:57 2006 From: fwgnyelt at fufmxels.com (jhdshydsguisfdbjk@zoominternet.net) Date: Sat, 27 May 2006 00:22:57 -0400 Subject: need a date look here Message-ID: <1148703444_11237@sp6iad.superfeed.net> Get all the hots girls @ www.pearlymae.com -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060527/1f1209e5/attachment.html> From gdkinney at gmail.com Tue May 9 10:59:42 2006 From: gdkinney at gmail.com (gdkinney at gmail.com) Date: 9 May 2006 07:59:42 -0700 Subject: Python editor recommendation. In-Reply-To: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <1147186782.792802.227170@g10g2000cwb.googlegroups.com> I've always just used Idle myself. From oliphant.travis at ieee.org Sat May 27 05:23:55 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Sat, 27 May 2006 03:23:55 -0600 Subject: matplotlib and numpy installation In-Reply-To: <1148715666.148775.85390@i39g2000cwa.googlegroups.com> References: <1148715666.148775.85390@i39g2000cwa.googlegroups.com> Message-ID: <e595rb$s4c$1@sea.gmane.org> cesco wrote: > Hi, > > I wanted to install python, numpy and matplotlib on Linux Ubuntu. > I installed python with the following commands > ./configure --enable-unicode=ucs4 > [snip] > running build_ext > building 'matplotlib.backends._ns_backend_agg' extension > gcc options: '-pthread -fno-strict-aliasing -DNDEBUG -g -O3 -Wall > -Wstrict-prot\ > otypes -fPIC' > compile options: > '-I/usr/local/lib/python2.4/site-packages/numpy/core/include -\ > I/usr/include -I. -Isrc -Iswig -Iagg23/include -I. -I/usr/include -I. > -I/usr/lo\ > cal/lib/python2.4/site-packages/numpy/core/include/freetype2 > -I/usr/include/fre\ > etype2 -I./freetype2 -Isrc/freetype2 -Iswig/freetype2 > -Iagg23/include/freetype2\ > -I./freetype2 -I/usr/include/freetype2 -I./freetype2 > -I/usr/local/include/pyth\ > on2.4 -c' > extra options: '-DSCIPY=1' > gcc: src/_image.cpp > src/_image.cpp:5:17: png.h: No such file or directory This is the source of the remaining errors.... On my system the "png.h" file comes from a libpng3-devel rpm Perhaps you need to use apt-get to obtain the development package for png. -Travis From keith.b.perry at gmail.com Wed May 31 09:25:16 2006 From: keith.b.perry at gmail.com (kbperry) Date: 31 May 2006 06:25:16 -0700 Subject: Way to get an array of latitude/longitude points (tuples) from a trip In-Reply-To: <4e3sv1F1cvehrU1@uni-berlin.de> References: <1148991896.430571.33700@j55g2000cwa.googlegroups.com> <4e3sv1F1cvehrU1@uni-berlin.de> Message-ID: <1149081916.521113.254530@i39g2000cwa.googlegroups.com> > The problem is not the latitude/longitude. It would be trivial to > compute the great circle, thus the length of the trip between A and B > and divide it in smaller pieces to get 1-mile-distances. Yeah, I am starting to wish we drove in straight lines. > But unless you own an Aircraft & are important enough to take flights > the direct route without air traffic control getting mad at you (aka: > you are George W. Bush or some other bigwig goverment guy), this won't > do you much good. What you needed would be a vectormap of the streets so > that you could do route planning. Which is expensive to get. It just seems odd with all of the map software out there, that this isn't available. > So I guess you are better off trying to find someone who offers that as > part of the service. I wonder how expensive that would be....probably way out of our price range. From vbgunz at gmail.com Tue May 23 03:29:28 2006 From: vbgunz at gmail.com (vbgunz) Date: 23 May 2006 00:29:28 -0700 Subject: New beginner to python for advice In-Reply-To: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> References: <1148367055.409713.51170@j55g2000cwa.googlegroups.com> Message-ID: <1148369368.892701.310670@g10g2000cwb.googlegroups.com> > I am a new beginner to python, would you like give me some > advice on studying it? http://www.python.org/doc/ is a real great place to start. Are you looking for different advice? From hancock at anansispaceworks.com Wed May 24 01:52:38 2006 From: hancock at anansispaceworks.com (Terry Hancock) Date: Wed, 24 May 2006 05:52:38 +0000 Subject: graphs and charts In-Reply-To: <4473444E.4060102@telus.net> References: <4473444E.4060102@telus.net> Message-ID: <4473F4A6.1000805@anansispaceworks.com> Yaron Butterfield wrote: > What's the best way to on-the-fly graphs and charts using Python? Or > is Python not really the best way to do this? I quite enjoyed using Biggles for this: http://biggles.sf.net There are many different choices, though. Cheers, Terry -- Terry Hancock (hancock at AnansiSpaceworks.com) Anansi Spaceworks http://www.AnansiSpaceworks.com From gherron at islandtraining.com Sun May 7 12:21:41 2006 From: gherron at islandtraining.com (Gary Herron) Date: Sun, 07 May 2006 09:21:41 -0700 Subject: NumTut view of greece In-Reply-To: <87k68xakmq.fsf@localhost.localdomain> References: <87k68xakmq.fsf@localhost.localdomain> Message-ID: <445E1E95.9090307@islandtraining.com> Gary Wessle wrote: >Hi > >not sure if this would be the right place to ask this question! >using the shell prompt >:~$ python >Python 2.3.5 (#2, Mar 6 2006, 10:12:24) >[GCC 4.0.3 20060304 (prerelease) (Debian 4.0.2-10)] on linux2 >Type "help", "copyright", "credits" or "license" for more information. > > >>>>import Numeric >>>>from NumTut import * >>>>view(greece) >>>> >>>> >>>> >shows a photo of the street in a tk window. > >but if I have this file >**************** tut.py **************** >#!/usr/bin/env python >import Numeric >from NumTut import * >view(greece) >print "done" >**************************************************************** >and then type >$ ./tut.py >done >$ >and not tk view of greece. > > That's because, as soon as the program quits, the view window is removed. In your interactive example, the view command opens the window, and then immediately starts waiting for you to type the next command. Python is still running and so the view window stays up. In the non-interactive case, as soon as the view command executes, Python immediately goes to the next line, does the print, then exits. The view command, which was busily preparing to show your picture is shut down when python exits before it had enough time to open the window. (It was trying -- it just didn't have enough time.) If you don't want the program to quit that quickly, you need to put in something to keep it from running off the bottom and exiting. I'd suggest something like this after the view line: raw_input("Type ENTER when done viewing: ") Gary Herron >thanks > > From blair.houghton at gmail.com Mon May 22 12:43:09 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 22 May 2006 09:43:09 -0700 Subject: Python - Web Display Technology In-Reply-To: <slrne6o7r9.k84.sybrenUSE@schuimige.stuvel.eu> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5867.1147935817.27775.python-list@python.org> <slrne6o7r9.k84.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1148316188.691369.215440@u72g2000cwu.googlegroups.com> Sybren Stuvel wrote: > Heiko Wundram enlightened us with: > > And: the web is a platform to offer _information_. Not to offer > > shiny graphics/sound [...] > > Many would disagree... > > Not me, but I know a lot of people that would. I would. Most people would, once they realize that shiny/flashy is information too. High "production values" affect value-determining centers of the brain, bypassing the linguistic and logical centers. They make you understand that the thing you're being presented is "worth something". Most of the time, it's only worth a fat cash profit to the person doing the presenting, who is giving you a piece of junk at an inflated price. But your brain doesn't care. It's got a shortcut to your wallet, and the information on the screen is accessing that. --Blair From nobody at 127.0.0.1 Thu May 18 19:35:31 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 23:35:31 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <mailman.5905.1147988818.27775.python-list@python.org> Message-ID: <7x7bg.78394$H71.74215@newssvr13.news.prodigy.com> Ben Finney wrote: > Until we get the code to examine independently, all we have is an > anecdote. Thus the comparison to UFO sightings. Except UFO sightings comprise a large body of data containing a vast number of known false reports and others that appear to be in the same vein with no verified positives despite many concerted efforts to produce such evidence. Here we have a single data point with no positive or negative corroborations. It's like a guy saying he saw a cloud that looks like a python. The cloud's gone now, but other people can watch other clouds and report what they see. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From sybrenUSE at YOURthirdtower.com.imagination Mon May 15 04:37:15 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 15 May 2006 10:37:15 +0200 Subject: Web framework to recommend References: <e495q1$1085$1@news.hgc.com.hk> Message-ID: <slrne6gfdr.6g0.sybrenUSE@schuimige.stuvel.eu> Jacky enlightened us with: > I just started learning Python and would like to starting writing > some web-based applications with Python. You could check out my web framework, the UnrealTower Engine. It uses Cheetah as template engine, it's fast and small - it doesn't get in your way. http://www.unrealtower.org/engine Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From abuse at dopiaza.cabal.org.uk Tue May 30 10:12:39 2006 From: abuse at dopiaza.cabal.org.uk (Peter Corlett) Date: 30 May 2006 14:12:39 GMT Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> Message-ID: <447c52d7$0$696$fa0fcedb@news.zen.co.uk> Grant Edwards <grante at visi.com> wrote: [...] > Under Linux there isn't really anything. IIRC, many years ago, somebody > had written a kernel module that inserted itself between application and > serial port and logged operations, but the last time I tried to find it, I > was unsuccessful. A dirty hack that might work is to rename /dev/ttyS* off somewhere else and replace them with named pipes. Have a process monitor the named pipes and relay data back and forth to the actual serial ports while logging it. The serial ioctls won't work to the named pipe, but the application might not notice it failed. But this is probably way too advanced for the OP. -- PGP key ID E85DC776 - finger abuse at mooli.org.uk for full key From nobody at 127.0.0.1 Sun May 14 17:08:52 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 14 May 2006 21:08:52 GMT Subject: Named regexp variables, an extension proposal. References: <1147513160.977268.253690@j33g2000cwa.googlegroups.com> <1147631397.922734.167880@u72g2000cwu.googlegroups.com> Message-ID: <E%M9g.6358$fb2.467@newssvr27.news.prodigy.net> Paddy wrote: > I have another use case. > If you want to match a comma separated list of words you end up writing > what constitutes a word twice, i.e: > r"\w+[,\w+]" That matches one or more alphanum characters followed by exactly one comma, plus, or alphanum. I think you meant r'\w+(,\w+)*' or if you don't care where or how many commas there are r'[\w,]*' or if previous but has to start with alphanum r'\w[\w,]*' > As what constitues a word gets longer, you have to repeat a longer RE > fragment so the fact that it is a match of a comma separated list is > lost, e.g: > r"[a-zA-Z_]\w+[,[a-zA-Z_]\w+]" That's why god invented % interpolation. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From johnjsal at NOSPAMgmail.com Wed May 10 11:52:20 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 15:52:20 GMT Subject: MySQLdb trouble In-Reply-To: <lf-dnZCNfuzLn__ZRVn-uQ@telcove.net> References: <mailman.5547.1147249433.27775.python-list@python.org> <Xnm8g.2076$No6.45677@news.tufts.edu> <lf-dnZCNfuzLn__ZRVn-uQ@telcove.net> Message-ID: <U_n8g.2079$No6.45875@news.tufts.edu> Thomas Bartkus wrote: > 1) His code body will be less likely to cause migrane headaches when he > tries to read and interpret what he did a year from now. If you are trying > to figure out what is going on with the logic, user names and passwords can > be so much chaff your brain needs to wade through in order to get to the > central idea. > > 2) The coder won't have to repeat himself if he needs to re-open the > databases. Ah, that makes sense! It seemed like an unnecessary step, but in some ways it might end up being more efficient. From john at castleamber.com Sun May 21 19:13:16 2006 From: john at castleamber.com (John Bokma) Date: 21 May 2006 23:13:16 GMT Subject: python vs perl lines of code References: <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> <Xns97C9ADA375FCCcastleamber@130.133.1.4> <lFMbg.19879$Lm5.7431@newssvr12.news.prodigy.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> <Xns97C9B5C01B657castleamber@130.133.1.4> <1148172321.824018.207540@j33g2000cwa.googlegroups.com> <Xns97C9EDC00DC96castleamber@130.133.1.4> <1148189521.803453.142860@j73g2000cwa.googlegroups.com> <Xns97CA11C302CC1castleamber@130.133.1.4> <1148199608.054443.110150@i39g2000cwa.googlegroups.com> Message-ID: <Xns97CAB95AAF93Dcastleamber@130.133.1.4> "George Sakkis" <george.sakkis at gmail.com> wrote: > Oh, I think I get it now. Spamvertizing _one_ site is worth your > host's subscription; doing it for _four_ sites at your signature is > perfectly ok though. Do yourself and many others a favour before you post again, educate yourself on Usenet. It might stop you from making stupid remarks like the one you just made. -- 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 zlatko.matic1 at sb.t-com.hr Sun May 28 05:07:53 2006 From: zlatko.matic1 at sb.t-com.hr (tatamata) Date: Sun, 28 May 2006 11:07:53 +0200 Subject: starting some Python script from C# References: <e58ta7$jns$1@fegnews.vip.hr> <1148728940.440692.166330@i39g2000cwa.googlegroups.com> Message-ID: <e5bp9c$la0$1@fegnews.vip.hr> Hello. I tried to implement ypour suggestion, but an error apears: "Exception System.ComponentModel.Win32Exception was thrown in debugee: The specified executable is not a valid Win32 application. StartWithCreateProcess() Start() Start() Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop Projects\CS_script\CS_script\Main.cs:32,5 " The C# code is the following: /* * Created by SharpDevelop. * User: Zlatko * Date: 28.5.2006 * Time: 9:38 * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Diagnostics; using System.Windows.Forms; namespace CS_script { class MainClass { public static void Main(string[] args) { System.Diagnostics.ProcessStartInfo psi =new System.Diagnostics.ProcessStartInfo(); psi.FileName="my_script.py"; psi.WorkingDirectory=Environment.CurrentDirectory; psi.RedirectStandardOutput = true; psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; psi.UseShellExecute = false; psi.CreateNoWindow = true; System.Diagnostics.Process script; script = System.Diagnostics.Process.Start(psi); System.IO.StreamReader myOutput = script.StandardOutput; script.WaitForExit(2000); if (script.HasExited) { string output = myOutput.ReadToEnd(); //this.processResults.Text = output; } MessageBox.Show("finished!"); } } } When running the program, I have the following error: "Exception System.ComponentModel.Win32Exception was thrown in debugee: The specified executable is not a valid Win32 application. StartWithCreateProcess() Start() Start() Main() - c:\Documents and Settings\Zlatko\My Documents\SharpDevelop Projects\CS_script\CS_script\Main.cs:32,5 " "Gerard Flanagan" <grflanagan at yahoo.co.uk> je napisao u poruci interesnoj grupi:1148728940.440692.166330 at i39g2000cwa.googlegroups.com... > tatamata wrote: >> Hello. >> >> How can I run some Python script within C# program? >> > > --------------------------------------------------------------------------------- > ProcessStartInfo startInfo; > Process process; > string directory; > string pyArgs; > string script; > > startInfo = new ProcessStartInfo("python"); > startInfo.WorkingDirectory = directory; > startInfo.Arguments = script + " " + pyArgs; > startInfo.UseShellExecute = false; > startInfo.CreateNoWindow = true; > startInfo.RedirectStandardOutput = true; > startInfo.RedirectStandardError = true; > > process = new Process(); > process.StartInfo = startInfo; > process.Start(); > > string s; > while ((s = process.StandardOutput.ReadLine()) != null) > { > //do something with s > } > --------------------------------------------------------------------------------- > > HTH > > Gerard > From see at signature.invalid Fri May 12 03:06:55 2006 From: see at signature.invalid (Nigel Rowe) Date: Fri, 12 May 2006 17:06:55 +1000 Subject: Calling python functions from C References: <1147194348.285669.218280@g10g2000cwb.googlegroups.com> Message-ID: <q-Sdnfl6pKKOqfnZnZ2dnUVZ_uWdnZ2d@giganews.com> robert.differentone at gmail.com wrote: > I am a newbie to Python. I want to call python functions from C. I > looked for examples but I couldn't get any simple one. Lets say my > python code is : > def add(a,b) > return (a+b) > > I want to call add from C. Could anybody please help me? Thanks in > advance. > > R. You might look at elmer <http://elmer.sourceforge.net/> Quote: What is elmer? Elmer is a tool which embeds a Python module into a C, C++, or Tcl application. The embedded Python module is used just as if it was written in the same language as the application itself, without requiring any knowledge of the Python/C API. Elmer generates "glue" code that embeds an interpreter for one type of language into an extension for another. Elmer allows function calls and various data types, both native and custom, to pass transparently between the two languages. -- Nigel Rowe A pox upon the spammers that make me write my address like.. rho (snail) swiftdsl (stop) com (stop) au From robert.kern at gmail.com Sun May 21 14:59:45 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 May 2006 13:59:45 -0500 Subject: Feature request: sorting a list slice In-Reply-To: <1148198065.724613.253490@j55g2000cwa.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> <e4ouaa$cu6$1@sea.gmane.org> <e4ougq$dba$1@sea.gmane.org> <e4p00b$fts$2@sea.gmane.org> <mailman.6023.1148192006.27775.python-list@python.org> <1148198065.724613.253490@j55g2000cwa.googlegroups.com> Message-ID: <e4qdb0$6ou$1@sea.gmane.org> John Machin wrote: > Context? The whole message asked for a new feature. Please tell me what > context I should have supplied. When you reply to a message, please quote part of that message. That's what was meant by context. -- 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 johnjsal at NOSPAMgmail.com Tue May 16 10:17:04 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 16 May 2006 14:17:04 GMT Subject: my cryptogram program In-Reply-To: <4468f9af$0$12816$636a55ce@news.free.fr> References: <ZI3ag.2095$No6.46239@news.tufts.edu> <gh5ag.2100$No6.46182@news.tufts.edu> <4468f2c4$0$7135$626a54ce@news.free.fr> <7xfyjbrmzl.fsf@ruckus.brouhaha.com> <4468f9af$0$12816$636a55ce@news.free.fr> Message-ID: <A9lag.2104$No6.46276@news.tufts.edu> Bruno Desthuilliers wrote: > At least someone reading this may learn about the max_split param of > str.split() !-) LOL. The first thing I did was scramble to the docs to see what that second parameter meant! :) But I was a little confused about why you included it. Just to insure that only two elements are returned? I plan on making either a text file or a database with quotes in that format (quote|author), so maybe the maxsplit isn't needed? From claudio.grondi at freenet.de Tue May 16 10:18:05 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Tue, 16 May 2006 16:18:05 +0200 Subject: Large Dictionaries In-Reply-To: <1147788226.309918@teuthos> References: <1147699064.107490@teuthos> <e49va0$m72$1@newsreader3.netcologne.de> <1147772420.405097@teuthos> <e4cfd3$rq$1@newsreader3.netcologne.de> <1147788226.309918@teuthos> Message-ID: <e4cmuq$g19$1@newsreader3.netcologne.de> Chris Foote wrote: > Claudio Grondi wrote: > >> Chris Foote wrote: >> >>> However, please note that the Python bsddb module doesn't support >>> in-memory based databases - note the library documentation's[1] wording: >>> >>> "Files never intended to be preserved on disk may be created >>> by passing None as the filename." >>> >>> which closely mirrors the Sleepycat documentation[2]: >>> >>> "In-memory databases never intended to be preserved on disk >>> may be created by setting the file parameter to NULL." >>> >>> It does actually use a temporary file (in /var/tmp), for which >>> performance for my purposes is unsatisfactory: >>> >>> # keys dictionary metakit bsddb (all using psyco) >>> ------ ---------- ------- ----- >>> 1M 8.8s 22.2s 20m25s[3] >>> 2M 24.0s 43.7s N/A >>> 5M 115.3s 105.4s N/A >>> >>> Cheers, >>> Chris >>> >>> [1] bsddb docs: >>> http://www.python.org/doc/current/lib/module-bsddb.html >>> >>> [2] Sleepycat BerkeleyDB C API: >>> http://www.sleepycat.com/docs/api_c/db_open.html >>> >>> [3] Wall clock time. Storing the (long_integer, integer) key in >>> string form "long_integer:integer" since bsddb doesn't support keys >>> that aren't integers or strings. > > > > >> I have to admit, that I haven't wrote any own code to actually test >> this, but if 20m25s for storing of a single MByte of strings in a >> database table index column is really what you are getting, I can't >> get rid of the feeling, that there is something elementary wrong with >> your way doing it. > > > Hi Claudio. > > 1M is one million, referring to the number of insertions of keys; > not a Megabyte. I'm sorry that you took it that way :-( > > Berkeley DB is great for accessing data by key for things already > stored on disk (i.e. read access), but write performance for each > key-value pair is slow due to it being careful about flushing > writes to disk by default. > >> Posting the code for your test cases appears to me to be the only >> option to see what is the reason for the mystery you are getting here >> (this will clarify also the other mysterious things considered by the >> posters to this thread up to now). > > > I agree that posting some test code would have proved useful, but > the code is big and has too many interdependencies on external > things (e.g. databases, threads & pyro RPC calls) to allow me > to separate out examples easily. But if you go back to my > original posting, I think my question was quite clear. > > Best regards, > Chris > I have some code demonstrating the mystery from my point of view (including timings which differ from what you experience in the order of a magnitude on my 2.8 GHz P4): dctA = {} import time strt = time.clock() lst = range(123456789010000000L, 123456789010000000L + 5000000) import random endt = time.clock() print "lst = range(12345678901L, 12345678901L + 5000000) [s] : ", endt - strt strt = time.clock() random.shuffle(lst) endt = time.clock() print "random.shuffle(lst) [s] : ", endt - strt random.shuffle(lst) counter = 0 for item in lst: if (counter == 0): print "Listing of some of lst items:" if (counter > 4): print ":END of listing of lst items" break else: print "item no. %i "%(counter,), repr(item) counter += 1 #:for # raw_input('continue with ENTER) #>') strt = time.clock() dctA.fromkeys(lst, None) endt = time.clock() print "dctA.fromkeys(lst, None) [s] : ", endt - strt # raw_input('continue with ENTER) #>') strt = time.clock() strLst = [] for item in lst: strLst.append(str(item)) dctA = {} endt = time.clock() print "for item in lst: strLst.append(str(item)) [s] : ", endt - strt # raw_input('continue with ENTER) #>') strt = time.clock() dctA = dctA.fromkeys(strLst, None) endt = time.clock() print "dctA.fromkeys(strLst, None) [s] : ", endt - strt # raw_input('continue with ENTER) #>') print "len(dctA) : %i " % (len(dctA),) counter = 0 for key in dctA.keys(): if (counter == 0): print "Listing of some of dctA items:" if (counter > 4): print ":END of listing of dctA items" break else: print "key no. %i "%(counter,), repr(key) counter += 1 #:for raw_input('exit with ENTER) #>') # Gives as output : # # lst = range(12345678901L, 12345678901L + 5000000) [s] : 0.81327347470 # random.shuffle(lst) [s] : 8.06178829991 # Listing of some of lst items: # item no. 0 123456789011010733L # item no. 1 123456789013585761L # item no. 2 123456789013610266L # item no. 3 123456789011311029L # item no. 4 123456789010968853L # :END of listing of lst items # dctA.fromkeys(lst, None) [s] : 3.11773256098 # for item in lst: strLst.append(str(item)) [s] : 11.5454232312 # dctA.fromkeys(strLst, None) [s] : 3.98027849908 # len(dctA) : 5000000 # Listing of some of dctA items: # key no. 0 '123456789014515319' # key no. 1 '123456789014116699' # key no. 2 '123456789014116698' # key no. 3 '123456789010800915' # key no. 4 '123456789014116696' # :END of listing of dctA items So the insertion into the dictionary is according to you: # keys dictionary 5M 115.3s according to me: 5M 3.9s I need according to the task manager about 0.5 GByte memory for this (including the lists I keep alive). I conclude from that, that your results from Berkeley approach are also a case of unfortunate way of doing things (in Python and with the DB) and using the Python dictionaries is here the simplest way to go (I suppose that your main problem is, that you are not using .fromkeys() on a list of your input data). Claudio From taleinat at gmail.com Mon May 1 10:04:26 2006 From: taleinat at gmail.com (taleinat at gmail.com) Date: 1 May 2006 07:04:26 -0700 Subject: self modifying code In-Reply-To: <4455D863.6070906@jessikat.plus.net> References: <445399A1.9020506@jessikat.plus.net> <slrne57r50.uh0.spamspam@bowser.marioworld> <44548536.7060409@jessikat.plus.net> <1146469385.334797.128930@i39g2000cwa.googlegroups.com> <4455D863.6070906@jessikat.plus.net> Message-ID: <1146492266.605324.282670@u72g2000cwu.googlegroups.com> Yes, my implementation was less efficient because of the extra function call. > class Weird(object): > @staticmethod > def __call__(arg): > data = 42 > def func(arg): > return arg+data > Weird.__call__ = staticmethod(func) > return func(arg) > c = Weird() Ugh... you've used a class just like a function. You can't have two different objects of this class, since you are overriding a static method of the class! And you've hard-coded the data into the class definition. Yes, it works, but I would never, ever trust such code to someone else to maintain. And you'll have to manually define such a class for every such function. That's not very Pythonic. Here's a reusable function that will define such a class for you, as well as hide most of the ugliness (in fact, it supports -exactly- the same interface as my previous implementation): def InitializingFunction(func): class temp: @staticmethod def __call__(*args, **kw): temp.__call__ = staticmethod(func()) return temp.__call__(*args, **kw) return temp() @InitializingFunction def func(): data = somethingcomplexandcostly() def foo(a): return simple(data, a) return foo From sandro at e-den.it Thu May 4 19:04:47 2006 From: sandro at e-den.it (Sandro Dentella) Date: Thu, 04 May 2006 23:04:47 GMT Subject: __init__.py, __path__ and packaging References: <slrne5i46s.3hc.sandro@bluff.diade.it> <445932cc$1@nntp0.pdx.net> Message-ID: <slrne5l24f.3nl.sandro@bluff.diade.it> In comp.lang.python, hai scritto: > Sandro Dentella wrote: >> The structure of my package: >> >> python/ >> `-- dbg/ >> |-- __init__.py >> `-- lib >> |-- __init__.py >> |-- debug.py >> `-- gtk_dbg.py >> >> my sys.path includes 'python' and I wanted that the content of debug.py was >> simply included by: 'import dbg', so I wrote dbg/__init__.py as follows: >> >> import os >> Dir = os.path.dirname(__file__) >> __path__ = [os.path.join(Dir, 'lib')] >> from debug import * > > What you probably want in python/dbg/__init__.py to get values is: > > from dbg.lib.debug import * This does not work: Traceback (most recent call last): File "<string>", line 1, in ? File "dbg/__init__.py", line 8, in ? from dbg.lib.debug import * ImportError: No module named lib.debug > >> BUT, if I set some variables they are not correctly seen: >> import dbg >> dbg.DBG = 1 >> function test included in debug.py raises NameError: >> def test(): >> print DBG >> NameError: global name 'DBG' is not defined` >> >> What's happening? DBG seems to be set, as shown by dir(dbg)... any hints? > You misunderstand modules and python variables. Each module has a > dictionary associating the names of its globals and their current > values. After: > import dbg.lib.debug, dbg.lib.gtk_dbg > you have four modules: > dbg # Corresponds to python/dbg/__init__.py > dbg.lib # Corresponds to python/dbg/lib/__init__.py > dbg.lib.debug # Corresponds to python/dbg/lib/debug.py > dbg.lib.gtk_dbg # Corresponds to python/dbg/lib/gtk_dbg.py > Each has its own globals. > after: > dbg.DBG = 1 > the dbg module's global dictionary contains an entry mapping 'DBG' to 1 > after: > dbg.DBG = 1+2 > the dbg module's global dictionary contains an entry mapping 'DBG' to 3 > > In no case will an assignment to a global in dbg cause an assignment to > anything in dbg.lib.debug. The "from dbg.lib.debug import *" statement > can be seen as a module import followed by a fancy multiple assignment, > where module dbg.lib.debug is first imported, then its globals are > assigned to globals of the same names in module dbg. This confirms to me that I'm seriously confused... so I started with a very simple setup: $ cat dbg.py DBG = 1 def test(): global DBG print DBG def set(): global DBG DBG = 3 $ cat m.py from dbg import * test() #dbg.DBG = 2 ## does not work, no way to assign in module dbg set() # this acts in dbg module and sets 'DBG = 3' test() # test the value of DBG print DBG $ python m.py 1 3 # changed by 'set' that was 'imported' 1 # value of local DBG isn't this contraddicting you words: > can be seen as a module import followed by a fancy multiple assignment, > where module dbg.lib.debug is first imported, then its globals are > assigned to globals of the same names in module dbg. So: which is the way I can change a value of a package 'imported', only with a function that sets it? is there a way to assign the value directly? is there any way to make some introspection of what is really there (in dbg)? Thanks angain for any possible hint. sandro *:-) -- Sandro Dentella *:-) http://www.tksql.org TkSQL Home page - My GPL work From simon at arrowtheory.com Thu May 18 19:48:05 2006 From: simon at arrowtheory.com (Simon Burton) Date: 18 May 2006 16:48:05 -0700 Subject: realization: no assignments inside expressions Message-ID: <1147996085.277185.23280@i39g2000cwa.googlegroups.com> I've been doing a little c programming again (ouch!) and it's just hit me why python does not allow assignment inside expressions (as in c): because it is absolutely essential that all assignments are as visible as possible. In python the assignment is the declaration; when declarations are as cheap as this it's hard not to fall to the temptation to re-use a variable unknowingly. I am constantly scanning the line of assignments to see what variables are already live, and I just realised how easy it is to do that. Up to now I guess I thought it was just a restriction to stop new users of python from writing too obfuscated code. wow. Simon. From robert.kern at gmail.com Thu May 11 14:36:31 2006 From: robert.kern at gmail.com (Robert Kern) Date: Thu, 11 May 2006 13:36:31 -0500 Subject: which windows python to use? In-Reply-To: <44633047.8010007@bryant.edu> References: <44633047.8010007@bryant.edu> Message-ID: <e4007f$vnk$1@sea.gmane.org> Brian Blais wrote: > Are there advantages/disadvantages? I have used enthought before, but it seems as if > they are not at 2.4, and may lag behind in versions (which may not be a bad thing). We will be releasing a 2.4 version "shortly" although I'm sure if you search the archives of this list, you will probably see me saying that several times. I will try to get us to push out a public beta release next week. -- 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 fidtz at clara.co.uk Mon May 8 11:05:37 2006 From: fidtz at clara.co.uk (fidtz at clara.co.uk) Date: 8 May 2006 08:05:37 -0700 Subject: A better way to split up a list In-Reply-To: <mailman.5478.1147099260.27775.python-list@python.org> References: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> <445F469D.60007@lexicon.net> <1147095747.554970.173460@i40g2000cwc.googlegroups.com> <mailman.5478.1147099260.27775.python-list@python.org> Message-ID: <1147100734.395456.306490@y43g2000cwc.googlegroups.com> Thanks very much, that is a far tidier solution!! From nil at dev.nul Mon May 22 01:16:05 2006 From: nil at dev.nul (Christian Stapfer) Date: Mon, 22 May 2006 07:16:05 +0200 Subject: dynamic drawing in web page References: <1148245752.728480.238540@u72g2000cwu.googlegroups.com> <1148253577.595049.222370@y43g2000cwc.googlegroups.com> Message-ID: <3f27f$4471491b$54482a70$4372@news.hispeed.ch> Paul Boddie <paul at boddie.org.uk> wrote in message news:1148253577.595049.222370 at y43g2000cwc.googlegroups.com... > barbaros wrote: >> >> I need to put some dynamic drawings on my web page. More precisely, I >> need to draw a number of geometric figures (circles, rectangles) which >> evolve into a graphics windows according to some law (a little bit like >> the solar system). I need also to have several fields aside the window, >> where the visitor can change values for several significant parameters >> (like the mass of each body). >> >> Could you please suggest a solution (preferably not involving hundreds >> of lines of code) ? The computations should be performed on the client >> machine. > > In the context of recent Flash-related discussions and the usage of > open Web standards, I searched for 'animation SVG "solar system"' and > discovered this example: > > http://www.svgelves.com/svg/L_chrisa_02.svg > > Sadly, it only works in Opera amongst the browsers I have. It also works under IE6, using Adobe's SVG Viewer 3.0 Regards, Christian From deets at nospam.web.de Fri May 19 09:49:25 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 May 2006 15:49:25 +0200 Subject: noob import question References: <mailman.5945.1148045097.27775.python-list@python.org> <4d5vqaF18i4l1U1@uni-berlin.de> <mailman.5946.1148046277.27775.python-list@python.org> Message-ID: <4d60neF18gn2mU1@uni-berlin.de> Brian Blazer wrote: > Thank you for your responses. I had a feeling is had something to do > with a namespace issue but I wasn't sure. > > You are right, I do come from a Java background. If it is poor form > to name your class file the same as your class, can I ask what the > standard is? Consider python modules what packages are in JAVA - aggregations of related classes. Only if your module grows to an unmanagable size, split it up into two modules. Diez From davidschein at alumni.tufts.edu Tue May 9 10:53:29 2006 From: davidschein at alumni.tufts.edu (David S.) Date: Tue, 9 May 2006 14:53:29 +0000 (UTC) Subject: distutils References: <loom.20060509T161902-311@post.gmane.org> <4460A9D0.50503@sccs.swarthmore.edu> Message-ID: <loom.20060509T164814-180@post.gmane.org> Dan Crosta <dcrosta <at> sccs.swarthmore.edu> writes: > > fsi\ > > - common\ # some modules > > - db\ # some modules > > - someutility\ # my script > > > > Your setup.py should live in fsi/setup.py. try: > Thank you. This introduces a new problem for me. I have other scripts that I want to install likewise. But now I have to overwrite setup.py for each install. Alternatively, I can create script1setup.py, script2setup.py, etc. That would be fine except that there are other files, ie. MANIFEST.IN and README, that need to be there too. I have not found a way to similarly rename these. Finally, it seems odd that I should have so many XXXsetup.py scripts in my package root directory. Thanks again, David S. From email at christoph-haas.de Fri May 5 04:21:37 2006 From: email at christoph-haas.de (Christoph Haas) Date: Fri, 5 May 2006 10:21:37 +0200 Subject: Python for Perl programmers In-Reply-To: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> References: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> Message-ID: <20060505082137.GA17891@torf.workaround.org> On Thu, May 04, 2006 at 12:02:52PM -0400, A.M wrote: > Is there any efficient online resource or book that help experienced Perl > programmers to Python? I've been using Perl for a decade and had a hard start into Python. Mainly because I used those "phrasebooks" and tried to convert my Perl syntax statement-by-statement. However Python doesn't just have another syntax but also other concepts. It's worth working yourself through the diveintopython tutorial. Or if you want to spend money I strongly recommend the book "Beginning Python: From Novice to Professional" (ISBN 159059519X) because you learn a lot about daily problems and gotchas, too. Besides from the "I'm cool because I'm the only one who can read my code" factor that Perl delivers Python has everything you need. :) Kindly Christoph From kentilton at gmail.com Sat May 6 10:56:28 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 10:56:28 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <xcvslnnef5a.fsf@conquest.OCF.Berkeley.EDU> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> <wvW6g.1646$Ez6.507@fe09.lga> <xcvslnnef5a.fsf@conquest.OCF.Berkeley.EDU> Message-ID: <xO27g.15$pv7.9@fe08.lga> Thomas F. Burdick wrote: > Ken Tilton <kentilton at gmail.com> writes: > > >><g> Hopefully it can be a big issue and still not justify a flame war. >> >>Mileages will always vary, but one reason for lambda is precisely not >>to have to stop, go make a new function for this one very specific >>use, come back and use it as the one lambda statement, or in C have an >>address to pass. but, hey, what are editors for? :) >> >>the bigger issue is the ability of a lambda to close over arbitrary >>lexically visible variables. this is something the separate function >>cannot see, so one has to have a function parameter for everything. >> >>but is such lexical scoping even on the table when Ptyhon's lambda >>comes up for periodic review? > > > This is second-hand, as I don't actually follow Python closely, but > from what I've heard, they now have reasonable scoping rules (or maybe > they're about to, I'm not sure). And you can use def as a > Scheme-style inner define, so it's essentially a LABELS that gets the > indentation wrong. Cool. And I know how much you like labels/flet. :) > This means they have proper closures, just not > anonymous ones. And an egregiously misnamed lambda that should be > fixed or thrown out. > > If Python gets proper macros it won't matter one bit that they only > have named closures, since you can macro that away in a blink of an > eye. Ah, well, there we go again. Without sexpr notation, the lexer/parser again will be "hard", and "hardly worth it": we get even more sour grapes, this time about macros not being such a big deal. One of the hardest things for a technologist to do is admit that a neat idea has to be abandoned. Initial success creates a giddy over-commitment to the design choice. After then all difficulties get brushed aside or kludged. This would not be a problem for Python if it had stayed a scripting language... well, maybe "no Macro!s" and "no real lambda!" and "no continuations!" are GvR's way of keeping Python just a scripting language. :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From cvanarsdall at mvista.com Fri May 19 17:16:27 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 19 May 2006 14:16:27 -0700 Subject: [silly] Does the python mascot have a name ? In-Reply-To: <89i1k3-17m.ln1@prcm.tecont.de> References: <mailman.5890.1147966982.27775.python-list@python.org> <e4i9hb$f1r$1@emma.aioe.org> <_s2bg.8867$aa4.296233@news20.bellglobal.com> <Xns97C8B0412BD14BaldHeadedJohn@216.196.109.145> <89i1k3-17m.ln1@prcm.tecont.de> Message-ID: <446E35AB.9030003@mvista.com> Ralf Muschall wrote: > John D Salt wrote: > > >> I'll believe you if you can give me a list of ten things that don't have >> names. >> > > [ sub{$_}, sub{$_+1}, sub{$_+2}, sub{$_+3}, sub{$_+4}, > sub{$_+5}, sub{$_+6}, sub{$_+7}, sub{$_+8}, sub{$_+9}] > > That was easy. > Wakka wakka. -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From nobody at 127.0.0.1 Wed May 3 12:42:06 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 16:42:06 GMT Subject: Newbie question on code vetting References: <yvT5g.132$yh.117@trnddc04> <iokg521d387uvt3teoegi17t032ht6sjr5@4ax.com> Message-ID: <y356g.81306$dW3.7774@newssvr21.news.prodigy.com> Dennis Lee Bieber wrote: >> I work for a risk-averse company, and I want to compile a solid case for >> obtaining and using Python at work. >> > Given the nature of the US Patent Office... You might as well lock > the doors now... > > The Patent Office could issue a patent next week that makes all > bytecode interpreted languages subject to some royalty... Risk isn't just what could happen, it's how likely it is and what effects it would have. A patent affecting millions of installed interpreters is pretty unlikely and would have many challengers. Even if it were upheld, how many larger companies with deeper pockets would they go after before his? And everyone stuck in the same boat would quickly work towards a non-infringing solution. Cases like MS-EOLAS and RIM-NTP aren't exactly a daily occurence. They also demonstrate why there really is safety in numbers. Plus all the potential negatives have to weighed against the increased productivity his company gains from using a scripting language. The gains may more than offset any potential patent settlement. Risk-averse doesn't mean head-in-the-sand. From malvert at telenet.be Wed May 31 16:09:51 2006 From: malvert at telenet.be (malv) Date: 31 May 2006 13:09:51 -0700 Subject: using import * with GUIs? References: <R2mfg.2200$No6.47332@news.tufts.edu> <mailman.6381.1149104575.27775.python-list@python.org> <bsmfg.2202$No6.47400@news.tufts.edu> Message-ID: <1149106190.986823.189740@j55g2000cwa.googlegroups.com> John Salerno wrote: > Terry Reedy wrote: > > > If I were to use Tkinter, I would 'import Tkinter as tk'. > > Good idea! > > I was kind of excited about Tkinter for a little while...seems very > easy, and it has an event delegation system that I understand! But then > I saw that for a toolbar you use a Frame? And for a status bar you use a > Label? Ick! > > I guess if I'm going to learn a GUI, I might as well jump right into > wxPython from the beginning. Better first look at Qt/PyQt before jumping right into wxPython. You will at least know what you will be jumping into. From me+python at modelnine.org Tue May 2 17:23:36 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 23:23:36 +0200 Subject: simultaneous assignment In-Reply-To: <e38ghu$he1$1@avnika.corp.mot.com> References: <8dM5g.2031$No6.43874@news.tufts.edu> <RAN5g.2037$No6.43926@news.tufts.edu> <e38ghu$he1$1@avnika.corp.mot.com> Message-ID: <200605022323.36346.me+python@modelnine.org> Am Dienstag 02 Mai 2006 22:47 schrieb Gary Duzan: > >Here's a scan of the page from the puzzle book: > >http://johnjsalerno.com/spies.png > > > >Basically I'm reading this book to give me little things to try out in > >Python. There's no guarantee that this puzzle is even conducive to (or > >worthy of) a programming solution. > > Given the appropriate spy() function, this will return a set of > values for the truthful (logically coherent) spy and nothing for > the other spy. The details are left as an exercise for the reader. Hummm... Isn't it easier and faster to solve this problem by hand than to code a Python program for it? I had proofs for what has to be on both papers in about 30 seconds... ;-) If you're looking for things to code in Python, I'd rather suggest you look at number theory than at logic problems. Basically, every logic problem can be solved by exhaustive search (which is always the same algorithm), whereas a number theory problem requires that you implement a certain algorithm from scratch for each problem you're trying to tackle. Implementing the sieve of Erathosthenes comes to mind straight away. --- Heiko. From maric at aristote.info Tue May 16 05:52:01 2006 From: maric at aristote.info (Maric Michaud) Date: Tue, 16 May 2006 11:52:01 +0200 Subject: problem with namespaces using eval and exec In-Reply-To: <1147770312.756392.147920@i39g2000cwa.googlegroups.com> References: <1147770312.756392.147920@i39g2000cwa.googlegroups.com> Message-ID: <200605161152.02664.maric@aristote.info> Le Mardi 16 Mai 2006 11:05, Jens a ?crit?: > s = """ > def a(n): > ? return n*n > > > def b(t): > ? return a(t) > """ > > > ns = {} > exec(s, {}, ns) > eval("b(2)", ns, {}) you passed an empty globals dictionnary to the eval func (the local one is not in the scope of b defintion) try this : exec s // like exec s in globals(), locals() eval("b(2)") // like , eval("b(2)", globals(), locals()) or if you to keep this dictionnary as a specific scope in your appplication : exec s in ns eval("b(2)", ns) -- _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From 123 at 321.com Tue May 9 07:34:56 2006 From: 123 at 321.com (DeepBlue) Date: Tue, 09 May 2006 19:34:56 +0800 Subject: Python editor recommendation. Message-ID: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Hi all, Can any one please recommend me an editor for coding Python. Thank u. I have Komodo (www.activestate.com) in my mind. Is the editor any good? regards. From fccoelho at gmail.com Sat May 13 03:37:51 2006 From: fccoelho at gmail.com (Flavio) Date: 13 May 2006 00:37:51 -0700 Subject: distributing a app frozen by cx_freeze In-Reply-To: <1147501391.800070.265860@g10g2000cwb.googlegroups.com> References: <1147482467.404798.187530@y43g2000cwc.googlegroups.com> <1147501391.800070.265860@g10g2000cwb.googlegroups.com> Message-ID: <1147505871.924101.149640@j73g2000cwa.googlegroups.com> Thanks for the hint. I'll try to get cx_freeze to bundle up other shared libraries it may not be bundling such as qtcanvas, qtext, qtui, etc. and see if it works. I'll post back the results to help other poor souls like me. Thanks From Dennis.Benzinger at gmx.net Sun May 21 14:48:57 2006 From: Dennis.Benzinger at gmx.net (Dennis Benzinger) Date: Sun, 21 May 2006 20:48:57 +0200 Subject: escapes in regular expressions In-Reply-To: <1148233776.133200.59280@u72g2000cwu.googlegroups.com> References: <1148233776.133200.59280@u72g2000cwu.googlegroups.com> Message-ID: <4470b620$1@news.uni-ulm.de> James Thiele schrieb: > I was helping a guy at work with regular expressions and found > something I didn't expect: > > >>>>re.match('\d', '7').group() > > '7' '\d' is not recognized as a escape sequence by Python and therefore it is left unchanged <http://docs.python.org/ref/strings.html> in the string which is passed to re.match. > >>>>re.match('\\d', '7').group() > > '7' > [...] This is the correct version. The first backslash escapes the second one and this version will work even if a future version of Python recognizes \d as an escape sequence. Dennis From johnjsal at NOSPAMgmail.com Sun May 7 14:16:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 07 May 2006 14:16:34 -0400 Subject: md5 from python different then md5 from command line In-Reply-To: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> Message-ID: <445e3a3b$0$22630$c3e8da3@news.astraweb.com> ursache.marius at gmail.com wrote: > Hi > > I noticed that the md5 computed with md5 module from python is > different then the md5 sum computed with md5sum utility (on slackware > and gentoo). > > i.e. > $echo marius|md5sum > 0f0f60ac801a9eec2163083a22307deb - > >>>> test = md5.new("marius") >>>> print test.hexdigest() > 242aa1a97769109065e3b4df359bcfc9 > > > Any idea why? and how to get the same md5 sum for both calls? > > Thanks > Just a quick md5-related follow-up question: I was experimenting with it and making md5 sums for strings, but how do you use the md5 module to create a sum for an actual file, such as an .exe file? Thanks. From onurb at xiludom.gro Wed May 17 11:46:18 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 17 May 2006 17:46:18 +0200 Subject: Process forking on Windows In-Reply-To: <126mgi2j7fl4b4b@corp.supernews.com> References: <126mgi2j7fl4b4b@corp.supernews.com> Message-ID: <446b45b1$0$7132$636a55ce@news.free.fr> Andrew Robert wrote: > Hi everyone, > > > I have a python program that will need to interact with an MQSeries > trigger monitor. > > It does this fine but it hogs the trigger monitor while it executes. > > I'd like to fork the program off and terminate the parent process so > that the trigger monitor frees up. <just-asking> Is this really the solution ? </just-asking> > > Does anyone how this can be accomplished on a Windows platform? AFAIK, there's no fork in Windows - you might want to give a try with CreateProcess. http://www.byte.com/art/9410/sec14/art3.htm http://msdn.microsoft.com/library/default.asp?url=/library/en-us/dnucmg/html/UCMGch01.asp HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From larry.bates at websafe.com Tue May 9 12:23:02 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 09 May 2006 11:23:02 -0500 Subject: do "some action" once a minute In-Reply-To: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> References: <1147157571.050604.70880@y43g2000cwc.googlegroups.com> Message-ID: <4460C1E6.4040905@websafe.com> Petr Jakes wrote: > I would like to do "some action" once a minute. My code (below) works, > I just wonder if there is some more pythonic approach or some "trick" > how to do it differently. > > minutes=time.localtime()[4] > while 1: > min, sec = time.localtime()[4:6] > if sec==0 and minutes!=min: # first occur of sec==0 only!! polling > 10x a second > minutes=min > print "Eureca" > time.sleep(0.1) > > Regards > > Petr Jakes > What platform? If it is Windows, they write your application as a Windows Service and have it sleep for however long you want. It won't impact your system looping and sleeping. It will also be asynchronous, as it will sleep for time you specify, run your code to completion and then sleep again which isn't the same as running every one minute. If it is Linux, others have answered separately. -Larry Bates From akameswaran at gmail.com Wed May 31 11:02:52 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 31 May 2006 08:02:52 -0700 Subject: Strange behavior with iterables - is this a bug? In-Reply-To: <mailman.6341.1149028250.27775.python-list@python.org> References: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> <mailman.6341.1149028250.27775.python-list@python.org> Message-ID: <1149087772.403131.270480@f6g2000cwb.googlegroups.com> Gary Herron wrote: > List comprehension is a great shortcut, but when the shortcut starts > causing trouble, better to go with the old ways. You need to reopen each > file each time you want to iterate through it. You should be able to > understand the difference between these two bits of code. > > The first bit opens each file but uses (two of them) multiple times. > Reading from a file at EOF returns an empty sequence. > > The second bit opened the file each time you want to reuse it. That > works correctly. > > And that suggest the third bit of correctly working code which uses list > comprehension. > > # Fails because files are opened once but reused > f1 = open('word1.txt') > f2 = open('word2.txt') > f3 = open('word3.txt') > for i1 in f1: > for i2 in f2: > for i3 in f3: > print (i1.strip(),i2.strip(),i3.strip()) > > and > > # Works because files are reopened for each reuse: > f1 = open('word1.txt') > for i1 in f1: > f2 = open('word2.txt') > for i2 in f2: > f3 = open('word3.txt') > for i3 in f3: > print (i1.strip(),i2.strip(),i3.strip()) > > and > > # Also works because files are reopened for each use: > print [(i1.strip(),i2.strip(),i3.strip()) > for i1 in open('word1.txt') > for i2 in open('word2.txt') > for i3 in open('word3.txt')] > > Hope that's clear! > > Gary Herron My original problem was with recursion. I explicitly nested it out to try and understand the behavior - and foolishly looked in the wrong spot for the problem, namely that file is not reitreable. In truth I was never concerned about file objects, the problem was failing with my own custom iterators (wich also were not reiterable) and I switched to file, to eliminate possible code deficiencies on my own part. I was simply chasing down the wrong problem. As was pointed out to me in a nother thread - the cleanest implementation which would allow me to use one copy of the file (in my example the files are identical) would be to use a trivial iterator class that opens the file, uses tell to track position and seek to set position, and returns the appropriate line for that instance - thus eliminating unnecessary file opens and closes. From paul at wolfbone.ath.cx Fri May 26 02:57:56 2006 From: paul at wolfbone.ath.cx (P.L.Hayes) Date: Fri, 26 May 2006 07:57:56 +0100 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> <447479A1.8050809@hotORgooMAIL.invalid> <3j0dg.27$u4.11@newsread1.news.pas.earthlink.net> Message-ID: <87slmwbhx5.fsf@wolfbone.ath.cx> "Mumia W." <mumia.w.18.spam+fbi.gov at earthlink.net> writes: > Mitch wrote: >> John Bokma wrote: >> [...] >>> You're mistaken. All you need to do is report it. After some time >>> Xah will either walk in line with the rest of the world, or has >>> found somewhere else to yell. As long as it's not my back garden >>> and not around 4AM, I am ok with it. >>> >> Walk in line with the rest of the world? Pah. >> This is no-ones back garden. > > But it is a place where John Bokma can engage in a little power play. > > Notice how John Bokma pretends to own these newsgroups. In every > analogy, Bokma uses "ownership" concepts to support his harassment of > Xah. > > John Bokma conceptualizes these newsgroups as something that he > dominates. Without other people to recognize his power, it's empty, so > he bashes and then trashes Xah, and in doing so, proves that he is > dominant here. > > Don't let it happen. Write the abuse address at Dreamhost, and try to > help Xah out. I agree. I have already written to Dreamhost and I hope more people will do so. I have found some of what has been posted here quite astonishing and the actions of certain people to be reprehensible: by far the most serious violation of netiquette I see here is this thoroughly wrong-headed campaign to try to censor Xah by appealing to his service provider. In my opinion it is that, not anything Xah has done, which comes any where near deserving any sort of termination of access to the Internet. Since Xah's website is hosted by Dreamhost, the unwarranted censorship will be compounded by an act of gratuitous vandalism, potentially depriving people of useful resources: http://online.redwoods.cc.ca.us/instruct/darnold/CalcProj/Index.htm Paul. From cfc at shell01.TheWorld.com Wed May 10 10:48:07 2006 From: cfc at shell01.TheWorld.com (Chris F Clark) Date: 10 May 2006 10:48:07 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> <NUP7g.17$G22.12@fe11.lga> <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> <ubn362tg2ft4la26hq4so0ron8lsj7fvqe@4ax.com> Message-ID: <sddwtcuc4wo.fsf@shell01.TheWorld.com> David C Ullrich asked: > Q: How do we ensure there are no loops in the dependencies? > > Do we actually run the whole graph through some algorithm > to verify there are no loops? The question you are asking is the dependency graph a "directed acyclic graph" (commonly called a DAG)? One algorithm to determine if it is, is called "topological sort". That algorithm tells you where there are cyclces in your graph, if any, and also tells you the order of the dependencies, i.e. if x is updated, what you have to update downstream AND THE ORDER you have to perform the downstream computations in. We use this algorithm for solving just the kind of dataflow problems you are talking about in our circuit design tools. Circuit designs have one-way dependencies that we want to sort and resolve--similarly, we don't want cycles in our circuits except ones that pass through clocked flip-flops. We solve such problems on circuits with millions of gates, i.e. enough gates to represent the CPU of your computer or a disk controller chip or a router. I believe there are also algorithms that allow you to construct only acyclic (the technical term for non-looping) graphs and don't require you to enter the vertexes (verticies if you prefer) of the graph in any specific order, and in the worst case you can always run the topological sort on any graph and determine if the graph is cyclic. The area is well-studied and you can find a variety of algorithms that solve most interesting graph problems as they all occur over-and-over in numerous diverse fields. Hope this helps, -Chris ***************************************************************************** Chris Clark Internet : compres at world.std.com Compiler Resources, Inc. Web Site : http://world.std.com/~compres 23 Bailey Rd voice : (508) 435-5016 Berlin, MA 01503 USA fax : (978) 838-0263 (24 hours) ------------------------------------------------------------------------------ From maxerickson at gmail.com Tue May 16 14:17:43 2006 From: maxerickson at gmail.com (Max Erickson) Date: Tue, 16 May 2006 18:17:43 +0000 (UTC) Subject: Option parser question - reading options from file as well as command line References: <126k3273j7kb28f@corp.supernews.com> Message-ID: <Xns97C591968E618maxericksongmailcom@80.91.229.5> Andrew Robert <andrew.arobert at gmail.com> wrote in news:126k3273j7kb28f at corp.supernews.com: > Hi Everyone. > > > I tried the following to get input into optionparser from either > a file or command line. > > > The code below detects the passed file argument and prints the > file contents but the individual swithces do not get passed to > option parser. > > Doing a test print of options.qmanager shows it unassigned. > > Any ideas? > Check parser.usage, it is likely to look a lot like your infile. I'm not sure, but I think you need to pass your alternative arguments to parser.parse_args. max From onurb at xiludom.gro Thu May 4 06:19:45 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 04 May 2006 12:19:45 +0200 Subject: scope of variables In-Reply-To: <87lktinmp2.fsf@localhost.localdomain> References: <874q06bz4c.fsf@localhost.localdomain> <pan.2006.05.03.21.37.01.804277@hastings.org> <87zmhyagqq.fsf@localhost.localdomain> <mailman.5292.1146698030.27775.python-list@python.org> <87lktinmp2.fsf@localhost.localdomain> Message-ID: <4459d59d$0$27055$626a54ce@news.free.fr> Gary Wessle wrote: > Ryan Forsythe <ryan at cs.uoregon.edu> writes: > > >>Gary Wessle wrote: >> >>>the example was an in-accuretlly representation of a the problem I am >>>having. my apologies. >>> (snip) > I finally was able to duplicate the error with a through away code > as follows, > > **************************************************************** > acc = [1,2,3] > > def a(): > b = [4, 5, 6] > acc = acc + b > print len(acc) > > a() > > **************** error **************** > Traceback (most recent call last): > File "a.py", line 12, in ? > a() > File "a.py", line 9, in a > acc = acc + b > UnboundLocalError: local variable 'acc' referenced before assignment This is a FAQ: http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python For short: if a name is 'assigned' (in Python, the correct term is 'bound') in the local scope, it'll be considered a local name. If it's *only* accessed, it'll be looked up in the enclosing namespace - here the so-called 'global' (which means: 'module') namespace. The dirty solution is to declare 'acc' as global in the function: def a(): b = [4, 5, 6] global acc acc = acc + b print len(acc) but this is really BadCode(tm). As a general rule, functions should not silently modify or rebind global variables - this leads to maintenance nightmares. In this case, you should manage to either 1/ pass acc as a param to a(), or 2/ have a() return the sequence to be added to acc: # 1 acc = [1,2,3] def a(alist): alist.extend([4, 5, 6]) return alist acc = a(acc) print acc, len(acc) # 2 acc = [1,2,3] def a(): return [4, 5, 6] acc.extend(a()) print acc, len(acc) The Right Thing(tm) to do of course depends on the real code, so it may be yet another solution, but it's impossible to decide with dummy code... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From mcfletch at vrplumber.com Mon May 29 17:50:54 2006 From: mcfletch at vrplumber.com (Mike C. Fletcher) Date: Mon, 29 May 2006 17:50:54 -0400 Subject: Beginner Python OpenGL difficulties In-Reply-To: <1148833256.751748.291270@j55g2000cwa.googlegroups.com> References: <1148833256.751748.291270@j55g2000cwa.googlegroups.com> Message-ID: <447B6CBE.8000709@vrplumber.com> jg.campbell.ng at gmail.com wrote: > I'm beginning learning Python and OpenGL in Python. > > Python fine. But difficulties with OpenGL; presumably with the > installation of OpenGL. > > OS = Linux FC5. > > Python program gl_test.py: > > from OpenGL.GLUT import * > from OpenGL.GLU import * > from OpenGL.GL import * > > name = "Hello, World" > height = 400 > etc. > > jc at localhost~/etc/python>$ python2 gl_test.py > > Traceback (most recent call last): > File "gl_test.py", line 1, in ? > from OpenGL.GLUT import * > ImportError: No module named OpenGL.GLUT > > jc at localhost~/etc/python>$ echo $PYTHONPATH > /usr/lib/python2.2/site-packages/OpenGL > You should already have site-packages in your PythonPath. You want the directory *above* OpenGL in the path, not OpenGL itself. I'm unsure why you're running a Python 2.2 instance on a modern Linux. I'd suspect that you're using an RPM for an older Linux? Not sure there, I run Gentoo, so everything builds from source for the packages that are installed. There are some Fedora Core build patches in CVS that are waiting for me to get my posterior in gear with Win32 testing to be released. Not sure if that would change anything for you, though. Good luck, Mike -- ________________________________________________ Mike C. Fletcher Designer, VR Plumber, Coder http://www.vrplumber.com http://blog.vrplumber.com From sybrenUSE at YOURthirdtower.com.imagination Fri May 19 04:33:27 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 19 May 2006 10:33:27 +0200 Subject: Opensource vs Microsoft, Wat do you think about opensource? References: <1147996793.841733.109020@j33g2000cwa.googlegroups.com> <mailman.5920.1148002224.27775.python-list@python.org> Message-ID: <slrne6r0mn.m6t.sybrenUSE@schuimige.stuvel.eu> Ben Finney enlightened us with: > Please don't spam here to ask for discussion on another forum, on a > tangentially related topic. Hey, it's at least better than asking for a discussion on a tangentially related topic _here_ ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From socha at cs.washington.edu Tue May 23 18:36:22 2006 From: socha at cs.washington.edu (David Socha) Date: Tue, 23 May 2006 15:36:22 -0700 Subject: determining available space for Float32, for instance Message-ID: <519D71619DEB5348BFCBC6AEBC3F9A03014E1146@exchsrv2.cseresearch.cs.washington.edu> I am looking for a way to determine the maxium array size I can allocate for arrays of Float32 values (or Int32, or Int8, ...) at an arbitrary point in the program's execution. This is needed because Python cannot allocate enough memory for all of the data we need to process, so we need to "chunk" the processing, as described below. Python's memory management process makes this more complicated, since once memory is allocated for Float32, it cannot be used for any other data type, such as Int32. I'd like a solution that includes either memory that is not yet allocated, or memory that used to be allocated for that type, but is no longer used. We do not want a solution that requires recompiling Python, since we cannot expect our end users to do that. Does anyone know how to do this? The following describes our application context in more detail. Our application is UrbanSim (www.urbansim.org), a micro-simulation application for urban planning. It uses "datasets," where each dataset may have millions of entities (e.g. households), and each entity (e.g. household) may have dozens of attributes (e.g. number_of_cars, income, etc.). Attributes can be any of the standard Python "base" types, though most attributes are Float32 or Int32 values. Our models often create a set of 2D arrays with one dimension being agents, and the second dimention being choices from another dataset. For insances, the agents may be households that choose a new gridcell to live in. For our Puget Sound application, there are 1 to 2 million households, and 800K gridcells. Each attribute of a dataset has such a 2D array. Given that we may have dozens of attributes, they can eat up a lot of memory, quickly. Given the sizes of these arrays, and Python's limited address space, Python usually cannot allocate enough memory for us to create the entire set of 2D arrays at once. Instead, we "chunk" the model along the agents dimension, processing a chunk of agents at a time. Some of our models can do their work in a single chunk. Others require hundreds of chunks. It depends upon the number of agents, the number of locations, the number of agent attributes, and the number of location attributes used by that particular model. What we would like is for the code to be able to automatically determine the number of agents that can be in a single chunk. This requires we solve two sub-problems. First, we need to know how many attributes of each type (Float32, Int32, etc.) will be used by this model. We can do that. Second, we need to know how much space is available for an array of a particular type of values, e.g. for Float32 values. Is there a way to get this information for Python? Cheers, David Socha Center for Urban Simulation and Policy Analysis University of Washington www.urbansim.org From steve at holdenweb.com Fri May 19 04:56:55 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 19 May 2006 09:56:55 +0100 Subject: galaxql In-Reply-To: <E1FgwHK-0001Z9-00@mrvnet.kundenserver.de> References: <E1FgwHK-0001Z9-00@mrvnet.kundenserver.de> Message-ID: <446D8857.7070404@holdenweb.com> Further to my recent mention of galaxql as a SQL learning tool, I had the following feedback through holdenweb.com: > Below is the result of your feedback form. It was submitted by > jari komppa (jari.komppa at gmail.com) on Friday, May 19, 2006 at 00:07:53 > --------------------------------------------------------------------------- > > > comments: Steve Holden wrote: "Also I just discovered a shareware > application called galaxql.." > > I'd like to note that it's not shareware - I'm not asking money for it. Thanks for spreading the word =) > > --------------------------------------------------------------------------- > Aah, so I should have called it "freeware"? I believe it's not open source, but I may be incorrect there too - I just downloaded a Windows installer, which worked very smoothly. Sorry to be inaccurate. I am posting to python-list at python.org to correct the mistake. Please feel free to post there yourself to direct people to the Galaxql web site. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From aurelien.campeas at free.fr Wed May 3 05:06:46 2006 From: aurelien.campeas at free.fr (aurelien.campeas at free.fr) Date: 3 May 2006 02:06:46 -0700 Subject: An Atlas of Graphs with Python In-Reply-To: <4455e186$0$14794$4fafbaef@reader4.news.tin.it> References: <4455e186$0$14794$4fafbaef@reader4.news.tin.it> Message-ID: <1146647206.372011.13070@i39g2000cwa.googlegroups.com> You could have a look at the Mozart/Oz community. Oz is a language supporting logic and constraint programming out of the box and people are using these capabilities to play linguistic with graph matching. See http://www.lifl.fr/~duchier/papers/duchier-xdg-cslp2004.pdf for a possibly enlightening example. I know that right now people are working on graphs as first-class finite domain entities to be integrated in Oz (or the constraint solver that was forked from Mozart/Oz, known as Gecode) : http://cpgraph.info.ucl.ac.be/. Incidentally, there is a CPython wrapper for Gecode waiting to be finished, but that is not likely to be ready next month. Cheers, Aur?lien. From 4zumanga at gmail.com Tue May 23 13:28:45 2006 From: 4zumanga at gmail.com (4zumanga) Date: 23 May 2006 10:28:45 -0700 Subject: Guide to using python for bash-style scripting In-Reply-To: <1148405239.840908.120910@j33g2000cwa.googlegroups.com> References: <1148405239.840908.120910@j33g2000cwa.googlegroups.com> Message-ID: <1148405325.101047.181370@j73g2000cwa.googlegroups.com> Yes, there is a stupid mistake in that script, last line should be: diff new_out1 new_out2 However, this is hopefully not important, what is important is the general kind of (very simple) things I'm trying to do. From nobody at 127.0.0.1 Mon May 29 14:18:46 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 29 May 2006 18:18:46 GMT Subject: Finding a lost PYTHONPATH with find References: <87zmh2oxwr.fsf@pobox.com> Message-ID: <aWGeg.103050$F_3.22115@newssvr29.news.prodigy.net> John J. Lee wrote: > find / -maxdepth 3 -size -100k -type f -exec grep -sli pythonpath '{}' \; > > > The minus in '-100k' (meaning "less than 100k") seems to be > undocumented, at least on my system. It should be standard in linux man pages, can't speak for other unices: TESTS Numeric arguments can be specified as +n for greater than n, -n for less than n, n for exactly n. Maybe you were fooled because it's not directly under the description of -size. > I suppose the -maxdepth is > redundant since I think find searches breadth-first by default. ??? maxdepth determines how deep the search will look, not the order the search occurs. Your search only find things within 3 levels of the root, unless your directory tree goes no deeper than that (very unlikely) the maxdepth can't be redundant. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From deets at nospam.web.de Wed May 24 21:21:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 May 2006 03:21:45 +0200 Subject: Bind an instance of a base to a subclass - can this be done? In-Reply-To: <mailman.6167.1148508382.27775.python-list@python.org> References: <pecoraREMOVE-120DFE.15351024052006@ra.nrl.navy.mil> <4djshnF1asdovU1@uni-berlin.de> <mailman.6167.1148508382.27775.python-list@python.org> Message-ID: <4dkf5aF1amcjrU1@uni-berlin.de> Maric Michaud schrieb: > Le Mercredi 24 Mai 2006 22:04, Diez B. Roggisch a ?crit : >> Nope, not in that way. But you might consider writing a proxy/wrapper >> for an object. That looks like this (rouch sketch from head): >> >> class FileWrapper(object): >> def __init__(self, f): >> self._f = f >> >> def __getattr__(self, name): >> return getattr(self._f, name) >> >> def myreadline(self): >> .... > Why use a proxy when you can just inherit from the builtin file object ? To be honest - in my perception file is a function. Which it isn't, but I see it that way :) You are of course right, and have the better solution (unless the OP is not in control of file creation). Diez From durumdara at gmail.com Mon May 15 07:48:29 2006 From: durumdara at gmail.com (DurumDara) Date: Mon, 15 May 2006 13:48:29 +0200 Subject: Unicode to DOS filenames (to call FSUM.exe) In-Reply-To: <1147691744.880789.296320@y43g2000cwc.googlegroups.com> References: <mailman.5697.1147679156.27775.python-list@python.org> <1147691744.880789.296320@y43g2000cwc.googlegroups.com> Message-ID: <44686A8D.7020101@gmail.com> John Machin ?rta: > According to my reading of the source, the function you have called > expects an 8-bit string. > ==== > static PyObject * > PyGetShortPathName(PyObject * self, PyObject * args) > { > char *path; > if (!PyArg_ParseTuple(args, "s:GetShortPathName", &path)) > ==== > If it is given Unicode, PyArg_ParseTuple will attempt to encode it > using the default encoding (ascii). Splat. > > Looks like you need a GetShortPathNameW() but it's not implemented. > Raise it as an issue on the pywin32 sourceforge bug register. Tell Mark > I sent you :-) > > It may be possible to fake up your default encoding to say cp1252 BUT > take the advice of anyone who screams "Don't do that!" and in any case > this wouldn't help you with a Russian, Chinese, etc etc filename. > > Another thought: try using ctypes. > Hi ! I trying with that, but I get error, because the result is unicode too... :-((( from ctypes import windll, create_unicode_buffer, sizeof, WinError buf=create_unicode_buffer(512) if windll.kernel32.GetShortPathNameW(UFN,buf,sizeof(buf)): name=buf.value print [name] ###################################################### Commandline: C:\Python24\python.exe G:\SPEEDT~1\Module1.py Workingdirectory: G:\speedtest Timeout: 0 ms [u'G:\\SPEEDT~1\\xA\xff'] Process "Pyhton Interpeter" terminated, ExitCode: 00000000 ###################################################### Can I do anything with this unicoded filename ? My code must be universal ! Thanx for help: dd From fphsml at gmail.com Thu May 25 02:09:34 2006 From: fphsml at gmail.com (James) Date: 24 May 2006 23:09:34 -0700 Subject: John Bokma harassment In-Reply-To: <1148463588.566212.36300@i39g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> Message-ID: <1148537374.878049.312270@y43g2000cwc.googlegroups.com> > We seem to have strayed a long way from Voltaire's > "I do not agree with what you say, but I will defend to the death your > right to say it." Not at all. My problem with Xah Lee is that he is abusing the Usenet as a personal BLOG. He has a web site to post these articles and he can certainly put up a discussion board there if he wants a vigorous discussion of his ideas. It's worse. He does not even respond to questions directly posed to him in the thread of his "articles". Just imagine if every blogger on the Internet started using Usenet instead and cross-posting at that. From bbands at gmail.com Wed May 3 16:27:46 2006 From: bbands at gmail.com (BBands) Date: 3 May 2006 13:27:46 -0700 Subject: list*list In-Reply-To: <1146525844.275261.266620@e56g2000cwe.googlegroups.com> References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> <1146525844.275261.266620@e56g2000cwe.googlegroups.com> Message-ID: <1146688066.212425.248780@i39g2000cwa.googlegroups.com> Very useful comments... Thanks to all! Once again this community has demonstrated why Python is THE language. jab From johnjsal at NOSPAMgmail.com Fri May 19 13:50:56 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 17:50:56 GMT Subject: Python sqlite and regex. In-Reply-To: <Zwnbg.46846$CH2.28826@tornado.texas.rr.com> References: <mailman.5942.1148042842.27775.python-list@python.org><1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> <hunbg.46845$CH2.29994@tornado.texas.rr.com> <Zwnbg.46846$CH2.28826@tornado.texas.rr.com> Message-ID: <4Anbg.2134$No6.46516@news.tufts.edu> Paul McGuire wrote: > "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message > news:hunbg.46845$CH2.29994 at tornado.texas.rr.com... > >> where '*' matches one or more characters, and '?' matches any single > > oops, I meant '*' matches zero or more characters. '?' also matches 0 characters From nobody at 127.0.0.1 Tue May 2 21:00:01 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 01:00:01 GMT Subject: assignment in if References: <87iroodnqz.fsf@localhost.localdomain> <roy-746AEB.19412402052006@reader1.panix.com> Message-ID: <lgT5g.66665$F_3.13831@newssvr29.news.prodigy.net> Roy Smith wrote: > decision. In Python, assignment is not an operator with side effects like > in C or Java, but a statement. <nitpick> assignemnt is actually an expression in those languages, not a statement. </nitpick> > The lack of embedded assignments leads to slightly more verbose code in > situations like this, but on the other hand, it avoids the typical C > disaster of writing a whole function as a one liner. Writing disasters in python just takes a little more creativity. ;) From fccoelho at gmail.com Sat May 13 12:13:45 2006 From: fccoelho at gmail.com (Flavio) Date: 13 May 2006 09:13:45 -0700 Subject: distributing a app frozen by cx_freeze In-Reply-To: <1147501391.800070.265860@g10g2000cwb.googlegroups.com> References: <1147482467.404798.187530@y43g2000cwc.googlegroups.com> <1147501391.800070.265860@g10g2000cwb.googlegroups.com> Message-ID: <1147536825.158172.73480@i40g2000cwc.googlegroups.com> Well I managed to get rid of the undefined symbol message by copying all qt libs to the freeze directory, the problem is that now the package is huge (83MB)! So my question is: is there a way to find out exactly which lib is missing ? Thanks From dakman at gmail.com Fri May 5 09:22:07 2006 From: dakman at gmail.com (dakman at gmail.com) Date: 5 May 2006 06:22:07 -0700 Subject: Tkinter Canvas Pre-Buffer Message-ID: <1146835327.380237.130190@e56g2000cwe.googlegroups.com> Is there a way that using Tkinter I can pre-render the canvas then draw it on the screen? Thanks. From parker at hiredatum.demon.co.uk Thu May 25 03:38:32 2006 From: parker at hiredatum.demon.co.uk (Ian Parker) Date: Thu, 25 May 2006 08:38:32 +0100 Subject: os listdir access denied when run as a service References: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz> <1146620207.56.7672@mint-julep.mondoinfo.com> <002901c66e57$05a69090$346ea8c0@tintz.co.nz> <1146624295.41.7841@mint-julep.mondoinfo.com> <003501c66e64$316deb30$346ea8c0@tintz.co.nz> <1146677203.2.7870@mint-julep.mondoinfo.com> <00f701c673e5$a3af0860$346ea8c0@tintz.co.nz> <1147292340.91.3040@mint-julep.mondoinfo.com> <012d01c67473$09fc0450$346ea8c0@tintz.co.nz> <1147305886.06.3304@mint-julep.mondoinfo.com> <016201c67497$22a91d70$346ea8c0@tintz.co.nz> <1147311218.22.3304@mint-julep.mondoinfo.com> <mailman.6178.1148529545.27775.python-list@python.org> Message-ID: <VWBdEjH47VdEFwxx@hiredatum.demon.co.uk> In message <mailman.6178.1148529545.27775.python-list at python.org>, Thomas Thomas <thomas at eforms.co.nz> writes >Hi All, > >I am trying to access a mapped network drive folder. everything works fine >normally. But when i run the application as service I am getting the error > >Traceback (most recent call last): > File "docBoxApp.py", line 129, in ? > File "core\PollFiles.pyc", line 332, in doPoll > File "core\PollFiles.pyc", line 47, in createFileList > File "core\PollFiles.pyc", line 25, in addFolderFiles >WindowsError: [Errno 5] Access is denied: 'G:\\DT Hot Folder test/*.*' > > >below is my code > > >def addFolderFiles(folder,filelist=[]): > logger=ServerInterface.getErrorLogger() > folder = folder.encode('ascii') #convert path to ascii for File Method > for filename in os.listdir(folder):#line 25 > file=os.path.join(folder,filename) > logger.error("loop file :"+file); > if os.path.isfile(file): > logger.error("is file :"+file); > if ((not (file.find(".tmp")>=0)) and (not >(file.find("~")>=0))): > filelist.append(file) > elif os.path.isdir(file): > logger.error("file is a directory :"+file); > addFolderFiles(file,filelist) > >def createFileList(files,folders,filelist=[]): > logger=ServerInterface.getErrorLogger() > for file in files: > file = file.encode('ascii') #convert path to ascii for File Method > if os.path.isfile(file): > if ((not (file.find(".tmp")>=0)) and (not (file.find("~")>=0))): > filelist.append(file) > > for folder in folders: > logger.error("got a folder :"+folder); > logger.error("it was in the list :"+folders.__str__()); > addFolderFiles(folder,filelist) > return (1,filelist) > >anything I can do about this.. > > >----------------------------------------------------- >Thomas Thomas > This may be relevant. IIRC, when you run a service under the system account it doesn't have network access. You need to run it under an account that does have access to the drive. Regards Ian -- Ian Parker From trebucket at gmail.com Thu May 25 17:38:34 2006 From: trebucket at gmail.com (trebucket at gmail.com) Date: 25 May 2006 14:38:34 -0700 Subject: Multi-dimensional list initialization trouble In-Reply-To: <1148592170.709560.307030@j55g2000cwa.googlegroups.com> References: <1148592170.709560.307030@j55g2000cwa.googlegroups.com> Message-ID: <1148593113.944379.40160@j33g2000cwa.googlegroups.com> An expression like this creates a list of integers: >>> [0] * 2 [0, 0] But an expression like this creates list of references to the list named `foo': >>> foo = [0, 0] >>> baz = [foo] * 2 [foo, foo] So, setting baz[0][0] = 1, is really setting foo[0] = 1. There is only one instance of foo, but you have multiple references. Try a list comprehension to get the result you want: >>> foo = [[0 for ii in range(2)] for jj in range(2)] From jantod at gmail.com Sun May 28 19:53:32 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 28 May 2006 16:53:32 -0700 Subject: itertools.count() as built-in References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> Message-ID: <1148860412.898545.64870@u72g2000cwu.googlegroups.com> Oh and I use repeat, chain and cycle quite a bit. But I don't mind importing them as they are usually limited to one module. From rowen at cesmail.net Mon May 22 15:27:13 2006 From: rowen at cesmail.net (Russell E. Owen) Date: Mon, 22 May 2006 12:27:13 -0700 Subject: PEP-xxx: Unification of for statement and list-comp syntax References: <mailman.6031.1148224219.27775.python-list@python.org> Message-ID: <rowen-6B2BC4.12271322052006@news.isp.giganews.com> +1 It does seem like a natural unificiation of the language -- one less exception to learn. -- Russell From ronnyma at math.uio.no Tue May 9 15:58:05 2006 From: ronnyma at math.uio.no (Ronny Mandal) Date: Tue, 09 May 2006 21:58:05 +0200 Subject: Calling python functions from C References: <1147194348.285669.218280@g10g2000cwb.googlegroups.com> Message-ID: <00t16251bd7qh1hjhmflu094blrq33h5i3@4ax.com> On 9 May 2006 10:05:48 -0700, robert.differentone at gmail.com wrote: >I am a newbie to Python. I want to call python functions from C. I >looked for examples but I couldn't get any simple one. Lets say my >python code is : >def add(a,b) > return (a+b) > >I want to call add from C. Could anybody please help me? Thanks in >advance. This is also known as "callback". Check out http://www.google.com/search?client=opera&rls=en&q=python+c+callback&sourceid=opera&ie=utf-8&oe=utf-8 or http://www.python.org/doc/current/ext/ext.html -RM > >R. From aisaac0 at verizon.net Mon May 1 12:32:24 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 01 May 2006 16:32:24 GMT Subject: Numeric, vectorization References: <1146500254.216411.166700@u72g2000cwu.googlegroups.com> Message-ID: <sKq5g.3214$6d4.2070@trnddc03> "RonnyM" <ronnyma at math.uio.no> wrote in message news:1146500254.216411.166700 at u72g2000cwu.googlegroups.com... > e.g. y = [ 1, 2, 3, 4, 5, 6 ,7 ,8, 9 ] > ybar = [ 1, (1 + 3)*.5,(2 + 4)*.5,(3 + 5)*.5,..., (n-1 + n+1)*.5 ], n = > 1,...len(y) -1 > How do I make a vectorized version of this, I will prefer not to > utilize Map or similar functions, but numeric instead. You treat the first element asymmetrically, so that does not vectorize. The rest does: >>> import numpy as N >>> y=N.arange(1,10) >>> slice1 = slice(0,-2,1) >>> slice2 = slice(2,None,1) >>> ybar = 0.5*(y[slice1]+y[slice2]) >>> ybar array([ 2., 3., 4., 5., 6., 7., 8.]) hth, Alan Isaac From liupeimail at gmail.com Mon May 1 12:32:02 2006 From: liupeimail at gmail.com (liupei) Date: 1 May 2006 09:32:02 -0700 Subject: how to do with the multi-frame GIF Message-ID: <1146501122.180961.11580@i39g2000cwa.googlegroups.com> how to do with the multi-frame GIF, I used the PIL ,but it seems not support? From sjmachin at lexicon.net Wed May 24 23:29:02 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 May 2006 13:29:02 +1000 Subject: Unexpected extension module behaviour In-Reply-To: <1148522952.022925.229350@u72g2000cwu.googlegroups.com> References: <1148522952.022925.229350@u72g2000cwu.googlegroups.com> Message-ID: <4475247E.5090506@lexicon.net> On 25/05/2006 12:09 PM, rimmer wrote: > I'm writing an extension module in C in which I'm passing an array of > floats from C to python. The code below illustrates a simple C > function designed to output an array of floats. > [snip] Couldn't restrain myself from reading further :-) > > Then I write a wrapper function to pass the data back and forth between > C and Python. > > ---------------- > extTestWrapper.c > ---------------- > > #include "/usr/include/python2.4/Python.h" > #include <stdio.h> > > // external declarations > extern float *testArray(int); Um, shouldn't that be "double", not "float"? > > // Python wrapper for the testArray function > PyObject *extTest_testArray(PyObject *self, PyObject *args) { > > double *nums; > int nsamp; > int i; > PyObject *pynums; > > if (!PyArg_ParseTuple(args, "i", &nsamp)) { > return NULL; > } > > // call the C function > nums = testArray(nsamp); > > // build a Python list object containing the array values > pynums = PyList_New(nsamp); Test for errors! > for (i=0; i<=nsamp; i++){ Um, shouldn't that be "<", not "<="??? Note, you have the same problem in the C function. "nsamp" is presumed in the absence of any docs to mean "number of samples". A caller passing in 5 expects to get 5 values, NOT 6. But you are calling PyList_New with 5. > PyList_SetItem(pynums, i, PyFloat_FromDouble(nums[i])); Given you are trying to stuff one extra item into the list, you should definitely test for errors here!!! I suggest that you change this incrementally. First, just change the above line to test for errors. Then run it again so you can see what happens. Second, fix the other problems. > } > return Py_BuildValue("O", pynums); Rather unnecessary; you can just return pynums. [read before snipping :-)] HTH, John From durumdara at gmail.com Wed May 3 03:53:39 2006 From: durumdara at gmail.com (DurumDara) Date: Wed, 03 May 2006 09:53:39 +0200 Subject: How to encode html and xml tag datas with standard python modules ? Message-ID: <44586183.2030903@gmail.com> Hi ! Have the python standard mod. lib. a html/xml encoder functions/procedures ? like this: def ToSafeHTM(Text): s=ToHuStrSafe(Text) l=[] for c in s: b=ord(c) if c=="\n": c="<br>" else: if b<32 or b>127 or c in ['<','>','"',';','&','@','%','#']: c="&#%03d;"%b l.append(c) s="".join(l) return s Thanx for help: dd From klaus at seistrup.dk Sun May 28 04:25:19 2006 From: klaus at seistrup.dk (Klaus Alexander Seistrup) Date: Sun, 28 May 2006 08:25:19 +0000 (UTC) Subject: Generating random passwords ... for a csv file with user details References: <1148802192.793574.209720@i40g2000cwc.googlegroups.com> Message-ID: <e5bmpf$ub3$1@minji.szn.dk> Kanthi skrev: > I have a csv file which in taken as the input file for adding > users in my linux mail server with the format > > userid,fullname,passwword,dateofbith > > Now I have to write a script to generate random password in the > password field for each user. A simple algorithm is sufficient > for passwords #v+ >>> import sha >>> sha.sha('userid,fullname,passwword,dateofbith').digest().encode('base64')[:10] 'q0nCDQ1YdL' >>> #v- Mvh, -- Klaus Alexander Seistrup SubZeroNet, Copenhagen, Denmark http://magnetic-ink.dk/ From bignose+hates-spam at benfinney.id.au Tue May 16 22:28:56 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Wed, 17 May 2006 12:28:56 +1000 Subject: help with a function References: <446a85c6$0$61170$ae4e5890@news.nationwide.net> Message-ID: <87sln9peon.fsf@benfinney.id.au> Lance Hoffmeyer <lance at augustmail.com> writes: > def even_odd_round(num): > if(round(num,2) + .5 == int(round(num,2)) + 1): > if(int(num,0) % 2): #an odd number > rounded_num = round(num,2) + .1 > else: #an even number > rounded_num = round(num,2) - .1 > rounded_num = int(rounded_num) > return rounded_num > > even_odd_round(5.5) > > Traceback (most recent call last): > File "<interactive input>", line 1, in ? > File "<interactive input>", line 3, in even_odd_round > TypeError: int() can't convert non-string with explicit base > >>> Two problems. One is the simple fact reported by the error message: you're attempting to specify that a number object (already represented inside Python as a number) should be converted using a particular base. (Why you've chosen 0 as the base is beyond me.) That only makes sense with a string of digit characters, where Python needs to be told what numeric base each digit is (decimal, octal, hexadecimal, whatever). It makes no sense for objects that are already numbers, since they're not represented as digits in a base. The other problem is specifying a base at all. Why not just convert the object to an int using the default base? If you're confused about how built-in types or functions work, you should become familiar with the help system in the interpreter: help(int) -- \ "Any sufficiently advanced bug is indistinguishable from a | `\ feature." -- Rich Kulawiec | _o__) | Ben Finney From bob at greschke.com Tue May 23 14:16:56 2006 From: bob at greschke.com (Bob Greschke) Date: Tue, 23 May 2006 12:16:56 -0600 Subject: Don't wish to give up on a Tkinter GUI Builder :( References: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> <1148371674.932205.83160@j55g2000cwa.googlegroups.com> <1148382609.644438.267020@j55g2000cwa.googlegroups.com> Message-ID: <A6qdnQFPrLgDzO7ZnZ2dnUVZ_uidnZ2d@nmt.edu> "vbgunz" <vbgunz at gmail.com> wrote in message news:1148382609.644438.267020 at j55g2000cwa.googlegroups.com... > Thank you very much for the link and info. It looks promising but I am > still on the lookout for a drag-n-drop Gui builder like vltc so if > anyone has more links to new projects I am definitely interested! > > PS. I do love the code generated from rapyd! > What are you building? I routinely do things like these by hand www.greschke.com/unlinked/images/changeo.jpg www.greschke.com/unlinked/images/pocus.jpg www.greschke.com/unlinked/images/pis.jpg www.greschke.com/unlinked/images/petm.jpg and I can't imagine using a builder for anything 'simpler'. If you are just starting out I'd go the long-hand route first until you really have a good grasp of Tkinter, then go the easier route. Once you find your own "style" it becomes easier to just do it rather than try to get some other program to do it for you. I tried rapyd today, too. Started it, drug a button to the frame, but then couldn't figure out how to set the text of the button. Deleted it. :) Bob From bob at passcal.nmt.edu Fri May 26 12:41:16 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Fri, 26 May 2006 10:41:16 -0600 Subject: Tkinter canvas zooming (sortof) Message-ID: <YvSdnfxcW74PsurZnZ2dnUVZ_t6dnZ2d@nmt.edu> I have a program that sucks in a list of equipment positions (Lats/Longs), opens a Toplevel frame with a canvas set to, for example, 700x480 pixels, and then does all of the calculations and plots the objects with 10-pixel wide ovals and rectangles. Now I want to zoom in (or out), but I don't want the ovals and rectangles to change size. I just want them to spread out or get closer together. So scale() doesn't seem to be the way to go. What I want to do is just make the "logical" canvas bigger and replot everything, but when I reconfigure the canvas size to make it bigger the Toplevel frame itself gets bigger. I want the frame to stay the same size, but still be resizable. I have scrollbars, and they seem to work ok, and scrollregion seems to do what it should, but I can't figure out how to get them to all work together to do what I want. Help? Thanks! Bob From brian at sweetapp.com Thu May 18 11:59:09 2006 From: brian at sweetapp.com (Brian Quinlan) Date: Thu, 18 May 2006 17:59:09 +0200 Subject: ANN: Vancouver Python Workshop - keynote speakers announced Message-ID: <446C99CD.5090001@sweetapp.com> What's New? =========== We are pleased to announce the keynote speakers for this year's Vancouver Python Workshop: Guido van Rossum and Jim Hugunin. Guido van Rossum (Google) is the inventor of Python and has managed its growth and development for more than a decade. Guido was awarded the Free Software Foundation Award in 2002 and Dr.Dobb's 1999 Excellence in Programming Award. Today Guido works at Google, spending half of his time on Python. Jim Hugunin (Microsoft) is the creator of IronPython, Jython and Numeric Python. IronPython is Python for the .NET platform and integrates Python into Microsoft's .NET strategy. Jython is Python for the Java platform and was the second production quality implementation of Python. Numeric Python adapts Python to the needs of number crunching applications. Today, Jim works at Microsoft where he helps them adapt the .NET runtime to meet the needs of dynamic languages like Python. About the Vancouver Python Workshop =================================== The conference will begin with keynote addresses on August 4st. Further talks (and tutorials for beginners) will take place on August 5th and 6th. The Vancouver Python Workshop is a community organized conference designed for both the beginner and for the experienced Python programmer with: * tutorials for beginning programmers * advanced lectures for Python experts * case studies of Python in action * after-hours social events * informative keynote speakers * tracks on multimedia, Web development, education and more More information see: http://www.vanpyz.org/conference/ or contact Brian Quinlan at: brian at sweetapp.com Vancouver ========= In addition to the opportunity to learn and socialize with fellow Pythonistas, the Vancouver Python Workshop also gives visitors the opportunity to visit one of the most extraordinary cities in the world (1). For more information about traveling to Vancouver, see: http://www.vanpyz.org/conference/vancouver.html http://www.tourismvancouver.com http://en.wikipedia.org/wiki/Vancouver Important dates =============== Talk proposals accepted: May 15th to June 15th Early registration (discounted): May 22nd to June 30th Normal registration: from July 1st Keynotes: August 4th Conference and tutorial dates: August 5th and 6th (1) http://news.bbc.co.uk/2/hi/business/2299119.stm Cheers, Brian From Serge.Orlov at gmail.com Thu May 11 10:24:56 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 11 May 2006 07:24:56 -0700 Subject: Memory leak in Python References: <1147137301.956884.317970@g10g2000cwb.googlegroups.com> <ccl062h5tc24b4qe3d66b7hvh7ujgrklcp@4ax.com> <1147182643.738945.166000@j33g2000cwa.googlegroups.com> <1147252803.325579.151510@j33g2000cwa.googlegroups.com> <1147303585.301968.270590@i39g2000cwa.googlegroups.com> Message-ID: <1147357496.710958.164370@g10g2000cwb.googlegroups.com> diffuser78 at gmail.com wrote: > I ran simulation for 128 nodes and used the following > > oo = gc.get_objects() > print len(oo) > > on every time step the number of objects are increasing. For 128 nodes > I had 1058177 objects. > > I think I need to revisit the code and remove the references....but how > to do that. I am still a newbie coder and every help will be greatly > appreciated. The next step is to find out what type of objects contributes to the growth most of all, after that print several object of that type that didn't exist on iteration N-1 but exist on iteration N From harisekhon at gmail.com Wed May 17 07:37:29 2006 From: harisekhon at gmail.com (Hari Sekhon) Date: Wed, 17 May 2006 12:37:29 +0100 Subject: Strange IO Error when extracting zips to a network location In-Reply-To: <446AF1F1.9040907@gmail.com> References: <446AF1F1.9040907@gmail.com> Message-ID: <446B0AF9.4080008@gmail.com> I put a try-pass around the line "outfile.write(zip.read(x)) " so that everything extracts regardless. After extraction I checked the file size of every single file in the directory tree and only 2 files on the network drive are of different size to the ones extracted locally. Both these files are .dbf files that are over 100MB when extracted. Both of them is short by exactly 4 KB. Strange. I wonder if I'm hitting a size limit or something with this "zipfile" module, or perhaps a python limitation on buffer or something? I've change the code to contents=zip.read(x) outfile.write(contents) but I still get the same result. -h Hari Sekhon wrote: > Hi, > I've written a script to run on windows to extract all zips under a > given directory path to another directory path as such: > > python extractzips.py <fetch all zips under this dir> <put all > extracted files under this dir> > > The purpose of this script is to retrieve backup files which are > individually zipped under a backup directory tree on a backup server. > > This scripts works nicely and has input validation etc, exiting > gracefully and telling you if you gave a non existent start or target > path... > > When running the script as follows > > python extractzips.py \\backupserver\backupshare\machine\folder > d:\unziphere > > the script works perfectly, but if I do > > python extractzips.py \\backupserver\backupshare\machine\folder > \\anetworkmachine\share\folder > > then it unzips a lot of files, recreating the directory tree as it > goes but eventually fails with the traceback: > > File "extractzips.py", line 41, in zipextract > outfile.write(zip.read(x)) > IOError: [Errno 22] Invalid argument > > > But I'm sure the code is correct and the argument is passed properly, > otherwise a hundred files before it wouldn't have extracted > successfully using this exact same piece of code (it loops over it). > It always fails on this same file every time. When I extract the same > tree to my local drive it works fine without error. > > I have no idea why pushing to a network share causes an IO Error, > shouldn't it be the same as extracting locally from our perspective? > > It pulls fine, why doesn't it push fine? > > > Thanks for any help or suggestions anybody can give me. > > Hari > From nobody at 127.0.0.1 Tue May 2 20:55:04 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 00:55:04 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <mailman.5240.1146612890.27775.python-list@python.org> Message-ID: <IbT5g.66663$F_3.45591@newssvr29.news.prodigy.net> Ben Finney wrote: > So the tradeoff you propose is: > > - Honour "explicit is better than implicit", but users are confused > over "why do I need to declare the instance in the method > signature?" > > against > > - Break "explicit is better than implicit", take away some of the > flexibility in Python, and users are confused over "where the heck > did this 'self' thing come from?" or "how the heck do I refer to > the instance object?" Essentially, but 1. it removes zero flexibility (everything works as before) 2. it's no more confusing than "where did this len/count/dir/type/str/any other builtin thing come from?" 3. learning "how do i access this instance object" is certainly no harder or less intuitive than learning "how do i initialize this instance object?" > I don't see a net gain by going with the latter. Ok. Would you care to explain in more detail? From me+python at modelnine.org Thu May 11 09:54:58 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 11 May 2006 15:54:58 +0200 Subject: Python memory deallocate In-Reply-To: <1147353348.028544.143470@u72g2000cwu.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <1147347601.597292.15220@j73g2000cwa.googlegroups.com> <1147353348.028544.143470@u72g2000cwu.googlegroups.com> Message-ID: <200605111554.58287.me+python@modelnine.org> Am Donnerstag 11 Mai 2006 15:15 schrieb mariano.difelice at gmail.com: > I MUST find a system which deallocate memory... > Otherwise, my application crashes not hardly it's arrived to > break-point system As was said before: as long as you keep a reference to an object, the object's storage _will not be_ reused by Python for any other objects (which is sensible, or would you like your object to be overwritten by other objects before you're done with them?). Besides, even if Python did free the memory that was used, the operating system wouldn't pick it up (in the general case) anyway (because of fragmentation issues), so Python keeping the memory in an internal free-list for new objects is a sensible choice the Python developers took here. Basically, what I think is happening is that you are loading all images that you use for your program into memory at once, and these simply will eat up your memory until your program crashes (because Python can't know you no longer need them). As you keep a reference to the image (somewhere, someplace), del(eting) the reference in one scope isn't going to free the memory for Python (or PIL in this case) to reuse for the next image. An object is kept alive because of a memory leak inherent to your application. This is a programming problem, not a Python problem. And, if you don't post any sources, we won't be able to help you much here, save to tell you to look closely where you create objects, and where you store them to. PIL isn't known to have any memory leaks, by the way (AFAICT), just to confirm what I've written before, but the effbot should be of more help here... --- Heiko. From larry.bates at websafe.com Tue May 2 12:33:46 2006 From: larry.bates at websafe.com (Larry Bates) Date: Tue, 02 May 2006 11:33:46 -0500 Subject: ConfigParser and multiple option names In-Reply-To: <e37rji$c46$1@news.in.tum.de> References: <e37rji$c46$1@news.in.tum.de> Message-ID: <gvqdnVa4wK51FMrZnZ2dnUVZ_t6dnZ2d@comcast.com> Florian Lindner wrote: > Hello, > since ConfigParser does not seem to support multiple times the same option > name, like: > > dir="/home/florian" > dir="/home/john" > dir="/home/whoever" > > (only the last one is read in) > > I wonder what the best way to work around this. > > I think the best solution would be to use a seperation character: > > dir="/home/florian, /home/john, home/whoever" > > What character would be best to work on various operating systems? (of what > names may a path consist is the question) > > What do you think? Any better ideas? > > Thanks, > > Florian I would either use (not tested): [directories] dir_01="/home/florian" dir_02="/home/john" dir_03="/home/whoever" and in my program do: INI=ConfigParser.ConfigParser() INI.read(inifilepath) section="directories" dirs=[x for x in INI.options(section) if x.startswith('dir_')] or more easily: [init] dirs=/home/florian,/home/john,home/whoever and in program do: section="init" dirs=INI.get(section, 'dirs',).split(',') Which one to use depends on how many dirs you would be supporting. If it is a lot, I like the first version. If a few, the second seems better. -Larry Bates From skip at pobox.com Wed May 3 07:52:56 2006 From: skip at pobox.com (skip at pobox.com) Date: Wed, 3 May 2006 06:52:56 -0500 Subject: [Python-3000] bug in modulus? In-Reply-To: <20060503044158.c6wxhrx2ygrbgoo0@login.werra.lunarpages.com> References: <20060503044158.c6wxhrx2ygrbgoo0@login.werra.lunarpages.com> Message-ID: <17496.39320.652859.443575@montanaro.dyndns.org> Michael> So why not make "x % y" for floats behave exactly like it does Michael> for integers and provide a separate operation with your Michael> described behavior? %% anyone? (Skip ducks and runs...) Skip From deets at nospam.web.de Mon May 15 07:19:00 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 13:19:00 +0200 Subject: please help me is sms with python References: <mailman.5701.1147690409.27775.python-list@python.org> Message-ID: <4cr6deF17i9mpU1@uni-berlin.de> huda ahmed wrote: > hi >>>> > please i need your help ..... > > how can i send sms from pc(windows xp) > to mobile symbian 60 6630 by python > > i need your help please > i hope you answer me as fast as u can > > thanks in advance...... Attach a Mobile to your computer using USB/Bluetooth, open it with a terminal program and use these AT-commands. http://www.cellular.co.za/hayesat.htm#SMS Command Set You can do that in python too, by opening the COM-port the handset is attached to and issuing the commands yourself. Diez From ny_r_marquez at yahoo.com Fri May 5 08:59:09 2006 From: ny_r_marquez at yahoo.com (RM) Date: 5 May 2006 05:59:09 -0700 Subject: ANN: 4 little Python programs Message-ID: <1146833949.544241.88330@y43g2000cwc.googlegroups.com> I recently got access to one of those new GooglePages and decided to play around with it a little. I figured it would be a nice *easy* way to get a website going. I may eventually do something more professional, but hey, this was free in both money and time. :) I had been thinking of releasing some of my little personal apps for a while. So, this finally motivated me to clean them up enough for release. The website is not yet finished, but I couldn't wait to share with you these little Python programs. I have packaged them nicely for Windows using py2exe and InnoSetup. Unfortunately, I haven't had the time to do the same for Linux. I plan to that soon. You can get them here. http://rmcorrespond.googlepages.com/customsoftware I have been using them for several years, but never got around to releasing them. Any way, I hope you like them. Oh, they are all licensed with the GPL, but for now, since I don't yet have a way to track downloads, I am only making the source available upon request. If you have any questions or suggestions let me know. -Ruben From http Thu May 18 12:39:59 2006 From: http (Paul Rubin) Date: 18 May 2006 09:39:59 -0700 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5872.1147945818.27775.python-list@python.org> <1147961360.404525.203520@j55g2000cwa.googlegroups.com> Message-ID: <7xiro3mgm8.fsf@ruckus.brouhaha.com> "SamFeltus" <sam at nuevageorgia.com> writes: > I guess there isn't much to understand. If you are satisfied with a > text based, static image web, that is light on artistic possabilities, > all that HTML stuff is acceptable. Perhaps the HTML/JS group will even > get off their rear ends and bring some decent cross platform graphics > capabilities to the web one decade? Perhaps even bring some 90's style > graphics to the browser one decade? If I want to watch movies, I'll go out and buy a TV set. For web sites, stick with HTML. I don't have (and refuse to install) the Flash plugin in my browser and it's a pain in the neck that many business sites are impossible to even navigate, because there's no way past the Flash entry screen. The sensible ones have a "skip intro" link, but a lot of them don't. From johnjsal at NOSPAMgmail.com Mon May 8 10:33:02 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 14:33:02 GMT Subject: regular expressions, substituting and adding in one step? Message-ID: <yEI7g.2056$No6.45379@news.tufts.edu> Ok, this might look familiar. I'd like to use regular expressions to change this line: self.source += '<p>' + paragraph + '</p>\n\n' to read: self.source += '<p>%s</p>\n\n' % paragraph Now, matching the middle part and replacing it with '%s' is easy, but how would I add the extra string to the end of the line? Is it done all at once, or must I make a new regex to match? Also, I figure I'd use a group to match the word 'paragraph', and use that group to insert the word at the end, but how will I 'retain' the state of \1 if I use more than one regex to do this? I'd like to do this for several lines, so I'm trying not to make it too specific (i.e., matching the entire line, for example, and then adding text after it, if that's possible). So the questions are, how do you use regular expressions to add text to the end of a line, even if you aren't matching the end of the line in the first place? Or does that entail using separate regexes that *do* do this? If the latter, how do I retain the value of the groups taken from the first re? Thanks, hope that made some sense. From tdw at tdw.net Tue May 2 07:12:48 2006 From: tdw at tdw.net (Tim Williams) Date: Tue, 2 May 2006 12:12:48 +0100 Subject: stripping In-Reply-To: <9afea2ac0605020351w46e816fehdbbcd8e30b29f41@mail.gmail.com> References: <W40649344.961.442.1@mx-extra.net> <9afea2ac0605020351w46e816fehdbbcd8e30b29f41@mail.gmail.com> Message-ID: <9afea2ac0605020412u5234adc5y10400df033f3c63c@mail.gmail.com> On 02/05/06, Tim Williams <tdw at tdw.net> wrote: > > > On 1 May 2006 23:20:56 -0700, micklee74 at hotmail.com <micklee74 at hotmail.com > > wrote: > > > > hi > > i have a file test.dat eg > > > > > f = open("test.dat") > while 1: > line = f.readline().rstrip("\n") > if line: > print line > > is simpler and easier to read. > Except for my obvious mistake, tThe while never terminates: >>> for line in f: ... line = line.rstrip("\n") ... if line: ... print line ... abcdefgh ijklmn opqrs tuvwxyz or even >>> for line in open("test.dat"): ... line = line.rstrip("\n") ... if line: ... print line ... abcdefgh ijklmn opqrs tuvwxyz :) -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060502/69f05446/attachment.html> From jstroud at ucla.edu Tue May 9 22:03:41 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 09 May 2006 19:03:41 -0700 Subject: interactive shell -- reload definitions? In-Reply-To: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> References: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> Message-ID: <e3rhlt$bvu$1@zinnia.noc.ucla.edu> Metalone wrote: > I have a question about the interactive Python shell. Is it possible > to reload a file and get the new definitions. > > For example, if I do > import xyz > > Then I find a bug in some function in xyz. > So, I edit xyz.py > > I would like to reload the definitions in xyz.py without leaving my > current shell session. > Is this possible? > > > Also, is there any way to save definitions created in the interactive > shell to a file? > Sometimes I write a simple function in the shell, and this wish I had > that function in an external file. > > Thanks. > Quoting my python interpreter: """ Help on built-in function reload: reload(...) reload(module) -> module Reload the module. The module must have been successfully imported before. """ James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From nobody at 127.0.0.1 Fri May 12 05:02:03 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 09:02:03 GMT Subject: Reg Ex help References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> <4463a7be$0$290$626a54ce@news.free.fr> <S4P8g.69868$_S7.2226@newssvr14.news.prodigy.com> <446446df$0$289$636a55ce@news.free.fr> Message-ID: <faY8g.71357$F_3.9755@newssvr29.news.prodigy.net> bruno at modulix wrote: > parts = s.replace(' ', '/').strip('/').split('/') > branch = parts[parts.index('CHECKEDOUT') - 1] > > Edward Elliott wrote: >> >> marker = s.index('/CHECKEDOUT') >> branch = s [s.rindex('/', 0, marker) + 1 : marker] > > Much cleaner than mine. I shouldn't try to code when it's time to bed !-) Not terribly readable though, hard to tell what the magic slice indexes mean. Yours is easier to follow. I think I'd just use a regex though. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From nnorwitz at gmail.com Sat May 6 22:37:29 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 6 May 2006 19:37:29 -0700 Subject: python 2.5a2, gcc 4.1 and memory problems In-Reply-To: <UwZ6g.111186$A83.2617718@twister1.libero.it> References: <UwZ6g.111186$A83.2617718@twister1.libero.it> Message-ID: <1146969449.567022.245750@u72g2000cwu.googlegroups.com> Michele Petrazzo wrote: > > I haven't tried to recompile py 2.4 myself with gcc 4.1 because it is > already compiled with it (4.0.3), so I think (only think) that is a py > 2.5 problem. > I'm right? or I have to compile it with something other switches? Sounds like a gcc problem to me. Try adding --with-pydebug in the configure options. My guess is that it will work. This option enables asserts, but more importantly disables optimization. My guess is that this is an optimization problem with gcc. I assume -fno-strict-aliasing is one of the gcc flags. It should be as this is required for building python. Cheers, n From python.list at tim.thechases.com Thu May 4 07:54:17 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 04 May 2006 06:54:17 -0500 Subject: RegEx with multiple occurrences In-Reply-To: <1146742939.692014.201270@e56g2000cwe.googlegroups.com> References: <1146742939.692014.201270@e56g2000cwe.googlegroups.com> Message-ID: <4459EB69.8030306@tim.thechases.com> > p = re.compile("(\<script.*>*\</script>)",re.IGNORECASE | re.DOTALL) > m = p.search(data) First, I presume you didn't copy & paste your expression, as it looks like you're missing a period before the second asterisk. Otherwise, all you'd get is any number of greater-than signs followed by a closing "</script>" tag. Second, you're likely getting some foobar results because you're not using a "real" string of the form r'(\<script...script>)' > The problem is that I'm getting everything from the 1st > script's start tag to the last script's end tag in one > group - so it seems like it parses the string from both > ends therefore removing far more from that data than I > want. What am I doing wrong? Looks like you want the non-greedy modifier to the "*" described at http://docs.python.org/lib/re-syntax.html (searching the page for "greedy" should turn up the paragraph on the modifiers) You likely want something more like: r'<script[^>]*>.*?</script>' In the first atom, you're looking for the remainder of the script tag (as much stuff that isn't a ">" as possible). Then you close the tag with the ">", and then take as little as possible (".*?") of anything until you find the closing "</script>" tag. HTH, -tkc From rdh at new.rr.com Fri May 12 17:45:49 2006 From: rdh at new.rr.com (DataSmash) Date: 12 May 2006 14:45:49 -0700 Subject: unzip zip files Message-ID: <1147470349.415553.324710@y43g2000cwc.googlegroups.com> I need to unzip all zip file(s) in the current directory into their own subdirectories. The zip file name(s) always start with the string "usa" and end with ".zip". The code below will make the subdirectory, move the zip file into the subdirectory, but unzips the contents into the root (current) directory. I want the contents of the zip file unloaded into the newly created subdirectory where the zip file is. Any ideas? Thanks. R.D. import subprocess # Get all the zip files in the current directory. for zip in os.listdir(''): if zip.endswith(".zip"): # Remove the first 3 and the last 4 characters # e.g. usa12345.zip becomes 12345 zipBase = zip[3:-4] # Make directory for unzipping os.mkdir(zipBase) # Move the zip file to the subdirectory shutil.move(zip, zipBase) # Make system call "unzip" subprocess.Popen(["unzip", zipBase + "\\" + zip]).wait() From tim.leeuwvander at nl.unisys.com Mon May 8 04:12:16 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 8 May 2006 01:12:16 -0700 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <1147071499.135783.193610@e56g2000cwe.googlegroups.com> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> <1147071499.135783.193610@e56g2000cwe.googlegroups.com> Message-ID: <1147075936.448666.174760@j33g2000cwa.googlegroups.com> So you write: for key in sorted(dict.iterkeys()): ... do it ... dict.iterkeys() returns an iterable which doesn't even have a sort-method; and somehow I find it unnatural to apply a 'sort' method to an iterator whereas I find it perfectly natural to feed an iterator to a function that does sorting for anything iterable... Cheers, --Tim From aleax at mac.com Tue May 9 23:12:28 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 9 May 2006 20:12:28 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1147194791.809735.251500@g10g2000cwb.googlegroups.com> Message-ID: <1hf33s3.1bdn2e4juoow0N%aleax@mac.com> Joe Marshall <eval.apply at gmail.com> wrote: ... > The problem is that a `name' is a mapping from a symbolic identifier to > an object and that this mapping must either be global (with the > attendant name collision issues) or within a context (with the > attendant question of `in which context'). Why is that a problem? Even for so-called "global" names, Python supports a structured, hierarchical namespace, so there can never be any collision betwen the "globals" of distinct modules (including modules which happen to have the same name but live in distinct packages or subpackages) -- I did mention that names could usefully be displayed in some strcutured form such as apackage.somemodule.thefunction but perhaps I was too tangential about it;-). > Matthias Felleisen once suggested that *every* internal function should > be named. I just said `continuations'. He immediately amended his > statement with `except those'. If I used continuations (I assume you mean in the call/cc sense rather than some in which I'm not familiar?) I might feel the same way, or not, but I don't (alas), so I can't really argue the point either way for lack of real-world experience. But if we can agree to name every function except continuations I'll be content: Python doesn't support continuations, so it's consistent for it to require every function to be named (since in its case "every function" and "every function except continuations" coincide;-). Alex From dejan.wirusrodiger at ck.t-com.hr Sun May 7 06:23:13 2006 From: dejan.wirusrodiger at ck.t-com.hr (Dejan Rodiger) Date: Sun, 07 May 2006 12:23:13 +0200 Subject: md5 from python different then md5 from command line In-Reply-To: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> Message-ID: <e3khpu$1hk$1@ss408.t-com.hr> ursache.marius at gmail.com said the following on 07.05.2006 12:07: > Hi > > I noticed that the md5 computed with md5 module from python is > different then the md5 sum computed with md5sum utility (on slackware > and gentoo). > > i.e. > $echo marius|md5sum > 0f0f60ac801a9eec2163083a22307deb - > >>>> test = md5.new("marius") >>>> print test.hexdigest() > 242aa1a97769109065e3b4df359bcfc9 > > > Any idea why? and how to get the same md5 sum for both calls? > > Thanks > try md5sum marius probably "new line" character is not computed in "echo marius|md5sum" -- Dejan Rodiger - PGP ID 0xAC8722DC Delete wirus from e-mail address From kentilton at gmail.com Mon May 8 08:33:00 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 08 May 2006 08:33:00 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147068524.966560.52210@y43g2000cwc.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> <yfshd41yeaj.fsf@oc.ex.ac.uk> <O7A7g.59$sC4.54@fe09.lga> <1147068524.966560.52210@y43g2000cwc.googlegroups.com> Message-ID: <0UG7g.8$u17.6@fe08.lga> Adam Jones wrote: > Ken Tilton wrote: > >>Alexander Schmolck wrote: >> >>>[trimmed groups] >>> >>>Ken Tilton <kentilton at gmail.com> writes: >>> >>> >>> >>>>yes, but do not feel bad, everyone gets confused by the /analogy/ to >>>>spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief >>>>period I swore off the analogy because it was so invariably misunderstood. >>>>Even Graham misunderstood it. >>> >>> >>>Count me in. >> >><g> But looking at what it says: "Think of the slots as cells in a >>spreadsheet (get it?), and you've got the right idea. ", if you follow >>the analogy (and know that slot means "data member" in other OO models) >>you also know that Serge's Spreadsheet example would have scored a big >>fat zero on the Miller Analogy Test. Serge in no way made slots in >>Python classes behave like cells in a spreadsheet. He simply started >>work on a Spreadsheet application, using Python classes along the way. Bzzt. >> >>While everyone makes the mistake, it is only because few of us (me >>included) read very carefully. Especially if they are more interested in >>flaming than learning what someone is saying. >> > > > I don't really mean any disrespect here, but if an analogy is not > interpreted correctly by a large group of people, the analogy is crap, > not the people. No, I do not think that follows. I reiterate: people (inluding me!) read too quickly, and this analogy has a trap in it: spreadsheets are /also/ software. The analogy is fine and the people are fine, but as you suggest there is a human engineering problem to be acknowledged. btw, I have a couple of links to papers on similar art and they all use the spreadshett metaphor. It is too good not to, but... > Yes, I understood it, specifically because I have spent > enough time dinking around with cell functions in a spreadhseet to > understand what you meant. > > Maybe it would help to change the wording to "functions with cell > references in a spreadsheet" instead of "cells in a spreadsheet". <g> We could do a study. I doubt your change would work, but, hey, that is what studies are for. I think probably the best thing to do with the human engineering problem is attack the misunderstanding explicitly. "Now if you are like most people, you think that means X. It does not." And then give an example, and then again say what it is not. Anyone who comes away from /that/ with the wrong idea just is not trying. But I would not put that in the project synopsis, and that is all the original confused poster read. Just not trying. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From x31equsenet at gmail.com Sat May 27 09:46:46 2006 From: x31equsenet at gmail.com (Graham Breed) Date: 27 May 2006 06:46:46 -0700 Subject: Pyrex speed References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> <4dqq38F1bi6btU1@uni-berlin.de> <1148728491.640293.298470@38g2000cwa.googlegroups.com> Message-ID: <1148737606.827020.47600@g10g2000cwb.googlegroups.com> Jim Lewis \/\/|20+3: > I'm not planning to write C functions. My understanding is that by > using cdefs in the python code one can gain substantial speed. I'm > trying to find a description of how to modify python code in more > detail so it runs fast under pyrex. I've used pyrex to speed up my code. It worked. While it isn't intended as a tutorial on pyrex you can have a look at it here: http://www.microtonal.co.uk/temper.html The trick is to write C functions using pyrex. That's not much easier than writing C functions in C. But I still found it convenient enough to be worth doing that way. Some tips: - declare functions with cdef - declare the type of every variable you use - don't use Python builtins, or other libraries The point of these rules is that generated C code using Python variables will still be slow. You want Pyrex to write C code using C variables only. To check this is happening you can look at the automatically generated source code to make sure there are no reference counting functions where there shouldn't be. The usual rule for C optimization applies -- rewrite the code that you're spending most time in. But if that innermost function's being called from a loop it can be worth changing the loop as well so that you pass in and out C variables. HTH, Graham From sybrenUSE at YOURthirdtower.com.imagination Wed May 17 04:00:51 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 17 May 2006 10:00:51 +0200 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> Message-ID: <slrne6lm1j.h00.sybrenUSE@schuimige.stuvel.eu> Duncan Booth enlightened us with: > In particular a common convention is to have indentations at 4 > spaces and tabs expanding to 8 spaces. Aaaw that is SO ugly! Sure, it displays correctly on systems that have tab stops every 8 spaces given a monospaced font, but that is about all that is positive about that. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From charl.loubser at gmail.com Mon May 1 16:10:12 2006 From: charl.loubser at gmail.com (Merrigan) Date: 1 May 2006 13:10:12 -0700 Subject: How do I take a directory name from a given dir? In-Reply-To: <mailman.5193.1146513444.27775.python-list@python.org> References: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> <mailman.5193.1146513444.27775.python-list@python.org> Message-ID: <1146514212.412745.21040@i39g2000cwa.googlegroups.com> WOW, Thanks guys. I am really awestruck by the speed you guys relied with. Thanks a lot for the help. I eventually found a way that did the job for me. I will definitely visit this Group more often. Thanks for all the help! :D From roy at panix.com Wed May 17 10:14:20 2006 From: roy at panix.com (Roy Smith) Date: Wed, 17 May 2006 14:14:20 +0000 (UTC) Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147873879.818361.10040@i40g2000cwc.googlegroups.com> <mailman.5804.1147874795.27775.python-list@python.org> Message-ID: <e4fb3s$15e$1@reader1.panix.com> Peter Decker <pydecker at gmail.com> wrote: >In my experience, whenever there is a 'religious' issue like this, one >side tends to be quick to pronounce the other as 'evil', and insist >that everyone do things their way, I don't think people who use tabs are evil. They may be ignorant and misguided, but they can still have the potential to be saved though education and persuasion :-) From dreedmac at columbus.rr.com Thu May 11 20:16:21 2006 From: dreedmac at columbus.rr.com (David Reed) Date: Thu, 11 May 2006 20:16:21 -0400 Subject: Threads In-Reply-To: <1147392171.914234.48260@q12g2000cwa.googlegroups.com> References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> Message-ID: <E5D9C4C4-C6D8-43DA-AFA5-523A87CB6D45@columbus.rr.com> On May 11, 2006, at 8:02 PM, placid wrote: > > Carl J. Van Arsdall wrote: >> placid wrote: >>> Hi all, >>> >>> In Python, Threads cannot be paused, i remember reading this >>> somewhere, >>> so is there a way around this ? >>> >> >> When you say paused do you mean paused by an external source or >> paused >> by a call internal to the thread? There are plenty of >> synchronization >> constructs for making threads wait: Check out Events and Conditions > > I have a thread that has a job Queue, it continuosly polls this queue > to see if there are any jobs for it, what i really wont to be able to > do is, when the queue is empty, i want the thread to pause (or more > technical, i want the thread to block) until the queue gets populated > again. Is this possible ? > > The previous poster answered your question - you want to use a condition variable. http://docs.python.org/lib/condition-objects.html Dave From dale at riverhall.nospam.co.uk Tue May 9 09:37:53 2006 From: dale at riverhall.nospam.co.uk (Dale Strickland-Clark) Date: Tue, 09 May 2006 14:37:53 +0100 Subject: Python editor recommendation. References: <44607e6a$0$3275$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Message-ID: <RW08g.19915$D61.2897@fe58.usenetserver.com> Vim. Everything else is Notepad. DeepBlue wrote: > Hi all, > > Can any one please recommend me an editor for coding Python. Thank u. > I have Komodo (www.activestate.com) in my mind. Is the editor any good? > > regards. -- Dale Strickland-Clark Riverhall Systems www.riverhall.co.uk We're recruiting. See the web site for details. From aleax at mac.com Fri May 12 01:59:53 2006 From: aleax at mac.com (Alex Martelli) Date: Thu, 11 May 2006 22:59:53 -0700 Subject: Threads References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <e414h9$f8g$01$1@news.t-online.com> Message-ID: <1hf73u2.1x2vojls751vfN%aleax@mac.com> Peter Otten <__peter__ at web.de> wrote: > placid wrote: > > > I have a thread that has a job Queue, it continuosly polls this queue > > to see if there are any jobs for it, what i really wont to be able to > > do is, when the queue is empty, i want the thread to pause (or more > > technical, i want the thread to block) until the queue gets populated > > again. Is this possible ? > > Isn't that the default behaviour of Queue.get()? Absolutely! placid, just call the get method of that Queue instance: if the queue is empty your thread DOES pause, or block, until there's some item put on the queue by another thread. Alex From python.list at tim.thechases.com Sat May 20 10:43:42 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sat, 20 May 2006 09:43:42 -0500 Subject: Generating Cutter numbers In-Reply-To: <1148133784.844430.23130@38g2000cwa.googlegroups.com> References: <1148114166.590393.176250@u72g2000cwu.googlegroups.com> <1148133784.844430.23130@38g2000cwa.googlegroups.com> Message-ID: <446F2B1E.6080105@tim.thechases.com> > I am stumped about what to do when the first letter is Q not > followed by U. It says to use numbers 2-29 for the second > letters a-t, but that is obviously not right (for one thing t > would be 21, not 29). > > Since you seem a little bit more experienced in library > science could you explain what is going on? :) I too tried to play with it, and Steve found one of the cases with which I was having trouble ("Q[^u]"). Additionally, is "Y" considered a consonant or vowel for the sake of this exercise? Other trouble came when consonants were not followed by the list of letters given. It also looks like the definiton of "initial letter" seems to change a bit. In some cases, "initial letter" seems to refer to the first letter (which gets output carte-blanche), and in other cases, it seems to be used to refer to "the first letter that should be converted to a number" (meaning the second letter of the input). Some examples for which expected results (and the reasoning/logic/algorithm/table behind how they were generated) would be helpful: "Cyr", "Cyprus", "Mbarine", "McGrady", "Sczepanski", "Yvette" They're all are sample last-names pulled from my local phonebook. Too bad my librarian wife is working today :) -tkc From sam at nuevageorgia.com Mon May 22 19:02:17 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 22 May 2006 16:02:17 -0700 Subject: Python - Web Display Technology In-Reply-To: <mailman.6089.1148337451.27775.python-list@python.org> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <bhv172hbu1i37nqi3kp1rhnuaujj1qo208@4ax.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <mailman.6089.1148337451.27775.python-list@python.org> Message-ID: <1148338937.422985.197170@y43g2000cwc.googlegroups.com> """I find it tiresome that Flash apologists believe technical advantages can overcome a need for open, community-driven, vendor-independent standards. """ :) From vbgunz at gmail.com Wed May 24 00:55:11 2006 From: vbgunz at gmail.com (vbgunz) Date: 23 May 2006 21:55:11 -0700 Subject: Don't wish to give up on a Tkinter GUI Builder :( References: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> <1148371674.932205.83160@j55g2000cwa.googlegroups.com> <1148382609.644438.267020@j55g2000cwa.googlegroups.com> <A6qdnQFPrLgDzO7ZnZ2dnUVZ_uidnZ2d@nmt.edu> Message-ID: <1148446511.364805.127020@j33g2000cwa.googlegroups.com> >What are you building? I routinely do things like these by hand >www.greschke.com/unlinked/images/changeo.jpg >www.greschke.com/unlinked/images/pocus.jpg >www.greschke.com/unlinked/images/pis.jpg >www.greschke.com/unlinked/images/petm.jpg >and I can't imagine using a builder for anything 'simpler'. the reason I do not wish to go the hand-route is because I am personally very bad at math *but* am very attentive to aesthetic organization. I am somewhat more of an artist than I am an architect. I do wish to choose an editor for my designs :) >I tried rapyd today, too. Started it, drug a button to the frame, but >then couldn't figure out how to set the text of the button. Deleted it. :) next time don't drug it. take the button to at least one dinner and then drug it, then drag it to the frame and you'll find the text option in the left pane under options :) From simon at brunningonline.net Tue May 16 11:04:39 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 16 May 2006 16:04:39 +0100 Subject: what is the difference between tuple and list? In-Reply-To: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> References: <1147790844.336448.243680@j33g2000cwa.googlegroups.com> Message-ID: <8c7f10c60605160804y1d32158xf274145fe3979c73@mail.gmail.com> On 16 May 2006 07:47:24 -0700, daniel <daniel.huangfei at gmail.com> wrote: <http://www.python.org/doc/faq/general.html#why-are-there-separate-tuple-and-list-data-types> -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ernesto.adorio at gmail.com Mon May 1 11:49:47 2006 From: ernesto.adorio at gmail.com (ernesto.adorio at gmail.com) Date: 1 May 2006 08:49:47 -0700 Subject: Converting floating point to string in non-scientific format In-Reply-To: <1146471023.468344.178050@i40g2000cwc.googlegroups.com> References: <Pine.SOL.4.56.0605010352270.5230@pollux.cse.buffalo.edu> <1146471023.468344.178050@i40g2000cwc.googlegroups.com> Message-ID: <1146498587.695347.42160@g10g2000cwb.googlegroups.com> See also non-exponential floating point representation in http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/358361 by R. Hettinger. From larry.bates at websafe.com Wed May 3 12:06:17 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 03 May 2006 11:06:17 -0500 Subject: __getattr__ on non-instantiated class In-Reply-To: <1146671588.529743.249570@v46g2000cwv.googlegroups.com> References: <1146671588.529743.249570@v46g2000cwv.googlegroups.com> Message-ID: <4458D4F9.8010900@websafe.com> Fredp wrote: > Hi > I was wondering if it is possible to have the various magic methods, > mainly __getattr__ and __setattr__, and @property attributes called > when accessing the attribute of a non-intantiated class. > > Imagin something like this: > ##### > class MyClass: > @property > def prop(self): > print "Accessed" > return "ABCD" > > print MyClass.prop > ##### > having it printing: > ##### > Accessed > ABCD > ##### > > Thanks very much > Looks like you want Python to execute a method on an uninstantiated class. I can't imagine how you would use such a thing. Can you give us a real-life "use case"? This produces the output you want: m=MyClass() print m.prop() -Larry Bates From steve at holdenweb.com Fri May 26 21:49:04 2006 From: steve at holdenweb.com (Steve Holden) Date: Sat, 27 May 2006 02:49:04 +0100 Subject: John Bokma harassment In-Reply-To: <Xns97CD686303698castleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <XRZcg.6994$8G3.6399@twister.nyroc.rr.com> <Xns97CD686303698castleamber@130.133.1.4> Message-ID: <e58b67$oku$1@sea.gmane.org> John Bokma wrote: > Eli Gottlieb <eligottlieb at gmail.com> wrote: > > >>Who reads blogs? They're well known for housing crackpots far worse >>than Xah, and I estimate he doesn't want to associate himself with that >>sort. > > > Yup, he seems to be quite happy as a Usenet Kook > An area in which you appear to be pretty expert. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From apgwoz at gmail.com Fri May 5 14:36:08 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Fri, 5 May 2006 14:36:08 -0400 Subject: how to remove 50000 elements from a 100000 list? In-Reply-To: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> Message-ID: <F8309858-74D0-4FD9-809C-F3B2FB3E5386@gmail.com> It's easy in this case: a = range(50000, 100000) But, I'm just trying to add some humor to this thread :) On May 5, 2006, at 9:36 AM, Ju Hui wrote: > I want to remove about 50000 elements from a list,which has 100000 > elements. > sample code like below: > >>>> a=range(10) >>>> b=range(4) >>>> for x in b: > ... a.remove(x) > ... >>>> a > [4, 5, 6, 7, 8, 9] > > when a and b is small size, it will finished quickly, but when a and b > have many elements. > such as: >>>> a=range(100000) >>>> b=range(50000) >>>> for x in b: > ... a.remove(x) > ... > it will very slowly. Shall I change to another data structure and > choos > a better arithmetic? > any suggestion is welcome. > thanks a lot! > > -- > http://mail.python.org/mailman/listinfo/python-list --- Andrew Gwozdziewycz apgwoz at gmail.com http://www.23excuses.com http://ihadagreatview.org http://and.rovir.us From george.sakkis at gmail.com Tue May 23 11:39:39 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2006 08:39:39 -0700 Subject: dict literals vs dict(**kwds) Message-ID: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> Although I consider dict(**kwds) as one of the few unfortunate design choices in python since it prevents the future addition of useful keyword arguments (e.g a default value or an orderby function), I've been finding myself lately using it sometimes instead of dict literals, for no particular reason. Is there any coding style consensus on when should dict literals be preferred over dict(**kwds) and vice versa ? George From onurb at xiludom.gro Fri May 12 12:22:33 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 18:22:33 +0200 Subject: Decorator In-Reply-To: <4464959f$1$13578$5402220f@news.sunrise.ch> References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> <44644a76$0$290$626a54ce@news.free.fr> <4464959f$1$13578$5402220f@news.sunrise.ch> Message-ID: <4464b6ad$0$6828$636a55ce@news.free.fr> Martin Blume wrote: > "bruno at modulix" schrieb > (snip) >>def deco(func): >> print "decorating %s" % func.__name__ >> def _wrapper(*args, **kw): >> print "%s called " % func.__name__ >> res = func(*args, **kw) >> print "%s returned %s" % (func.__name__, str(res)) > > return res > ^^^^^^^^^^ > Shouldn't here be a return res, so that wrapper > behaves like the original function? oops, my bad :( And yes, of course. > >> return _wrapper >> >># python < 2.4 >>def somefunc(): >> print "in somefunc" >> return 42 >> >>somefunc = deco(somefunc) >> > > Thanks for the explanation. > > > Another question: Isn't decorating / wrapping usually > done at runtime, It is. I mean, using decorator syntax, this is done during import, which happens at runtime. > so that the @deco notation is pretty > useless (because you'd have to change the original > code)? I don't understand your question. > What do I miss here? Ok, I get it (well, I think...). The use case for @decorator is for wrapping functions or method *in the module/class itself*. It's not for module client code (but this of course doesn't prevent client code to dynamically add other wrappers...) One of the primary use case makes this pretty clear IHMO : classmethod and staticmethod : # python < 2.4: class Cleese(object): def doSillyWalk(cls): pass doSillyWalk = classmethod(doSillyWalk) # python >= 2.4: class Cleese(object): @classmethod def doSillyWalk(cls): pass Another example : CherryPy uses decorators to mark methods which are 'published' (ie: are action controllers responding to a given URL) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gh at ghaering.de Wed May 3 15:47:29 2006 From: gh at ghaering.de (=?ISO-8859-1?Q?Gerhard_H=E4ring?=) Date: Wed, 03 May 2006 21:47:29 +0200 Subject: python strings In-Reply-To: <1146684876.311829.297280@i39g2000cwa.googlegroups.com> References: <1146684876.311829.297280@i39g2000cwa.googlegroups.com> Message-ID: <445908D1.7040008@ghaering.de> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 mike7411 at gmail.com wrote: > Is it possible for python strings to contain a zero byte? Yes. Here's how to produce one: gerhard at lara:~$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> s = "\x000" >>> s[0] == chr(0) True >>> - -- Gerhard -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Thunderbird - http://enigmail.mozdev.org iD8DBQFEWQjRdIO4ozGCH14RAsf4AJ4xdbT/FQTSzfciijgVBEfMyTH8SQCeJP39 xzJxWxlAnRgKimsKSKWhSQ0= =Dd3B -----END PGP SIGNATURE----- From tjreedy at udel.edu Wed May 17 14:54:57 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Wed, 17 May 2006 14:54:57 -0400 Subject: How to add columns to python arrays References: <1147882432.166728.207820@j55g2000cwa.googlegroups.com> Message-ID: <e4fri0$khm$1@sea.gmane.org> "CC" <chuangwoo at gmail.com> wrote in message news:1147882432.166728.207820 at j55g2000cwa.googlegroups.com... > I wanna compile a 6000x1000 array with python. The array starts from > 'empty', each time I get a 6000 length list, I wanna add it to the > exist array as a column vector. Is there any function to do so? > > Or, I can add the list as a rows, if this is easier, and transpose the > whole array after all the rows are setup. Python does not come with a 2D array type either as a builtin type or as a standard library module. You can only simulate one with a sequence of sequences (list of lists, for instance). You could initialize as follows: aray = [] for l6000 in source(): aray.append(l6000) While this will print as a list of rows, you are free to think of it as a list of columns. That said, I suspect you should use the 3rd party NumPy package which defines multiple-dimensional arrays of several base types. Terry Jan Reedy From robert.kern at gmail.com Mon May 1 12:44:41 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 May 2006 11:44:41 -0500 Subject: How to efficiently read binary files? In-Reply-To: <125c8sbqsd7a952@corp.supernews.com> References: <zda5g.5247$nV4.1486@trnddc04> <125acgep357kbd8@corp.supernews.com> <mailman.5165.1146434636.27775.python-list@python.org> <125c8sbqsd7a952@corp.supernews.com> Message-ID: <e35dtq$pco$1@sea.gmane.org> Grant Edwards wrote: > On 2006-04-30, Robert Kern <robert.kern at gmail.com> wrote: > >>Grant Edwards wrote: >>>Perhaps the numarray module? >> >>numpy for new code, please. > > So numarray and numpy were both written to replace numeric? numpy was written to replace both Numeric and numarray. There is a good explanation in Chapter 1 of _The Guide to NumPy_ included in the sample chapters: http://numeric.scipy.org/scipybooksample.pdf There were a number of features in Numeric that could not be replicated in numarray, among them the ufunc C API and the speed for small arrays. numpy's code base is closer to Numeric's but it incorporates nearly all (if not all) of the features of numarray. The numarray developers fully support the migration to numpy as the one array package. -- 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 andy at neotitans.com Sun May 21 22:55:02 2006 From: andy at neotitans.com (Andy Sy) Date: Mon, 22 May 2006 10:55:02 +0800 Subject: The ONE TRUE WAY to use tabs (if you must...) In-Reply-To: <e4n1vr$pk8$1@sea.gmane.org> References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <mailman.5846.1147904183.27775.python-list@python.org> <1147907634.532463.63730@u72g2000cwu.googlegroups.com> <e4n1vr$pk8$1@sea.gmane.org> Message-ID: <e4r965$g2j$1@sea.gmane.org> Andy Sy wrote: > Actually a couple of the responses on this newsgroup > have settled the question for me. I did learn something > new by engaging in this holy war. > > > Tabs need not be evil, but ONLY if they are used in one > particular way: > > If you really must use tabs, use them *ONLY* for 'semantic' > indentation and use pure spaces when you need arbitrary > indentation (e.g. arbitrary spacing). > > PHP Example > =========== > > function xyz() { > ->print "This is a really really really long line that I'd ". > -> "like to extend to the one down below while preserving ". > -> "ease of readability by aligning the start of the string". > -> "lines. I use tabs to reflect syntactical (e.g. semantic) ". > -> "indentation, but use spaces for arbitrary indentation.\n\n".; > ->while (10) { > ->->print "This code will align properly no matter what tabsize setting ". > ->-> "the reader uses, and is the only real benefit of using tab ". > ->-> "characters instead of pure spaces.\n\n"; > } > > > > I did some basic tests, and it looks like this style should also > work for Python code. > > > THIS IS THE *SINGLE* CORRECT WAY TO USE TABS IN CODE! ANYTHING > ELSE WILL BE A PAIN FOR PEOPLE WITH TABSIZE SETTINGS DIFFERENT > FROM YOURS!! Also... remember that the 'ONE TRUE WAY' essentially involves *mixing* tabs and spaces for indentation with all the objections that that entails... (although like mentioned above, it should work with Python, at least in the simple cases i've tried) Frankly, the case for tab usage is not that compelling... -- It's called DOM+XHR and it's *NOT* a detergent! From larry.bates at websafe.com Thu May 4 14:59:28 2006 From: larry.bates at websafe.com (Larry Bates) Date: Thu, 04 May 2006 13:59:28 -0500 Subject: Tuple assignment and generators? In-Reply-To: <just-6A9E96.19084404052006@news1.news.xs4all.nl> References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <just-6A9E96.19084404052006@news1.news.xs4all.nl> Message-ID: <1vSdnRC7JP5K08fZRVn-rw@comcast.com> Just wrote: > In article <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d at comcast.com>, > Larry Bates <larry.bates at websafe.com> wrote: > >> While I have never needed anything like this in my 5 years of Python >> programming, here is a way: >> >> a,b,c = 3*[0] >> q,r,s,t,u,v = 6*[0] > > This is (IMO) fairly idiomatic: > > a = b = c = 0 > q = r = s = t = u = v = 0 > > Just You must be careful with this as they all point to exactly the same object. Example: >>> q = r = s = t = u = v = 0 >>> id(q) 3301924 >>> id(r) 3301924 >>> id(s) 3301924 >>> Notice that all of them point to exactly the same object, not 6 copies of zero which is "probably" what the poster was thinking. Most of the time when I see this, it is because people are thinking of variables having values which is mostly a carry-over from old Fortran/Cobol/Basic programming ideas. In python variables are pointers to objects. Objects could be values, but they are not placeholders where you store stuff. I read on this list (quite frequently) that people think they are getting 6 separate variables each with a zero stored in them. They are not. They are getting six pointers that all point to an integer zero (IMHO it would be a rather odd application for a programmer to want this). Here is where multiple assignments causes problems for beginners: >>> a=[] >>> b=c=a >>> a.append(6) >>> b [6] What?? 'b' should contain an empty list, right? Nope. a, b, and c all point to the SAME list just like the poster's q, r, s, t, u, v all point to the SAME zero. What they meant to write was: c=a[:] # Shallow copy of list b=a[:] My rule, don't do it unless you know exactly why you want to do it. It will trip you up at some point and be VERY hard to find. -Larry Bates From bdesth.quelquechose at free.quelquepart.fr Fri May 19 22:38:10 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sat, 20 May 2006 04:38:10 +0200 Subject: memory error with zipfile module In-Reply-To: <1148072514.207383.26370@j55g2000cwa.googlegroups.com> References: <mailman.5938.1148039030.27775.python-list@python.org> <A4x*kx3gr@news.chiark.greenend.org.uk> <446e07ab$0$12795$636a55ce@news.free.fr> <1148072514.207383.26370@j55g2000cwa.googlegroups.com> Message-ID: <446e51e6$0$6831$636a55ce@news.free.fr> Roger Miller a ?crit : > The basic problem is that the zipfile interface only reads and writes > whole files, so it may perform poorly or fail on huge files. At one > time I implemented a patch to allow reading files in chunks. However I > believe that the current interface has too many problems to solve by > incremental patching, Yeps, that was the general tone of some thread on python-dev. And from what I saw of the source code, it may effectively not be the cleanest part of the stdlib. But what, it does what it was written for at first : provide working support for zipped packages. > and that a zipfile2 module is probably warranted. > (Is anyone working on this?) Seems like Bob Ippolito was on the rank, but I guess you'll get better answers on python-dev. > In the meantime I think the best solution is often to just run an > external zip/unzip utility to do the heavy lifting. Indeed !-) But while having zip/unzip installed OOTB on a unix-like system is close to warrented, it may not be the case on Windows. From nobody at 127.0.0.1 Fri May 12 14:20:49 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 18:20:49 GMT Subject: Python Translation of C# DES Encryption References: <mailman.5620.1147425991.27775.python-list@python.org> Message-ID: <5m49g.86150$dW3.66874@newssvr21.news.prodigy.com> Andreas Pauley wrote: > Hi all, > > I'm trying to implement a Python equivalent of a C# method that encrypts > a string. > My Python attempt is in the attached file, but does not return the same > value as the C# method (see below). > > Any hints? I can't tell from the code you posted what a DESCryptoServiceProvider does, but I think you're using two different block cipher modes. The C/C# code uses an IV, which means it's probably not using ECB mode. Meanwhile your Python code uses ECB mode, which doesn't even use an IV (the one you provided is probably just ignored). You need to find the exact algorithm the DESCryptoServiceProvider uses. CBC and CTR are common modes with IVs. Besides mode of operation, there's the issue of how it pads the data (in the cipher, not base64). There could also be differences in things like the key scheduling routines, but that's less likely. Until you know exactly what the original code does, your only option is trial and error. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From nobody at 127.0.0.1 Fri May 19 12:40:41 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 19 May 2006 16:40:41 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <mailman.5918.1147998380.27775.python-list@python.org> <i%8bg.73738$F_3.4617@newssvr29.news.prodigy.net> <mailman.5953.1148048012.27775.python-list@python.org> Message-ID: <dymbg.18810$Lm5.4783@newssvr12.news.prodigy.com> Terry Hancock wrote: > Edward Elliott wrote: > >>For inquiries into real-world code, it's enough to >>believe that I'm not lying >> > So I don't make assumptions about people without some kind > of evidence. There *are* plenty of "bad guys" out there, so > one learns both to have a thick skin and to rely on that which > is reasonably proven, rather than making casual assumptions > of good will. That'd be like leaving your car in downtown LA > overnight with the doors unlocked. So lookup my post history in comp.lang.python on google groups. Do I behave like a scammer or troll? Have I wasted time posting in other threads just to build credibility and dupe everyone here? You make judgements about people in the real world all the time on significantly less information. If you really think I'm making all this up, feel free to ignore to me. Or reserve judgement until you have more data for comparison. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From mario.lacunza at gmail.com Wed May 3 15:36:03 2006 From: mario.lacunza at gmail.com (Mario Lacunza) Date: Wed, 3 May 2006 14:36:03 -0500 Subject: Ann: pyDia2Code Message-ID: <715936150605031236n7f7bbe4eod54f1f30585a26a@mail.gmail.com> Hello, This is a GUI program for Dia2Code lib under GPL licence: "Dia2Code basically reads a Dia diagram file that contains an UML class diagram and creates files in the language of choice that contain the bare bones of the classes represented in the diagram..." "Generates code for: Ada, C, C++, Java, PHP, Python, shapefile, SQL and C#...." Build in Python with the same function like gDia2Code and Kaptain (obsolete) This is a Beta stage, please send me any comments or suggest. I search help for i18n, for translate into english the interface, right now its only available in spanish. The website: http://sourceforge.net/projects/pydia2code/ Thanks in advance!! -- Saludos / Best regards Mario Lacunza Desarrollador de Sistemas - Webmaster Tel?fono: 51-1-242-0058 Celular: 51-1-9310-0386 (Tim) Email: mario.lacunza at gmail.com Email: mario_lacunza at yahoo.es Messenger MSN: mario_lacunza at hotmail.com Website: http://www.lacunza.tk Lima - Peru -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060503/679512d2/attachment.html> From danmcleran at yahoo.com Sat May 6 23:47:10 2006 From: danmcleran at yahoo.com (danmcleran at yahoo.com) Date: 6 May 2006 20:47:10 -0700 Subject: Splice two lists In-Reply-To: <1146965920.842441.168920@i40g2000cwc.googlegroups.com> References: <1146961724.195038.18680@u72g2000cwu.googlegroups.com> <1146965920.842441.168920@i40g2000cwc.googlegroups.com> Message-ID: <1146973630.629933.323210@y43g2000cwc.googlegroups.com> Thanks, this worked great. Can you explain the syntax of the '*' on the return value of izip? I've only ever seen this syntax with respect to variable number of args. Thanks again. From jens.goepfert at tracetronic.de Tue May 9 07:54:30 2006 From: jens.goepfert at tracetronic.de (Jens) Date: 9 May 2006 04:54:30 -0700 Subject: eval and exec in an own namespace Message-ID: <1147175670.849952.39620@v46g2000cwv.googlegroups.com> Hi, has anyone an idea why the following code does not work. s = """ def a(n): return n*n def b(t): return a(t) """ ns = {} exec(s, {}, ns) eval("b(2)", ns, {}) executing this script raises an exception (NameError: global name 'a' is not defined) in the last line. Hope for your help. From NOatkinwSPAM at rpi.edu Wed May 24 11:25:19 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Wed, 24 May 2006 11:25:19 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> Message-ID: <87ejyjv40w.fsf@rpi.edu> John Bokma <john at castleamber.com> writes: > Ken Tilton <kentilton at gmail.com> wrote: > >> Ben Bullock wrote: >>> "Xah Lee" <xah at xahlee.org> wrote in message >>> news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... >>> >>>> If you believe this lobbying to my webhosting provider is unjust, >>>> please write to my web hosting provider abuse at dreamhost.com >>> >>> >>> Why don't you just change your provider? It would take less time than >>> this. >> >> Are you joking. "Just change your provider?" Do you have a little >> button on your computer that says "Change provider"? Cool! :) > > No, it will cost Xah money. In the end he will be with a bullet proof > hoster, like other kooks on Usenet, or get the message. > >> C'mon, John Bokma (and everyone else dumb enough to crosspost their >> shushing to every group on the crosspost list -- why do they do that? > > So other people can read that reporting Xah *does* have an effect. A lot > of people think that a kill file is the only solution. You win my unofficial contest for "Usenet Tool of the Year." It is not difficult to skip to the next file or to add a sender to a killfile. It is certainly less of a hassle than all this complaining you do. Life is short, John Bokma. There are more important things in the world than tattling on Xah to his host. Maybe you can start experiencing them if you learn to make use of the 'next message' key. >> So Xah will hear them six times? No, they want everyone to see how >> witty they are when they tell Xah off. > > So you haven't noticed that Xah does just hit & run posting? I've noticed it - but have you? It would be only one post that could easily be ignored, if not for all this rubbish that you and people like you feel the need to post (sure, I realize I'm contributing to the problem). Isn't "hit & run posting" better than a thread full of nonsense? -- You fool! You fell victim to one of the classic blunders! The most famous is, "Never get involved in a land war in Asia", but only slightly less well-known is this: "Never go in against a Sicilian when death is on the line"! From kar1107 at gmail.com Tue May 9 21:06:13 2006 From: kar1107 at gmail.com (Karthik Gurusamy) Date: 9 May 2006 18:06:13 -0700 Subject: Enumerating Regular Expressions In-Reply-To: <1147151007.157938.185270@u72g2000cwu.googlegroups.com> References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> <e3p46c$j21$1@zinnia.noc.ucla.edu> <1147148644.762057.238640@v46g2000cwv.googlegroups.com> <e3p74r$3ol$1@daisy.noc.ucla.edu> <1147151007.157938.185270@u72g2000cwu.googlegroups.com> Message-ID: <1147223173.394439.87100@j73g2000cwa.googlegroups.com> blair.bethwaite at gmail.com wrote: > James Stroud wrote: > > You see the difficulty don't you? How will the computer know in advance > > that the regex matches only a finite set of possible strings? > > Well sure it might be a little difficult to figure _that_ out, although > probably not all that hard if you converted to an FSA or something. I > imagine detecting looping would be as simple as applying the right > graph algorithm. That's right. For finite regular language, you don't allow cycles. That means the graph must be a DAG (directed acyclic graph. If not directed it must be a tree, simple to check as node-count is edge-count plus one). Once you have a DAG, the problem becomes enumerating all paths from root node to any final node. This is a pretty straighforward problem in graph theory. I think you can simply find all from root-node to any other node and discard any of the path ending in a non-final state node. Karthik > > But that's not the point, you don't strictly need to know in advance > whether the regex represents a finite or infinite language. I just > want to enumerate it, if it's going to take longer than the life of the > universe and a stack size to match to do it, then so be it. It's > surely up to the user to be careful about how they form their > expressions. One way to get around it would be to disallow the * > operator in enumerations. > > Cheers, > -Blair From me+python at modelnine.org Tue May 2 17:49:05 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 23:49:05 +0200 Subject: SGML parsing tags and leeping track In-Reply-To: <1146595097.141061.318390@g10g2000cwb.googlegroups.com> References: <1146543123.663415.48640@g10g2000cwb.googlegroups.com> <1146595097.141061.318390@g10g2000cwb.googlegroups.com> Message-ID: <200605022349.05667.me+python@modelnine.org> Am Dienstag 02 Mai 2006 20:38 schrieb hapaboy2059 at gmail.com: > could i make a global variable and keep track of each tag count? > > Also how would i make a list or dictionary of tags that is found? > how can i handle any tag that is given? The following snippet does what you want: >>> from sgmllib import SGMLParser class MyParser(SGMLParser): def __init__(self): SGMLParser.__init__(self) self.tagcount = {} self.links = set() # Tag count handling # ------------------ def handle_starttag(self,tag,method,args): self.tagcount[tag] = self.tagcount.get(tag,0) + 1 method(args) def unknown_starttag(self,tag,args): self.tagcount[tag] = self.tagcount.get(tag,0) + 1 # Argument handling # ----------------- def start_a(self,args): self.links.update([value for name, value in args if name == "href"]) parser = MyParser() parser.feed(file("test.html").read()) # Insert your data source here... parser.close() print parser.tagcount print parser.links >>> See the documentation for sgmllib for more info on handle_starttag (whose logic might just as well have been implemented in start_a, but if you want argument handling for more tags, it's best to keep it at this one central place) and unknown_starttag. --- Heiko. From sjmachin at lexicon.net Sun May 21 07:08:11 2006 From: sjmachin at lexicon.net (John Machin) Date: 21 May 2006 04:08:11 -0700 Subject: Python update trouble (2.3 to 2.4): x<<y References: <cef393a0512232219w6fab1b09tfb10debd31fd12b7@mail.gmail.com> <mailman.6016.1148188117.27775.python-list@python.org> <1148197232.312628.255650@i39g2000cwa.googlegroups.com> <mailman.6025.1148204320.27775.python-list@python.org> Message-ID: <1148209690.978989.65430@j55g2000cwa.googlegroups.com> Gonzalo wrote: """ I missed the point to add the *and* to workaround the long result issue! I think I understand it now. I am timing the code once translated, so here are the results for the crc calculation function. """ Yes, and both of us were missing the point that the "16" means 16 bits wide!! It is carrying an extra 16 redundant bits that don't contribute to the checking ability. If your software *needs* to generate/check the exact same 32-bit-wide CRC as calculated by that C routine, then what I gave you should be OK. Do you have any more test values? In particular test an empty string and say "\x00" * 8 -- sometimes a CRC specification will do something special with short strings e.g. pad them put with null bytes. That C routine is actually, on further reading, mind-boggling!! It stops on a null byte, rather than working on a given length. A CRC is normally expected to work on any data (including binary data) whether it contains \x00 or not. What are you using it for?? If you don't have to interface with other software, AND a 16-bit check is adequate, then at the end of this message is a 16-bit version which will use only ints and therefore may run faster. However you may wish to use a CRC32 which is supplied with Python (in the binascii module). A further note: what we have so far seems not to be the CCITT aka X.25 standard CRC-16 , but a reflection. See http://www.joegeluso.com/software/articles/ccitt.htm and also if you have the time and the determination, the article by Ross Williams that it refers to. Cheers, John === 16-bit version === gCRC16Table = [] def InitCRC16(): global gCRC16Table for i in xrange(0,256): crc = i << 8 for j in xrange(0,8): if (crc & 0x8000) != 0: tmp = 0x1021 else: tmp = 0 crc = (crc << 1) ^ tmp crc &= 0xFFFF gCRC16Table.append(crc) def CalcCRC16(astr): crc = 0xFFFF for c in astr: crc = gCRC16Table[((crc >> 8) & 255)] ^ ((crc & 0xFF) << 8) ^ ord(c) assert 0 <= crc <= 0xffff # remove when doing timings :-) return crc test = "123456asdfg12345123" InitCRC16() result = CalcCRC16(test) print result, hex(result) ====== From DustanGroups at gmail.com Fri May 19 06:58:16 2006 From: DustanGroups at gmail.com (Dustan) Date: 19 May 2006 03:58:16 -0700 Subject: Which is More Efficient? In-Reply-To: <1148036087.843911.307990@u72g2000cwu.googlegroups.com> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> <1147990753.406649.80150@y43g2000cwc.googlegroups.com> <mailman.5912.1147991444.27775.python-list@python.org> <1147991742.990761.144730@j73g2000cwa.googlegroups.com> <mailman.5927.1148019669.27775.python-list@python.org> <1148036087.843911.307990@u72g2000cwu.googlegroups.com> Message-ID: <1148036296.125181.5140@i39g2000cwa.googlegroups.com> Dustan wrote: > Fredrik Lundh wrote: > > Dustan wrote: > > > > > Obviously it takes a geek to know you have to time it, as opposed to > > > any other task you could be talking about. > > > > wasn't the original question "my program uses a lot of CPU, and I want > > to make it more efficient" ? what does "a lot of CPU" and "more > > efficient" mean to you, and how do you know that your program uses "a > > lot of CPU" ? > > The task manager says "CPU Usage: 100%" when the program is running, > and only when the program is running. > > Efficiency is a measure of 2 things: CPU usage and time. If you measure > just time, you're not necessarily getting the efficiency. > > > > > </F> By the way, I've only been programming for a year or so (probably 18 months at the most). I'm sure that can't label me as a 'newbie', but at least consider that before you criticize me like you did when I asked about scientific notation. From maxerickson at gmail.com Fri May 19 07:48:35 2006 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 19 May 2006 11:48:35 +0000 (UTC) Subject: Which is More Efficient? References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> <1147990753.406649.80150@y43g2000cwc.googlegroups.com> <mailman.5912.1147991444.27775.python-list@python.org> <1147991742.990761.144730@j73g2000cwa.googlegroups.com> <mailman.5927.1148019669.27775.python-list@python.org> <1148036087.843911.307990@u72g2000cwu.googlegroups.com> Message-ID: <Xns97C84FAA5AE6maxericksongmailcom@80.91.229.5> "Dustan" <DustanGroups at gmail.com> wrote in news:1148036087.843911.307990 at u72g2000cwu.googlegroups.com: > > The task manager says "CPU Usage: 100%" when the program is > running, and only when the program is running. > > Efficiency is a measure of 2 things: CPU usage and time. If you > measure just time, you're not necessarily getting the efficiency. > A lot of people, when they say 'uses a lot of CPU' are leaving off 'time'. I.e., CPU usage is pretty much talked about in terms of cycles, which is roughly utilization*time. Profiling tools often report both clock time and cpu time. Cpu time is a rough analog for cycles, clock time is self explanatory. max From jstroud at ucla.edu Sat May 27 19:13:16 2006 From: jstroud at ucla.edu (James Stroud) Date: Sat, 27 May 2006 16:13:16 -0700 Subject: Using a package like PyInstaller In-Reply-To: <DD4eg.2432$As2.2216@trnddc02> References: <FyYdg.2216$As2.860@trnddc02> <e5ab5l$tkm$1@daisy.noc.ucla.edu> <DD4eg.2432$As2.2216@trnddc02> Message-ID: <e5amec$64m$1@daisy.noc.ucla.edu> LittlePython wrote: > Thx for the tip. > > I am referring more to the use of PyInstaller or py2exe. Packages that > create exe files that basically have your py script and a small py > interpreter all rolled up into one. This way py does not need to be > installed on a system to execute a py script. I am being advised that python > is installed onto systems (windows) it should not be on. I am new to python > and these types of packages and am not too sure how dumb a question this > really is.. but can these packages bleed out files, dll, exe ect. to systems > they are run on? They don't have to "bleed" anything. Everything, including the python interpreter, and 3rd party libraries can be included in a single executable. Here is an example script for pyinstaller that rolls evertyhing into one file (this is what I use to roll up my passerby program at passerby.souceforge.net): setenv TEMP temp set pythonexe='c:/Python23-Enthought/python' set pbydir='z:/Code/pby/current/' rm *.pyc rm -rf ./temp/ ./passerby/ mkdir temp $pythonexe Configure.py $pythonexe Makespec.py --onefile --tk --noconsole \ --icon $pbydir/../icons/passerby.ico \ $pbydir/passerby.py passerby/passerby.spec $pythonexe Build.py passerby/passerby.spec You can control installation with innosetup. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From viridia at gmail.com Mon May 22 17:02:40 2006 From: viridia at gmail.com (Talin) Date: 22 May 2006 14:02:40 -0700 Subject: PEP 3102 for review and comment In-Reply-To: <rowen-DB5DB2.12221822052006@news.isp.giganews.com> References: <1148102845.438543.16380@38g2000cwa.googlegroups.com> <rowen-DB5DB2.12221822052006@news.isp.giganews.com> Message-ID: <1148331760.363378.294350@j73g2000cwa.googlegroups.com> Allowing keyword arguments without defaults may seem like a syntactical change, but in fact it's not. You can do this in Python now - any argument can be a 'keyword' argument, whether it has a default value or not. So for example: def func( a, b, c=0 ): pass func( a=1, b=2, c=3 ) In other words, the use of '=' to indicate a keyword argument, and the use of '=' to indicate a default argument value have *nothing* to do with each other, other than the fact that they both have the requirement that they have to come after positional arguments. If you wanted to require keyword-only arguments to have default values, that would require adding an additional check, which would be a syntactical change. -- Talin From python.list at tim.thechases.com Fri May 26 14:08:05 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 26 May 2006 13:08:05 -0500 Subject: sort a dictionary by keys in specific order In-Reply-To: <1148665851.182749.101720@g10g2000cwb.googlegroups.com> References: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> <mailman.6254.1148665126.27775.python-list@python.org> <1148665851.182749.101720@g10g2000cwb.googlegroups.com> Message-ID: <44774405.7020809@tim.thechases.com> > how do i get the result back into the dictionary ? Well, if you must, if you've just got the results in my previous post, you can take them and shove them back into a dict with results = [('key1','value1'),('key2','value2)] newDict = dict(results) If you're not doing anything with that the resulting list of ordered key/value pairs (such as inserting, printing, whatever), then skip the whole matter: newDict = dic :) HOWEVER...as I noted, a dictionary is an INHERENTLY UNSORTED COLLECTION. There are some wrapper-classes around that will feign sortedness if you want them, but they may not handle your custom sortedness constraint. There are few reasons for a sorted dict. Most of them regard displaying them. If this is the case, just do the sorting/selection of the items before you print: print "\n".join([dic[k] for k in order]) Other reasons might involve dependancies, where some process requires that you access the keys in a particular order. Just order them before you call the process. -tkc From robert.kern at gmail.com Mon May 1 15:17:50 2006 From: robert.kern at gmail.com (Robert Kern) Date: Mon, 01 May 2006 14:17:50 -0500 Subject: How to efficiently read binary files? In-Reply-To: <125cmm985vbaf@corp.supernews.com> References: <zda5g.5247$nV4.1486@trnddc04> <125acgep357kbd8@corp.supernews.com> <mailman.5165.1146434636.27775.python-list@python.org> <125c8sbqsd7a952@corp.supernews.com> <mailman.5184.1146501930.27775.python-list@python.org> <125cfokq609se5d@corp.supernews.com> <mailman.5188.1146509722.27775.python-list@python.org> <125cmm985vbaf@corp.supernews.com> Message-ID: <e35mst$np8$1@sea.gmane.org> Grant Edwards wrote: > On 2006-05-01, Robert Kern <robert.kern at gmail.com> wrote: > >>Grant Edwards wrote: >> >>>On 2006-05-01, Robert Kern <robert.kern at gmail.com> wrote: >>> >>>>>>>Perhaps the numarray module? >>>>>> >>>>>>numpy for new code, please. >>>>> >>>>>So numarray and numpy were both written to replace numeric? >>>> >>>>numpy was written to replace both Numeric and numarray. >>> >>>too many batteries... >> >>Too many cryptic complaints... > > Too easy to miss the intended humor on Usenet... Oh, I saw the smiley. I knew it was meant to be humorous. I just didn't understand it. The only "batteries" reference I know of in this context is the "batteries included" philosophy of the stdlib. Of course, none of Numeric, numarray, or numpy have anything to do with the stdlib, so again I am confused. -- Robert Kern "I have come to believe that the whole world is an enigma, a harmless enigma that is made terrible by our own mad attempt to interpret it as though it had an underlying truth." -- Umberto Eco From sybrenUSE at YOURthirdtower.com.imagination Mon May 22 11:23:08 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 22 May 2006 17:23:08 +0200 Subject: XML/HTML Encoding problem References: <Emkcg.80446$fj3.40225@fe48.usenetserver.com> Message-ID: <slrne73lqs.8pe.sybrenUSE@schuimige.stuvel.eu> Dale Strickland-Clark enlightened us with: > So it encodes the entity reference to ??? (Euro sign). ??I need it to > remain as € so that the resulting HTML can render properly in > a browser. If you want proper display, why not use UTF-8? Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From claird at lairds.us Wed May 10 21:14:37 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 11 May 2006 01:14:37 +0000 Subject: data entry tool References: <445f038f@news.maxnet.co.nz><1147267750.833367.234180@v46g2000cwv.googlegroups.com> <446236d5@news.maxnet.co.nz> <1147291993.831470.156300@y43g2000cwc.googlegroups.com> Message-ID: <tofaj3-o7r.ln1@lairds.us> In article <1147291993.831470.156300 at y43g2000cwc.googlegroups.com>, <bearophileHUGS at lycos.com> wrote: >Peter wrote>Wow - why so big for such a simple tool? 2MB sounds like a >LOT of coding.< > >Yes, it's a lot of code, but it's code written by other people (Python, >Tkinter). Using Tkinter your program will probably be quite short, even >if you use some dbase. >If the data to be entered is simple and textual you can even think >about using a text only interface. The resulting program will be really >simple, and probably good enough. >2+ MB is the size of the executable package you need to give people to >install Python + some libs + your program. . . . ... and if it's really an issue, it's generally feasible to squish a Python installable down enough so it fits on a 1.4 Mb floppy. From fredrik at pythonware.com Thu May 18 10:54:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 16:54:01 +0200 Subject: Question about exausted iterators In-Reply-To: <446c88a2$0$7121$626a54ce@news.free.fr> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <mailman.5879.1147959939.27775.python-list@python.org> <446c7f44$0$7128$626a54ce@news.free.fr> <4d3f10F18q0d9U1@uni-berlin.de> <446c88a2$0$7121$626a54ce@news.free.fr> Message-ID: <e4i1q8$luc$2@sea.gmane.org> Christophe wrote: > Maybe I've used more iterables than most of you. Maybe I've been doing > that wrong. your problem is that you're confusing iterables with sequences. they're two different things. </F> From eric_brunel at despammed.com Fri May 19 03:26:37 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Fri, 19 May 2006 09:26:37 +0200 Subject: Tkinter Dialog Management problems: References: <mailman.5891.1147967578.27775.python-list@python.org> Message-ID: <ops9seynojrqur0o@eb.pragmadev> On Thu, 18 May 2006 11:52:54 -0400, Michael Yanowitz <m.yanowitz at kearfott.com> wrote: > Thanks. That helped alot. No problem. > However it leaves a couple very minor problems which I think I can live > with. > 1) It brings up an empty additional 'main window'. > I have tried using the Tkinter.NoDefaultRoot() option, but run into > other problems with other things not defined. > NameError: global name '_default_root' is not defined > Exception exceptions.AttributeError: "IntVar instance has no attribute > '_tk'" in > <bound method IntVar.__del__ of <Tkinter.IntVar instance at 0x009C7990>> > ignored > > 2) By deriving the 'dialog' from Tk, existing calls to self.pack() no > longer are valid, but they don't appear to be necessary. > > My only 'Tkinter tutorial' is what is included in Orielly's > "Programming > Python". Still looking for a good tutorial. I am not clear what the > difference > between Tk() and Toplevel() are. They seem totally interchangeable. No, they're not! Never - and I mean *never* - create two instances of Tk in the same application! The Tk instance does not only represent the main window for the application, but also creates the underlying tcl interpreter. Creating two instances of Tk will then create two interpreters and you'll never know which one executes your commands, producing weird TclError's everywhere. If you have a window which can be considered as the main window for your application - there is only one of it, it is always there and closing it means quitting the application -, then make it a sub-class of Tk. If you do not have such a window, use the following trick at the beginning of your application: root = Tkinter.Tk() root.withdraw() This basically creates a main window and immediately hides it. All your other windows must be sub-classes of Toplevel. Calling the quit method of these windows should still quit the application, and calling the destroy method should only close the window. As for tutorials, there are many; just see there: http://tkinter.unpy.net/wiki/Tkinter Apart from the one already given by Rony (which is more a reference than a tutorial), my favorite ones are: - Stephen Ferg's "Thinking in Tkinter" - http://www.ferg.org/thinking_in_tkinter/index.html - The one at http://doctormickey.com/python/index.html - Gerard Swinnen's "Apprendre a programmer avec Python" (in French) - http://www.cifen.ulg.ac.be/inforef/swi/python.htm At least, these ones avoid the confusion Frame/window usually found in many others: the first two don't use inheritance at all; only the last (the one in French) implements windows as sub-classes of Tk or Toplevel. Unfortunately, I don't know any english translation of it. A last advice: if you want to do serious Tkinter, it really helps to know how the underlying tcl/tk layer works. So maybe you should learn at least the basics of tcl/tk. And if you do that, you will be able to use tcl/tk resources, such as: http://www.tcl.tk/man/ which is the only documentation I ever need now... HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From scott.daniels at acm.org Tue May 16 17:53:53 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 16 May 2006 14:53:53 -0700 Subject: Unable to extract Python source code using Windows In-Reply-To: <1147803594.844448.271640@i39g2000cwa.googlegroups.com> References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> <446a0229$1@nntp0.pdx.net> <1147803594.844448.271640@i39g2000cwa.googlegroups.com> Message-ID: <446a45fe$1@nntp0.pdx.net> Elric02 at rogers.com wrote: > Scott , > I tried downloading for different archives, (different versions of > Python) I can't believe they are all garbled. But they all don't work > with WinZip. And what checksum did you get? --Scott David Daniels scott.daniels at acm.org From chris.cavalaria at free.fr Thu May 18 04:28:30 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 10:28:30 +0200 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <mailman.5846.1147904183.27775.python-list@python.org> References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <mailman.5846.1147904183.27775.python-list@python.org> Message-ID: <446c3055$0$5298$626a54ce@news.free.fr> Carl J. Van Arsdall a ?crit : > glomde wrote: > >>> >> >> >> But If you work in a team it is kind of hard to make sure that >> everybody use tabs and not spaces. And it is not very easy to spot >> either. > > The converse can also be said, "it's difficult to make sure everyone > uses spaces and not tabs". > > I think we've just about beat this discussion to death... nice work > everyone! > No, it's really easy : a simple precoomit hook which will refuse any .py file with the \t char in it and it's done ;) From ramen at lackingtalent.com Thu May 11 18:57:02 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Thu, 11 May 2006 17:57:02 -0500 Subject: Time to bundle PythonWin In-Reply-To: <1147388148.406918.76040@q12g2000cwa.googlegroups.com> References: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> <1147388148.406918.76040@q12g2000cwa.googlegroups.com> Message-ID: <Pine.LNX.4.63.0605111755470.10983@lackingtalent.com> On Thu, 11 May 2006, Robert Hicks wrote: > No it isn't. It is a Windows only package. It needs to stay a separate > download. The Windows installer for Python is an MSI file. It's already Windows only. Dave From johnzenger at gmail.com Tue May 16 11:01:01 2006 From: johnzenger at gmail.com (johnzenger at gmail.com) Date: 16 May 2006 08:01:01 -0700 Subject: constucting a lookup table In-Reply-To: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> References: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> Message-ID: <1147791661.748573.30270@u72g2000cwu.googlegroups.com> How about a dictionary, keyed on tuples of (height, weight)? mhodkin at comcast.net wrote: > I'm new to Python and want to contruct a "lookup table" which would be > similar to a spreadsheet in that a value is read along the first > column, then along the top row, and the intersection of the two gives a > value that is hard-coded, i.e. not mathmatically related. An example > would be a table with HEIGHT in the first column, WEIGHT in the first > row, and estimated SUITSIZE with the body of the table. > > Which Python type would be most appropriate and/or efficient? > > thanks From sjmachin at lexicon.net Fri May 19 08:40:53 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 May 2006 05:40:53 -0700 Subject: Encode exception for chinese text References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> <1148037335.595690.49030@g10g2000cwb.googlegroups.com> <1148039249.873491.234770@38g2000cwa.googlegroups.com> Message-ID: <1148042447.460782.156990@j73g2000cwa.googlegroups.com> 1. *By definition*, you can encode *any* Unicode string into utf-8. Proves nothing. 2. \u00a0 [no-break space] has no equivalent in gb2312, nor in the later gbk alias cp936. It does have an equivalent in the latest Chinese encoding, gb18030. 3. gb2312 is outdated. It is not really an "appropriate" charset for anything much these days. You need to check out what your requirements really are. The unknowing will cheerfully use "gb" to mean one or more of those, or to mean "anything that's not big5" :-) 4. The slab of text you supplied is genuine unicode and encodes happily into all those gb* charsets. It does *not* contain \u00a0. I do hope some of this helps .... Cheers, John From nnorwitz at gmail.com Wed May 17 00:34:00 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 16 May 2006 21:34:00 -0700 Subject: build now requires Python exist before the build starts In-Reply-To: <4469df8d$0$442$6c56d894@reader0.news.be.easynet.net> References: <4469df8d$0$442$6c56d894@reader0.news.be.easynet.net> Message-ID: <1147840440.217866.314750@u72g2000cwu.googlegroups.com> Toon Knapen wrote: > I'm trying to build the svn-trunk version of python on a Solaris box. > However I do not have a python installed yet and apparantly the build of > python requires a python to be accessible (as also annotated in the > Makefile generated during the ./configure). How can I solve this situation? It shouldn't actually be required. I'm assuming the problem is while trying to run asdlgen.py. The generated files are checked in, but the timestamps are wrong and the Makefile is trying to be helpful. Try: touch Include/Python-ast.h Python/Python-ast.c make I believe those are the two files that are generated. If not, try posting the error message. HTH, n From roy at panix.com Mon May 15 09:11:21 2006 From: roy at panix.com (Roy Smith) Date: Mon, 15 May 2006 09:11:21 -0400 Subject: Large Dictionaries References: <1147699064.107490@teuthos> Message-ID: <roy-765731.09112115052006@reader1.panix.com> In article <1147699064.107490 at teuthos>, Chris Foote <chris at foote.com.au> wrote: > Hi all. > > I have the need to store a large (10M) number of keys in a hash table, > based on a tuple of (long_integer, integer). The standard python > dictionary works well for small numbers of keys, but starts to > perform badly for me inserting roughly 5M keys: > > # keys dictionary metakit (both using psyco) > ------ ---------- ------- > 1M 8.8s 22.2s > 2M 24.0s 43.7s > 5M 115.3s 105.4s Are those clock times or CPU times? How much memory is your process using and how much is available on your machine? I'm guessing a integer takes 4 bytes and a long integer takes roughly one byte per two decimal digits. Plus a few more bytes to bundle them up into a tuple. You've probably got something like 20 bytes per key, so 5M of them is 100 meg just for the keys. To get reasonable hashing performance, the hash table needs to be maybe half full, and figure a hash key is 4 bytes, so that's another 40 meg for the hash table itself. Plus whatever the values stored in the dictionary take up. Even if you're not storing any values (i.e., there's probably 4 bytes for a null pointer (or reference to None), so that's another 40 meg. These are all vague guesses, based on what I think are probably conservative estimates of what various objects must take up in memory, but you see where this is going. We're already up to 180 meg. I wonder if the whole problem is that you're just paging yourself to death. A few minutes watching your system memory performance with ps or top while your program is running might give you some idea if this is the case. From duncanm255 at hotmail.com Fri May 19 11:00:36 2006 From: duncanm255 at hotmail.com (D) Date: 19 May 2006 08:00:36 -0700 Subject: Python Install In-Reply-To: <1147967540.424467.138910@38g2000cwa.googlegroups.com> References: <1147962608.945821.226220@i40g2000cwc.googlegroups.com> <mailman.5887.1147965090.27775.python-list@python.org> <1147967540.424467.138910@38g2000cwa.googlegroups.com> Message-ID: <1148050836.772555.175960@j33g2000cwa.googlegroups.com> Thanks guys - I will give it another go! From danb_83 at yahoo.com Wed May 24 18:07:25 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 24 May 2006 15:07:25 -0700 Subject: Why can't timedeltas be divided? Message-ID: <1148508445.853563.170030@i39g2000cwa.googlegroups.com> If I try to write something like: num_weeks = time_diff / datetime.timedelta(days=7) I get: TypeError: unsupported operand type(s) for /: 'datetime.timedelta' and 'datetime.timedelta' Of course, one could extend the timedelta class to implement division, def _microseconds(self): return (self.days * 86400 + self.seconds) * 1000000 + self.microseconds def __truediv__(self, other): if isinstance(other, datetime.timedelta): return self._microseconds() / other._microseconds() else: return datetime.timedelta(0, 0, self._microseconds() / other) def __floordiv__(self, other): if isinstance(other, datetime.timedelta): return self._microseconds() // other._microseconds() return NotImplemented but why is a basic arithmetic operation missing from the standard datetime module? From sjmachin at lexicon.net Fri May 12 18:40:50 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 13 May 2006 08:40:50 +1000 Subject: find all index positions In-Reply-To: <1147449337.164504.307670@j73g2000cwa.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <1147374826.341124.129260@g10g2000cwb.googlegroups.com> <4463C188.3030202@lexicon.net> <1147448743.445465.124200@u72g2000cwu.googlegroups.com> <1147449337.164504.307670@j73g2000cwa.googlegroups.com> Message-ID: <44650EF2.4050800@lexicon.net> On 13/05/2006 1:55 AM, vbgunz wrote: > I forgot to explain my reason for over shadowing the 'string' built-in > within my iterator. To me, it doesn't matter because the string > identifier is temporary within the function and dies when the function > dies. Also, I personally don't use the string function and prefer > ''.join('hi'), etc. Also, at least for me just starting out in Python, > I find 'string' to be as readable as possible :) > > what do you think about that? > 1. 'string' is not a function, it is a module. I'm glad you don't use the non-existent 'string function'. 2. >>> ''.join('hi') 'hi' You prefer to do that instead of what? Look at the docs on the .join() method carefully, and consider the following: >>> '-'.join('hello') 'h-e-l-l-o' >>> 3. Back to the shadowing thing: 'string' is admittedly not a good example to pull you up on, as that module is little used these days. However it is the thin end of the wedge, and your adding 'index' in round 2 just drove the wedge in a little further. Once you start using words like 'file' and 'list' as variable names, your code will be almost as *UN*readable as possible. It's not just the shadowing possibility, it's the confusion in the reader's mind between the usual/normal Python meaning of a word and the meaning that you have attached to it. As you are just starting out in Python, now is the time to acquire good habits. Cheers, John From joesb.coe9 at gmail.com Tue May 9 11:08:58 2006 From: joesb.coe9 at gmail.com (Pisin Bootvong) Date: 9 May 2006 08:08:58 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <slrne60qrk.dac.apardon@rcpc42.vub.ac.be> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> <slrne60jsm.dac.apardon@rcpc42.vub.ac.be> <1147165989.106261.164090@j33g2000cwa.googlegroups.com> <slrne60qrk.dac.apardon@rcpc42.vub.ac.be> Message-ID: <1147186004.090085.234980@j73g2000cwa.googlegroups.com> Antoon Pardon wrote: > Op 2006-05-09, Pisin Bootvong schreef <joesb.coe9 at gmail.com>: > > > > Antoon Pardon wrote: > >> Op 2006-05-09, Pisin Bootvong schreef <joesb.coe9 at gmail.com>: > >> > Is this a Slippery Slope fallacious argument? > >> > (http://c2.com/cgi/wiki?SlipperySlope) > >> > >> No it is not. > >> > >> [...] > >> > >> So the question I have is: Why is requiring me to give this function > >> a name considered a good thing, when it leads to a situation that > >> is considered bad practice in case of a number. > >> > >> -- > > > > Slippery Slope:: > > "Argumentation that A is bad, because A might lead to B, and B > > to C, and we all know C is very bad." > > But I have seen noone here argue that requiring functions to be named > leads to requiring all variables to be named. > If I misinterpret your intended meaning, then I'm terribly sorry. However let me clarify how I understand your statements -- English is not my native language but I'm quite sure I have good English skill. you said: > >> Why is requiring me to give this function > >> a name considered a good thing, when it leads to a situation that > >> is considered bad practice in case of a number. So in that question, one of the your assumption is that: "it (required function naming) ***LEADS*** to a situation that is considered bad practice in case of a number (required number naming)" You have not seen anyone here >> "argue that requiring functions to be named leads to requiring all variables to be named" But obviously I have seen someone "argue that requiring functions to be named leads to requiring **NUMBER** to be named" And you said that requiring number to be named is bad. Where did I misunderstand that you, with all good faith, were not trying to say that "A leads B which is bad so "why is A considered a good thing""? And how is it not slippery argument? To put my response another way, I would ask: Does Python require you to name all your number? expression? (Hint: the answer is no) So where did you get the idea that requiring function to be named, as Python does, leads to requiring number to be named? Is it in a research anywhere? Or do majority of people here agree so (that it leads to)? > >> Why is requiring me to give this function > >> a name considered a good thing, when it leads to a situation that > >> is considered bad practice in case of a number. > > > > A === "requiring me to give function a name" > > no B > > C === "requiring me to give number a name" > > > > "Argumentation that requiring one to give function a name is bad, > > because that might lead to requiring one to give number a name, and we > > all know that that is very bad." > > That is not the arguement I'm making. > > The argument is that a particular pratice is considered bad coding, > (with an example giving a number) and then showing that requiring > a name for a function, almost makes such a practice inevitable (for > certain functions used as parameters) > Your example: def incr_cnt_by_one(obj): obj.cnt += 1 treat_all(lst, incr_cnt_by_one) Did not in anyway show that the number one is required to be named. 1 in that code is written literally; you didn't have to write "one = 1" first. The function to increment obj.cnt by one is named. but the number 1 itself is not named. > Antoon Pardon From tim.golden at viacom-outdoor.co.uk Mon May 22 10:44:03 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: Mon, 22 May 2006 15:44:03 +0100 Subject: Win32: Detecting when system is locked or sleeping Message-ID: <CCAC78D42E32184F8E26DC163DB9830617E1E4@vogbs009.gb.vo.local> [rodmc] | I have written an application which works perfectly when the | machine is | operating under normal conditions, however when the screen becomes | locked it imediately starts to fill up several hundred MB's of memory. | | Is there a way to detect when the system is locked? This may not be exactly what you want, but hopefully it's a starting point. http://timgolden.me.uk/python/win32_how_do_i/see_if_my_workstation_is_lo cked.html 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 anthra.norell at tiscalinet.ch Fri May 12 13:25:03 2006 From: anthra.norell at tiscalinet.ch (Anthra Norell) Date: Fri, 12 May 2006 19:25:03 +0200 Subject: Reg Ex help References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> Message-ID: <042701c675e9$022d70c0$0201a8c0@mcuf7> >>> se = SE.SE ('<EAT> "~/[A-Za-z0-9_]+/CHECKEDOUT~==" | /= CHECKEDOUT=') >>> se ('/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT') 'dbg_for_python' If I understand your problem, this might be a solution. It is a stream editor I devised on the impression that it could handle in a simple manner a number of relatively simple problems on this list for which no commensurately simple methodologies seem to exist. I intend to propose it to the group when I finish the doc. Meantime who do I propose it to? Frederic ----- Original Message ----- From: "don" <abhidon at gmail.com> Newsgroups: comp.lang.python To: <python-list at python.org> Sent: Thursday, May 11, 2006 7:39 PM Subject: Reg Ex help > I have a string from a clearcase cleartool ls command. > > /main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT > from /main/parallel_branch_1/release_branch_1.0/4 > > I want to write a regex that gives me the branch the file was > checkedout on ,in this case - 'dbg_for_python' > > Also if there is a better way than using regex, please let me know. > > Thanks in advance, > Don > > -- > http://mail.python.org/mailman/listinfo/python-list From __peter__ at web.de Thu May 4 02:07:28 2006 From: __peter__ at web.de (Peter Otten) Date: Thu, 04 May 2006 08:07:28 +0200 Subject: Defining class methods outside of classes References: <mailman.5281.1146692558.27775.python-list@python.org> Message-ID: <e3c5jt$45d$01$1@news.t-online.com> Lord Landon wrote: > Hi, I'm working on a bot written in python. It will consist of a > mostly empty class that will then call a loader which in turn defines > functions and adds them to the class. At the moment, I do this by > using execfile(file,globals()) and calling a load(bot) method defined > in every "module" which takes the functions defined in that perticular > module and does bot.function=function. The problem with that is when I > call bot.function() self doesn't get passed as an argument to the > function. Is there anything I can do to sort this besides calling > bot.function(bot, ...) everytime? Either add the method to the class or make it an instance method. >>> class Bot(object): ... def __init__(self): ... self.name = "bot" ... >>> bot = Bot() >>> def method(self): print "hello from", self.name ... >>> Bot.greet = method >>> bot.greet() hello from bot >>> import new >>> bot.hello = new.instancemethod(method, bot) >>> bot.hello() hello from bot Peter From mcherm at mcherm.com Wed May 3 07:41:58 2006 From: mcherm at mcherm.com (Michael Chermside) Date: Wed, 03 May 2006 04:41:58 -0700 Subject: [Python-3000] bug in modulus? Message-ID: <20060503044158.c6wxhrx2ygrbgoo0@login.werra.lunarpages.com> Tim Peters writes: > IMO, it was a mistake (and partly my fault cuz I didn't whine early) > for Python to try to define % the same way for ints and floats. [...] > I'd like to see this change in Python 3000. Note that IBM's proposed > standard for decimal arithmetic (which Python's "decimal" module > implements) requires two operations here, one that works like > math.fmod(a, b) (exact and sign of a), and the other as described > above (exact and |a%b| <= |b/2|). Providing both operations is a no-brainer. But only one gets to be spelled "x % y". Experts will care about sensible behavior of numerical algorithms... but they're experts, they can use whichever operation they need. Beginners will care that floats and integers behave "the same" (okay, that's not actually possible, but beginners don't know it). So why not make "x % y" for floats behave exactly like it does for integers and provide a separate operation with your described behavior? (Or is that what you were suggesting, and I'm just confused?) If you're worried about beginners who are implementing numerical algorithms and hoping to make the language smart enough to "just work" for them, then I'm afraid it's hopeless. I'm far from a beginner, but I don't think I could implement a non-trivial numerical algorithm. (Well, I could make it work, but I'm betting it would be non-optimal or have corner cases of failure that an expert could point out.) -- Michael Chermside From duncan.booth at invalid.invalid Thu May 4 08:38:09 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 4 May 2006 12:38:09 GMT Subject: Python function returns: References: <mailman.5316.1146744053.27775.python-list@python.org> Message-ID: <Xns97B9899C9FD28duncanbooth@127.0.0.1> Michael Yanowitz wrote: > In Python, there does not seem to be an easy way to have functions > return > multiple values except it can return a list such as: > strHostname, nPortNumber, status = get_network_info (strIpAddress, > strHostname, > nPortNumber) > Am I missing something obvious? Is there a better, or more standard > way > to return values from functions? The only obvious thing you are missing is that you don't pass in values which are only results. Duplicating the parameters and results as you have above would be unlikely to happen very much in practice. Oh, and it doesn't return a list, it actually returns a tuple but it is easiest just to think of your function as just returning three results. Returning additional results is better than rebinding parameters because it makes it really clear at the point of calling which variables are parameters and which are results. The other not very pythonic thing about your example is that it returns a status code: Python largely tends towards using exceptions rather than status codes, so if in C you had: switch ((status=get_network_info(addr, &host, &port)) { case S_OK: break; case ERROR_1: ... handle error ... break; case default: ... handle other errors ... }; In Python you would have something like: try: host, port = get_network_info(addr) except ERROR_1: ... handle error ... except: ... handle other errors ... which means you can handle the error either right next to the call or at some outer level (you don't have to manually propogate your status), you can't accidentally forget to check the status code, and the actual call is much simpler and clearer (especially if the error is handled at some outer level). From kentilton at gmail.com Sat May 6 17:36:10 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sat, 06 May 2006 17:36:10 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <lr87g.502$SV1.253@fe10.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> Message-ID: <eF87g.503$SV1.75@fe10.lga> Ken Tilton wrote: > > Come on, try just one meaty Common Lisp project at Google. Have someone > port Cells to Python. I got halfway done but decided I would rather be > doing Lisp. uh-oh. Does Python have anything like special variables? :) Omigod. I scare myself sometimes. This would be a great Summer of Code project. Port Cells (see sig) to Python. Trust me, this is Silver Bullet stuff. (Brooks was wrong on that.) If a strong Pythonista wants to submit a proposal, er, move fast. I am mentoring through LispNYC: http://www.lispnyc.org/soc.clp Gotta be all over Python metaclasses, and everything else pure Python. PyGtk would be a good idea for the demo, which will involve a GUI mini app. Just gotta be able to /read/ Common Lisp. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From skip at pobox.com Tue May 9 21:16:33 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 9 May 2006 20:16:33 -0500 Subject: __all__ does not work? In-Reply-To: <j9ydnXEhmIkbrPzZnZ2dnUVZ_sadnZ2d@comcast.com> References: <j9ydnXEhmIkbrPzZnZ2dnUVZ_sadnZ2d@comcast.com> Message-ID: <17505.16113.337454.768510@montanaro.dyndns.org> Andy> This a mm.py module: Andy> _all__=('getsize1',) Andy> size=85 Andy> def getsize1(): Andy> return size Andy> def getsize2(): Andy> return 2*size Andy> I do not know why but getsize2 is not kept priviate? That's not what __all__ is used for. Try this: from mm import * The only name added to your namespace will be getsize1. Skip From scott.daniels at acm.org Tue May 30 17:01:39 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 30 May 2006 14:01:39 -0700 Subject: TIming In-Reply-To: <pan.2006.05.30.19.50.38.152274@none.none> References: <pan.2006.05.30.01.24.04.677340@none.none> <ecin725eh7mk1teolpfi2ulj349ogptdir@4ax.com> <pan.2006.05.30.05.23.09.936650@none.none> <mailman.6326.1148969845.27775.python-list@python.org> <pan.2006.05.30.19.50.38.152274@none.none> Message-ID: <447cae5a$1@nntp0.pdx.net> WIdgeteye wrote: > <Osome rude drivel> Thank you very much for your participation. --Scott David Daniels scott.daniels at acm.org From gregory.petrosyan at gmail.com Mon May 22 10:29:06 2006 From: gregory.petrosyan at gmail.com (Gregory Petrosyan) Date: 22 May 2006 07:29:06 -0700 Subject: enumerate() question Message-ID: <1148308146.493287.323770@38g2000cwa.googlegroups.com> Hello! I have a question for the developer[s] of enumerate(). Consider the following code: for x,y in coords(dots): print x, y When I want to iterate over enumerated sequence I expect this to work: for i,x,y in enumerate(coords(dots)): print i, x, y Unfortunately, it doesn't =( and I should use (IMHO) ugly for i,pair in enumerate(coords(dots)): print i, pair[0], pair[1] So, why enumerate() works this way and is there any chance of changing the behaviour? -- Regards, Gregory. From me at privacy.net Mon May 15 14:52:45 2006 From: me at privacy.net (Dan Sommers) Date: Mon, 15 May 2006 14:52:45 -0400 Subject: common practice for creating utility functions? References: <ZI3ag.2095$No6.46239@news.tufts.edu> Message-ID: <m2k68n2k8y.fsf@unique.fqdn> On Mon, 15 May 2006 18:26:01 GMT, John Salerno <johnjsal at NOSPAMgmail.com> wrote: > So my first question is this: should I make a Cryptogram class for > this, or are functions fine? ... Perhaps I'm "old school," but I don't bother with classes unless I'm going to end up with multiple instances (or I'm pushed into a corner by, e.g., a GUI framework). > ... If the latter, then back to my original point: can I do something > like this: > def convert_quote(quote): > return make_code(quote) Of course you can. Or, since this is python, you can also do this: convert_quote = make_quote > Or does it not make sense to have a function just call another > function? If there's a good design-level reason (like keeping certain objects or classes unaware of others, or leaving room for something you know you will add later), then there's nothing wrong with a function consisting solely of another function call. If you end up with a lot of those tiny functions, though, and they persist through multiple development cycles, then you may be making a systematic mistake in your design. Regards, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From paul at boddie.org.uk Fri May 5 07:28:26 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 5 May 2006 04:28:26 -0700 Subject: Tuple assignment and generators? References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1146760580.143027.38100@y43g2000cwc.googlegroups.com> <mailman.5343.1146771299.27775.python-list@python.org> Message-ID: <1146828506.424711.49020@v46g2000cwv.googlegroups.com> Tim Chase wrote: > > I was hoping that there was just some __foo__ property I was > missing that would have been called in the process of tuple > unpacking that would allow for a more elegant solution such > as a generator (or generator method on some object) rather > than stooping to disassembling opcodes. :) I suppose you wanted something like this... a, b, c, d, e = xyz # first, let's consider a plain object ...to use the iterator "protocol" to populate the tuple elements, like this: _iter = xyz.__iter__() a = _iter.next() b = _iter.next() c = _iter.next() d = _iter.next() e = _iter.next() For such plain objects, it is possible to use such a mechanism. Here's a "countdown" iterator: class A: def __init__(self, size): self.size = size def __iter__(self): return B(self.size) class B: def __init__(self, size): self.n = size def next(self): if self.n > 0: self.n -= 1 return self.n else: raise StopIteration xyz = A(5) a, b, c, d, e = xyz In fact, similar machinery can be used to acquire new values from a generator: def g(size): while size > 0: size = size - 1 yield size a, b, c, d, e = g(5) Note that if the iterator (specifically, the generator in the second case) doesn't provide enough values, or provides too many, the tuple unpacking operation will fail with the corresponding exception message. Thus, generators which provide infinite or very long sequences will not work unless you discard trailing values; you can support this either by adding support for slicing to whatever is providing your sequences or, if you're using generators anyway, by employing an additional "limiting" generator: def limit(it, size): while size > 0: yield it.next() size -= 1 xyz = A(5) a, b, c, d = limit(iter(xyz), 4) The above generator may be all you need to solve your problem, and it may be the case that such a generator exists somewhere in the standard library. Paul From charl.loubser at gmail.com Mon May 1 15:42:58 2006 From: charl.loubser at gmail.com (Merrigan) Date: 1 May 2006 12:42:58 -0700 Subject: How do I take a directory name from a given dir? Message-ID: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> Hi, I am trying to write a script to backup all my company's server configs weekly. The script will run in a cronjob, on whatever I set it. The issue I am currently having isto "extract" the directory name from a given directory string. For example: from the string "/home/testuser/projects/" I need to extract the "projects" part. The problem is that the directory names that needs to be used will never be the same lenght, so as far as my (very limited) knowledge stretches, slicing and indicing is out of the question. Can anybody help me, or give me an idea of what I should look at, seeing as I'm seriously stuck. I only started coding at the beginnig of the year, and was never interested before that, so my knowlege is basically non-existent. Thanks in advance for the help :) From nobody at 127.0.0.1 Tue May 2 16:39:09 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 20:39:09 GMT Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> Message-ID: <NrP5g.11087$Lm5.1177@newssvr12.news.prodigy.com> bruno at modulix wrote: > re-phrase it according to how Python works, and you'll get the answer: > > "Is there a way to bind multiple names to the same object, but so the > identity of this object is different from the identity of this object ?" Which raises an interesting parallel question: is there a way to clone an arbitrary object? If so you could do this: >>> a = something >>> b = clone (a) >>> id(a) == id(b) False For lists, a slice-copy creates a clone: >>> a = [1,2,3] >>> b = a[:] >>> id(a) == id(b) False For arithmetic types, an identity operation works for large values: >>> a = 12345 >>> b = a + 0 >>> id(a) == id(b) False but not small ones: >>> a = 5 >>> b = a + 0 >>> id(a) == id(b) True With booleans (and None) it will never work since the interpreter only stores one copy of each value. I'm not saying this approach is a good idea -- value semantics are almost always preferable, and playing with interpreter internals usually leads to trouble. But as an academic exercise, how close can you get to a universal clone function? From conor.robinson at gmail.com Thu May 11 16:25:49 2006 From: conor.robinson at gmail.com (py_genetic) Date: 11 May 2006 13:25:49 -0700 Subject: segmentation fault in scipy? In-Reply-To: <mailman.5605.1147377458.27775.python-list@python.org> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <mailman.5571.1147301063.27775.python-list@python.org> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <mailman.5572.1147304930.27775.python-list@python.org> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> <mailman.5576.1147320706.27775.python-list@python.org> <1147373294.235202.188220@y43g2000cwc.googlegroups.com> <mailman.5604.1147375226.27775.python-list@python.org> <1147376927.857632.310430@j33g2000cwa.googlegroups.com> <mailman.5605.1147377458.27775.python-list@python.org> Message-ID: <1147379149.476230.173150@g10g2000cwb.googlegroups.com> True! it is rediculous/insane as I mentioned and noted and agreed with you (in all your responses) and was my problem, however, not wrong (same result), as I was just simply noting (not to be right), although, yes, insane. Thanks again. From robert.kern at gmail.com Thu May 4 00:36:34 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 03 May 2006 23:36:34 -0500 Subject: pythonic way to sort In-Reply-To: <1146715940.923869.91730@u72g2000cwu.googlegroups.com> References: <1146715940.923869.91730@u72g2000cwu.googlegroups.com> Message-ID: <e3c0cj$9jh$1@sea.gmane.org> micklee74 at hotmail.com wrote: > hi > I have a file with columns delimited by '~' like this: > > 1SOME STRING ~ABC~12311232432D~20060401~00000000 > 2SOME STRING ~DEF~13534534543C~20060401~00000000 > 3SOME STRING ~ACD~14353453554G~20060401~00000000 > > ..... > > What is the pythonic way to sort this type of structured text file? > Say i want to sort by 2nd column , ie ABC, ACD,DEF ? so that it becomes > > 1SOME STRING ~ABC~12311232432D~20060401~00000000 > 3SOME STRING ~ACD~14353453554G~20060401~00000000 > 2SOME STRING ~DEF~13534534543C~20060401~00000000 > ? > I know for a start, that i have to split on '~', then append all the > second columns into a list, then sort the list using sort(), but i am > stuck with how to get the rest of the corresponding columns after the > sort.... In Python 2.4 and up, you can use the key= keyword to list.sort(). E.g. In [2]: text = """1SOME STRING ~ABC~12311232432D~20060401~00000000 ...: 2SOME STRING ~DEF~13534534543C~20060401~00000000 ...: 3SOME STRING ~ACD~14353453554G~20060401~00000000""" In [3]: lines = text.split('\n') In [4]: lines Out[4]: ['1SOME STRING ~ABC~12311232432D~20060401~00000000', '2SOME STRING ~DEF~13534534543C~20060401~00000000', '3SOME STRING ~ACD~14353453554G~20060401~00000000'] In [5]: lines.sort(key=lambda x: x.split('~')[1]) In [6]: lines Out[6]: ['1SOME STRING ~ABC~12311232432D~20060401~00000000', '3SOME STRING ~ACD~14353453554G~20060401~00000000', '2SOME STRING ~DEF~13534534543C~20060401~00000000'] -- 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 aleaxit at yahoo.com Sun May 7 00:18:00 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 21:18:00 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> <1hexigt.h7vk5s1i5fkn3N%aleaxit@yahoo.com> <87bquay2rv.fsf@rpi.edu> Message-ID: <1hexp3q.xnospn3zjszxN%aleaxit@yahoo.com> Bill Atkins <NOatkinwSPAM at rpi.edu> wrote: ... > > And here is where we check if you're as gracious about admitting your > > errors, as I am about mine. Brooks' law is: > > > > """Adding manpower to a late software project makes it later.""" > > > > These are Brooks' words, literally. OK so far? > > You are correct. > > I posted too hastily. Here is what my paragraph ought to have said: > > Buh? The project doesn't have to be late for Brooks's law to hold; > adding programmers *in the middle of a project*, so goes Brooks > reasoning, will always increase the time required to complete the > project because of various communication issues. > > Agree? "What does one do when an essential software project is behind schedule? Add manpower, naturally. As Figs 2.1 through 2.4 suggest, this may or may not help". How do you translate "may or may not help" into "will always increase the time required", and manage to impute that translation to "Brooks reasoning"? It *MAY* help -- Brooks says so very explicitly, and from the Fig 2.4 he quotes just as explicitly you may infer he has in mind that the cases in which it may help are those in which the project was badly understaffed to begin with (a very common case, as the rest of the early parts of chapter 2 explains quite adequately). I could further critique Brooks for his ignoring specific personal factors -- some extremely rare guys are able to get up to speed on an existing project in less time, and requiring less time from those already on board, than 99.9% of the human race (the JOAT in my previous example); and, another crucial issue is that sometimes the key reason a project is late is due to lack of skill on some crucial _specialty_, in which case, while adding more "generic" programmers "may or may not help" (in Brooks' words), adding just the right specialist (such as, the cryptography expert in my previous example) can help a LOT. But, it would be uncourteous to critique a seminal work in the field for not anticipating such detailed, nuanced discussion (besides, in the next chapter Brooks does mention teams including specialists, although if I recall correctly he does not touch on the issue of a project which finds out the need for a specialist _late_, as in this case). I'm still more interested in critiquing your overgeneralization of Brooks' assertions and reasoning. Alex From mhellwig at xs4all.nl Sat May 6 06:24:03 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Sat, 06 May 2006 12:24:03 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <87y7xf8swl.fsf@rpi.edu> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> Message-ID: <445c794e$0$31647$e4fe514c@news.xs4all.nl> Bill Atkins wrote: <cut> > > How do you define scalability? > http://www.google.com/search?hl=en&q=define%3Ascalability&btnG=Google+Search ;-) -- mph From fredrik at pythonware.com Thu May 18 12:06:16 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 18:06:16 +0200 Subject: Windows Registry Dump In-Reply-To: <1147967425.773885.227230@u72g2000cwu.googlegroups.com> References: <1147964415.540190.47480@i40g2000cwc.googlegroups.com> <1147967425.773885.227230@u72g2000cwu.googlegroups.com> Message-ID: <e4i61n$9q4$1@sea.gmane.org> olsongt at verizon.net wrote: >> Does someone know how I can make a Text-Dump-File of a remote >> Windows-Computer's Registry (not the whole registry - only a part of >> it)? >> >> Thanks a lot for some code or a helpful link! > > the win32api module has a bunch of Reg* functions that let you do this. most (all?) of which are also available in the _winreg module in the standard distribution. </F> From fredrik at pythonware.com Wed May 3 04:10:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 10:10:08 +0200 Subject: How to encode html and xml tag datas with standard python modules ? References: <44586183.2030903@gmail.com> Message-ID: <e39oh1$ppp$1@sea.gmane.org> DurumDara wrote: > Have the python standard mod. lib. a html/xml encoder functions/procedures ? you can use cgi.escape(s) # escapes < > & for CDATA sections, and cgi.escape(s, True) # escapes < > & " for attributes. to output ASCII, use cgi.escape(s).encode("ascii", "xmlcharrefreplace") cgi.escape(s, True).encode("ascii", "xmlcharrefreplace") > if b<32 or b>127 or c in ['<','>','"',';','&','@','%','#']: > c="&#%03d;"%b that's a rather odd set of reserved characters... </F> From ptmcg at austin.rr._bogus_.com Fri May 19 14:52:38 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 18:52:38 GMT Subject: Python sqlite and regex. References: <mailman.5942.1148042842.27775.python-list@python.org> <1148054261.004682.310800@38g2000cwa.googlegroups.com> <mailman.5966.1148057291.27775.python-list@python.org> <hunbg.46845$CH2.29994@tornado.texas.rr.com> <m2u07lq2s5.fsf@unique.fqdn> Message-ID: <Wtobg.46855$CH2.42030@tornado.texas.rr.com> "Dan Sommers" <me at privacy.net> wrote in message news:m2u07lq2s5.fsf at unique.fqdn... > On Fri, 19 May 2006 17:44:45 GMT, > "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote: > > > "Gerhard H?ring" <gh at ghaering.de> wrote in message > > news:mailman.5966.1148057291.27775.python-list at python.org... > > >> """ > >> The REGEXP operator is a special syntax for the regexp() user > >> function. No regexp() user function is defined by default and so use > >> of the REGEXP operator will normally result in an error message. If a > >> user-defined function named "regexp" is defined at run-time, that > >> function will be called in order to implement the REGEXP operator. > >> """ > > > This is very interesting. So I *could* define my own regexp function > > that processes not regular expressions, but say, glob-like strings, > > which are usually much easier for end users to work with (very basic > > wild-carding where '*' matches one or more characters, and '?' matches > > any single character - maybe add '#' to match any single digit and '@' > > to match any single alpha character). > > Doesn't SQL already have lightweight wildcards? > > SELECT somefield FROM sometable WHERE someotherfield LIKE '%foo%' > Yes it does - '%' is like '*', and '_' is like '?'. But it is rare for application users to be familiar with these. In my experience, users are more likely to have seen '*' and '?'. The reason I keep citing end/application users, as opposed to developers, is for the case where the user has filled in some kind of wildcard search field, to be passed to SQL in a query. Woe to the app designer who figures that users want to enter a regular expression in such a field. '%' and '_' wildcards a little better, but frankly, I think '*' and '?' looks more like a wildcards than '%' and '_'. -- Paul From LittlePython at lost.com Sat May 27 09:33:25 2006 From: LittlePython at lost.com (LittlePython) Date: Sat, 27 May 2006 13:33:25 GMT Subject: Using a package like PyInstaller Message-ID: <FyYdg.2216$As2.860@trnddc02> Is it possible when using packages like PyInstaller to create an .exe for distribution that parts of the package can bleed out and be left on a system when the .exe is executed? Thx From steve at holdenweb.com Tue May 23 19:41:35 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 24 May 2006 00:41:35 +0100 Subject: WeakrefValueDictionary of Callables? In-Reply-To: <4470E52C.7080700@fusion.net.nz> References: <446FD83E.2000007@fusion.net.nz> <e4ovpk$fts$1@sea.gmane.org> <4470E52C.7080700@fusion.net.nz> Message-ID: <e506jb$jc5$1@sea.gmane.org> Lloyd Weehuizen wrote [top-posting, for which he should have his wrist smacked]: > Steve Holden wrote: > > Lloyd Weehuizen wrote: > >> Hey > >> > >> I'm trying to set up a WeakrefValueDictionary of callables however as > >> soon as my method that adds the callable to the dictionary exits the > >> value is removed? Is there any way around this? > > > > > > I believe your problem is that the bound method references aren't > > being retained (i.e. referenced) anywhere else. A bound method is an > > object its own right, and can cease to exist at any time - > > particularly in your > > case when the weak reference is the only reference to it! > > > > Consider that the following code actually appears to work: > > > >import weakref > >TEST_EVENT = 1 > > > >class TestBinder: > > def __init__(self): > > self.entries = weakref.WeakValueDictionary() > > > > def BindFunction(self, event_id, obj): > > self.entries[event_id] = obj > > > > def CallFunction(self, event_id, *args): > > self.entries[event_id].TestFunction(*args) > > Thanks for that, I had a feeling that was the problem. Is there anyway > around this? I'd prefer not to have to assume the method name on the object. > > This could be solved by passing the object and method name in as two > separate parameters to the Bind function. But ideally I'd like to > extract this information somehow from the bound method and give the > external API a more natural feel. Is that possible? > Well, you *could* try extracting the object and the method name from the bound method inside your method. No promises, but let's see ... OK, here's something that allows you to keep the same API. It has the disadvantage of using a dict that parallels the WeakValueDictionary but doesn't drop entries as the wekrefs disappear. Which reminds me, you need to rewrite the code so that the absence of a weakref is correctly detected, which it isn't here. import weakref TEST_EVENT = 1 class TestBinder: def __init__( self ): self.objects = weakref.WeakValueDictionary() self.names = {} def BindFunction( self, event_id, function ): self.objects[event_id] = function.im_self self.names[event_id] = function.im_func.func_name def CallFunction( self, event_id, *args ): getattr(self.objects[event_id], self.names[event_id])( *args ) class TestCase: def __init__( self, binder ): binder.BindFunction( TEST_EVENT, self.TestFunction ) def TestFunction(self): print "TestFunction OK" test_binder = TestBinder() test_case = TestCase( test_binder ) test_binder.CallFunction( TEST_EVENT ) But it gives you a place to start from. Now back to the need for speed. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From softwindow at gmail.com Fri May 26 03:21:36 2006 From: softwindow at gmail.com (softwindow) Date: 26 May 2006 00:21:36 -0700 Subject: hi,everyone. a problem with shelve Module Message-ID: <1148628096.075581.113290@i40g2000cwc.googlegroups.com> according to the book instruduction , i use shelve Module to write record to file. i only write ten records like this: name sex age jim male 22 tom male 23 lucy female 21 .................................................others( about ten records) but i find the size of this file .oh my god , it is about 24k the file is too large ! is it normal ? i don't dare to think that if i has 1000 records , it will be a very large file! From bearophileHUGS at lycos.com Fri May 19 14:08:34 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 19 May 2006 11:08:34 -0700 Subject: newb: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <4d4chmF185ohoU1@uni-berlin.de> <1148038726.023455.145900@j73g2000cwa.googlegroups.com> Message-ID: <1148062114.800989.293270@j73g2000cwa.googlegroups.com> I think a way to solve the problem may be: 1) create a little Python script to separate the original words in many files, each one containing only words of the same length. Every filename can contain the relative word length. 2) write a little C program with two nested loops, that scans all the pairs of the words of a single file, looking for single char differences using a scanning of the chars. Probably there are many possible tricks to speed up this search (like separating the words in subgroups, of using some assembly-derived tricks, etc) but maybe you don't need them. As C data structure you may simply use a single block (because you know the length of a single word, so the files produced by Python can be without spaces and returns). I have suggested C because if the words are all of the same length then you have 30000^2 = 90 000 000 000 pairs to test. If you want, before creating the C program you can create a little Python+Psyco prototype that uses array.array of chars (because sometimes Psyco uses them quite quickly). Bye, bearophile From mramos at montevideo.com.uy Fri May 12 18:48:00 2006 From: mramos at montevideo.com.uy (Marcelo Ramos) Date: Fri, 12 May 2006 19:48:00 -0300 Subject: unzip zip files In-Reply-To: <1147470349.415553.324710@y43g2000cwc.googlegroups.com> References: <1147470349.415553.324710@y43g2000cwc.googlegroups.com> Message-ID: <446510A0.1010005@montevideo.com.uy> DataSmash escribi?: > I need to unzip all zip file(s) in the current directory > into their own subdirectories. The zip file name(s) always > start with the string "usa" and end with ".zip". > The code below will make the subdirectory, move the zip > file into the subdirectory, but unzips the contents into the > root (current) directory. I want the contents of the zip file > unloaded into the newly created subdirectory where the zip file is. > > Any ideas? > Thanks. > R.D. > > import subprocess > > # Get all the zip files in the current directory. > for zip in os.listdir(''): > if zip.endswith(".zip"): > > # Remove the first 3 and the last 4 characters > # e.g. usa12345.zip becomes 12345 > zipBase = zip[3:-4] > > # Make directory for unzipping > os.mkdir(zipBase) > > # Move the zip file to the subdirectory > shutil.move(zip, zipBase) > > # Make system call "unzip" > subprocess.Popen(["unzip", zipBase + "\\" + zip]).wait() > > See "-d" zip's parameter in man zip. Regards. -- Marcelo Ramos Fedora Core 5 | 2.6.16 Socio UYLUG Nro 125 From benji at benjiyork.com Tue May 2 17:57:29 2006 From: benji at benjiyork.com (Benji York) Date: Tue, 02 May 2006 17:57:29 -0400 Subject: ConfigParser and multiple option names In-Reply-To: <e37rji$c46$1@news.in.tum.de> References: <e37rji$c46$1@news.in.tum.de> Message-ID: <4457D5C9.7020906@benjiyork.com> Florian Lindner wrote: > since ConfigParser does not seem to support multiple times the same option > name, like: > > dir="/home/florian" > dir="/home/john" > dir="/home/whoever" I generally do this: dirs = /home/florian /home/john /home/whoever ...and then use str.split() in my program. -- Benji York From deets at nospam.web.de Wed May 17 11:18:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 17 May 2006 17:18:11 +0200 Subject: List behaviour References: <1147878414.819145.88580@i40g2000cwc.googlegroups.com> Message-ID: <4d0t5mF17r7maU1@uni-berlin.de> barberomarcelo at gmail.com wrote: > Maybe I'm missing something but the latter is not the behaviour I'm > expecting: > >>>> a = [[1,2,3,4], [5,6,7,8]] >>>> b = a[:] >>>> b > [[1, 2, 3, 4], [5, 6, 7, 8]] >>>> a == b > True >>>> a is b > False >>>> for i in range(len(b)): > ... for x in range(4): > ... b[i][x] = b[i][x] + 10 > ... >>>> b > [[11, 12, 13, 14], [15, 16, 17, 18]] >>>> a > [[11, 12, 13, 14], [15, 16, 17, 18]] >>>> b = a[:] does clone a, but doesn't make a deepcopy of its contents, which you are manipulating! So do [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. poWelcome to rlcompleter2 0.96 for nice experiences hit <tab> multiple times >>> import copy >>> a = [[10]] >>> b = copy.deepcopy(a) >>> b[0][0] = 20 >>> a [[10]] >>> b [[20]] >>> HTH, Diez From ziggy at fakedaddress.com Thu May 25 18:49:35 2006 From: ziggy at fakedaddress.com (ziggy) Date: Thu, 25 May 2006 18:49:35 -0400 Subject: [ANNOUNCE] Thirty-second release of PythonCAD now available References: <mailman.6209.1148591765.27775.python-list@python.org> Message-ID: <ziggy-F06524.18493525052006@news.isp.giganews.com> In article <mailman.6209.1148591765.27775.python-list at python.org>, "Art Haas" <ahaas at airmail.net> wrote: > Hi. > > I'm pleased to announce the thirty-second development release of PythonCAD, > a CAD package for open-source software users. As the name implies, > PythonCAD is written entirely in Python. The goal of this project is > to create a fully scriptable drafting program that will match and eventually > exceed features found in commercial CAD software. PythonCAD is released > under the GNU Public License (GPL). > > PythonCAD requires Python 2.2 or newer. The interface is GTK 2.0 > based, and uses the PyGTK module for interfacing to GTK. The design of > PythonCAD is built around the idea of separating the interface > from the back end as much as possible. By doing this, it is hoped > that both GNOME and KDE interfaces can be added to PythonCAD through > usage of the appropriate Python module. Addition of other PythonCAD > interfaces will depend on the availability of a Python module for that > particular interface and developer interest and action. > > The thirty-second release fixes a configuration problem where the > newly added autosplitting feature would not be activated properly > or could disable autosplitting in a Layer. A small bug in the > reworked splitting code was also fixed, as well as a few other > small errors. > > A mailing list for the development and use of PythonCAD is available. > Visit the following page for information about subscribing and viewing > the mailing list archive: > > http://mail.python.org/mailman/listinfo/pythoncad > > Visit the PythonCAD web site for more information about what PythonCAD > does and aims to be: > > http://www.pythoncad.org/ > > Come and join me in developing PythonCAD into a world class drafting > program! > > Art Haas Cool. From grante at visi.com Mon May 1 13:02:12 2006 From: grante at visi.com (Grant Edwards) Date: Mon, 01 May 2006 17:02:12 -0000 Subject: How to efficiently read binary files? References: <zda5g.5247$nV4.1486@trnddc04> <125acgep357kbd8@corp.supernews.com> <mailman.5165.1146434636.27775.python-list@python.org> <125c8sbqsd7a952@corp.supernews.com> <mailman.5184.1146501930.27775.python-list@python.org> Message-ID: <125cfokq609se5d@corp.supernews.com> On 2006-05-01, Robert Kern <robert.kern at gmail.com> wrote: >>>>Perhaps the numarray module? >>> >>>numpy for new code, please. >> >> So numarray and numpy were both written to replace numeric? > > numpy was written to replace both Numeric and numarray. too many batteries... ;) -- Grant Edwards grante Yow! ... bleakness... at desolation... plastic visi.com forks... From sjmachin at lexicon.net Sun May 14 19:41:19 2006 From: sjmachin at lexicon.net (John Machin) Date: 14 May 2006 16:41:19 -0700 Subject: comparing values in two sets References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> Message-ID: <1147650079.597881.285730@j73g2000cwa.googlegroups.com> John Salerno wrote: > I'd like to compare the values in two different sets to test if any of > the positions in either set share the same value (e.g., if the third > element of each set is an 'a', then the test fails). > > I have this: > > def test_sets(original_set, trans_letters): > for pair in zip(original_set, trans_letters): > if pair[0] == pair[1]: > return False > return True > > > zip() was the first thing I thought of, but I was wondering if there's > some other way to do it, perhaps a builtin that actually does this kind > of testing. There is no such concept as "position in [a] set". Sets in math[s]/logic are *NOT* ordered. The order in which Python retrieves elements when you do (for example) list(a_set) is a meaningless artefact of the implementation du jour, and is not to be relied on. >>> s = set(['xyzzy', 'plugh', 'sesame']) >>> t = set(['xyzzy', 'plugh', 'mellon']) >>> s set(['sesame', 'plugh', 'xyzzy']) >>> t set(['plugh', 'mellon', 'xyzzy']) >>> zip(s, t) [('sesame', 'plugh'), ('plugh', 'mellon'), ('xyzzy', 'xyzzy')] >>> You may need one or more of these: >>> s & t set(['plugh', 'xyzzy']) >>> s ^ t set(['sesame', 'mellon']) >>> s | t set(['sesame', 'plugh', 'mellon', 'xyzzy']) >>> (s | t) - t set(['sesame']) >>> (s | t) - s set(['mellon']) >>> If that doesn't meet your needs: back up a level and tell us what you are trying to achieve If True: read about sets in the Python docs HTH, John From jairodsl at gmail.com Wed May 3 00:38:00 2006 From: jairodsl at gmail.com (jairodsl) Date: 2 May 2006 21:38:00 -0700 Subject: UPGMA algorithm ??? In-Reply-To: <mailman.5247.1146630513.27775.python-list@python.org> References: <1146629951.014136.121890@y43g2000cwc.googlegroups.com> <mailman.5247.1146630513.27775.python-list@python.org> Message-ID: <1146631080.248316.137690@j73g2000cwa.googlegroups.com> thank you, google works fine, but dont show me that i expect. thanks again. jDSL From me+python at modelnine.org Thu May 18 12:50:56 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 18 May 2006 18:50:56 +0200 Subject: Python - Web Display Technology In-Reply-To: <1147961355.652526.230610@i39g2000cwa.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <mailman.5872.1147945818.27775.python-list@python.org> <1147961355.652526.230610@i39g2000cwa.googlegroups.com> Message-ID: <200605181850.56796.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 16:09 schrieb SamFeltus: > I guess there isn't much to understand. Sure, there's a lot to understand here. What I guess you can't come to terms with is the fact that the web (hell, the whole Internet) isn't designed for Windows personal computers only, but for a whole range of computer systems which need to interoperate. For that, you need standards. And: Flash isn't one, and will never become one. Simply, because it's full of bad design decisions, and because the company that has the "power" over Flash doesn't want to make it an open standard. At least I don't see that happen any time soon. > If you are satisfied with a > text based, static image web, that is light on artistic possabilities, > all that HTML stuff is acceptable. Are you actually familiar with what you can do with JavaScript and HTML/CSS? CSS is pretty powerful. Hell, it's very powerful, even. And: why do I need animated graphics to convey _information_ to a user? I don't surf the web to have the feeling of walking through an art gallery, but rather surf the web to gather information I need for my daily life. And: HTML is designed for that explicitly. CSS too (as in proper presentation of the content you're trying to convey to the user). And even JavaScript is designed to deal with _content_, not with pretty but meaningless graphical imagery. I'm not saying that graphics can't convey meaning. But: the tools to deal with images are sufficiently advanced in HTML and CSS that I can display any kind of graphic imagery I need to convey the information to the user. > Perhaps the HTML/JS group will even > get off their rear ends and bring some decent cross platform graphics > capabilities to the web one decade? Perhaps even bring some 90's style > graphics to the browser one decade? Same as before: do you actually know what the HTML group (well, the W3C) is doing? They are a very active group, have designed an open format for vector graphics (SVG, which has been referenced here before), and actually have the guts to stand up to MickeySoft and their lackeys to keep the format open, and to keep development of further extensions open. This is technological advancement at work. Not some company like Macromedia trying to design a proprietary, insufficiently engineered format, that's just there so that people who think they need to burry the information they are trying to convey to the user in graphic imagery so that noone will notice that there's no actual content in what they are trying to tell you. --- Heiko. From rNOSPAMon at flownet.com Thu May 18 20:06:13 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 May 2006 17:06:13 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> <mailman.5917.1147995329.27775.python-list@python.org> Message-ID: <rNOSPAMon-86BDAA.17061318052006@news.gha.chartermi.net> In article <mailman.5917.1147995329.27775.python-list at python.org>, Robert Kern <robert.kern at gmail.com> wrote: > Ron Garret wrote: > > > I'm using an OS X terminal to ssh to a Linux machine. > > Click on the "Terminal" menu, then "Window Settings...". Choose "Display" > from > the combobox. At the bottom you will see a combobox title "Character Set > Encoding". Choose "Unicode (UTF-8)". It was already set to UTF-8. > > But what about this: > > > >>>>f2=open('foo','w') > >>>>f2.write(u'\xFF') > > > > Traceback (most recent call last): > > File "<stdin>", line 1, in ? > > UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in > > position 0: ordinal not in range(128) > > > > That should have nothing to do with my terminal, right? > > Correct, that is a different problem. f.write() expects a string of bytes, > not a > unicode string. In order to convert unicode strings to byte strings without > an > explicit .encode() method call, Python uses the default encoding which is > 'ascii'. It's not easily changeable for a good reason. Your modules won't > work > on anyone else's machine if you hack that setting. OK. > > I just found http://www.amk.ca/python/howto/unicode, which seems to be > > enlightening. The answer seems to be something like: > > > > import codecs > > f = codecs.open('foo','w','utf-8') > > > > but that seems pretty awkward. > > <shrug> About as clean as it gets when dealing with text encodings. OK. Thanks. rg From mhellwig at xs4all.nl Wed May 3 16:36:49 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Wed, 03 May 2006 22:36:49 +0200 Subject: This coding style bad practise? Message-ID: <44591463$0$31639$e4fe514c@news.xs4all.nl> Hi all, I created a class which creates a relative unique id string, now my program just works fine and as expected but somehow I get the feeling that I misused the __repr__ since I guess people expect to 'execute' a function in an instance instead of using it's representation string of the instance itself, could you elaborate whether you find this bad practice and if yes what would have been a better way to do it? TIA ----- script ----- > import string > import time > > class IDGenerator(object): > """(serverID,subversion_length) > Create an ID from the server name, datetimestamp and version number. > Calling the instance returns the ID using the __repr__ class function > > Example usage: > >>> id = idgen('01',4) > >>> id > 01_20060424_151903_1 > >>> id > 01_20060424_151905_2 > >>> id > 01_20060424_151905_3 > >>> id > 01_20060424_151906_4 > >>> id > 01_20060424_151907_1 > >>> > >>> id = idgen(04,100) > >>> id > 4_20060424_152043_001 > > """ > > def __init__(self,serverID,subversion_length): > self.ID = str(serverID) > self.length = int(subversion_length) > fill_length = len(str(self.length)) > > def fill(number): > return(string.zfill(number,fill_length)) > self.fill = fill > > > def __repr__(self): > # If the subversion length has been reached or the generator has not > # been defined, (re)define it, otherwise return the next value of the > # subversion. > try: > return_value = self.range_gen.next() > > except: > self.range_gen = ( number for number in range(1,self.length+1) ) > return_value = self.range_gen.next() > > # Create the version stamp. > return_value = self.ID +\ > time.strftime("_%Y%m%d_%H%M%S_",time.gmtime())+\ > self.fill(return_value) > > # And return it. > return(return_value) ----- script ----- -- mph From nospam at nospam.nospam Tue May 16 02:58:35 2006 From: nospam at nospam.nospam (Nic) Date: Tue, 16 May 2006 08:58:35 +0200 Subject: List and order References: <446842f7$0$14785$4fafbaef@reader4.news.tin.it> <1147691967.998184.285120@u72g2000cwu.googlegroups.com> <446872cb$0$18288$4fafbaef@reader1.news.tin.it> <e49u2k$3i2$02$1@news.t-online.com> <4468a8b7$0$29719$4fafbaef@reader2.news.tin.it> <e4aahn$l16$01$1@news.t-online.com> Message-ID: <44697821$0$14775$4fafbaef@reader4.news.tin.it> Perfect. Thanks. Nic "Peter Otten" <__peter__ at web.de> ha scritto nel messaggio news:e4aahn$l16$01$1 at news.t-online.com... > Nic wrote: > >> The only problem is that from: >> 12 >> 22 >> 21 >> In spite of writing >> 12 12 22 >> it writes >> 12 21 22 >> Do you know how is it possible to delete also this last trouble? > > I thought that the two 12 were a typo, but it seems you want to reorder > the > nodes inside an edge, too. Here's a fix that normalizes the edge before > sorting the list of edges: > > edges = [sorted((ddeg[u], ddeg[v])) for u, v in G.edges()] > edges.sort() > for a, b in edges: > print a, b, > print > > Peter > > From beliavsky at aol.com Wed May 10 20:25:04 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 10 May 2006 17:25:04 -0700 Subject: Econometrics in Panel data? References: <445fbefb$0$3245$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <07l062li47gjhuskkkqsai7kji82fpfjnq@4ax.com> <44606dd5$0$3285$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <mub6j3-sne.ln1@lairds.us> <ff67j3-fih.ln1@lairds.us> Message-ID: <1147307104.586106.63890@g10g2000cwb.googlegroups.com> Cameron Laird wrote: > In article <mub6j3-sne.ln1 at lairds.us>, I counseled: > >In article <44606dd5$0$3285$5a62ac22 at per-qv1-newsreader-01.iinet.net.au>, > >DeepBlue <123 at 321.com> wrote: > >>so are you saying that Python is not an appropriate language for doing > >>econometrics stuff? > >> > >> > >>Dennis Lee Bieber wrote: > >>> On Tue, 09 May 2006 05:58:10 +0800, DeepBlue <123 at 321.com> declaimed the > >>> following in comp.lang.python: > >>> > >>>> Hi all, > >>>> > >>>> I am new to Python. Just wondering can Python able to do econometric > >>>> regression in either Time-series or pooled (panel) data? As well as test > >>>> for hetero, autocorrelation, or endogeneity? > . > . > . > >There is not, however, a readily-accessible library targeted > >for this sort of work. If I had the opportunity to work in > >econometrics now, I'd think seriously about R, Lisp, and > >Mathematica, and see what's available among the functional > >languages, along with Python. > > Smalltalk, too; I'd throw it in the mix. Much serious econometrics > has been done with Fortran, but I have no enthusiasm for pursuing > that direction, mostly because I think too much of the computing > world is going in a different one. There are many statistics packages and programming languages used in econometrics and in general, so most of the computing world is going in a different "direction", no matter which package or language you choose. Enough programmers still use Fortran that major hardware vendors such as Intel, IBM, and Sun are actively maintaining their Fortran 95 compilers and adding features from Fortran 2003. G95 is free, available almost everywhere that gcc is, and good enough for production use IMO. The recent book http://methcenter.psu.edu/newbooks/fortranbook/thebook.html Developing Statistical Software in Fortran 95 by David R. Lemmon and Joseph L. Schafer Spriger (2005) discusses how to build statistical software components in Fortran that can be used in statistical packages. The IMSL and NAG software libraries have extensive statistical functionality and are available in Fortran, among other languages. It is important for a programming language used for econometrics to conveniently handle multidimensional arrays, and here Fortran outshines C, C++, and Java (NumPy is good, though). I am a quantitative financial analyst who implements econometrics algorithms. Data sets are getting bigger -- use of intraday data is now common -- and the CPU time for many algorithms scales as the N^2 or N^3, where N is the number of observations. Speed still matters. From nobody at 127.0.0.1 Wed May 17 16:46:12 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 20:46:12 GMT Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <slrne6mkt5.hoa.sybrenUSE@schuimige.stuvel.eu> <_2Jag.88816$dW3.57801@newssvr21.news.prodigy.com> <kurm62ph2d18bcal7jkm08q0dohmlg6nll@4ax.com> Message-ID: <oYLag.18303$Lm5.11202@newssvr12.news.prodigy.com> Dave Hansen wrote: > On Wed, 17 May 2006 17:28:26 GMT in comp.lang.python, Edward Elliott >>Just for the sake of completeness: >> >>cat file |sed 's/\t/ /g' > > That doesn't always work. If you don't see why, you don't understand > my objection to TAB characters in text files. > >>less -x4 file > > That will work. As long as the creator of file used four-space TABs, > anyway... I fail to see why less 'will work' but cat 'doesn't always work'. The net effect of both is the same. Unless you're in some weird place that pipes aren't allowed, these should be equivalent: cat file |sed 's/\t/ /g' |less less -x4 file Now if you're talking about the conversion altering the data's semantics, that's a separate issue that has nothing to do with unix utilities and everything to do with the file formatting. In that case, I'll simply refer you to the rest of this thread for discussion. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From me at privacy.net Wed May 10 15:59:14 2006 From: me at privacy.net (Dan Sommers) Date: Wed, 10 May 2006 15:59:14 -0400 Subject: data entry tool References: <445f038f@news.maxnet.co.nz> <4c8gkoF14mu9cU1@uni-berlin.de> <4461a499@news.maxnet.co.nz> <1147267750.833367.234180@v46g2000cwv.googlegroups.com> <446236d5@news.maxnet.co.nz> Message-ID: <m21wv1ejn1.fsf@unique.fqdn> On Thu, 11 May 2006 06:54:14 +1200, Peter <nospamjynyl at yahoo.co.nz> wrote: > Serge Orlov wrote: [ ... ] >> Keep in mind that standalone application for windows will be about >> 2Mb. > Wow - why so big for such a simple tool? > 2MB sounds like a LOT of coding. Actually, just the opposite: that's 2MB of things someone else wrote in order that your application code remain small. Regards, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From jeremy at emperorlinux.com Fri May 26 12:54:20 2006 From: jeremy at emperorlinux.com (Jeremy L. Moles) Date: Fri, 26 May 2006 12:54:20 -0400 Subject: chop() and empty() functions Message-ID: <1148662460.2149.20.camel@localhost.localdomain> I've been using the following lambda/function for a number of months now (I got the idea from someone in #python, though I don't remember who): def chop(s, n): """Chops a sequence, s, into n smaller tuples.""" return zip(*[iter(s)] * n) ...or... chop = lambda s, n: zip(*[iter(s)] * n) I was wondering if something like this already exists in Python proper somewhere, perhaps in an optimized way? (I checked itertools, but I didn't see anything right away). Furthermore, what do people think about the idea of adding a truly empty, no-op global lambda somewhere in Python? I use them a lot (usually defining a: empty = lambda *a, **k: None somewhere at the topmost module space), but if enough people did too, it might be worth adding an empty() builtin to much later versions of Python. Anyways, if these are stupid ideas I'm not surprised. Just some things I've been thinking about and figured I'd toss out there on my lunch break. :) From johnjsal at NOSPAMgmail.com Wed May 3 14:16:03 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 03 May 2006 18:16:03 GMT Subject: what is the 'host' for SMTP? In-Reply-To: <pan.2006.05.03.17.40.51.38448@hastings.org> References: <44581205$0$25583$c3e8da3@news.astraweb.com> <pan.2006.05.03.03.42.28.745634@hastings.org> <IB46g.2043$No6.43969@news.tufts.edu> <pan.2006.05.03.17.40.51.38448@hastings.org> Message-ID: <Dr66g.2044$No6.44066@news.tufts.edu> Steve R. Hastings wrote: > On Wed, 03 May 2006 16:10:16 +0000, John Salerno wrote: >> If all I >> put in is, for example, smtp.gmail.com, how is that directed to my own >> email address? > > The address of the SMTP server does not specify where the email will go. > SMTP is a protocol, and when you are talking SMTP to the server, part of > what the conversation includes will be to whom you wish to send the email. > > Please Google for information on SMTP. You can also start here: > > http://en.wikipedia.org/wiki/SMTP > Thanks, I'll give it a look. From bignose+hates-spam at benfinney.id.au Sun May 14 07:45:44 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 14 May 2006 21:45:44 +1000 Subject: send an email with picture/rich text format in the body References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> Message-ID: <87u07srfrr.fsf@benfinney.id.au> "anya" <anyab5 at gmail.com> writes: > I want to send an email message with picture in it. Please, reconsider. Email is a text medium. > I dont want to put it as attachment but make it in the body of the > mail, so every one who open the email will see the picture.. No, they won't; my email client displays only text, and that's the case for a great many people on the net. > Does anyone have a solution? If you want people to view something other than text, email is not what you want. Give a URL to the place where they can view what you want them to see; then they can choose a time when they are using a graphically capable terminal. -- \ "Why should I care about posterity? What's posterity ever done | `\ for me?" -- Groucho Marx | _o__) | Ben Finney From grante at visi.com Tue May 2 22:11:43 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 03 May 2006 02:11:43 -0000 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <RAN5g.2037$No6.43926@news.tufts.edu> <4457dadd$0$9654$636a55ce@news.free.fr> <44580e23$0$5389$c3e8da3@news.astraweb.com> Message-ID: <125g4avdtmbse83@corp.supernews.com> On 2006-05-03, John Salerno <johnjsal at NOSPAMgmail.com> wrote: > Bruno Desthuilliers wrote: > >> But my question (sorry, it may not have been clear) was more >> along the line of : "why do you worry about identity in the >> given snippet ?". > > Actually, I kind of thought that maybe it *didn't* matter in > this particular example anyway, so my question was meant to be > more general than I might have written it. It seems like the > identity issue can be a problem in certain cases, although I > can't think of a case right now! :) When it seems like the "identity issue" is a problem, that usually indicates you're looking at the problem from the wrong angle. 1/2 :) -- Grant Edwards grante Yow! I am having a at CONCEPTION-- visi.com From http Sun May 14 13:21:49 2006 From: http (Paul Rubin) Date: 14 May 2006 10:21:49 -0700 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> <tj2kj3-82b.ln1@lairds.us> Message-ID: <7x4pzswmhe.fsf@ruckus.brouhaha.com> claird at lairds.us (Cameron Laird) writes: > For that matter, would it be an advantage for len() to operate > on iterables? print len(itertools.count()) Ouch!! From bborcic at gmail.com Wed May 10 05:48:13 2006 From: bborcic at gmail.com (Boris Borcic) Date: Wed, 10 May 2006 11:48:13 +0200 Subject: simultaneous assignment In-Reply-To: <pan.2006.05.03.04.02.14.139249@hastings.org> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> <I9O5g.2039$No6.43918@news.tufts.edu> <pan.2006.05.02.19.35.15.219815@hastings.org> <4457b69b$1_1@news.bluewin.ch> <pan.2006.05.03.04.02.14.139249@hastings.org> Message-ID: <4461b6ec$1_6@news.bluewin.ch> Steve R. Hastings wrote: > You could also use a function that counts all different values in a list, > reducing the list to a dictionary whose keys are the unique values from > the list. I got the idea from a discussion here on comp.lang.python; I > called my version of it tally(). > > d = tally(bool(x) for x in seq) > print d[True] # prints how many true values in seq > print d[False] # prints how many false values in seq > > > tally() is in my iterwrap.py module, which you can get here: > > http://home.blarg.net/~steveha/iterwrap.tar.gz > >>> from itertools import groupby >>> tally = lambda it : dict((x,sum(1 for _ in y)) for x,y in groupby(sorted(it))) >>> tally('abbcabbcca') {'a': 3, 'c': 3, 'b': 4} From me+python at modelnine.org Tue May 2 17:51:46 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 23:51:46 +0200 Subject: Wake on LAN and Shutdown for Windows and Linux In-Reply-To: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> References: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> Message-ID: <200605022351.46872.me+python@modelnine.org> Am Dienstag 02 Mai 2006 21:02 schrieb diffuser78 at gmail.com: > Also, How can I shutdown other Linux terminals from my Main (Linux) ? Has this got anything to do with Python? --- Heiko. From tomlongridge at gmail.com Sat May 13 13:59:56 2006 From: tomlongridge at gmail.com (Tom Longridge) Date: 13 May 2006 10:59:56 -0700 Subject: PyX on Windows Message-ID: <1147543196.035109.15310@j73g2000cwa.googlegroups.com> Hi, I'm trying to use PyX to draw some diagrams with text in. I want to change the font, so need to change the text mode from TeX to LaTeX. However I get an error when I do so: pyx.text.TexResultError: unhandled TeX response (might be an error) The expression passed to TeX was: \documentclass{article}% \PyXInput{3}% After parsing the return message from TeX, the following was left: * *(C:\Program Files\MiKTeX\tex\latex\base\article.cls Document Class: article 2004/02/16 v1.4f Standard LaTeX document class (C:\Program Files\MiKTeX\tex\latex\base\size10.clo)) I'm using MikTek on Windows to run LaTeX; does anyone know if is this likely to be the problem? Many thanks, Tom From lunz at falooley.org Sat May 27 11:17:53 2006 From: lunz at falooley.org (Jason Lunz) Date: Sat, 27 May 2006 15:17:53 +0000 (UTC) Subject: monkeypatching NamedTemporaryFile References: <mailman.6216.1148614516.27775.python-list@python.org> <1148719498.352149.251740@38g2000cwa.googlegroups.com> Message-ID: <e59qj1$q81$1@sea.gmane.org> craighse888 at googlemail.com said: > Maybe that should be the default behaviour. Presumably the file has > been deleted by some other process? The use case is that a NamedTemporaryFile was used to securely create and populate a file, which is then atomically (on posix) os.rename()d to its final location. If any error occurs prior to the rename, NamedTemporaryFile takes care of deleting the tempfile on the error path. But in the success case, NamedTemporaryFile causes an unsightly "ignored exception" message on stderr when it fails to unlink the now-nonexistent tempfile. Jason From andrew.arobert at gmail.com Mon May 22 14:24:32 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Mon, 22 May 2006 14:24:32 -0400 Subject: Class probkem - getting msg that self not defined Message-ID: <12740frcoaju883@corp.supernews.com> Hi Everyone, I am having a problem with a class and hope you can help. When I try to use the class listed below, I get the statement that self is not defined. test=TriggerMessage(data) var = test.decode(self.qname) I would have thought that self would have carried forward when I grabbed an instance of TriggerMessage. Any ideas on this? The class in question is: class TriggerMessage(object): def __init__(self,data): """ Unpacks the passed binary data based on the MQTCM2 format dictated in the MQ Application Programming Reference """ self.data=data self.structid=None self.version=None self.qname=None self.procname=None self.trigdata=None self.appltype=None self.applid=None self.envdata=None self.userdata=None self.qmgr=None def decode(self): import struct format='4s 4s 48s 48s 64s 4s 256s 128s 128s 48s' size=struct.calcsize(format) self.data=data self.structid, self.version, self.qname, self.processname, \ self.triggerdata, self.appltype, self.applid, \ self.envdata, self.userdata, self.qmgr \ = struct.unpack(format,self.data) From johnjsal at NOSPAMgmail.com Wed May 24 10:50:08 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 24 May 2006 14:50:08 GMT Subject: Python Programming Books? In-Reply-To: <1148474604.279491.71090@j55g2000cwa.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <1148474604.279491.71090@j55g2000cwa.googlegroups.com> Message-ID: <Ao_cg.2162$No6.46749@news.tufts.edu> vbgunz wrote: > Learning Python by Mark Lutz will be the most perfect book to get you > started! Perhaps there are others aimed at the non-programmer but after > getting through that book (2 times) I finally left it with wings... It > is a great book for the n00b in my humble opinion. After that, you'll > pretty much start flying higher on your own as long as you always keep > the python docs handy along with the addresses to comp.lang.python and > it's IRC channel #python on irc.freenode.net... > > Good luck, welcome to Python! > I second this opinion completely. Use this book to start with! It is a wonderful intro to the language and will give you a solid foundation. As for waiting for a 3rd edition, don't do it! If you're like me, you'll want the latest there is, so I was tempted to start with something newer too (since this book covers up to 2.2), but honestly it covers everything you need to know. There are maybe two or three new additions that you can read about elsewhere, but Learning Python is THE book to start with, IMO. Get it now! :) From sjmachin at lexicon.net Mon May 29 21:33:46 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 30 May 2006 11:33:46 +1000 Subject: How to calc easier the "long" filesize from nFileSizeLow and nFileSizeHigh In-Reply-To: <mailman.6311.1148917245.27775.python-list@python.org> References: <mailman.6311.1148917245.27775.python-list@python.org> Message-ID: <447BA0FA.5000200@lexicon.net> On 30/05/2006 1:40 AM, DurumDara wrote: > Hi ! > > I get the file datas with FindFilesW. > I want to calc the filesize from nFileSizeLow and nFileSizeHigh with > easiest as possible, without again calling os.getsize(). > How to I do it ? I need good result ! > > Thanx for help: > dd Hello, *again*, dd Well I've never heard of this caper before but what I'd do would be a Google search for e.g. nFileSizeHigh and read the first few articles ... in particular the first one which warns about bulldust on the MS website :-) HTH, John P.S. You have heard of Google, haven't you? From cvanarsdall at mvista.com Wed May 17 14:26:25 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 17 May 2006 11:26:25 -0700 Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) In-Reply-To: <e4fofp$8sp$1@sea.gmane.org> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> Message-ID: <446B6AD1.4080104@mvista.com> Andy Sy wrote: > achates wrote: > > >> Andy Sy: >> >>> Code with anything other than 8-space tabs will *NEVER* display >>> properly using everyday unix utilities such as less and cat. >>> >> less -x<tabstop> does what you want. >> >> > > > Ok, that tip certainly counts for something. This is > definitely going to make viewing tabbed code suck much > less (although you still have to guess the tab setting > using trial and error). > > > Next major objection then, how can one practically use 'tabs as > semantic indentation' without screwing up formatting of code like > the below?? > > > def sqlcall(): > cursor.execute('select id, item, amount, field4, field5, field6'+ > 'from table1 where amount>100') > > Why couldn't you tab your third line over as close as possible to the start of the quote then use a couple spaces? Then the tabs would work just fine and you could still have your pretty line. .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From mike.barry at gmail.com Mon May 1 16:56:58 2006 From: mike.barry at gmail.com (juxstapose) Date: 1 May 2006 13:56:58 -0700 Subject: Difference between threading.local and protecting data with locks Message-ID: <1146517018.585434.218870@i39g2000cwa.googlegroups.com> Hello, I have been develop a blocking socket application with threading. The main thread handles connections and inserts them into python's protected queue as jobs for the thread pool to handle. There is not much information on threading.local except that it states that in maintains variable uniqueness among multiple instances of the same thread. I am assuming that it implements some sort of locking functionality under the covers? Is it possible to run into a race condition using threading.local? In a non-blocking threaded socket receive handler is it better to use a threading.local variable for writes or protect the write with a lock.acquire/lock.release ? I know the size of the incoming request so the receive handler finishes when the max size is reached. However in case of network problems I also have timeout functionality. Both of these behaviors require writing to variables in a possible critical section. What is the best way to handle writes in a multi-threaded non-blocking receive handler? From chris.cavalaria at free.fr Tue May 9 05:31:42 2006 From: chris.cavalaria at free.fr (Christophe) Date: Tue, 09 May 2006 11:31:42 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <mailman.5357.1146820360.27775.python-list@python.org> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com><4457cb5b$0$16422$626a54ce@news.free.fr> <1146634135.469447.54670@j73g2000cwa.googlegroups.com><mailman.5248.1146637412.27775.python-list@python.org> <445880e8$0$27057$626a54ce@news.free.fr><mailman.5305.1146727852.27775.python-list@python.org> <4459c1e5$0$2617$636a55ce@news.free.fr> <mailman.5357.1146820360.27775.python-list@python.org> Message-ID: <446061c4$0$30014$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > Christophe wrote: > > >>I think you've made a mistake in your example. > > > >>> constant A = [] > >>> def foo(var): > ... var.append('1') > ... print var > ... > >>> b = A > >>> foo(b) > >>> foo(b) > > >>>and this ? >>> >>> >>> constant A = [] >>> >>> print A is A >> >>Obviously, False. > > > why obviously ? why shouldn't a constant be constant ? > > </F> Because the name A is bound by the compiler to mean construct a new object since [] is mutable. Same reason why : >>> def A(): return [] >>> print A() is A() False It gives btw one possible implementation ;) From nobody at 127.0.0.1 Sun May 14 23:50:42 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 15 May 2006 03:50:42 GMT Subject: help using smptd References: <FHM9g.6356$fb2.6054@newssvr27.news.prodigy.net> Message-ID: <mUS9g.76811$H71.15059@newssvr13.news.prodigy.com> Edward Elliott wrote: > import smtpd > > class SMTPProxy (smtpd.SMTPServer): > def process_message (self, peer, mailfrom, rcpttos, data): > # my code here > > proxy = SMTPProxy (listen_addr, relay_addr) > # now what? Update: I think I've solved it. SMTPServer registers with asyncore, so the 'now what' to handle connections is this: asyncore.loop() I tried that once before I posted without success, however I think I had accidentally closed the socket already. Now a follow-up question: does anyone know the purpose of the timeout parameter to loop()? The asyncore docs say this: "The timeout argument sets the timeout parameter for the appropriate select() or poll() call, measured in seconds; the default is 30 seconds." According to the select man page, timeout determines how long it blocks before returning. But AFAICT, asyncore.loop() runs forever (as long as a channel is open) no matter how long select blocks. What's the point of passing a timeout for select when loop just calls it again every time it returns? -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From rNOSPAMon at flownet.com Thu May 18 19:12:10 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 May 2006 16:12:10 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> Message-ID: <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> In article <1147992722.970761.220840 at j73g2000cwa.googlegroups.com>, "Serge Orlov" <Serge.Orlov at gmail.com> wrote: > Ron Garret wrote: > > In article <mailman.5906.1147989402.27775.python-list at python.org>, > > Robert Kern <robert.kern at gmail.com> wrote: > > > > > Ron Garret wrote: > > > > > > > I forgot to mention: > > > > > > > >>>>sys.getdefaultencoding() > > > > > > > > 'utf-8' > > > > > > A) You shouldn't be able to do that. > > > > What can I say? I can. > > > > > B) Don't do that. > > > > OK. What should I do instead? > > Exact answer depends on what OS and terminal you are using and what > your program is supposed to do, are you going to distribute the program > or it's just for internal use. I'm using an OS X terminal to ssh to a Linux machine. But what about this: >>> f2=open('foo','w') >>> f2.write(u'\xFF') Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in position 0: ordinal not in range(128) >>> That should have nothing to do with my terminal, right? I just found http://www.amk.ca/python/howto/unicode, which seems to be enlightening. The answer seems to be something like: import codecs f = codecs.open('foo','w','utf-8') but that seems pretty awkward. rg From llosee at gmail.com Sat May 13 12:17:42 2006 From: llosee at gmail.com (Lou Losee) Date: Sat, 13 May 2006 12:17:42 -0400 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <pqna621sn8s3qk56dt58qsnud6olbammfv@4ax.com> References: <jz09g.2091$No6.46071@news.tufts.edu> <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> <pqna621sn8s3qk56dt58qsnud6olbammfv@4ax.com> Message-ID: <a6a837f50605130917p5694ec35y2800e5f9235ee987@mail.gmail.com> On 5/13/06, Dennis Lee Bieber <wlfraed at ix.netcom.com> wrote: > > On Fri, 12 May 2006 21:00:49 -0400, John Salerno > <johnjsal at NOSPAMgmail.com> declaimed the following in comp.lang.python: > > > > > Latest development: I turned off my firewall and it worked. :) > > Next step -- figure out what rule you need to define to the > firewall > to permit it to work... > -- > Wulfraed Dennis Lee Bieber KD6MOG > wlfraed at ix.netcom.com wulfraed at bestiaria.com > HTTP://wlfraed.home.netcom.com/ > (Bestiaria Support Staff: web-asst at bestiaria.com) > HTTP://www.bestiaria.com/ > -- > http://mail.python.org/mailman/listinfo/python-list > The default port that the MySQL server listens on is 3306. This can be changed during install. -- Artificial Intelligence is no match for Natural Stupidity -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060513/931e8138/attachment.html> From robert.kern at gmail.com Wed May 3 00:28:11 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 02 May 2006 23:28:11 -0500 Subject: UPGMA algorithm ??? In-Reply-To: <1146629951.014136.121890@y43g2000cwc.googlegroups.com> References: <1146629951.014136.121890@y43g2000cwc.googlegroups.com> Message-ID: <e39bgr$noq$1@sea.gmane.org> jairodsl wrote: > Hello ! > > I have searching this algorithm (UPGMA) writting in python, i didnt > found, could anybody help me ??? Thanks a lot!!! Is Google broken today? http://www.google.com/search?q=UPGMA+python -- 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 john at castleamber.com Tue May 30 21:28:32 2006 From: john at castleamber.com (John Bokma) Date: 31 May 2006 01:28:32 GMT Subject: interactive programme (voice) References: <mailman.6340.1149026849.27775.python-list@python.org> Message-ID: <Xns97D3D0483799Acastleamber@130.133.1.4> "Bell, Kevin" <kevin.bell at slcgov.com> wrote: > http://www.cs.unc.edu/~parente/tech/tr02.shtml Thanks! -- 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 sybrenUSE at YOURthirdtower.com.imagination Wed May 31 06:17:11 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 31 May 2006 12:17:11 +0200 Subject: shuffling elements of a list References: <1149045499.212967.13120@f6g2000cwb.googlegroups.com> <mailman.6345.1149049261.27775.python-list@python.org> <1149051212.139046.155340@c74g2000cwc.googlegroups.com> <otpq72t7c1n3puh4omc42k3f98db968lhs@4ax.com> Message-ID: <slrne7qr97.8hm.sybrenUSE@schuimige.stuvel.eu> David C Ullrich enlightened us with: > I thought that the fact that you could use the same trick for > _shuffling_ a list was my idea, gonna make me rich and famous. I > guess I'm not the only one who thought of it. Anyway, you can use > DSU to _shuffle_ a list by decorating the list with random numbers. This is often done in database queries that need to randomize the data ;-) Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From h.b.furuseth at usit.uio.no Tue May 2 17:37:43 2006 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Tue, 02 May 2006 23:37:43 +0200 Subject: Dispatching operations to user-defined methods Message-ID: <hbf.20060502stiz@bombur.uio.no> I'm wondering how to design this: An API to let a request/response LDAP server be configured so a user-defined Python module can handle and/or modify some or all incoming operations, and later the outgoing responses (which are generated by the server). Operations have some common elements, and some which are distinct to the operation type (search, modify, compare, etc). So do responses. There are also some "operations" used internally by the server - like checking if the current session has access to perform the operation it requested. The server will have various internal classes for operations and data in operations, and methods for the user to access them. One obvious implementation would be to provide a class Operation, let the user define a single subclass of this, and have the server call request_search(), response_search(), request_modify(), check_access() etc in that subclass. Then I suppose the server would turn individual operations into instance of internal subclasses of the user's subclass - class SearchOperation(<user's class>), ModifyOperation(<user's class>) etc. Begins to look a bit messy now. And I'd like to try several methods - first try if the user defined response_search_entry() (one type of Search operation response), then response_search(), then response(), and after that give up. For that one, the Pythonic approach seems to be to define a class hierarchy for these, let the user subclass the subclasses and define request() and response() methods for them, and let Python handle the search for which request() method to use for which operation. And the server must keep track of which subclasses the user defined. This too feels a bit messy to me. Also there are plenty of operation parameters the user might wish to dispatch on, e.g. maybe he can handle Entry but not Referral search responses. I imagine it's more efficient to dispatch in a Python C module than to leave that to the user. But I may be getting too ambitious now. Anyway, ideas? Am I overlooking something obvious? -- Hallvard From Joel.Hedlund at gmail.com Sat May 6 13:36:14 2006 From: Joel.Hedlund at gmail.com (Joel.Hedlund at gmail.com) Date: 6 May 2006 10:36:14 -0700 Subject: Is this a good use of __metaclass__? In-Reply-To: <445baf1a$0$2386$626a54ce@news.free.fr> References: <e3f96d$3oi$1@news.lysator.liu.se> <445baf1a$0$2386$626a54ce@news.free.fr> Message-ID: <1146936973.992372.275310@u72g2000cwu.googlegroups.com> I played around with my old code before I saw your post, and I believe I've found a solution that's a bit neater than what I had before. I thought I could just as well post it if you're interested and have the time. This one uses multiple inheritance, but it's legal and there's only one metaclass. When executed, this prints: Validating admin. Scary stuff done. Cheers! /Joel Here ya go! -------------------------------------------------------------------------- from decorator import decorator # Metaclass for decorating public methods: class DecoratePublicMethods(type): """Equip public methods of a class with a specified decorator. Class data members: decorator_attribute = '_public_method_decorator': <str> If this attribute of the class exists and evaluates to True, then it is used to decorate all public methods of the class. no_decoration_attribute = '_do_not_decorate': <str> If this attribute of the class exists it should contain a list of names of public methods that should not be decorated. """ decorator_attribute = '_public_method_decorator' no_decoration_attribute = '_do_not_decorate' def __new__(cls, classname, bases, classdict): decorator = classdict.get(cls.decorator_attribute, None) if not decorator: return type.__new__(cls,classname,bases,classdict) do_not_decorate = classdict.get(cls.no_decoration_attribute, []) for attr,item in classdict.items(): if not callable(item): continue if attr in do_not_decorate or attr.startswith('_'): continue classdict[attr] = decorator(item) return type.__new__(cls, classname, bases, classdict) # Some decorators: @decorator def validate_job(func, self, id, response, *pargs, **kwargs): """Bogus authentiction routine""" print "Validating job." return func(self, id, response, *pargs, **kwargs) @decorator def validate_user(func, self, id, response, *pargs, **kwargs): """Bogus authentiction routine""" print "Validating user." return func(self, id, response, *pargs, **kwargs) @decorator def validate_admin(func, self, id, response, *pargs, **kwargs): """Bogus authentiction routine""" print "Validating admin." return func(self, id, response, *pargs, **kwargs) # My API: class BaseAPI(object): __metaclass__ = DecoratePublicMethods class JobValidatedAPI(BaseAPI): _public_method_decorator = validate_job def do_routine_stuff(self, clientid, response, foo): print "Routine stuff done." class UserValidatedAPI(BaseAPI): _public_method_decorator = validate_user def do_mundane_stuff(self, clientid, response, moo): print "Mundane stuff done." class AdminValidatedAPI(BaseAPI): _public_method_decorator = validate_admin def do_scary_stuff(self, clientid, response, moose): print "Scary stuff done." ## FIXED: Multiple inheritance now legal. class FullAPI(JobValidatedAPI, UserValidatedAPI, AdminValidatedAPI): _public_method_decorator = None # Now this works: b = FullAPI() b.do_scary_stuff('bofh', 2, 3) -------------------------------------------------------------------------- From fredrik at pythonware.com Fri May 12 02:47:05 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 May 2006 08:47:05 +0200 Subject: syntax for -c cmd References: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> <bVM8g.85722$dW3.77269@newssvr21.news.prodigy.com> Message-ID: <e41b1e$2sk$2@sea.gmane.org> Edward Elliott wrote: > Now this is interesting. I broke the line up into separate arguments and it > seemed to work fine: > > $ python -c 'if 1==1: print "yes"' 'else: print "no"' > yes > > But then I tested the else branch and it produces no output: > $ python -c 'if 1==0: print "yes"' 'else: print "no"' > $ > > If putting the else in a separate arg unbinds it from the if, I would expect > a syntax error. If OTOH naked elses are allowed on the command line for > some odd reason, then this shouldn't happen: > > $ python -c 'else: print "no"' > File "<string>", line 1 > else: print "no" > ^ > SyntaxError: invalid syntax > > What's with the silent failure in the two-arg version? If the else arg is > syntactically acceptable, why doesn't it behave as expected? hint: $ python -c 'import sys; print sys.argv' 'else: print "no"' </F> From niemand.leermann at thomas-guettler.de Fri May 5 08:35:00 2006 From: niemand.leermann at thomas-guettler.de (Thomas Guettler) Date: Fri, 05 May 2006 14:35:00 +0200 Subject: Python for Perl programmers References: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> Message-ID: <pan.2006.05.05.12.35.00.830838@thomas-guettler.de> Am Thu, 04 May 2006 12:02:52 -0400 schrieb A.M: > Hi, > > > > Is there any efficient online resource or book that help experienced Perl > programmers to Python? You can try the examples of pleac: http://pleac.sourceforge.net/pleac_python/index.html This is the Per Cookbook translated into several languages. Thomas -- Thomas G?ttler, http://www.thomas-guettler.de/ E-Mail: guettli (*) thomas-guettler + de Spam Catcher: niemand.leermann at thomas-guettler.de From mpeters42 at gmail.com Wed May 10 14:52:43 2006 From: mpeters42 at gmail.com (mpeters42 at gmail.com) Date: 10 May 2006 11:52:43 -0700 Subject: reusing parts of a string in RE matches? References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <whq8g.2082$No6.45965@news.tufts.edu> Message-ID: <1147287162.914661.237370@i39g2000cwa.googlegroups.com> >From the Python 2.4 docs: findall( pattern, string[, flags]) Return a list of all ***non-overlapping*** matches of pattern in string.... By design, the regex functions return non-overlapping patterns. Without doing some kind of looping, I think you are out of luck. If you pattern is fixed, then a solution might be: >>>string = 'abababababababab' >>>pat = 'aba' >>>[pat for s in re.compile('(?='+pat+')').findall(string)] ['aba', 'aba', 'aba', 'aba', 'aba', 'aba', 'aba'] If the pattern is not fixed (i.e. 'a.a') then this method can still get a count of overlapping matches, but cannot get the individual match strings themselves. A simple loop should do in this case, though: >>> for i in range(len(string)): ... r= re.match(pat,string[i:]) ... if r: print r.group() ... aba aba aba aba aba aba aba From riklaunim at gmail.com Sun May 21 15:23:02 2006 From: riklaunim at gmail.com (=?ISO-8859-2?Q?piotr_mali=F1ski?=) Date: Sun, 21 May 2006 20:23:02 +0100 Subject: Does anybody know how to install PythonMagick? In-Reply-To: <1148228905.504465.75820@i40g2000cwc.googlegroups.com> References: <446f97fe.776259062@News.Individual.DE> <1148228905.504465.75820@i40g2000cwc.googlegroups.com> Message-ID: <1f7f7cf70605211223w4655849ew81f3494adeccf324@mail.gmail.com> python imaging library is more advanced and up to date :) try using this one. From kano.priv at gmail.com Wed May 17 10:13:22 2006 From: kano.priv at gmail.com (Lee Caine) Date: Wed, 17 May 2006 15:13:22 +0100 Subject: taking qoutes in arguments In-Reply-To: <8764k5r3s6.fsf@benfinney.id.au> References: <98063b170605150748h3d0fffddibd6f8de28fff3d4f@mail.gmail.com> <87k68mrisa.fsf@benfinney.id.au> <98063b170605160623h2eca5a04xf106264d7909ef8f@mail.gmail.com> <8764k5r3s6.fsf@benfinney.id.au> Message-ID: <98063b170605170713t42dff8ebh445d8460b7c76432@mail.gmail.com> oh, well you learn somthing new everyday, thanks for that :) oh and i typed the command and got '/bin/bash', means nothing at the moment but im sure it will thanks for your help Lee. -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060517/183b3eb7/attachment.html> From vwehren at home.nl Sat May 6 09:48:37 2006 From: vwehren at home.nl (Vincent Wehren) Date: Sat, 6 May 2006 14:48:37 +0100 Subject: Building Python (2.4.x) with Visual C++ 2005 Express Edition? References: <tr2dnYBW2uZDRsbZRVn-ig@comcast.com> Message-ID: <e3i9fk$911$1@news2.tilbu1.nb.home.nl> Heikki Toivonen" <heikki at osafoundation.org> wrote in message news:tr2dnYBW2uZDRsbZRVn-ig at comcast.com... |I did some searches but did not find any definitive answers as to | whether or not it should be possible to build Python 2.4+ with Microsoft | Visual C++ 2005 Express Edition. | | I tried it myself (have VC++ project files that work with Visual Studio | 2003 .NET commercial version, just opened and closed them in vcexpress | to convert the projects) and the compilation finished without errors | (although with a bunch of deprecation warnings). But when I try to run, | python crashes on startup. | | Has anyone gotten this to work? | | -- | Heikki Toivonen Looking at your post, I tried building 2.4.3 using Visual Studio 2005 Professional - but ran into trouble with the way signals are treated by the new CRT (which may be the error you are talking about). I saw there was a patch on http://sourceforge.net/tracker/index.php?func=detail&aid=1350409&group_id=5470&atid=305470 which apparently has been applied to 2.5a2 - which started fine after building debug. Maybe this helps? Regards, Vincent Wehren From blair.houghton at gmail.com Tue May 23 14:51:58 2006 From: blair.houghton at gmail.com (Blair P. Houghton) Date: 23 May 2006 11:51:58 -0700 Subject: Python - Web Display Technology In-Reply-To: <1148316580.043077.76310@y43g2000cwc.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148316580.043077.76310@y43g2000cwc.googlegroups.com> Message-ID: <1148410317.817145.278750@j73g2000cwa.googlegroups.com> dingbat at codesmiths.com wrote: > SamFeltus wrote: > > Here is a visual argument, > > http://samfeltus.com/swf/contact_globes.swf > > Here's a text-based argument. > > If I search Golge for "gardener, Athens, GA" then Google's spiders > won't have recorded your contact page. So I don't find you as a local > gardener, so I don't hire you for my mansion in Athens. > > Your contact page is arguably pretty, but pretty just isn't selling for > that particular sort of page. That's why Flash often comes with a heapin' helpin' o' metadata. --Blair From johnjsal at NOSPAMgmail.com Mon May 15 14:26:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 15 May 2006 18:26:01 GMT Subject: common practice for creating utility functions? Message-ID: <ZI3ag.2095$No6.46239@news.tufts.edu> Just a quickie for today: Is it common (and also preferred, which are two different things!) to create a function that has the sole job of calling another function? Example: for fun and exercise, I'm creating a program that takes a quote and converts it into a cryptogram. Right now I have four functions: convert_quote -- the main function that starts it all make_code -- makes and returns the cryptogram make_set -- called from make_code, converts the quote into a set so each letter gets only one coded letter test_sets -- makes sure a letter isn't assigned to itself So my first question is this: should I make a Cryptogram class for this, or are functions fine? If the latter, then back to my original point: can I do something like this: def convert_quote(quote): return make_code(quote) Or does it not make sense to have a function just call another function? From richie at entrian.com Mon May 15 08:58:01 2006 From: richie at entrian.com (Richie Hindle) Date: Mon, 15 May 2006 13:58:01 +0100 Subject: Large Dictionaries In-Reply-To: <1147699064.107490@teuthos> References: <1147699064.107490@teuthos> Message-ID: <hiug629hembcq6ii2ac1nrvcuu8cfn07bm@4ax.com> [Chris] > Has anyone written a fast hash module which is more optimal for > large datasets ? PyJudy might be what you're looking for, though I've never used it: http://www.dalkescientific.com/Python/PyJudy.html "Judy's key benefits are scalability, high performance, and memory efficiency. A Judy array is extensible and can scale up to a very large number of elements, bounded only by machine memory." ... "PyJudy arrays are similar to Python dictionaries and sets." -- Richie Hindle richie at entrian.com From Bulkan at gmail.com Sun May 14 20:14:06 2006 From: Bulkan at gmail.com (placid) Date: 14 May 2006 17:14:06 -0700 Subject: Threads In-Reply-To: <94e962h9jqkig61m7pseh42k1gg5d5t0j7@4ax.com> References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <jq8862dcirmmj5atp7tdv2q7t032ansquh@4ax.com> <1147417744.770080.11490@q12g2000cwa.googlegroups.com> <slrne68ddu.qon.sybrenUSE@schuimige.stuvel.eu> <12696vkcb08a0f5@corp.supernews.com> <94e962h9jqkig61m7pseh42k1gg5d5t0j7@4ax.com> Message-ID: <1147652046.619410.149510@y43g2000cwc.googlegroups.com> Dennis Lee Bieber wrote: > On Fri, 12 May 2006 14:30:12 -0000, Grant Edwards <grante at visi.com> > declaimed the following in comp.lang.python: > > > On 2006-05-12, Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> wrote: > > > placid enlightened us with: > > >>> Did you read the documentation for Queue methods? > > >> > > >> there is no need to be patronizing about this dude, im just learning > > >> Python in my spare time, as im a Intern Software Engineer > > > > > > There is nothing patronizing about the question, it's merely > > > an enquiry to a possible fact. If you're going to be a techie, > > > you should learn stuff like that. > > > > It's also valuable information to the maintainers of the > > documentation. If he _did_ read the documentation and still > > didn't know that Queue.get() could block, then one might ask > > how the documentation could be improved. > > If it means anything -- I typically do bring up the help files and > cut&paste the relevant paragraph. But I had a 24-hour backlog and it was > late at night so a straight off-the-cuff entry was made. Though I > suppose one could go back to the "smart questions" FAQ, and have > suggested the original poster tell us what documentation was read in > search of a solution prior to their post (in which case my short > response could be interpreted as a less than subtle hint to read the > references first). telling me to read the documentation would have been a good reminder dude! > -- > 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/ thanks again for all of you who replied with great answers. From phddas at yahoo.com Sat May 6 02:41:45 2006 From: phddas at yahoo.com (Gary Wessle) Date: 06 May 2006 16:41:45 +1000 Subject: combined files together Message-ID: <87psirslhy.fsf@localhost.localdomain> Hi is there a module to do things like concatenate all files in a given directory into a big file, where all the files have the same data formate? name address phone_no. or do I have to open each, read from old/write-or-append to new ... thanks From nobody at 127.0.0.1 Thu May 11 16:22:40 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 11 May 2006 20:22:40 GMT Subject: [ANN] tdir 1.69 Released And Available References: <1bq9j3-q86.ln1@eskimo.tundraware.com> Message-ID: <k2N8g.85729$dW3.5791@newssvr21.news.prodigy.com> Tim Daneliuk wrote: > 'tdir' is a reimplementation and enhancement of the old 'xdir' CP/M > utility from Ancient Times. > > 'tdir' is an advanced directory display utility written in Pure Python, > and runs on both *nix and Win32 systems.\ > > With 'tdir' you can display directories sorted by file "extension", ls -X > display directory trees, ls -R > and separate directories from files in the output listing. ls -u color me unimpressed ;) From rupole at hotmail.com Fri May 5 22:21:29 2006 From: rupole at hotmail.com (Roger Upole) Date: Fri, 5 May 2006 22:21:29 -0400 Subject: Active Directory Authentication References: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> Message-ID: <1146881874_5767@sp6iad.superfeed.net> If you have Pywin32 installed, you can use the win32com.adsi package to open an object with username/password credentials. See adsi.ADsOpenObject for details. Adsi also contains a number of interfaces for dealing with users, containers, etc. Roger "D" <duncanm255 at hotmail.com> wrote in message news:1146832748.087170.212860 at j33g2000cwa.googlegroups.com... > Is it possible to have Python authenticate with Active Directory? > Specifically what I'd like to do is have a user enter a > username/password, then have Python check the credentials with AD - if > what they entered is valid, for example, it returns a 1, otherwise a > 0.. Thanks! > ----== 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 grante at visi.com Sat May 27 01:18:11 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 05:18:11 -0000 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com> <44778e7f$1@nntp0.pdx.net> <127f61eluend535@corp.supernews.com> <127f7rrn8i2qea3@corp.supernews.com> <127fagudgh3fa7e@corp.supernews.com> Message-ID: <127fo8jp4kucbaf@corp.supernews.com> On 2006-05-27, Grant Edwards <grante at visi.com> wrote: > I found another module that claims to do what I want > > http://www.cdc.noaa.gov/people/jeffrey.s.whitaker/python/griddata.html > > But, no matter what data I pass, I get either all zeros or all > NaNs back. :/ Aaarrrggh. After some more sweating and swearing, it looks like both the griddata module and the scipy.delaunay.nn_interpolator do work as long as you pass the preferred brand of arrays to them and specify the mesh/grid using the right scheme. My problems seem to have been caused by the interaction of a number of factors: 1) Gnuplot.py seems to like convert _some_ floating-point arrays to integer values before plotting them -- this only seems to happen when passing 2D arrays to splot(). That was breaking some of my data. 2) Converting the arrays to nested lists prevents the rounding to an integer problem but it apparently transposed the x/y axis without my noticing. Then the "holes" in some of the interpolated surfaces showed up. It turns out there were NaNs in the input data that were causing the holes, but because of the transposed x/y axis, I was looking in the wrong place in the data. 3) Attempting to use the griddata module resulted in mixing array objects from pylab, numpy, numeric, and scipy (some of which may or may not be the same -- I can't keep track). Mixing array types seems to have tripped up some extensions. AFAICT, python code is happy with any of the array types since they're pretty much the same if you go by "duck" typing. But C/Fortran extensions only seem to work with one sort or the other, and some python modules that wrap those extensions will pass anything that quacks on down to C/Fortran code, when then gets confused. Maybe. 4) Even when the arrays were OK, there are a couple incompatible ways to specify a mesh/grid, and I picked the wrong one in at least one case. -- Grant Edwards grante Yow! MMM-MM!! So THIS is at BIO-NEBULATION! visi.com From rpdooling at gmail.com Wed May 17 15:44:49 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 17 May 2006 12:44:49 -0700 Subject: creating a new database with mysqldb References: <gcKag.2113$No6.46302@news.tufts.edu> <1147893204.503850.225770@j73g2000cwa.googlegroups.com> <wKKag.2114$No6.46328@news.tufts.edu> Message-ID: <1147895089.060039.77660@y43g2000cwc.googlegroups.com> I would learn basic, commandline SQL first and get comfortable creating tables, querying your dbs etc. THEN, add Python. Otherwise you spin your wheels not knowing whether it's your use of the Python modules or your bad SQL commands that are fouling things up. http://sqlcourse.com/intro.html or I recommend Chris Fehily's SQL 2nd Ed. Great book, and cheap. From onurb at xiludom.gro Fri May 12 08:02:33 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 14:02:33 +0200 Subject: Python memory deallocate In-Reply-To: <mailman.5622.1147431753.27775.python-list@python.org> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com><-yy*V4mgr@news.chiark.greenend.org.uk><1147355266.189030.131420@y43g2000cwc.googlegroups.com><4463462a$0$297$626a54ce@news.free.fr><1147358549.473182.89950@i40g2000cwc.googlegroups.com> <44636843$0$278$626a54ce@news.free.fr> <mailman.5622.1147431753.27775.python-list@python.org> Message-ID: <446479bc$0$287$626a54ce@news.free.fr> Fredrik Lundh wrote: > bruno at modulix" wrote: > > >>*please* re-read carefully what I and Diez wrote earlier in this thread >>before jumping to possibly erroneous conclusion. I didn't say that the >>problem *actually* was with Python - just that it *may* have to do with >>a memory management issue fixed in 2.5. > > > the only thing that has changed is that Python 2.5 is slightly more likely to release > memory areas held by the Python object allocator back to the C runtime memory > allocator. if you have a leak in your application, changing to Python 2.5 won't > change a thing. Which is mostly what I meant - sorry if it wasn't clear. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From webraviteja at gmail.com Thu May 11 23:57:46 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 11 May 2006 20:57:46 -0700 Subject: calling perl modules from python In-Reply-To: <1690502.fNiZoSDNhf@teancum> References: <1690502.fNiZoSDNhf@teancum> Message-ID: <1147406265.973309.112930@v46g2000cwv.googlegroups.com> > This thing implements a perl interpreter inside python. That seems like overkill to me. It does not *implement* Python, just embeds it. It is not an overkill if you can get it to work quickly and move on. If you are Windows, you can use COM. Support is available for both languages and is fairly simple to use. From bob at passcal.nmt.edu Fri May 26 13:40:11 2006 From: bob at passcal.nmt.edu (Bob Greschke) Date: Fri, 26 May 2006 11:40:11 -0600 Subject: Tkinter canvas zooming (sortof) References: <YvSdnfxcW74PsurZnZ2dnUVZ_t6dnZ2d@nmt.edu> Message-ID: <8fudnca3ZJ_9oOrZnZ2dnUVZ_uqdnZ2d@nmt.edu> "Bob Greschke" <bob at passcal.nmt.edu> wrote in message news:YvSdnfxcW74PsurZnZ2dnUVZ_t6dnZ2d at nmt.edu... >I have a program that sucks in a list of equipment positions (Lats/Longs), >opens a Toplevel frame with a canvas set to, for example, 700x480 pixels, >and then does all of the calculations and plots the objects with 10-pixel >wide ovals and rectangles. Now I want to zoom in (or out), but I don't >want the ovals and rectangles to change size. I just want them to spread >out or get closer together. So scale() doesn't seem to be the way to go. >What I want to do is just make the "logical" canvas bigger and replot >everything, but when I reconfigure the canvas size to make it bigger the >Toplevel frame itself gets bigger. I want the frame to stay the same size, >but still be resizable. I have scrollbars, and they seem to work ok, and >scrollregion seems to do what it should, but I can't figure out how to get >them to all work together to do what I want. Help? > > Thanks! > > Bob After further fiddling... I think I kind of figured this out. I could tell my plotting routine that the canvas was twice as large as I originally made it, and it would draw everything (i.e. if I drug the frame larger I could see more stuff off the edge of the canvas), but the scrollbars would not "activate" so I could scroll over to stuff off the edge of the canvas. What I was doing wrong was not setting the scrollregion to the whole new canvas size that I used for plotting. I kept setting it to the size of the visible canvas in the frame or not setting it at all. I almost understand. :) Now all I have to do is be able to grab the canvas and drag it around with the mouse and click on a spot and have it center that spot and zoom in there. Bob From herraotic at googlemail.com Wed May 24 08:47:52 2006 From: herraotic at googlemail.com (herraotic at googlemail.com) Date: 24 May 2006 05:47:52 -0700 Subject: Python Programming Books? In-Reply-To: <mn.c36f7d65ac4090ff.43626@yahoo.fr.invalid> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <mn.c36f7d65ac4090ff.43626@yahoo.fr.invalid> Message-ID: <1148474872.218991.93460@j73g2000cwa.googlegroups.com> Thanks, if you don't mind could I have a small <b>personal</b> description on the quality of the books (pros, cons). I also am interested if anyone has used "Python Programming: An Introduction to Computer Science" and if I could be given a detailes evaluation about it. Thanks again. From DaleWKing [at]gmail [dot] com Thu May 25 16:23:41 2006 From: DaleWKing [at]gmail [dot] com (Dale King) Date: Thu, 25 May 2006 16:23:41 -0400 Subject: John Bokma harassment In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <OLadnbkovJLJj-vZnZ2dneKdnZydnZ2d@insightbb.com> Xah Lee wrote: > I'm sorry to trouble everyone. But as you might know, due to my > controversial writings and style, recently John Bokma lobbied people to > complaint to my web hosting provider. After exchanging a few emails, my > web hosting provider sent me a 30-day account cancellation notice last > Friday. I'm probably stupid for contributing in this flame fest, but here goes. The reason that I consider Xah a troll and net abuser has little to do with cross-posting (which is still bad) or the length of his messages (he really should post them on his website and provide a summary and a link). My main problem is that he unloads his crap and then runs away. He doesn't participate in any discussion after that. This shows that he has no actual interest in discussion of the issues just in using Usenet as a form of publishing. The mention of free speech was raised. But the fact is that Usenet is not free (as in beer). We all pay for it. Your ISP has to pay for a server, the space for the messages, the bandwidth to download the messages, and the bandwidth to send them to your news reader. In reality the cost is shared among all of us. Therefore you do not have the "right" to do what you want with Usenet. You have a responsibility to use Usenet in a way that benefits the group as a whole (e.g. asking interesting questions that educate others). -- Dale King From grante at visi.com Wed May 3 16:41:49 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 03 May 2006 20:41:49 -0000 Subject: Because of multithreading semantics, this is not reliable. References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> Message-ID: <125i5cdbpsl83c2@corp.supernews.com> On 2006-05-03, OlafMeding at gmail.com <OlafMeding at gmail.com> wrote: > Because of multithreading semantics, this is not reliable. > This sentence is found in the Python documentation for "7.8.1 > Queue Objects". > > This scares me! Why would Queue.qsize(), Queue.empty( ), and a > Queue.full() not be reliable? IIRC from the last time this question came up, what the doc means by "not reliable" is that the result you get is accurate at the time of the call (for the period the call is inside in the mutex-protected region), but the saved result may not be correct at some point in the future because some other thread may have done an operation on the queue. I've argued that the "not reliable" phrase is simply wrong: IMO the calls _are_ reliable: they always return the correct value at the time the call was made (for my previous definition of "at the time the call was made"). That's "reliable" in my book. I've no idea why anybody would ever expect Queue.qsize() to return the size of the queue as it was going to be at some undetermined point in the future. If we were to use the "not reliable" semantics that are used in the Queue docs, pretty much everything is "not reliable" in a multi-threading environment. For example binding a global name to an object is "not reliable" in a multi-threaded environment because another thread can re-bind it later to a different object. I think describing that problem as "global name binding is not reliable in a multi-threaded environment" is very misleading. > Looking at the source code of Queue.py, all 3 calls use a > mutex (based on thread.allocate_lock()). Does this mean that > the thread.allocate_lock() mechanism is not reliable (scary > indeed) or does this have to do with other implementation > details? IMO, it has to do with a poor choice of language. > Many thanks for explaining this mystery. No problem. -- Grant Edwards grante Yow! Mr and Mrs PED, can I at borrow 26.7% of the RAYON visi.com TEXTILE production of the INDONESIAN archipelago? From tommy04 at gmail.com Mon May 29 20:40:39 2006 From: tommy04 at gmail.com (Tommy B) Date: 29 May 2006 17:40:39 -0700 Subject: Running External Commands + Seeing when they are Finished In-Reply-To: <1148808017.090240.301590@j55g2000cwa.googlegroups.com> References: <1148707745.744045.77770@g10g2000cwb.googlegroups.com> <1148808017.090240.301590@j55g2000cwa.googlegroups.com> Message-ID: <1148949639.700600.183290@j73g2000cwa.googlegroups.com> It works! Gasp! Thanks! From eligottlieb at gmail.com Sun May 14 22:44:54 2006 From: eligottlieb at gmail.com (Eli Gottlieb) Date: Mon, 15 May 2006 02:44:54 GMT Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> Actually, spaces are better for indenting code. The exact amount of space taken up by one space character will always (or at least tend to be) the same, while every combination of keyboard driver, operating system, text editor, content/file format, and character encoding all change precisely what the tab key does. There's no use in typing "tab" for indentation when my text editor will simply convert it to three spaces, or worse, autoindent and mix tabs with spaces so that I have no idea how many actual whitespace characters of what kinds are really taking up all that whitespace. I admit it doesn't usually matter, but then you go back to try and make your code prettier and find yourself asking "WTF?" Undoubtedly adding the second spark to the holy war, Eli -- The science of economics is the cleverest proof of free will yet constructed. From wrongbad at gmail.com Mon May 8 04:05:29 2006 From: wrongbad at gmail.com (I V) Date: Mon, 08 May 2006 01:05:29 -0700 Subject: printing out elements in list References: <1147074279.391832.158350@y43g2000cwc.googlegroups.com> Message-ID: <pan.2006.05.08.08.05.26.437021@gmail.com> On Mon, 08 May 2006 00:44:39 -0700, micklee74 wrote: > i have a list with contents like this > alist = ['>QWER' , 'askfhs', '>REWR' ,'sfsdf' , '>FGDG', > 'sdfsdgffdgfdg' ] > > how can i "convert" this list into a dictionary such that > > dictionary = { '>QWER':'askfhs' , '>REWR' : 'sfsdf' , '>FGDG', > 'sdfsdgffdgfdg' } This strikes me as a little bit voodish, but you could do: dictionary = dict(zip(alist[::2], alist[1::2])) From tobiasschlauch at web.de Wed May 3 15:34:00 2006 From: tobiasschlauch at web.de (tobi) Date: 3 May 2006 12:34:00 -0700 Subject: python modules for openAFS client functionalities Message-ID: <1146684840.825130.171300@j73g2000cwa.googlegroups.com> Did anybody try to provide python modules for the openAFS (http://www.openafs.org/) client functionalities (C API)? I think that there are already bindings available for Perl and Java. What could be the best aproach to provide bindings for Python? Using Swig? From e.frerich at nord-com.net Wed May 3 04:06:54 2006 From: e.frerich at nord-com.net (Egon Frerich) Date: Wed, 03 May 2006 10:06:54 +0200 Subject: Zope Guru... In-Reply-To: <226901c66e84$3d9f8240$0301a8c0@Mesa.com> References: <226901c66e84$3d9f8240$0301a8c0@Mesa.com> Message-ID: <4458649E.6040205@nord-com.net> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 Hi, I'm wether a Zope Guru nor a workflow Guru. But I think you should ask zope3-users at zope.org Regards, Egon bruce schrieb am 03.05.2006 09:36: > Hi.. > > In doing some research into Workflow apps regarding document management, I > came across Zope. Given that it's Python Based, I figured I'd shout to the > group here... > > Are there any Zope gurus that I can talk to regarding Zope, and what it > does/how it works? In particular, I'm looking for an app that I could use to > manage a pretty simple workflow for a bunch of scripts that are going to be > developed. > > I envision having a number of people on the team, each developing/testing > various scripts. I then need to somehow manage the process of the scripts > going from development to testing to production, which is the workflow. At > the same time, I have to implement/enforce some form of Access control for > the users, so they don't screw up with files that they shouldn't touch... > > If there's anyone on this list that I could talk to, I'd appreciate it.. > > Thanks > > -bruce > > - -- Egon Frerich, Freudenbergstr. 16, 28213 Bremen E-Mail: e.frerich at nord-com.net -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.2.2 (MingW32) Comment: GnuPT 2.7.2 Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEWGSduTzybIiyjvURAu0HAKDDGxd/7r5bav/PWzuqPhoH76iEUgCgpsm+ oS6G5dGy354rIAVaMpwvR/U= =n+V2 -----END PGP SIGNATURE----- From jweida at gmail.com Mon May 22 16:28:33 2006 From: jweida at gmail.com (Jerry) Date: 22 May 2006 13:28:33 -0700 Subject: freeze tool like perl2exe? Message-ID: <1148329713.916486.68410@i40g2000cwc.googlegroups.com> I am looking for a freeze tool for Python that is similar to perl2exe in that I can "compile" a script on one platform that is built for another. Basically, I would like to be able to build a Python script for Solaris using my Windows workstation. Is there any tool that fits the bill? Thanks, Jerry From jweida at gmail.com Tue May 23 12:02:47 2006 From: jweida at gmail.com (Jerry) Date: 23 May 2006 09:02:47 -0700 Subject: freeze tool like perl2exe? In-Reply-To: <1148388219.214377.170980@i39g2000cwa.googlegroups.com> References: <1148329713.916486.68410@i40g2000cwc.googlegroups.com> <e4uo5r$7lc$1@atlantis.news.tpi.pl> <1148388219.214377.170980@i39g2000cwa.googlegroups.com> Message-ID: <1148400167.485355.222140@u72g2000cwu.googlegroups.com> I did look at cx_Freeze at one point in time, but the documentation on their site is pretty sparse and doesn't actually mention being able to build for a different platform. I'll take another look. Thanks. -- Jerry From tim.leeuwvander at nl.unisys.com Mon May 8 04:53:34 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 8 May 2006 01:53:34 -0700 Subject: printing out elements in list In-Reply-To: <1147075890.042861.250650@i40g2000cwc.googlegroups.com> References: <1147074279.391832.158350@y43g2000cwc.googlegroups.com> <pan.2006.05.08.08.05.26.437021@gmail.com> <1147075890.042861.250650@i40g2000cwc.googlegroups.com> Message-ID: <1147078414.615247.165010@j73g2000cwa.googlegroups.com> alist[::2] means taking a slice. You should look up slice-syntax in the tutorials and reference manual. in general, alist[1:5] means: take list elements position 1 up to (excluding) 5. (List indexing starts at position 0, so the first element in the list is not included!) alist[0:5] means: take list elements position 0 up to (excluding) 5; in other words: the first 5 elements. A shortcut for this is: alist[:5] -- omitting an index position means a default of 'start' resp. 'end'. So to take all elements from the 5th to the end of list, you write: alist[4:] (remember that indexing starts at position 0, so 0 is your first element, 4 is your 5th). To take a slice that is the whole list, write: alist[:] Slices discussed so far take all elements in the indicated range, however you can specify a 'step' with your slices. Default step is 1, but to skip every other element you write: alist[::2] Which takes all elements of your list, starting at position 0, adding 2 to the index each step, so next is item 2, then 4, etc, until end of list. Now we have all the 'even-numbered' elements in the list, to get the 'odd-numbered elements' write: alist[1::2] I hope this helps. Cheers, --Tim From mhodkin at comcast.net Wed May 17 12:48:00 2006 From: mhodkin at comcast.net (mhodkin at comcast.net) Date: 17 May 2006 09:48:00 -0700 Subject: constucting a lookup table References: <1147790226.554111.267560@j73g2000cwa.googlegroups.com> <9aCdnR10Sej7bPTZnZ2dnUVZ_sidnZ2d@comcast.com> <1147831768.783996.10630@j33g2000cwa.googlegroups.com> Message-ID: <1147884480.797594.265760@u72g2000cwu.googlegroups.com> BTW, just for kicks to compare languages, how would one implement the same "lookup" table using C/C++? It would be a good lesson in high level vs. lower level programming.... From fuzzyman at gmail.com Tue May 30 18:33:57 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 30 May 2006 15:33:57 -0700 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 30) In-Reply-To: <e5i1h2$1vb$1@lairds.us> References: <e5i1h2$1vb$1@lairds.us> Message-ID: <1149028437.100527.240490@j55g2000cwa.googlegroups.com> Cameron Laird wrote: > QOTW: "Making a user class work anywhere you can put a mapping in Perl is > deep magic, but easy in Python. Creating types that act like files and can be > used wherever a file is used is SOP in Python; I'm not even sure it's > possible in Perl (probably is, but it's again deep magic)." - Mike Meyer > > "... I don't bother with classes unless I'm going to end up with multiple > instances (or I'm pushed into a corner ..." - Dan Sommers > > > Over TWO DOZEN Python-based projects have been accepted for > the 2006 Summer of Code: > http://wiki.python.org/moin/SummerOfCode > > While waiting for more polished summaries from the Iceland Sprint, > admire a few of the incidental photographs: > http://www.flickr.com/photos/tags/pyneedforspeed/ > http://www.flickr.com/photos/30842681 at N00/ > > John Machin and others stride throught the periods of sequences: > http://groups.google.com/group/comp.lang.python/msg/74c81885d7dd4b0e > http://groups.google.com/group/comp.lang.python/msg/b9d10df764bdd3df > > Under-invested desiderata: documentation, regression tests, > marketing, serenity, and, as Steve Holden recently discovered, > *benchmarks*: > http://groups.google.com/group/comp.lang.python/msg/903d5ba9745bad5b > > Fuzzyman advertises yet another convenience of Movable Python: > http://groups.google.com/group/comp.lang.python/msg/35baaa3af891c12f > That's a very surprising mention, thanks. :-) A *better* URL for the thread is : http://groups.google.com/group/comp.lang.python/browse_frm/thread/28edb6b248dbae85/6a64800985655dce#6a64800985655dce All the best, Fuzzyman http://www.voidspace.org.uk/python/index.shtml From Bulkan at gmail.com Wed May 31 23:52:49 2006 From: Bulkan at gmail.com (placid) Date: 31 May 2006 20:52:49 -0700 Subject: Is device Connected Windows? Message-ID: <1149133969.191368.224660@h76g2000cwa.googlegroups.com> Hi all, Just wondering is there a way (not brute force) to check if a usb storage device is connected? The brute force method im talking about is doing a os.path.isdir() or os.path.isdir() on all the drive letters from A-Z, because you know that this usb device contains a folder called A or file called foo.txt. Thanks in Advance From linnorm at gmail.com Fri May 26 10:17:39 2006 From: linnorm at gmail.com (linnorm at gmail.com) Date: 26 May 2006 07:17:39 -0700 Subject: how to clear up a List in python? References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <e54gtn$grs$1@ulysses.news.tiscali.de> Message-ID: <1148653059.381151.113360@j73g2000cwa.googlegroups.com> The original post only mentions deleting the values in the list, not the list itself. Given that you want to keep the list and just ditch the values it contains I'd go with: list1 = [] -Linnorm From m.yanowitz at kearfott.com Thu May 25 08:00:55 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 25 May 2006 08:00:55 -0400 Subject: how to change sys.path? In-Reply-To: <1148544408.348803.190320@j33g2000cwa.googlegroups.com> Message-ID: <HGEOKIAPAMCIFPPBDALKAEKLCAAA.m.yanowitz@kearfott.com> Is there something like a .pythoninitrc which can run whenever we start Python that can load a file with many sys.path.append(), etc? If not is there some way to modify the Python shell constructor and destructor? Thanks in advance: Michael yanowitz -----Original Message----- From: python-list-bounces+m.yanowitz=kearfott.com at python.org [mailto:python-list-bounces+m.yanowitz=kearfott.com at python.org]On Behalf Of per9000 Sent: Thursday, May 25, 2006 4:07 AM To: python-list at python.org Subject: Re: how to change sys.path? also se topic named 'problem(s) with import from parent dir: "from ../brave.py import sir_robin" ' I use this every day now: sys.path.append("../../py_scripts") best wishes, Per From jscrerar at compuserve.com Wed May 24 10:21:27 2006 From: jscrerar at compuserve.com (SaskMan) Date: 24 May 2006 07:21:27 -0700 Subject: How to find out a date/time difference In-Reply-To: <1148479557.226541.323100@i40g2000cwc.googlegroups.com> References: <1148479557.226541.323100@i40g2000cwc.googlegroups.com> Message-ID: <1148480487.706277.265010@j73g2000cwa.googlegroups.com> Convert datetime.datetime(2006, 5, 24, 16, 1, 26) to an ordinal number like: datetime.datetime(2006, 5, 24, 16, 1, 26).toordinal() and subtract them to get number of days. From deets at nospam.web.de Thu May 18 11:16:40 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 18 May 2006 17:16:40 +0200 Subject: Windows Registry Dump References: <1147964415.540190.47480@i40g2000cwc.googlegroups.com> Message-ID: <4d3hepF185ne6U1@uni-berlin.de> Dirk Hagemann wrote: > Hi! > > Does someone know how I can make a Text-Dump-File of a remote > Windows-Computer's Registry (not the whole registry - only a part of > it)? > > Thanks a lot for some code or a helpful link! I suggest you try asking the darker side of the internet - after all, accessing the registry remotely and all possibly privacy and security related issues that is of utmost importance to crackers and hackers. BackOrifice and your average Trojan spring into mind - maybe for a small fee the allow you to piggyback your (surely good-intended!) code on theirs! Diez From sjmachin at lexicon.net Sun May 28 19:03:53 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 May 2006 09:03:53 +1000 Subject: itertools.count() as built-in In-Reply-To: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> Message-ID: <447A2C59.2040002@lexicon.net> On 29/05/2006 4:14 AM, jantod at gmail.com wrote: > Is there any chance of itertools.count() ever becoming one of the > built-in functions? It's a wonderful little function and I find myself > importing it in every module I write. > Every module?? Do you use any/many other itertools functions? Care to give us a sample of your typical usage of itertools.count? Cheers, John From onurb at xiludom.gro Fri May 5 13:43:02 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 19:43:02 +0200 Subject: easy way to dump a class instance? In-Reply-To: <8SL6g.73271$H71.63860@newssvr13.news.prodigy.com> References: <8SL6g.73271$H71.63860@newssvr13.news.prodigy.com> Message-ID: <445b8f04$0$12442$626a54ce@news.free.fr> Mark Harrison wrote: > Is there a way to automatically print all the instance > data in a class? This is for debugging, I would like > to do something like dump(self) to snapshot the state > of the object. def dump(obj): buf = ['%r %s :' % (obj, str(obj)] for name in dir(obj): attr = getattr(obj, name) if not callable(attr): buf.append["- %s : %s" % (name, str(attr))] return '\n'.join(buf) Not tested... -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From phpbird at gmail.com Sat May 6 10:44:58 2006 From: phpbird at gmail.com (Ju Hui) Date: 6 May 2006 07:44:58 -0700 Subject: how to remove 50000 elements from a 100000 list? In-Reply-To: <zNudne9wssqeKcbZRVn-hg@comcast.com> References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> <4c13mdF13esivU1@uni-berlin.de> <4c14snF13tbobU1@uni-berlin.de> <1146844567.717687.228160@j33g2000cwa.googlegroups.com> <e3ftkp$qe7$03$1@news.t-online.com> <zNudne9wssqeKcbZRVn-hg@comcast.com> Message-ID: <1146926698.864650.22510@u72g2000cwu.googlegroups.com> to Andrew Gwozdziewycz: Real humor... Peter Otten: thanks your reminder, in my project, a will a superset of b. so symmetric_difference equals difference. thank you all again! From rpdooling at gmail.com Thu May 18 00:53:02 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 17 May 2006 21:53:02 -0700 Subject: creating a new database with mysqldb In-Reply-To: <446be190$0$5024$c3e8da3@news.astraweb.com> References: <gcKag.2113$No6.46302@news.tufts.edu> <126nj7utnok7u6e@corp.supernews.com> <446be190$0$5024$c3e8da3@news.astraweb.com> Message-ID: <1147927982.322181.20880@i39g2000cwa.googlegroups.com> I was hoping you'd find this earlier when I suggested that you type: creating a new database with MySQL into google. It's the number one hit: http://coronet.iicm.edu/mysql/create.html If you send the commands listed there via the commandline or through MySQLdb you should be in business. From jack at performancedrivers.com Wed May 10 13:46:01 2006 From: jack at performancedrivers.com (Jack Diederich) Date: Wed, 10 May 2006 13:46:01 -0400 Subject: interactive shell -- reload definitions? In-Reply-To: <1147280438.193621.66340@u72g2000cwu.googlegroups.com> References: <1147211886.998828.197710@y43g2000cwc.googlegroups.com> <4461d67a$0$3551$626a54ce@news.free.fr> <1147280438.193621.66340@u72g2000cwu.googlegroups.com> Message-ID: <20060510174601.GC5751@performancedrivers.com> On Wed, May 10, 2006 at 10:00:38AM -0700, malv wrote: > This is a question that comes up almost continuously for at least six > years now. > For Python users having to deal with major real-life applications, this > may make them think twice about the future suitability of Python as a > competitive development tool. > Ruby is featuring a software modify and go feature. Lisp is, even VB > does. In the design of Smalltalk this used to be one of the major > considerations. > > Plenty of posts will turn up doing a search on "reload". The following > references summarize some of these problems: > http://groups.google.com/group/comp.lang.python/browse_frm/thread/efba62d227ba4794/41f57f366affd057?q=Hung+Jung+Lu+reload&rnum=2#41f57f366affd057 > http://groups.google.com/group/comp.lang.python/browse_frm/thread/efba62d227ba4794/41f57f366affd057?q=Hung+Jung+Lu+reload&rnum=2#41f57f366affd057 > > In fact, doing a reload usually will not accomplish what one is looking > for. Class instances should also be upgraded on reload(), preferably > automatically. This can be accomplished as shown by Michael Hudson in: > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/160164 > Variants on this theme exist which seem to be broken. reload() cannot always do exactly what you want it to do because what you want it to do isn't always the same. Upgrading instances to the new definition of the class may be handy sometimes but what is the 'right' thing to do here? # test.py version 1 class A: def __init__(self, val): self.hello_wolrd = val def __str__(self): return self.hello_world # test.py version 2 class A: def __init__(self, val): self.himom = val def __str__(self): return self.himom reload() can never know that 'hello_world' was renamed to 'himom' so if you upgrade the class of existing instances str(ob) will explode. reload() is only handy for interactive use. If you try to use it in any non-trivial production program you will get burned. It can never be made magic enough. > Given the persistent push of Ruby, I would strongly recommend that a > workable integrated solution will be found for Reload & Go in Python, > taking priority on many way out features of rather low practicality for > many programmers. Link? Google finds lots of unrelated stuff because reload is a common word. -Jack From santosh.pandey at gmail.com Thu May 4 18:15:18 2006 From: santosh.pandey at gmail.com (san) Date: 4 May 2006 15:15:18 -0700 Subject: Can I use python for this .. ?? In-Reply-To: <1146775288.873572.69220@j73g2000cwa.googlegroups.com> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146774288.904851.278130@i39g2000cwa.googlegroups.com> <1146775288.873572.69220@j73g2000cwa.googlegroups.com> Message-ID: <1146780918.317375.222590@v46g2000cwv.googlegroups.com> Rick Thanks for your reply .. didnt quite get your point in loggin into password protected site. Will try to seach this group for more .. Still looking for tab browsing and logging in password protected site .. can i use ctype or something like that .. some modute that will introduce key strokes .. so that i can do "username" "tab" "password" "enter" so that i can log in .. ?? From vedranf at riteh.hr Tue May 2 08:05:32 2006 From: vedranf at riteh.hr (=?UTF-8?B?VmVkcmFuIEZ1cmHEjQ==?=) Date: Tue, 02 May 2006 14:05:32 +0200 Subject: Strange result with math.atan2() Message-ID: <chuji3xd2m.ln2@pollux.home> I think that this results must be the same: In [3]: math.atan2(-0.0,-1) Out[3]: -3.1415926535897931 In [4]: math.atan2(-0,-1) Out[4]: 3.1415926535897931 In [5]: -0 == -0.0 Out[5]: True This is python 2.4.4c0 on Debian GNU/Linux. Regards, Vedran Fura? From jstroud at ucla.edu Tue May 9 18:51:06 2006 From: jstroud at ucla.edu (James Stroud) Date: Tue, 09 May 2006 15:51:06 -0700 Subject: Dictionaries -- ahh the fun.. (newbie help) In-Reply-To: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> References: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> Message-ID: <e3r6cq$4hm$1@zinnia.noc.ucla.edu> rh0dium wrote: > Hi all, > > Can someone help me out. I am trying to determing for each run whether > or not the test should pass or fail but I can't seem to access the > results .. > > Alternatively can someone suggest a better structure ( and a lesson as > to the reasoning ) that would be great too!! > > cells={} > > cells["NOR3X1"]= { > 'run' : [ 'lvs', 'drc' ], > 'results' : [{ 'lvs' : 'pass' }, > { 'drc' : 'fail' }] > } > > cells["OR3X1"] = { > 'run' : [ 'lvs' ], > 'results' : [{ 'lvs' : 'pass' }] > } > > cells["AND3X1"] = { > 'run' : [ 'drc' ], > 'results' : [{ 'drc' : 'fail' }] > } > > > def main(): > > for cell in cells: > print cell > for run in cells[cell]['run']: > print cell, run, "should", > cells[cell]['results'].index(run) > > > I would expect the following > > OR3X1 > OR3X1 lvs should pass > NOR3X1 > NOR3X1 lvs should pass > NOR3X1 drc should fail > AND3X1 > AND3X1 drc should fail > This might be better cells["NOR3X1"]= { 'run' : [ 'lvs', 'drc' ], 'results' : { 'lvs' : 'pass', 'drc' : 'fail' } } # etc. print cell, run, "should", cells[cell]['results'][run] James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From sjmachin at lexicon.net Fri May 19 18:19:49 2006 From: sjmachin at lexicon.net (John Machin) Date: 19 May 2006 15:19:49 -0700 Subject: Which is More Efficient? References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1148036087.843911.307990@u72g2000cwu.googlegroups.com> <mailman.5948.1148046735.27775.python-list@python.org> <1148075356.525042.253100@j33g2000cwa.googlegroups.com> Message-ID: <1148077189.109501.251940@i40g2000cwc.googlegroups.com> Dustan wrote: > Fredrik Lundh wrote: >> are you for real? > And what exactly is that supposed to mean? The obscurity in that communication is probably caused by the instance of the effbot with which you have been corresponding having been invoked with mildmannered=True -- apparently this is not the default value for that arg and the constraints so imposed can lead to lack of precision in the output :-) HTH, John From fuzzyman at gmail.com Mon May 1 11:54:30 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 1 May 2006 08:54:30 -0700 Subject: [ANN] Movable Python 1.0.2 Message-ID: <1146498870.703191.311540@j33g2000cwa.googlegroups.com> `Movable Python 1.0.2 <http://www.voidspace.org.uk/python/movpy/>`_ is now available. This release if for the Python 2.4 distribution of **Movable Python**, and is now available for `download <http://voidspace.tradebit.com/groups.php>`_. Features new to this release include : * Now built with Python 2.4.3. * Other updated modules include : - pywin32 build 208 - ctypes 0.9.9.6 - wxPython 2.6.3.2 - Firedrop 0.2.1 - ConfigObj 4.3.1 - Wax 0.3.33 * Scripts (and ``customize.py``) are now executed in a specific namespace, no more movpy cruft. * When entering interactive mode (``movpy -``), any *additional* command line arguments are passed to IPython. * ``imp.find_module`` has been fixed to work with modules contained in the zipfile. This fix doesn't write any temporary files, but ``imp.load_module`` has been patched to accept a ``StringIO`` instance. * Built in support for *matplotlib* interactive sessions. (``movpy - pylab``) * Verified that ``__future__`` statements are handled correctly. * New look documentation and website. To try the new `matplotlib <http://matplotlib.sourceforge.net/>`_ support, you'll need the `matplotlib files <http://www.voidspace.org.uk/matplotlib.zip>`_ in your ``lib/`` directory. You can then run the following at the command line : ``movpy.exe - -pylab`` This should drop you straight into a IPython session, with pylab enabled. From deets at nospam.web.de Thu May 25 08:39:53 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 25 May 2006 14:39:53 +0200 Subject: a good explanation In-Reply-To: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> References: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> Message-ID: <4dlmsqF1abojeU1@uni-berlin.de> s99999999s2003 at yahoo.com schrieb: > hi > my friend has written a loop like this > cnt = 0 > files = [a,b,c,d] > while cnt < len(files) : > do_something(files[cnt]) > > i told him using > for fi in files: > do_something(fi) > > is better, because the while loop method makes another call to > len..which is slower.. > am i partly right? or is there a better explanation for using the for > method.? Several good reasons: - his loop won't terminate, as he (or you trying to copy his efforts) forgot to increment cnt - he needs additional statements & state. The more you have of this, the likelier you make errors. he could for example write <= len(files) - the whole loop is noisier to the eye, makes it harder to grasp what it's all about It seems that your friend comes from a language like C or JAVA (pre 1.5) where the for loop was basically what his while loop above is: one initializer, one condition test, one last statement, mostly incrementing the counter. Python's for is build around the concept of an iterable. Which lists, tuples, strings and many other things are - and thus the last, and possibly strongest reason is: its not idiomatic Python, he tries top shoehorn python into some schemes he's used from other languages. Don't do that, accept Python & it's ways for a better life :) Diez From beliavsky at aol.com Tue May 2 18:17:53 2006 From: beliavsky at aol.com (beliavsky at aol.com) Date: 2 May 2006 15:17:53 -0700 Subject: search file for tabs References: <1146606666.249084.12810@j73g2000cwa.googlegroups.com> <mailman.5237.1146607386.27775.python-list@python.org> Message-ID: <1146608273.918452.81350@j33g2000cwa.googlegroups.com> Fredrik Lundh wrote: > beliavsky at aol.com wrote: > > > The following code to search a file for tabs does not work, at least on > > Windows XP. Could someone please tell me what's wrong? Thanks. > > > > xfile = "file_with_tabs.txt" > > for text in open(xfile,"r"): > > text = text.strip() > > if ("\t" in text): > > print text > > since you're stripping away all leading and trailing whitespace from each > line, you'll only find lines that have tabs "in the middle". > > (your code is only five lines long. don't you think you could have double- > checked each line a couple of times, asking yourself "what exactly is this > line doing", in less time than it took you to compose the mail ?) Both your specific and general suggestions are correct. Thanks. From mgi820 at motorola.com Tue May 2 16:47:58 2006 From: mgi820 at motorola.com (Gary Duzan) Date: Tue, 2 May 2006 20:47:58 +0000 (UTC) Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <RAN5g.2037$No6.43926@news.tufts.edu> Message-ID: <e38ghu$he1$1@avnika.corp.mot.com> In article <RAN5g.2037$No6.43926 at news.tufts.edu>, John Salerno <johnjsal at NOSPAMgmail.com> wrote: >bruno at modulix wrote: > >> Now if I may ask: what is your actual problem ? > >Ok, since you're so curious. :) > >Here's a scan of the page from the puzzle book: >http://johnjsalerno.com/spies.png > >Basically I'm reading this book to give me little things to try out in >Python. There's no guarantee that this puzzle is even conducive to (or >worthy of) a programming solution. Exhaustive search is quite practical for this problem: [(x,y,z,w) for x in (True, False) for y in (True, False) for z in (True, False) for w in (True, False) if spy(x,y,x,w)] Given the appropriate spy() function, this will return a set of values for the truthful (logically coherent) spy and nothing for the other spy. The details are left as an exercise for the reader. :-) Gary Duzan Motorola CHS From simon at brunningonline.net Tue May 23 04:16:11 2006 From: simon at brunningonline.net (Simon Brunning) Date: Tue, 23 May 2006 09:16:11 +0100 Subject: manual http request In-Reply-To: <20060522183934.80428.qmail@web36507.mail.mud.yahoo.com> References: <20060522183934.80428.qmail@web36507.mail.mud.yahoo.com> Message-ID: <8c7f10c60605230116l49f146e6w2b13e17abab5a3a4@mail.gmail.com> On 5/22/06, Steve Young <drevil_53711 at yahoo.com> wrote: > Hi, I was wondering if there's a way to mimic a web pages' form and just > manually send the http request and get the html response without having to > go through a browser. For example, lets say i wanted to make a search on > google of the key word "cars" but i want to be able to get the results of > the search without having to go to google and typing it in and submiting it. Well, I think that's a breach of Google's terms and conditions, so don't do that, but to answer your technical query, take a look at Mechanize - <http://wwwsearch.sourceforge.net/mechanize/>. -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From ptmcg at austin.rr._bogus_.com Wed May 10 18:04:32 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 10 May 2006 22:04:32 GMT Subject: design a Condition class References: <1147297217.372888.167960@v46g2000cwv.googlegroups.com> Message-ID: <Qrt8g.15482$Qq.9484@tornado.texas.rr.com> <joh12005 at yahoo.fr> wrote in message news:1147297217.372888.167960 at v46g2000cwv.googlegroups.com... > Hello, > > i posted for suggestions a little idea even if it still needs further > thoughts but as i'm sure you could help :) > > if would like to implement some kind of Condition class which i coud > use to build bricks of more complex condition, conditions are based on > fields by using regexp > > class Condition: > def __init__(self, field0, field1, field2): > self.field0 = field0 > self.field1 = field1 > self.field2 = field2 > def match(self, against): > w, t, l = against > f0 = False > if self.field0 is None: > f0 = True > else: > f0 = self.field0.search(w) > if self.field1 is None: > f1 = True > else: > f1 = self.field1.search(t) > if self.field2 is None: > f2 = True > else: > f2 = self.field2.search(l) > return f0 and f1 and f2 > > c0 = Condition(re.compile("something"), None, > re.compile("somethingelse")) > c1 = Condition(re.compile("another"), None, None) > > i can use > > if c0.search(myitem) > > but i would like to be able to have composition such as : > > c2 = c0 | c1 > > which should be understood as defining a new c2 which is able to match > (c0 or c1) from c0 and c1 already defined. > > actually i can imagine a > > def OR(c0, c1): > # here => missing None support 'a or None' is 'a' > return Condition(re.compile("|".join((c0.field0.pattern, > c1.field0.pattern)), > re.compile("|".join((c0.field1.pattern, > c1.field1.pattern)), > re.compile("|".join((c0.field2.pattern, > c1.field2.pattern)) > > the idea is to build c2 = Condition(re.compile("something|another"), > None, re.compile("somethingelse")) > c2 = OR(c0, c1) > > but maybe have you clever suggestions ? > > best regards. > Your composition of expressions to match is very similar to the definition of grammars in pyparsing. Here's a small example, to parse "Hello, World!"-type strings. from pyparsing import Word, alphas # define grammar greet = Word( alphas ) + "," + Word( alphas ) + "!" # input string hello = "Hello, World!" # parse input string print hello, "->", greet.parseString( hello ) The Word class matches any group of characters composed of the letters in the string passed to the constructor. alphas is a string constant of the upper and lower case letters A thru Z. This sample program prints out: Hello, World! -> ['Hello', ',', 'World', '!'] pyparsing has many more expression types, including Literal, CaselessLiteral, Optional, ZeroOrMore, and OneOrMore. There are also combining forms, And, Or, MatchFirst, and Each. The handy part of these combining forms is that there are operator short-cuts: a + b is the same as And([a,b]) (that is, a followed by b) a | b is the same as MatchFirst([a,b]) (if not match a, then try to match b) a ^ b is the same as Or([a,b]) (try matching a and b, choose longest match) a @ b is the same as Each([a,b]) (match a and b in any order - good for matching options that can be specified in any order) The resulting grammar expressions are fairly readable. The greet expression above translates to greet is a word group of alphabetic characters, followed by a ",", followed by another word group of alphabetic characters, followed by a "!". Note that there is no explicit specification of whitespace - whitespace will terminate a word group, but is not necessary if the grammar is unambiguous without it. For instance, this expression will match any of: Hello,World! Hello , World ! Hello ,World ! ... and so on. Of course it will also match: Howdy, pardner! Greetings, Earthling! Aloha, wahini! The matched results are returned as an object of type ParseResults, which can be accessed like a list, a dictionary, or an object with attributes (if you associated names with individual elements of the parse expression). You can get more info and download info at pyparsing.wikispaces.com. Even if you choose not to use pyparsing, you might get some ideas on your own implementation. -- Paul From Serge.Orlov at gmail.com Wed May 3 16:43:51 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 3 May 2006 13:43:51 -0700 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> Message-ID: <1146689031.533474.320570@v46g2000cwv.googlegroups.com> OlafMeding at gmail.com wrote: > Below are 2 files that isolate the problem. Note, both programs hang > (stop responding) with hyper-threading turned on (a BIOS setting), but > work as expected with hyper-threading turned off. What do you mean "stop responding"? Not responding when you press ctrl-c? They stop printing? If you mean stop printing, try sys.stdout.flush() after each print From kai.grossjohann at verizonbusiness.com Wed May 10 13:27:16 2006 From: kai.grossjohann at verizonbusiness.com (Kai Grossjohann) Date: Wed, 10 May 2006 19:27:16 +0200 Subject: unittest: How to fail if environment does not allow execution? Message-ID: <44622274.5040907@verizonbusiness.com> I wrote a test case that depends on a certain file existing in the environment. So, I guess I should test that the file exists in the setUp method. But what if it doesn't exist? How do I fail in that case? I would like to emit an error message explaining what is wrong. tia, Kai From grante at visi.com Fri May 19 15:04:02 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 19 May 2006 19:04:02 -0000 Subject: number of different lines in a file References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> <1148063935.859890.173230@u72g2000cwu.googlegroups.com> <Vxobg.46856$CH2.5271@tornado.texas.rr.com> Message-ID: <126s5l24kd7u19a@corp.supernews.com> On 2006-05-19, Paul McGuire <ptmcg at austin.rr._bogus_.com> wrote: >> If the log has a lot of repeated lines in its original state then >> running uniq twice, once up front to reduce what needs to be sorted, >> might be quicker? >> >> uniq log_file | sort| uniq | wc -l >> >> - Pad. > > Why would the second running of uniq remove any additional lines that > weren't removed in the first pass? Because uniq only removes _adjacent_ identical lines. > For that matter, if this is a log file, wont every line have a timestamp, > making duplicates extremely unlikely? Probably. -- Grant Edwards grante Yow! If our behavior is at strict, we do not need fun! visi.com From onurb at xiludom.gro Thu May 18 05:07:22 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 11:07:22 +0200 Subject: Python - Web Display Technology In-Reply-To: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> Message-ID: <446c39b2$0$8047$636a55ce@news.free.fr> SamFeltus wrote: > I am trying to figure out why so little web development in Python uses > Flash as a display technology. It seems most Python applications > choose HTML/CSS/JS as the display technology, yet Flash is a far more > powerful and elegant display technology. On the other hand, HTML/JS > seems clunky and antiquated. I am a gardener, and not a coder by > trade, but Flash seems to integrate just fine with Python. Anyways, > what are the technical reasons for this? > - Flash is a proprietary technology requiring a proprietary plugin. - There aint actually no working Flash plugin for Mozilla on a 64bit processor - I just *can't* read Flash anims on my computer - Flash is meant to display animations, not web content - Flash content is not indexed by search engines - Flash content cannot be manipulated by normal text/HTML/XML tools (x)html/css/js is neither 'clunky' nor 'antiquated' (and FWIW, Flash is based on ActionScript, which is mostly javascript...). -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From im4u143 at gmail.com Sat May 13 03:10:39 2006 From: im4u143 at gmail.com (im4u143 at gmail.com) Date: 13 May 2006 00:10:39 -0700 Subject: Amazing offers for Computers,Laptops Message-ID: <1147504239.585773.101580@i39g2000cwa.googlegroups.com> Hy every one. An amazing opportunity for all the people to buy and get all the information related to the Laptops, Computer Systems, registration for free trail and for rental basis. Effort less thing, just make look over www.eazyrentals.com From andymac at bullseye.apana.org.au Thu May 11 07:04:01 2006 From: andymac at bullseye.apana.org.au (Andrew MacIntyre) Date: Thu, 11 May 2006 22:04:01 +1100 Subject: releasing interpreter lock in custom code? In-Reply-To: <1147340518.685734@blaat.sara.nl> References: <1147340518.685734@blaat.sara.nl> Message-ID: <44631A21.7050003@bullseye.apana.org.au> Bram Stolk wrote: > I've implemented, in C, a function that does a lot of I/O, and thus > can block for a long time. > > If I execute this function in my Python script, it does not > relinquish the global interpreter lock, like Python's native > blocking functions do, like I/O funcs, and time.sleep() func. > > How can I have my func release the lock? Search the Python documentation (Python/C API section) for information about the Py_BEGIN_ALLOW_THREADS and Py_END_ALLOW_THREADS macros. Perusing Python's source would also be educational (eg Modules/posixmodule.c). -- ------------------------------------------------------------------------- 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 gmc at serveisw3.net Sun May 21 22:31:41 2006 From: gmc at serveisw3.net (=?UTF-8?B?R29uemFsbyBNb256w7Nu?=) Date: Mon, 22 May 2006 04:31:41 +0200 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <e4r4va$711$2@sea.gmane.org> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <44710145.6040603@serveisw3.net> <e4r4va$711$2@sea.gmane.org> Message-ID: <4471228D.4020100@serveisw3.net> Robert Kern escribi?: >Gonzalo Monz?n wrote: > > >>sturlamolden escribi?: >> >> > > > >>>I don't think this is safe. MinGW links with msvcrt.dll whereas the >>>main Python distribution links with msvcr71.dll (due to Visual C++ >>>2003). It is not safe to mix and blend different C runtime libraries. >>>If you are to build a C extension with MinGW, you also need to build >>>Python against msvcrt.dll, i.e. you have to use a Python built with >>>MinGW or Visual C++ 6.0. There other option is to make MinGW link >>>against msvcr71.dll. I don't know if that is feasible. >>> >>> >>I use Python 2.4.3 (msvcrt71) and I succesfully installed the last >>version of binutils, pyrex and MinGW, some weeks ago, using Julien Fiore >>step-by-step guide, so "my" MinGW is linking with msvcrt71.dll, with the >>default configuration. >> >>I don't understand why do you say MinGW links with msvcrt.dll... perhaps >>you've got an older version than the ones Julien posted? >> >> > >Nope. He said it because it is true. Use Dependency Walker >(http://www.dependencywalker.com) to see for yourself what DLLs are linked in. >In fact, *both* DLLs are linked in. Sometimes this works fine, other times it >does not. > >If you would like a more visceral demonstration, write a small C++ extension >that uses std::cout. > > > I see there are both libraries linked in my pyrex modules... However, when one should expect to have problems with this "dll nightmare", if you always provide the right msvcr71.dll bundled within your project -I mean, using py2exe by example- ? Of course if you didn't bundle the right crt, it does depend on the available crt on target system... then you would be in trouble if user doesn't have msvcrt71, or anyway, could be in trouble linking the "right" library? Thanks for any explanation. Regards, Gonzalo From grflanagan at yahoo.co.uk Fri May 19 00:34:37 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 18 May 2006 21:34:37 -0700 Subject: Newbie append() question References: <mailman.5922.1148004495.27775.python-list@python.org> Message-ID: <1148013277.531319.111090@38g2000cwa.googlegroups.com> Brian Blazer wrote: > I promise that this is not homework. I am trying to self teach here > and have run into an interesting problem. I have created a method > that asks for a class name and then is supposed to add it to classes > []. Here is a snippet: > > def getCurrentClasses(): > classes = [] > print 'Please enter the class name. When finished enter D.' > while (c != "D"): > c = raw_input("Enter class name") > if (c != "D"): > classes.append(c) > > I have been running this in the interactive interpreter and if I > print the list I get the string "Enter class name" as the first entry > in the list and what was supposed to be the first entry as the second > element like this: > > Enter class name: cs1 > ['Enter class name: cs1'] > > I guess that I assumed that c would be equal to the value entered by > the user not the prompt string. It actually looks like it is taking > the whole thing as one string. But then if I enter more classes I > get this: > > Enter class name: cs2 > ['Enter class name: cs1', 'cs2'] > > So with the second and successive inputs, it appends the entered string. > > Hopefully someone could enlighten me as to what is going on and maybe > offer a suggestion to help me figure this one out. > > Thank you for your time, > > Brian > brian at brianandkate.com your code gives me: UnboundLocalError: local variable 'c' referenced before assignment Is this the exact code you ran? This should work: def getCurrentClasses(): classes = [] print 'Please enter the class name. When finished enter D.' c = None while (c != "D"): c = raw_input("Enter class name") if (c != "D"): classes.append(c) print classes but you are checking the same condition twice: c!= 'D', which is unnecessary.Try: def getCurrentClasses2(): classes = [] print 'Please enter the class name. When finished enter D.' while True: c = raw_input("Enter class name: ") if (c != "D"): classes.append(c) else: break print classes getCurrentClasses2() Gerard From claird at lairds.us Sun May 14 12:31:25 2006 From: claird at lairds.us (Cameron Laird) Date: Sun, 14 May 2006 16:31:25 +0000 Subject: count items in generator References: <1147583147.117388.72680@d71g2000cwd.googlegroups.com> <1hfarom.1lfetjc18leddeN%aleax@mac.com> Message-ID: <tj2kj3-82b.ln1@lairds.us> In article <1hfarom.1lfetjc18leddeN%aleax at mac.com>, Alex Martelli <aleax at mac.com> wrote: . . . >My preference would be (with the original definition for >words_of_the_file) to code > > numwords = sum(1 for w in words_of_the_file(thefilepath)) . . . There are times when numwords = len(list(words_of_the_file(thefilepath)) will be advantageous. For that matter, would it be an advantage for len() to operate on iterables? It could be faster and thriftier on memory than either of the above, and my first impression is that it's sufficiently natural not to offend those of suspicious of language bloat. From sybrenUSE at YOURthirdtower.com.imagination Thu May 11 08:58:17 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Thu, 11 May 2006 14:58:17 +0200 Subject: redirecting print to a a file References: <7JudnYwllewrrv7ZRVn-vA@comcast.com> Message-ID: <slrne66d79.d4s.sybrenUSE@schuimige.stuvel.eu> AndyL enlightened us with: > Can I redirect print output, so it is send to a file, not stdout. Change sys.stdout to a file object. > I have a large program and would like to avoid touching hundreds of > print's. I can suggest using the logging module instead of print. It's much more flexible than prints, and well suited for large programs. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From phddas at yahoo.com Wed May 10 17:56:59 2006 From: phddas at yahoo.com (Gary Wessle) Date: 11 May 2006 07:56:59 +1000 Subject: combined files together References: <87psirslhy.fsf@localhost.localdomain> <mailman.5416.1146898830.27775.python-list@python.org> <87slnmog19.fsf@localhost.localdomain> <slrne60k9e.ea7.edeveaud@localhost.localdomain> Message-ID: <873bfh1r2s.fsf@localhost.localdomain> Eric Deveaud <edeveaud at pasteur.fr> writes: > Gary Wessle wrote: > > > > I need to traverse those files in the order they were created > > chronologically. listdir() does not do it, is there a way besides > > build a list then list.sort(), then for element in list_of_files open > > element? > > are the name of the files describing the cration date, yes > or have to rely on the creation date ? no > > if the name allows to discriminate the chronology, check glob module. I just tried glob, it does not put out a list with file names sorted. > > Eric From robert.kern at gmail.com Sat May 13 19:20:03 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sat, 13 May 2006 18:20:03 -0500 Subject: Cellular automata and image manipulation In-Reply-To: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> References: <1147561778.799956.154770@d71g2000cwd.googlegroups.com> Message-ID: <e45pj3$dmk$1@sea.gmane.org> defcon8 at gmail.com wrote: > Hello. I have recently been experimenting with cellular automata and I > would like to know how I could convert a 2d list of 0's and 1's into > white and black squares on an image. I have tried to install matplotlib > and also NumTut but both to no avail. There seem to be bugs in their > installation and I have not been able to figure out how to resolve > them. I would be happy for someone to suggest a library and maybe give > a simple example of how to do what I want to do. Why don't you explain your problems with installing numpy (the Numeric Tutorial is out of date; don't bother with NumTut) or matplotlib on the appropriate mailing lists? http://lists.sourceforge.net/lists/listinfo/numpy-discussion http://lists.sourceforge.net/lists/listinfo/matplotlib-users -- 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 john at castleamber.com Wed May 24 11:58:44 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:58:44 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468767.551285.14290@u72g2000cwu.googlegroups.com> <Xns97CD6A2A4F305castleamber@130.133.1.4> <1148484776.213699.34610@i39g2000cwa.googlegroups.com> Message-ID: <Xns97CD6FAE520C8castleamber@130.133.1.4> olsongt at verizon.net wrote: > Both johnbokma.com and castleamber.com are hosted by seagull.net. Here > is a link to their TOS: > > http://www.seagull.net/tos.html > > Who can come up with the most violations that John is committing on > this thread? I count 4. Be my guest: hostmaster at seagull dot net. -- 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 mramos at montevideo.com.uy Fri May 12 18:34:45 2006 From: mramos at montevideo.com.uy (Marcelo Ramos) Date: Fri, 12 May 2006 19:34:45 -0300 Subject: How to pass variables between scripts? In-Reply-To: <5290E77B1FE2FE40B82AA54158825F0602EF50F5@hqosex01.fao.org> References: <5290E77B1FE2FE40B82AA54158825F0602EF50F5@hqosex01.fao.org> Message-ID: <44650D85.80303@montevideo.com.uy> Gross, Dorit (SDRN) escribi?: > Dear list, > > I am an absolute newbie to python and would appreciate your help very much > :) > > I am trying to write a little python script that wraps a set of external > scripts. The external scripts are either also written in python or are simple > bash scripts. My wrapping script should be able to send an argument to the > first script, to execute it, to read its results and to send them then as > arguments into the next script. > > This is the first part that I have written so far: > > #! /usr/local/bin/python > # test_exec.py > > import os, sys, glob > > fileList = glob.glob('/data/*.ZIP') > > for f in fileList: > try: > globvars = {'infile' : f} > locvars = {} > execfile('/scripts/second.py', globvars(), locvars) > except IOError: > exit(0) > print locvars > > > And this is what happens when calling test_exec.py > > ./test_exec.py > Traceback (most recent call last): > File "./test_exec.py", line 19, in ? > execfile('/scripts/second.py', vars(), results) > TypeError: 'dict' object is not callable > > > I tried already to modify the script in different ways but wasn't successful > so far to make it running. Could you maybe help what I am missing? Further, I > am not sure how the second python has to look like to actually read what is > given in "globvars" and to sent its results into "locvars". > > Or might os.popen* be a better option? > > > You are calling the dictionary globvars as a function then the error. The fixed line is: execfile('/scripts/second.py', globvars, locvars) What you want is the function globals(). Try putting this line in second.py: print globals()['infile'] Using the dictionary returned by globals() you can make second.py to read the contents of testexec.py's globvars dictionary. locvars is populated with the local variables of second.py and that is what you want. Regards. -- Marcelo Ramos Fedora Core 5 | 2.6.16 Socio UYLUG Nro 125 From raathm at gmail.com Thu May 4 08:03:07 2006 From: raathm at gmail.com (Mike) Date: 4 May 2006 05:03:07 -0700 Subject: RegEx with multiple occurrences In-Reply-To: <mailman.5313.1146743687.27775.python-list@python.org> References: <1146742939.692014.201270@e56g2000cwe.googlegroups.com> <mailman.5313.1146743687.27775.python-list@python.org> Message-ID: <1146744187.681812.266110@y43g2000cwc.googlegroups.com> Tim - you're a legend. Thanks. From riklaunim at gmail.com Wed May 31 18:04:41 2006 From: riklaunim at gmail.com (=?ISO-8859-2?Q?piotr_mali=F1ski?=) Date: Wed, 31 May 2006 23:04:41 +0100 Subject: is a wiki engine based on a cvs/svn a good idea? Message-ID: <1f7f7cf70605311504q1bb9660em2a8e6dcefd01e49d@mail.gmail.com> I'm planning to wite a fully featured wiki in Python in one of frameworks. I've seen some notes about wiki/documentation management scripts that use SVN as a data storage/versioning. I've been using SVN a bit but I don't know if it's a good idea to use it in a wiki engine. Pro: versioning / diffs, Cons: you need your own svn/cvs repository, can pyLucene or Xapwrap index this? From nobody at 127.0.0.1 Fri May 12 19:36:27 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Fri, 12 May 2006 23:36:27 GMT Subject: unzip zip files References: <1147470349.415553.324710@y43g2000cwc.googlegroups.com> <mailman.5649.1147474044.27775.python-list@python.org> Message-ID: <%Z89g.5104$fb2.2672@newssvr27.news.prodigy.net> Marcelo Ramos wrote: > DataSmash escribi?: >> file into the subdirectory, but unzips the contents into the >> root (current) directory. I want the contents of the zip file >> unloaded into the newly created subdirectory where the zip file is. >> > > See "-d" zip's parameter in man zip. or change the working dir before calling unzip. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From brian at sweetapp.com Sun May 7 03:54:48 2006 From: brian at sweetapp.com (brian at sweetapp.com) Date: 7 May 2006 00:54:48 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> <87bquaskap.fsf@rpi.edu> Message-ID: <1146988487.941796.32550@j73g2000cwa.googlegroups.com> Bill Atkins wrote: > Does Python have any support for closures? If so, ignore this point. > But if not, what about examples like this: > > (defun make-window (window observer) > ;; initialization code here > (add-handler window 'close > (lambda (event) > (notify observer event))) > ;; more code) > > Being able to keep pass around state with functions is useful. I agree and Python supports this. What is interesting is how counter-intuitive many programmers find this. For example, one of my colleges (who is a reasonably average programmer), was completely stumped by this: >>> def right_partial(fn, *args): ... def inner(*innerargs): ... return fn(*(innerargs + args)) ... return inner ... >>> square = right_partial(pow, 2) >>> square(5) 25 >>> cube = right_partial(pow, 3) >>> cube(5) 125 (for those of you unfamiliar with Python, the '>>>' and '...' means that I typed this in the interactive shell) So I try to use this sort of pattern sparingly because many programmers don't think of closures as a way of saving state. That might be because it is not possible to do so in most mainstream languages. There are already some people in the Python community who think that Python has already gone too far in supporting "complex" language features and now imposes two steep a learning curve i.e. you now have to know a lot to be considered a Python expert. And there is a lot of resistance to adding features that will raise the bar even higher. > There are also cases where a function is so trivial that the simplest > way to describe it is with its source code, where giving it a name and > putting it at the beginning of a function is just distracting and > time-consuming. E.g.: > > (remove-if (lambda (name) > (find #\- name :test #'char=)) > list-of-names) There are some ways to write it in Python (if I understand the code): # prefered [name for name in list_of_names if '-' not in name] OR: # 2nd choice def contains_no_dash(name): return '-' not in name filter(contains_no_dash, list_of_names) # not recommended filter(lambda name: return '-' not in name, list_of_names) > What's the sense of giving that function its own name? It's much > clearer to simply write it in place. Yes, it's _possible_ to use > named functions, but in this case its functionality is so simple that > it's clearer to simply type it in place. Why is this expressiveness a > bad thing, aside from its power to wreck an indentation-significant > language? There are a few people in the Python community who think that unnamed functions are inherently inferior to named ones because the name provides documentation. The majority probably just don't care about the issue at all. I will say that I am not sure that I know what your LISP code does. However, even if you didn't understand the Python code in my named-function version, the name "contains_no_dash" might provide you with a small clue. Cheers, Brian From johnjsal at NOSPAMgmail.com Tue May 2 13:35:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 02 May 2006 17:35:36 GMT Subject: simultaneous assignment In-Reply-To: <4bpj08F12b91rU1@uni-berlin.de> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <4bpj08F12b91rU1@uni-berlin.de> Message-ID: <ILM5g.2034$No6.43629@news.tufts.edu> Diez B. Roggisch wrote: > Then use a Proposition-class that holds the actual value. > >> Another thing I'm trying to do is write a function that tests to see if >> a list contains exactly one true item, and the rest are false (obviously >> this would have to be a list of boolean values, I guess). > > No - you can for example override the comparison-semantics on the > Proposition-class to be comparable with True/False with the proper > semantics: Hmm, classes still scare me a little, but I should consider this. The only thing is, it is not known in advance if the propositions are true or false, you have to figure that out yourself based on the combination of the statements given. I don't know if this changes the idea behind your Proposition class...I'll have to give it some more thought. From bdesth.quelquechose at free.quelquepart.fr Tue May 30 20:48:32 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 31 May 2006 02:48:32 +0200 Subject: interactive programme (voice) In-Reply-To: <mailman.6334.1149022649.27775.python-list@python.org> References: <mailman.6334.1149022649.27775.python-list@python.org> Message-ID: <447cb869$0$20889$626a54ce@news.free.fr> nigel a ?crit : > hi i have wrote an interactive programme,this is a small section of it. > #This is my first programme writing in python > s = raw_input ("hello what's your name? ") > if s=='carmel': > print "Ahh the boss's wife" > if s=='melvyn': > print "your the boss's dad" > if s=='rebecca': > print "you must be the wreath woman" > if s=='gareth ': > print "You must be the trucker" > if s=='carol': > print "you must be my boss's mom" The problem with this code is that: - it does a lots of useless tests (ie : even if the user enters 'carmel', all other names will be tested too). - it doesn't handle the default case (any other name than the one you test for) A minimal amelioration would be to use if/elif/else: s = raw_input ("hello what's your name? ") if s == 'carmel': print "Ahh the boss's wife" elif s == 'melvyn': print "your the boss's dad" elif s == 'rebecca': print "you must be the wreath woman" elif s == 'gareth ': print "You must be the trucker" elif s=='carol': print "you must be my boss's mom" else: # default print "I'm afraid I don't know you..." Now this is a little better, but still not very pythonic. We have a nice thing in Python named a dict (for 'dictionnary'). It stores pairs of key:value - and FWIW, it's the central data structure in Python, so you'll see them quite a lot. There very handy for this kind of use case: greetings = { 'carmel' : "Ahh the boss's wife", 'melvyn' : "your the boss's dad", 'rebecca': "you must be the wreath woman", 'gareth ': "You must be the trucker", 'carol' : "you must be my boss's mom", } name = raw_input ("hello what's your name? ") print greetings.get(name, "I'm afraid I don't know you...") > What i was wandering is there a way i can get sound, <sorry> Now this is a sound question !-) </sorry> >i mean instead of getting > it to just print text on my screen i would like my computer to say it. This depends mostly on your computer and what's installed on it. And this is not part of the standard lib AFAIK. From NOatkinwSPAM at rpi.edu Sat May 6 06:42:21 2006 From: NOatkinwSPAM at rpi.edu (Bill Atkins) Date: Sat, 06 May 2006 06:42:21 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> Message-ID: <87mzdvo2nm.fsf@rpi.edu> "Martin P. Hellwig" <mhellwig at xs4all.nl> writes: > Bill Atkins wrote: > <cut> >> >> How do you define scalability? >> > http://www.google.com/search?hl=en&q=define%3Ascalability&btnG=Google+Search > > ;-) > > -- > mph OK, my real question is: what features of Python make it "scalable"? -- This is a song that took me ten years to live and two years to write. - Bob Dylan From tim.peters at gmail.com Fri May 19 15:51:28 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 19 May 2006 15:51:28 -0400 Subject: Segmenting a pickle stream without unpickling In-Reply-To: <446d8566$1_3@news.bluewin.ch> References: <446d8566$1_3@news.bluewin.ch> Message-ID: <1f7befae0605191251q3a08d5a7u83e2259f95d3a333@mail.gmail.com> [Boris Borcic] > Assuming that the items of my_stream share no content (they are > dumps of db cursor fetches), is there a simple way to do the > equivalent of > > def pickles(my_stream) : > from cPickle import load,dumps > while 1 : > yield dumps(load(my_stream)) > > without the overhead associated with unpickling objects > just to pickle them again ? cPickle (but not pickle.py) Unpickler objects have a barely documented noload() method. This "acts like" load(), except doesn't import modules or construct objects of user-defined classes. The return value of noload() is undocumented and usually useless. ZODB uses it a lot ;-) Anyway, that can go much faster than load(), and works even if the classes and modules referenced by pickles aren't available in the unpickling environment. It doesn't return the individual pickle strings, but they're easy to get at by paying attention to the file position between noload() calls. For example, import cPickle as pickle import os # Build a pickle file with 4 pickles. PICKLEFILE = "temp.pck" class C: pass f = open(PICKLEFILE, "wb") p = pickle.Pickler(f, 1) p.dump(2) p.dump([3, 4]) p.dump(C()) p.dump("all done") f.close() # Now use noload() to extract the 4 pickle # strings in that file. f = open(PICKLEFILE, "rb") limit = os.path.getsize(PICKLEFILE) u = pickle.Unpickler(f) pickles = [] pos = 0 while pos < limit: u.noload() thispos = f.tell() f.seek(pos) pickles.append(f.read(thispos - pos)) pos = thispos from pprint import pprint pprint(pickles) That prints a list containing the 4 pickle strings: ['K\x02.', ']q\x01(K\x03K\x04e.', '(c__main__\nC\nq\x02o}q\x03b.', 'U\x08all doneq\x04.'] You could do much the same by calling pickletools.dis() and ignoring its output, but that's likely to be slower. From runlevelten at gmail.com Sun May 28 14:44:05 2006 From: runlevelten at gmail.com (Ten) Date: Sun, 28 May 2006 19:44:05 +0100 Subject: send an email with picture/rich text format in the body In-Reply-To: <1148797671.937857.151250@y43g2000cwc.googlegroups.com> References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <iAJ9g.76667$H71.54770@newssvr13.news.prodigy.com> <1148797671.937857.151250@y43g2000cwc.googlegroups.com> Message-ID: <200605281944.06128.runlevelten@gmail.com> On Sunday 28 May 2006 07:27, anya wrote: > Acctualy there is a solution: > see http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/473810 > (thanks darrin massena for sharing) > > and , if you will set all the neccessary parametrs, it won't be > recognized as a > spam, > thanks Ahah - a slightly different thing to what I thought you were after. I'd looked at "every one who open the email will see the picture" and discounted html mail. Glad you got what you wanted done, done. Ten. -- There are 10 types of people in this world, those who understand binary, and those who don't. From c.gillespie at ncl.ac.uk Fri May 5 08:35:30 2006 From: c.gillespie at ncl.ac.uk (Colin Gillespie) Date: Fri, 05 May 2006 13:35:30 +0100 Subject: regex to exctract informations In-Reply-To: <445a58ba$0$18262$636a55ce@news.free.fr> References: <445a58ba$0$18262$636a55ce@news.free.fr> Message-ID: <e3fgqk$63t$1@ucsnew1.ncl.ac.uk> Bob wrote: > Dears, > > I am trying to search and replace strings with regex. > > The string is identified by a keyword : > > IDImage("1M234567"); > DescriptionImage("Desc of the Image 1"); > > I want to exctract the IDImage (1M234567 ) and the Description. > > The ID are characters and numbers, the description too. > > Thx, > > Bertrand If the string is always in IDImage("#####"); Then what about x='IDImage("#####");' print x[9:-3] Likewise for the Description. HTH Colin From vmalloc at gmail.com Tue May 9 08:15:28 2006 From: vmalloc at gmail.com (Rotem) Date: 9 May 2006 05:15:28 -0700 Subject: import in execv after fork Message-ID: <1147176928.836116.17000@i40g2000cwc.googlegroups.com> Hello, We have been encountering several deadlocks in a threaded Python application which calls subprocess.Popen (i.e. fork()) in some of its threads. This has occurred on Python 2.4.1 on a 2.4.27 Linux kernel. Perliminary analysis of the hang shows that the child process blocks upon entering the execvp function, in which the import_lock is acquired due to the following line: def _execvpe(file, args, env=None): from errno import ENOENT, ENOTDIR ... It is known that when forking from a pthreaded application, acquisition attempts on locks which were already locked by other threads while fork() was called will deadlock. Due to these oddities I was wondering if it would be better to extract the above import line from the execvpe call, to prevent lock acquisition attempts in such cases. I'd appreciate any opinions you might have on the subject. Thanks in advance, Rotem From jhefferon at smcvt.edu Fri May 5 20:02:29 2006 From: jhefferon at smcvt.edu (Jim) Date: 5 May 2006 17:02:29 -0700 Subject: Elegent solution to replacing ' and " ? In-Reply-To: <1146872815.237738.57590@j73g2000cwa.googlegroups.com> References: <1146872815.237738.57590@j73g2000cwa.googlegroups.com> Message-ID: <1146873749.458665.126940@j73g2000cwa.googlegroups.com> Are you sure that your dB interface module doesn't do this for you? What dB and interface are you using? Jim From me at privacy.net Fri May 19 09:08:17 2006 From: me at privacy.net (Dan Sommers) Date: Fri, 19 May 2006 09:08:17 -0400 Subject: Python sqlite and regex. References: <mailman.5942.1148042842.27775.python-list@python.org> Message-ID: <m2y7wyp3ge.fsf@unique.fqdn> On Fri, 19 May 2006 14:47:10 +0200, Julien ARNOUX <julien.arnoux at ext.cri74.org> wrote: > cur.execute("select foo from test where foo regex 'aa.[0-9])") > and the error is: > cur.execute('select foo from test where foo regex tata') > apsw.SQLError: SQLError: near "regex": syntax error I think you're missing a closing quote on that regex; or perhaps that's an extra closing parenthesis at the end. Also, it's probably best to let the database module do any escaping you may need. For example: fooregex = r'aa.[0-9]' sql = 'select foo from test where foo regex %s' cur.execute( sql, tuple( fooregex ) ) See the DP API spec for more information. Regards, Dan -- Dan Sommers <http://www.tombstonezero.net/dan/> "I wish people would die in alphabetical order." -- My wife, the genealogist From claird at lairds.us Tue May 30 13:18:14 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 30 May 2006 17:18:14 +0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <akauk3-l2l.ln1@lairds.us> Message-ID: <mbbuk3-l2l.ln1@lairds.us> In article <akauk3-l2l.ln1 at lairds.us>, I confused matters with: > . > . > . >!? I hadn't realized there's no such monitor ... What do you >think of <URL: http://wiki.tcl.tk/moni >? Ugh. Please ignore, all; this was a first draft of what was intended for private e-mail. It escaped the corral through a mistake. I apologize for the distraction. From maric at aristote.info Fri May 26 09:21:10 2006 From: maric at aristote.info (Maric Michaud) Date: Fri, 26 May 2006 15:21:10 +0200 Subject: Use of lambda functions in OOP, any alternative? In-Reply-To: <4474bfe9$1@nntp0.pdx.net> References: <1148392558.891735.115060@j55g2000cwa.googlegroups.com> <4474bfe9$1@nntp0.pdx.net> Message-ID: <200605261521.13063.maric@aristote.info> Le Mercredi 24 Mai 2006 22:37, Scott David Daniels a ?crit?: > ? ? ?class Base(object): > ? ? ? ? ?def __init__(self, attr): > ? ? ? ? ? ? ?self._attr = attr > ? ? ? ? ?def getattr(self): > ? ? ? ? ? ? ?return self._attr > ? ? ? ? ?def attr(self): > ? ? ? ? ? ? ?return self.getattr() > ? ? ? ? ?attr = property(fget=attr) but this has one drawback IMO, if you also want a virtual setter, you won't be able to override both of them. This convention would be better to avoid lambdas : class Base(object): def __init__(self, attr): self._attr = attr def getattr(self): return self._attr def __gattr(self): # double _ shows that this method is not virtual return self.getattr() def setattr(self,v): self._attr = v def __sattr(self,v): return self.setattr(v) attr = property(fget=__gattr, fset=__sattr) But, this is too verbose for me, I would opt for the lambda syntax :). _____________ Maric Michaud _____________ Aristote - www.aristote.info 3 place des tapis 69004 Lyon Tel: +33 426 880 097 From pmartin at snakecard.com Fri May 5 15:05:40 2006 From: pmartin at snakecard.com (Philippe Martin) Date: Fri, 05 May 2006 14:05:40 -0500 Subject: cross platform libraries References: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> <tsml52pij438mt1goq071663t1r415nljl@4ax.com> Message-ID: <8mN6g.8747$B42.7664@dukeread05> Through Wine maybe ? Philippe Dennis Lee Bieber wrote: > On 4 May 2006 09:57:15 -0700, diffuser78 at gmail.com declaimed the > following in comp.lang.python: > >> I am using python on a linux terminal. >> >> I want to shutdown a remote windows box. I found a script which does >> something like this. My question is can we use windows libraries in >> linux as follows .... >> >> import win32api >> import win32con >> import win32netcon >> import win32security >> import win32wnet >> > That set... HIGHLY UNLIKELY... They all rely upon having the M$ > kernel DLLs available... > > Now, if the remote box is running a telnet server, you might be able > to telnet over (logging in as the boxes admin account) and initiate a > shutdown from it... (I seem to have a "shutdown.exe" on my system). > -- > 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 nogradi at gmail.com Mon May 1 04:59:13 2006 From: nogradi at gmail.com (Daniel Nogradi) Date: Mon, 1 May 2006 10:59:13 +0200 Subject: [ANN] markup.py 1.3 - an HTML and XML writer Message-ID: <5f56302b0605010159t702ef8dbl672e149de3d1e4ac@mail.gmail.com> The new 1.3 release of markup.py is available from http://markup.sourceforge.net/ The markup module attempts to make it easier to output HTML or XML from a python program without cluttering your code with tags in a simple and flexible way. Changes * improved documentation * function added to optionally escape < and > as &tl; and &gt; * several functions added for frequently used HTML tag combinations to speed up things From bignose+hates-spam at benfinney.id.au Thu May 4 22:28:55 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 05 May 2006 12:28:55 +1000 Subject: Newbie question on code vetting References: <yvT5g.132$yh.117@trnddc04> <mailman.5299.1146719004.27775.python-list@python.org> <_%w6g.44217$C63.42016@trnddc06> Message-ID: <87mzdxb3x4.fsf@benfinney.id.au> <william.boquist at gte.net> writes: > I hope the following message will not result in scorn being heaped > upon me. We try to heap scorn not upon individuals, but upon scorn-worthy ideas. Also, we heap scorn upon people who heap their responses on top of the quoted material. Please don't top-post. > It seems to me that Open Source generally would be more pervasive if > there was more transparency with respect to the practices observed > within the projects. You mean like publicly-accessible and archived developer discussion forums? Bug tracking systems which anyone can submit to? Source code with copyright statements and license grants directly in the files for anyone to examine? Who is it that needs to improve their transparency, again? I would love for all software vendors to be held to this standard. Are you suggesting your organisation expects some higher level of transparency from free software, when it happily accepts a far lower level of transparency from proprietary vendors? (good sigmonster, have a biscuit) -- \ "The right to search for truth implies also a duty; one must | `\ not conceal any part of what one has recognized to be true." | _o__) -- Albert Einstein | Ben Finney From Serge.Orlov at gmail.com Mon May 8 18:44:04 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 8 May 2006 15:44:04 -0700 Subject: Using time.sleep() in 2 threads causes lockup whenhyper-threading is enabled In-Reply-To: <mailman.5487.1147125430.27775.python-list@python.org> References: <mailman.5487.1147125430.27775.python-list@python.org> Message-ID: <1147128244.193773.303270@j73g2000cwa.googlegroups.com> Delaney, Timothy (Tim) wrote: > OlafMeding at gmail.com wrote: > > > I am a bit surprised that nobody else has tried running the short > > Python program above on a hyper-threading or dual core / dual > > processor system. > > Does it happen every time? Have you tried it on multiple machines? Is it > possible that that one machine is having problems? Does it take the same > amount of time each run to replicate - and if so, how long is that (give > or take a minute)? > > Until you can answer these questions with definite answers, people are > not going to dedicate machines *that they use* for hours on end trying > to replicate it. And from this thread, the time required appears to be > "minutes to hours". That suggests you have a race condition which > results in a deadlock - and of course, that is more likely to occur on a > dual-core or dual-cpu machine, as you really have multiple threads > executing at once. The test program in question doesn't require a dedicated machine and it doesn't consume a lot of CPU resources since it sleeps most of the time. > I'm surprised that so many people have been willing to dedicate as much > time as they have, but then again considering the people involved it's > not quite so surprising. This "problem" doesn't require more time than any other in comp.lang.python which I try to help to resolve. In fact, since OP is not a newbie, it took less time than some newbie questions. From martin.witte at gmail.com Thu May 18 13:09:47 2006 From: martin.witte at gmail.com (wittempj@hotmail.com) Date: 18 May 2006 10:09:47 -0700 Subject: Complex evaluation bug In-Reply-To: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> Message-ID: <1147972187.344227.86990@j33g2000cwa.googlegroups.com> py> c = complex(1, 3) py> print c (1+3j) py> d = complex('1+3j') py> print d (1+3j) py> str(1+3j) '(1+3j)' complex takes two numbers, or a string representing a complex number. the string you supply isn't a representation of valid complex number. From No.Spam at Spam.none Tue May 2 13:00:42 2006 From: No.Spam at Spam.none (I. Myself) Date: Tue, 02 May 2006 17:00:42 GMT Subject: Can Python kill a child process that keeps on running? In-Reply-To: <mailman.5200.1146536105.27775.python-list@python.org> References: <g0x5g.104639$7a.102977@pd7tw1no> <1146532884.872505.154370@i40g2000cwc.googlegroups.com> <MTy5g.104796$7a.25459@pd7tw1no> <mailman.5200.1146536105.27775.python-list@python.org> Message-ID: <_eM5g.106190$P01.81874@pd7tw3no> Steve Holden wrote: > I. Myself wrote: >> Serge Orlov wrote: >> >>> I. Myself wrote: >>> >>> >>>> Suppose we spawn a child process with Popen. I'm thinking of an >>>> executable file, like a compiled C program. >>>> Suppose it is supposed to run for one minute, but it just keeps going >>>> and going. Does Python have any way to kill it? >>>> >>>> This is not hypothetical; I'm doing it now, and it's working pretty >>>> well, but I would like to be able to handle this run-on condition. >>>> I'm >>>> using Windows 2000, but I want my program to be portable to linux. >>>> >>> >>> On linux it's pretty easy to do, just setup alarm signal. On windows >>> it's not so trivial to the point you cannot do it using python.org >>> distribution, you will need to poke in low level C API using win32 >>> extensions or ctypes. AFAIK twisted package <http://twistedmatrix.com> >>> has some code to help you. Also take a look at buildbot sources >>> <http://buildbot.sf.net> that uses twisted. Buildbot has the same >>> problem as you have, it needs to kill run away or non-responding >>> processes. >>> >> >> That is bad news. Thanks anyway; bad news is better than no news. >> > Note, however, that ctypes is planned to be a part of the 2.5 > distribution, so while there may not be a platform-independent way to > achieve your goals you will at leats be able to do so without external > extensions. I'm an intermediate Python programmer. Can you explain to me how ctypes will let me kill a child process? Thanks, Mitchell Timin -- I'm proud of http://ANNEvolve.sourceforge.net. If you want to write software, or articles, or do testing or research for ANNEvolve, let me know. Humans may know that my email address is: (but remove the 3 digit number) zenguy at shaw666 dot ca From paul at boddie.org.uk Thu May 18 19:48:21 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 18 May 2006 16:48:21 -0700 Subject: WTF? Printing unicode strings References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <rNOSPAMon-4204E3.14492518052006@news.gha.chartermi.net> <mailman.5906.1147989402.27775.python-list@python.org> <rNOSPAMon-E4E1BE.15040818052006@news.gha.chartermi.net> <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <rNOSPAMon-2E5F04.16120918052006@news.gha.chartermi.net> Message-ID: <1147996101.034614.247970@u72g2000cwu.googlegroups.com> Ron Garret wrote: > > But what about this: > > >>> f2=open('foo','w') > >>> f2.write(u'\xFF') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > UnicodeEncodeError: 'ascii' codec can't encode character u'\xff' in > position 0: ordinal not in range(128) > >>> > > That should have nothing to do with my terminal, right? Correct. But first try to answer this: given that you want to write the Unicode character value 255 to a file, how is that character to be represented in the file? For example, one might think that one could just get a byte whose value is 255 and write that to a file, but what happens if one chooses a Unicode character whose value is greater than 255? One could use two bytes or three bytes or as many as one needs, but what if the lowest 8 bits of that value are all set? How would one know, if one reads a file back and gets a byte whose value is 255 whether it represents a character all by itself or is part of another character's representation? It gets complicated! The solution is that you choose an encoding which allows you to store the characters in the file, thus answering indirectly the question above: encodings determine how the characters are represented in the file and allow you to read the file and get back the characters you put into it. One of the most common encodings suitable for the storage of Unicode character values is UTF-8, which has been designed with the above complications in mind, but as long as you remember to choose an encoding, you don't have to think about it: Python takes care of the difficult stuff on your behalf. In the above code you haven't made that choice. So, to answer the above question, you can either... * Use the encode method on Unicode objects to turn them into plain strings, then write them to a file - at that point, you are writing specific byte values. * Use the codecs.open function and other codecs module features to write Unicode objects directly to files and streams - here, the module's infrastructure deals with byte-level issues. * If you're using something like an XML library, you can often pass a normal file or stream object to some function or method whilst stating the output encoding. There is no universally correct answer to which encoding should be used when writing Unicode character values to files, contrary to some beliefs and opinions which, for example, lead to people pretending that everything is in UTF-8 in order to appease legacy applications with the minimum of tweaks necessary to stop them from breaking completely. Thus, Python doesn't make a decision for you here. Paul From bdesth.quelquechose at free.quelquepart.fr Tue May 9 22:34:54 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 10 May 2006 04:34:54 +0200 Subject: Dictionaries -- ahh the fun.. (newbie help) In-Reply-To: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> References: <1147213029.045866.297240@y43g2000cwc.googlegroups.com> Message-ID: <4461226a$0$26186$626a54ce@news.free.fr> rh0dium a ?crit : > Hi all, > > Can someone help me out. I am trying to determing for each run whether > or not the test should pass or fail but I can't seem to access the > results .. > (snip) > cells={} > > cells["NOR3X1"]= { > 'run' : [ 'lvs', 'drc' ], > 'results' : [{ 'lvs' : 'pass' }, > { 'drc' : 'fail' }] > } > > cells["OR3X1"] = { > 'run' : [ 'lvs' ], > 'results' : [{ 'lvs' : 'pass' }] > } > > cells["AND3X1"] = { > 'run' : [ 'drc' ], > 'results' : [{ 'drc' : 'fail' }] > } > > > def main(): > > for cell in cells: > print cell > for run in cells[cell]['run']: > print cell, run, "should", > cells[cell]['results'].index(run) > > > I would expect the following > > OR3X1 > OR3X1 lvs should pass > NOR3X1 > NOR3X1 lvs should pass > NOR3X1 drc should fail > AND3X1 > AND3X1 drc should fail > Congratulations, almost a perfect post - you just forgot to tell the actual result !-) >>> ## working on region in file /usr/tmp/python-99973O0... >>> main() OR3X1 OR3X1 lvs should Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/tmp/python-99973O0", line 24, in main ValueError: list.index(x): x not in list May I suggest that you type "help(list.index)" in your python shell ? > Alternatively can someone suggest a better structure ( and a lesson as > to the reasoning ) that would be great too!! What seems flawed is the cell['results'] : you use a list of dicts, each one having a single entry - which is somewhat useless. Since you want to use the values of cell['run'] to lookup the expected results, using a single dict for results makes things a bit more usable: cells={} cells["NOR3X1"]= { 'run' : [ 'lvs', 'drc' ], 'results' : {'lvs' : 'pass', 'drc' : 'fail' } } cells["OR3X1"] = { 'run' : [ 'lvs' ], 'results' : { 'lvs' : 'pass' } } cells["AND3X1"] = { 'run' : [ 'drc' ], 'results' : { 'drc' : 'fail' } } def main(): for cellname, cellcontent in cells.items(): print cellname for run in cellcontent['run']: print cellname, run, "should", cellcontent['results'][run] This runs and produces the expected output. Now let's simplify. The values of cell['run'] are uselessly duplicated as keys in cell['results'] - and duplication is Bad(tm). So let's get rid of this: cells={} cells["NOR3X1"]= { 'results' : {'lvs' : 'pass', 'drc' : 'fail' } } cells["OR3X1"] = { 'results' : { 'lvs' : 'pass' } } cells["AND3X1"] = { 'results' : { 'drc' : 'fail' } } Now we only have a single entry ('results') for each cell. This is a useless indirection level, so let's get rid of this too: cells={ "NOR3X1": { 'lvs' : 'pass', 'drc' : 'fail', }, "OR3X1" : { 'lvs' : 'pass', }, "AND3X1" : { 'drc' : 'fail', }, } Looks simpler, isn't it ?-) def main(): for cellname, cellcontent in cells.items(): print cellname for run, result in cellcontent.items(): print cellname, run, "should", result If you want to get the equivalent of cells[XXX]['runs'], just use cells[XXX].keys(). HTH From johnjsal at NOSPAMgmail.com Sat May 13 14:49:06 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 13 May 2006 14:49:06 -0400 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <pqna621sn8s3qk56dt58qsnud6olbammfv@4ax.com> References: <jz09g.2091$No6.46071@news.tufts.edu> <4465079d$0$11703$c3e8da3@news.astraweb.com> <446530ec$0$11696$c3e8da3@news.astraweb.com> <pqna621sn8s3qk56dt58qsnud6olbammfv@4ax.com> Message-ID: <44662a97$0$1949$c3e8da3@news.astraweb.com> Dennis Lee Bieber wrote: > On Fri, 12 May 2006 21:00:49 -0400, John Salerno > <johnjsal at NOSPAMgmail.com> declaimed the following in comp.lang.python: > >> Latest development: I turned off my firewall and it worked. :) > > Next step -- figure out what rule you need to define to the firewall > to permit it to work... Yeah, that's actually what I'm trying to do now. I'm not sure how to define it, but I assume it has something to do with 3306, since that's the default. I remember when I first installed MySQL on my computer, it would never get past the configuration wizard, also because of a port/firewall issue. So I uninstalled it, and then reinstalled it with the firewall off and it worked fine. And this works fine too with the firewall off, I just need to figure out what the criteria are for the new rule I need. From skip at pobox.com Sun May 14 19:18:47 2006 From: skip at pobox.com (skip at pobox.com) Date: Sun, 14 May 2006 18:18:47 -0500 Subject: comparing values in two sets In-Reply-To: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> References: <4467b6ed$0$1908$c3e8da3@news.astraweb.com> Message-ID: <17511.47831.563078.44592@montanaro.dyndns.org> John> I'd like to compare the values in two different sets to test if John> any of the positions in either set share the same value (e.g., if John> the third element of each set is an 'a', then the test fails). Do you really mean "set" and not "list"? Note that they are unordered. These two sets are equal: set(['b', 'a', 'c']) set(['a', 'b', 'c']) Skip From nholtz at docuweb.ca Fri May 12 14:20:43 2006 From: nholtz at docuweb.ca (nholtz) Date: 12 May 2006 11:20:43 -0700 Subject: Tkinter: ability to delete widgets from Text and then re-add them In-Reply-To: <1147457698.020383.213280@j33g2000cwa.googlegroups.com> References: <1147457698.020383.213280@j33g2000cwa.googlegroups.com> Message-ID: <1147458042.983652.238960@j33g2000cwa.googlegroups.com> Sigh. Of course, near the middle is supposed to be: #### delete the last one from Text widget = widgets[-1] From DustanGroups at gmail.com Thu May 18 18:25:55 2006 From: DustanGroups at gmail.com (Dustan) Date: 18 May 2006 15:25:55 -0700 Subject: Which is More Efficient? In-Reply-To: <mailman.5878.1147959629.27775.python-list@python.org> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <mailman.5878.1147959629.27775.python-list@python.org> Message-ID: <1147991154.936792.6490@j33g2000cwa.googlegroups.com> Fredrik Lundh wrote: > Dustan wrote: > > > I have a program that uses up a lot of CPU and want to make it is > > efficient as possible with what I have to work with it. So which of the > > following would be more efficient, knowing that l is a list and size is > > a number? > > > > l=l[:size] > > del l[size:] > > since you have the program, it shouldn't that hard to test the > two alternatives, should it ? > > (in theory, del should be faster in most cases, since it avoids > creating another object. but the only way to tell for sure is > to try it out). > > > If it makes a difference, everything in the list is mutable. > > the only difference between mutable and immutable objects in Python > is that mutable objects have methods that let you modify the object > contents, while immutable objects don't have such methods. And it can be referenced by different variables. What I was saying was that the contents weren't being copied over; it was only the list that was being copied in the first statement. > > </F> From onurb at xiludom.gro Fri May 19 08:45:25 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 14:45:25 +0200 Subject: memory error with zipfile module In-Reply-To: <mailman.5938.1148039030.27775.python-list@python.org> References: <mailman.5938.1148039030.27775.python-list@python.org> Message-ID: <446dbe4d$0$8013$626a54ce@news.free.fr> Hari Sekhon wrote: > I do > > import zipfile > zip=zipfile.ZipFile('d:\somepath\cdimage.zip') > zip.namelist() > ['someimage.iso'] > > then either of the two: > > A) file('someimage.iso','w').write(zip.read('someimage.iso')) > or > B) content=zip.read('someimage.iso') > > but both result in the same error: > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "D:\u\Python24\lib\zipfile.py", line 357, in read > bytes = dc.decompress(bytes) > MemoryError <ot>Is that the *full* traceback ?</ot> > I thought python was supposed to handle memory for you? Err... This doesn't mean that it bypasses system's memory management. http://pyref.infogami.com/MemoryError http://mail.zope.org/pipermail/zope/2004-October/153882.html """ MemoryError is raised by Python when an underlying (OS-level) allocation fails. (...) Normally this would mean that you were out of even virtual memory (swap), but it could also be a symptom of a libc bug, a bad RAM chip, etc. """ What do you think will append if you try to allocate a huge block when you've already eaten all available memory ? Do you really hope that Python will give you extra ram for free ?-) Please try this code: import zipfile zip=zipfile.ZipFile('d:\somepath\cdimage.zip') info = zip.getinfo('someimage.iso') csize = info.compress_size fsize = info.file_size print "someimage compressed size is : %s" % csize print "someimage real file size is : %s" % fsize print """ So, knowing how zipfile.read() is actually implemented, total needed ram is : %s """ % (csize + fsize) print "Well... Do I have that much memory available ???" > The python zipfile module is obviously broken... s/is obviously broken/could be improved to handle huge files/ Making such statements may not be the best way to make friends... > Any advise? Yes : Python is free software ('free' as in 'free speach' *and* as in 'free beer'), mostly written by benevolent contributors. So try and improve the zipfile module by yourself, and submit your enhancements. Then we all will be very grateful, and your name will be forever in the Python Hall of Fame. Or choose to behave as a whiny-whiny clueless luser making dumb statements, and your name will be buried for a long long time in a lot of killfiles. It's up to you !-) NB : If you go the first route, this may help: http://www.python.org/doc/2.4.2/lib/module-zlib.html with particular attention to the decompressobj. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From aurora00 at gmail.com Wed May 31 11:57:56 2006 From: aurora00 at gmail.com (aurora00 at gmail.com) Date: 31 May 2006 08:57:56 -0700 Subject: Find the context of importer Message-ID: <1149091076.533062.302640@c74g2000cwc.googlegroups.com> I'm using Python in a scripting environment. The host application would pass in some objects so that the script can act on it. But there are a number of things I like to add to every script to make it a decent environment, for example, setting up exception hook to show error properly. I tried to factorize this into a module called script_util. For example: ------------------------------------------------------------------------ script: # host application would pass in objects like window, document, etc. import script_util ... do something with window, document, etc, ... ------------------------------------------------------------------------ script_util.py: import sys def myExceptionHandler(...): importer.window.alert(message) sys.excepthook = myExceptionHandler sys.stdout = myOutputPipe ------------------------------------------------------------------------ However in order for script_util to work, it needs to have access to the importer's context to get access to the host objects. Is there anyway for it to find out? I guess I can do something like: ------------------------------------------------------------------------ import script_util script_util.init(globals()) ------------------------------------------------------------------------ But I like to make something brain dead easy with just the import statement if possible. Thank you, wy From kentilton at gmail.com Mon May 8 15:27:25 2006 From: kentilton at gmail.com (Ken Tilton) Date: Mon, 08 May 2006 15:27:25 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <W6M7g.24$Lo.17@fe12.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <87mzducj27.fsf@rpi.edu> <mailman.5444.1146995493.27775.python-list@python.org> <1heyrbd.4ug6sg7cgci5N%aleaxit@yahoo.com> <W6M7g.24$Lo.17@fe12.lga> Message-ID: <eZM7g.31$Lo.25@fe12.lga> Ken Tilton wrote: > > I just keep what I call a "datapulse ID", sequentially growing from > zero, in a global variable. Each ruled Cell keeps track of its memoized > value, datapulse stamp, and whether it in fact changed value in reaching > its current datapulse stamp. (I can reach the current datapulse stamp by > determining no dependency (direct or indirect recursively down the > dependency graph) is both more current than me /and/ in fact changed in > value getting there.[1] If not, I take on the current datapulse but > never run my rule. Or, if yes, I run my rule but might compute the same > value as last time. Either way, I can flag myself as current but > not-actually-changed.) > .... > > [1] Aha! I see a flaw. Arises if two datapulses pass before I (a cell > <g>) get read and must determine if my cache is obsolete, and some > dependency changed in the first datapulse but not the second. No, I do not think that can happen. I was conflating two mutually exclusive paths. If I am checking a dependency that means it would have notified me when it in fact changed. If my rule is running i will always get a valid value from a read. So i do not think there is a hole in there anywhere. In any case, I would not have needed a new last-changed-datapulse slot, i could just change the "changed" flag to be last-changed-datapulse. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From jes at nl.demon.net Thu May 25 07:56:35 2006 From: jes at nl.demon.net (Jim Segrave) Date: Thu, 25 May 2006 11:56:35 -0000 Subject: regex in python References: <1148551097.266423.141230@j55g2000cwa.googlegroups.com> Message-ID: <127b6rj4957s3bb@corp.supernews.com> In article <1148551097.266423.141230 at j55g2000cwa.googlegroups.com>, gisleyt <gisleyt at gmail.com> wrote: >I'm trying to compile a perfectly valid regex, but get the error >message: > > r = >re.compile(r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*') >Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "/usr/lib/python2.3/sre.py", line 179, in compile > return _compile(pattern, flags) > File "/usr/lib/python2.3/sre.py", line 230, in _compile > raise error, v # invalid expression >sre_constants.error: nothing to repeat >>>> > >What does this mean? I know that the regex >([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.* >is valid because i'm able to use it in Regex Coach. But is Python's >regex syntax different that an ordinary syntax? Your problem lies right near the end: >>> import re >>> r = re.compile(r'(\d*)?') Traceback (most recent call last): File "<stdin>", line 1, in ? File "/usr/local/lib/python2.4/sre.py", line 180, in compile return _compile(pattern, flags) File "/usr/local/lib/python2.4/sre.py", line 227, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat Since the term \d* can be matched by the empty string, what would it mean to ask for 0 or 1 copies of the empty string? How is that different from 17 copies of the empty string. So: r = re.compile(r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*).*') will be accepted. >By the way, i'm using it to normalise strings like: > >London|country/uk/region/europe/geocoord/32.3244,42,1221244 >to: >London|country/uk/region/europe/geocoord/32.32,42,12 > >By using \1\2\4 as replace. I'm open for other suggestions to achieve >this! But you're looking for a string followed by two floats and your sample input is a string, a float, an integer, a comma and another integer. If you actually mean the input is London|country/uk/region/europe/geocoord/32.3244,42.1221244 and you want to convert it to: London|country/uk/region/europe/geocoord/32.32,42.12 then the above regex will work -- Jim Segrave (jes at jes-2.demon.nl) From http Fri May 26 16:41:47 2006 From: http (Paul Rubin) Date: 26 May 2006 13:41:47 -0700 Subject: chop() and empty() functions References: <mailman.6253.1148664337.27775.python-list@python.org> <44776377.7090304@lexicon.net> Message-ID: <7xhd3cselw.fsf@ruckus.brouhaha.com> John Machin <sjmachin at lexicon.net> writes: > What is the use case? Why write something like """empty(foo, 42, > cmd="xyzzy")""" when you could merely write "pass" or nothing at all? The function might be a parameter to something. From sybrenUSE at YOURthirdtower.com.imagination Mon May 22 11:21:46 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 22 May 2006 17:21:46 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <bhv172hbu1i37nqi3kp1rhnuaujj1qo208@4ax.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> Message-ID: <slrne73loa.8pe.sybrenUSE@schuimige.stuvel.eu> SamFeltus enlightened us with: > I do find it interesting that Flash folks readily will acknowledge > that Flash has shortcomings yet anti-Flash folks seem to have great > difficulty acknowledging Flash's positive features over HTML. I must say I've never seen a pro-Flash person acknowledging that 99.9% of the Flash usage is done badly. Google Video is a nice example of more or less good Flash usage, although it's a shame they say "Download for Windows/Mac" instead of "Download as AVI" - but that's got nothing to do with Flash ;-) > Such situations always make me suspicious Ludditism is at work. If you suspect that, you didn't understand a single thing about the usability drawbacks I told you about. Not being able to use a scrollwheel, loss of the backbutton-functionality, and fonts that don't scale along with the browser's font, are all too common practice with Flash websites. I love new technology, as long as it's good technology. I've had my mouse with tiltwheel for a short time, and I'm completely hooked to the new functionality. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From caseyhHAMMER_TIME at istar.ca Tue May 16 11:51:46 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Tue, 16 May 2006 15:51:46 GMT Subject: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? References: <1147657728.064817.214850@j73g2000cwa.googlegroups.com> Message-ID: <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? You would need to know something of the input range and its uniformity! Self-balancing between dictionaries for separate dictionaries? -- Regards, Casey From elw000 at verizonz.net Sat May 6 13:35:22 2006 From: elw000 at verizonz.net (Eric) Date: Sat, 06 May 2006 17:35:22 GMT Subject: Replace References: <R40975357.427.5217.1@mx-extra.net> <mailman.5419.1146921316.27775.python-list@python.org> Message-ID: <u757g.202$NB6.173@trndny03> On 2006-05-06, Tim Williams wrote: > On 06/05/06, Eric <elw000 at verizonz.net> wrote: >> I have a string... >> >> str = "tyrtrbd =ffgtyuf == =tyryr =u=p ttttff" >> >> I want to replace the characters after each '=', what I ended up doing is >> somthing like this... >> >> buf = list(str) >> newchr = '#' >> >> count = 0 >> for i in range(len(buf)): >> if buf[count] == '=': >> buf[count + 1] = newchr >> count = count + 1 >> else: >> count = count + 1 >> >> newstr = ''.join(buf) >> >> Is there a better, faster way of doing it? Using somthing like >> str.index() dosn't work because... >> > > After you find an '=' you are updating the next chr in the list to '#' > then testing the '#' to see if it is an '=' . > > This would be quicker as it bypasses testing your self-added '#' , and > also removes a " count +1" > > #Untested > buf = list(str) > newchr = '#' > count = 0 > for i in range(len(buf)): > if buf[count] == '=': > count = count + 1 > buf[count] = newchr > count = count + 1 > > > I might have done something like this (using s instead of str) > > #untested >>>> buf = list(s) >>>> newstr = '' >>>> while buf: > ... newstr += buf.pop(0) # get the first item in buf and append it to newstr > ... if new[-1] == '=': > ... newstr += '#' > ... buf.pop(0) # discard the next item in buf > > > HTH :) Thanks, I should have included more info about what I was trying to do, just trying to keep my post short. I was messing around trying to write a simple script to decode yenc encoded usenet posts. Yenc uses the '=' before special chars like '\n', '\r', those chars need to handled differently. Iterating over each char in a file dosn't sound like the best idea. import sys import string crap = sys.stdin d42 = string.join([chr((x - 42) % 256) for x in range(256)], '') d64 = string.join([chr((x - 64) % 256) for x in range(256)], '') def proccess(crapstring): buffer = list(crapstring) count = 0 for count in range(len(buffer)): if buffer[count] != '=': buffer[count] = buffer[count].translate(d42) count = count + 1 else: buffer[count + 1] = buffer[count + 1].translate(d64) buffer[count] = '' count = count + 1 newstring = ''.join(buffer) return newstring while 1: line = crap.readline() if not line: break if line[:7] != '=ybegin': continue header = line.split() """Do somthing with header sometime""" break linebuf = [] while 1: line = crap.readline() if line[:5] != '=yend': if line[-2:] == "\r\n": line = line[:-2] pline = proccess(line) linebuf.append(pline) else: break deccrap = ''.join(linebuf) sys.stdout.write(deccrap) This script isn't working for some reason. I'll figure that out someday. From bborcic at gmail.com Thu May 11 14:11:04 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 11 May 2006 20:11:04 +0200 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> Message-ID: <44637e47_4@news.bluewin.ch> jayessay wrote: > "Michele Simionato" <michele.simionato at gmail.com> writes: > >> jayessay wrote: >>> I was saying that you are mistaken in that pep-0343 could be used to >>> implement dynamically scoped variables. That stands. >> Proof by counter example: >> >> from __future__ import with_statement >> import threading >> >> special = threading.local() >> >> def getvar(name): >> return getattr(special, name) >> >> def setvar(name, value): >> return setattr(special, name, value) >> >> class dynamically_scoped(object): >> def __init__(self, name, value): >> self.name = name >> self.value = value >> def __context__(self): >> return self >> def __enter__(self): >> self.orig_value = getvar(self.name) >> setvar(self.name, self.value) >> def __exit__(self, Exc, msg, tb): >> setvar(self.name, self.orig_value) >> >> if __name__ == '__main__': # test >> setvar("*x*", 1) >> print getvar("*x*") # => 1 >> with dynamically_scoped("*x*", 2): >> print getvar("*x*") # => 2 >> print getvar("*x*") # => 1 >> >> If you are not happy with this implementation, please clarify. > > I can't get this to work at all - syntax errors (presumably you must > have 2.5?, I only have 2.4). But anyway: > > This has not so much to do with WITH as relying on a special "global" > object which you must reference specially, which keeps track (more or > less) of its attribute values, which you use as "faked up" variable > Actually you probably need to hack this a bit more to even get that as > it doesn't appear to stack the values beyond a single level. Actually there's no problem there. hint : dynamically_scoped is a class that the with statement will instantiate before (any) entry. OTOH, as it is written, I am not convinced it will work in a multithreaded setting : isn't it the case that all threads that will import eg dynamically_scoped/getvar/setvar will act without sync on the /single/ special object of the /single/ thread that initialized the module ? But I'm not sure, it's been ages since I used python threading. > > > /Jon > From hannu at skype.net Mon May 15 18:12:10 2006 From: hannu at skype.net (Hannu Krosing) Date: Tue, 16 May 2006 01:12:10 +0300 Subject: [PATCHES] [HACKERS] Iterating generator from C (PostgreSQL's pl/python RETUN In-Reply-To: <14388.1147728092@sss.pgh.pa.us> References: <1147725190.3790.37.camel@localhost.localdomain> <14388.1147728092@sss.pgh.pa.us> Message-ID: <1147731131.3790.48.camel@localhost.localdomain> ?hel kenal p?eval, E, 2006-05-15 kell 17:21, kirjutas Tom Lane: > Hannu Krosing <hannu at skype.net> writes: > >> Sven Suursoho wrote: > >>> As for testing in actual pl/python build environment, we had objections from > >>> leading postgresql Tom Lane that even if we do test it at build time, > >>> a determined DBA may substitute a buggy python.so later and still crash her DB instance. > > The above is a straw-man depiction of my point. Sure ;) > What I said was that just > because python is up-to-date on the system where plpython is *compiled* > does not mean it'll be up-to-date on the system where plpython is *used*. Would running an external program at pl init time and testing for its crash status be a good broken lib test for plpython ? > With the increasing popularity of prebuilt packages (rpm, deb, etc), > I think it's folly to use a build-time check for this. I guess most packaging systems can require some minimal version of dependencies. And in general newer versions are less buggy than old ones. So i guess that some combination of build-time/run-time tests, documentation and packager education should take care of 99% of concerns ? Hopefully we can just ignore the "determined DBA" failure mode and move forward with including the patch. Or do you think that trying to hack in the extra python frame to all/some builds to ward of potentially broken libs would still be something to go for ? -- ---------------- Hannu Krosing Database Architect Skype Technologies O? Akadeemia tee 21 F, Tallinn, 12618, Estonia Skype me: callto:hkrosing Get Skype for free: http://www.skype.com NOTICE: This communication contains privileged or other confidential information. If you have received it in error, please advise the sender by reply email and immediately delete the message and any attachments without copying or disclosing the contents. From ankyhe at gmail.com Mon May 8 21:42:20 2006 From: ankyhe at gmail.com (ankyhe at gmail.com) Date: 8 May 2006 18:42:20 -0700 Subject: Why list.sort() don't return the list reference instead of None? In-Reply-To: <slrne5tskr.rd2.sybrenUSE@schuimige.stuvel.eu> References: <1147070358.336663.160440@i40g2000cwc.googlegroups.com> <1147071499.135783.193610@e56g2000cwe.googlegroups.com> <slrne5tskr.rd2.sybrenUSE@schuimige.stuvel.eu> Message-ID: <1147138940.317130.203080@i39g2000cwa.googlegroups.com> Thank you! I got it. From rupole at hotmail.com Thu May 11 22:49:59 2006 From: rupole at hotmail.com (Roger Upole) Date: Thu, 11 May 2006 22:49:59 -0400 Subject: Python and windows bandwidth statistics? References: <1147325828.414265.157030@u72g2000cwu.googlegroups.com> Message-ID: <1147401970_1611@sp6iad.superfeed.net> win32pdh from Pywin32 lets you access the network performance counters. Roger "Dave Reid" <dave at davereid.net> wrote in message news:1147325828.414265.157030 at u72g2000cwu.googlegroups.com... > I've been searching for a something in Python for me to be able to get > the total outbound or inbound bandwidth (in Windows (or cross-OS > compatible). Can anyone help me out? Thanks! > ----== 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 timo.stamm at arcor.de Mon May 22 17:59:18 2006 From: timo.stamm at arcor.de (Timo Stamm) Date: Mon, 22 May 2006 23:59:18 +0200 Subject: Software Needs Philosophers In-Reply-To: <e4q37v$ipo$2@magcargo.vodatel.hr> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <e4q37v$ipo$2@magcargo.vodatel.hr> Message-ID: <44723437$0$11063$9b4e6d93@newsread4.arcor-online.net> Dra?en Gemi? schrieb: > Xah Lee wrote: >> Software Needs Philosophers >> > > Welcome to my junk filters !!!! Thanks for informing each and every reader of the newsgroups comp.lang.perl.misc, comp.lang.python, comp.lang.java.programmer, comp.lang.lisp, comp.lang.function about your junk filters. Timo From rpdooling at gmail.com Mon May 15 11:09:48 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 15 May 2006 08:09:48 -0700 Subject: keyword help in Pythonwin interpreter In-Reply-To: <e4a4im$7bn$01$1@news.t-online.com> References: <1147702380.665861.106540@g10g2000cwb.googlegroups.com> <e4a4im$7bn$01$1@news.t-online.com> Message-ID: <1147705788.225115.104100@j73g2000cwa.googlegroups.com> Peter, >>> import pydoc >>> pydoc.help.docdir yields no result for me But adding the "break" into the pydoc module didn't work either. Mmm. I'll toy with this later. Thanks for pointing me to the right spot in the module. rick From miki.tebeka at gmail.com Sun May 28 07:16:00 2006 From: miki.tebeka at gmail.com (Miki) Date: 28 May 2006 04:16:00 -0700 Subject: Speed up this code? In-Reply-To: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> Message-ID: <1148814960.643281.257860@y43g2000cwc.googlegroups.com> Hello Martin, You can use gmpy (http://gmpy.sourceforge.net/) def primes(): n = 2 while 1: yield long(n) n = gmpy.next_prime(n) HTH, Miki http://pythonwise.blogspot.com/ From mystilleef at gmail.com Sat May 6 01:39:43 2006 From: mystilleef at gmail.com (mystilleef) Date: 5 May 2006 22:39:43 -0700 Subject: Designing Plug-in Systems in Python Message-ID: <1146893983.268034.206080@e56g2000cwe.googlegroups.com> Hello, I need to design a plug-in system for a project. The goal is to allow third party developers interact with an application via plug-ins in a clean and robust manner. At this point I am overwhelmed by my inexperience with designing plug-in systems. Are there any good tutorials on how to design good plug-in systems with Python, or any language? What are the best practices for designing plug-in systems in Python? How would you go about designing one? What are common pitfalls in designing one? Any pointers, suggestions, resources and advice is welcome. Thanks From kentilton at gmail.com Tue May 9 12:45:03 2006 From: kentilton at gmail.com (Ken Tilton) Date: Tue, 09 May 2006 12:45:03 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1147160240.954015.181480@j73g2000cwa.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> Message-ID: <%F38g.16$RR.4@fe10.lga> michele.simionato at gmail.com wrote: > Ken Tilton wrote: > >>Python has a weak lambda, statements do not always >>return values, it does not have macros, and I do not know if it has >>special variables. > > > I am pretty much ignorant of Common Lisp, but I have the impression > they are the > same as Scheme parameters, i.e. thread-local dynamically scoped > variables > (feel free to correct me if I am mistaken). If I am right, here is how > you would emulate them in recent versions of Python: > > import threading, time > > special = threading.local() > special.x = 0 > > def getx(): > return special.x > > def set_x(value): > special.x = value > time.sleep(3-value) # thread-2 completes after thread-1 > print "%s is setting x to %s" % (threading.currentThread(), getx()) > > if __name__ == '__main__': > print getx() # => 0 > threading.Thread(None, lambda : set_x(1)).start() # => 1 > threading.Thread(None, lambda : set_x(2)).start() # => 2 > time.sleep(3) > print getx() # => 0 > > Michele Simionato > I was not thinking about the thread issue (of which I know little). The big deal for Cells is the dynamic bit: (let ((*dependent* me)) (funcall (rule me) me)) Then if a rule forces another cell to recalculate itself, *dependent* gets rebound and (the fun part) reverts back to the original dependent as soon as the scope of the let is exited. In this case, because my code is so brilliant <g>, there is only one place in the code where a rule gets called, so it would be easy enough to manage by saving/restoring the existing value around storing a new value there. I do wonder what would happen to Cells if I ever want to support multiple threads. Or in a parallel processing environment. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From paddy3118 at netscape.net Tue May 23 13:12:46 2006 From: paddy3118 at netscape.net (Paddy) Date: 23 May 2006 10:12:46 -0700 Subject: Using python for a CAD program In-Reply-To: <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <e4ham3$1td$1@sea.gmane.org> <446C8950.3070107@anansispaceworks.com> <mailman.6000.1148109587.27775.python-list@python.org> <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> <mailman.6062.1148282177.27775.python-list@python.org> <4471aead$0$22975$c83e3ef6@nn1-read.tele2.net> Message-ID: <1148404366.743786.258280@u72g2000cwu.googlegroups.com> baalbek wrote: > David Cuthbert wrote: > > > This does not mean the design itself should be stored as an RDBMS. As > > I've stated previously, CAD data (both electrical and, it appears, > > mechanical) does not lend itself to RDBMS relationship modeling. > > I simply do not agree with this. > > A CAD program (like Autocad) is nothing > but an advanced database editor: the program loads data from a binary > file and creates its object (in memory) from the tables that it reads Hi Baalbek, Athouh they are database editors, they are not relational database editors. Relational database engines fit some type of problems but others have found that RDBMS don't fit CAD data. They are just too slow and add complexity in mapping the 'natural CAD data formats' to the RDBMS table format. - Pad. From onurb at xiludom.gro Mon May 15 07:55:02 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 15 May 2006 13:55:02 +0200 Subject: How to organise classes and modules In-Reply-To: <mailman.5703.1147691931.27775.python-list@python.org> References: <mailman.5703.1147691931.27775.python-list@python.org> Message-ID: <44686c81$0$6834$626a54ce@news.free.fr> Alex wrote: > Hi, this is my first mail to the list so please correct me if Ive done > anything wrong. > > What Im trying to figure out is a good way to organise my code. One > class per .py file is a system I like, keeps stuff apart. If I do > that, I usually name the .py file to the same as the class in it. First point is that Python doesn't force you to put everything in classes - if you just need a function, well, make it a function !-) Also, the common pattern is to put closely related classes/functions/constants in a same module, and closely related modules in the same package. Since Python uses a "one file == one module" scheme, the Javaish "one class per file" idiom leads to overly complicated imports. And the most common naming scheme for modules is 'alllowercase'. > File: Foo.py > *********************** > class Foo: > def __init__(self): > pass > def bar(self): > print 'hello world' > > ************************ > > Now, in my other module, I want to include this class. I tried these two > ways: > >>>> import Foo >>>> Foo.Foo.bar() > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: unbound method bar() must be called with Foo instance as > first argument (got nothing instead) > > Some unbound method error. Have I missunderstood something Yes: 1/ you usually need to instanciate the class to call an instance method 1/ in this case, bar doesn't need to be a method, since it doesn't depend on the instance it's called on - a plain old function would be a better fit. > or am I on > the right track here? > > I did this to, almost the same thing: > >>>> from Foo import Foo >>>> Foo.bar() > > Traceback (most recent call last): > File "<stdin>", line 1, in ? > TypeError: unbound method bar() must be called with Foo instance as > first argument (got nothing instead) > > One thing that I tried that worked ok was this: > >>>> import Foo >>>> instance=Foo.Foo() >>>> instance.bar() > > hello world > > But in my opinion, this is very ugly. Nope, it's just OO at work. > Especially if the class names > are long, like my module/class TileDataBaseManager. But is this the > "right" way in python? If you want to import a class from a module and create an instance of that class, yes. > Another (ugly) way that Ive considered is the following. Break it out > of the class, Which would be a sensible thing to do given the current implementation of bar(). > save the functions in a file alone, Nothing prevent you from putting many functions in a same module, you know... > import the file s/file/module/ > and > treat it like a class: ??? > File: Foo2.py > *********************** > def bar(self): > print 'hello world' > > ************************ > >>>> import Foo2 >>>> Foo2.bar() > > hello world You don't "treat it like a class", you're just using the normal namespace resolution mechanism. Modules are namespaces, classes are namespaces, objects (class instances) are namespaces, and the dot is the lookup operator (ie : somenamespacename.somename means 'retrieve what's actually bound to name 'somename' in namespace 'somenamespacename'). > Very clean from the outside. I would like something like this. But, > here, I loose the __init__ function. Which in the given implementation is just doing nothing. Ok, I understand that this is just example code. The rule here is: - if you need per-instance state management, use a class (that you of course need to instanciate - else you can't have per-instance state !-) - if you don't need per-instance state management, use a plain function. > I have to call it manually that > is, which s not good. Also, maybe the biggest drawback, its no longer > in a class. def MyFunc(): pass print MyFunc.__class__.__name__ Python function's are instances of the function class. > Maybe its not that important in python but from what Ive > learned (in c++) object orientation is something to strive for. print "object orientation".find("class") Being OO doesn't mean using classes. <troll>And FWIW, there quite enough procedural Java code around to prove that using classes doesn't mean doing OO !-) </troll> > So, to sum it up, I have one class in one file, both with the same > name. How do I store/import/handle it in a nice, clean and python-like > manner? Quit the Javaish "one-class-per-file" idiom, don't bother using classes when plain old function will do, and you'll be on track... FWIW, Python's standard lib is open-source, so why not have a look at the source code to see how it is organized ? HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From cvanarsdall at mvista.com Tue May 16 12:52:51 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Tue, 16 May 2006 09:52:51 -0700 Subject: [silly] Does the python mascot have a name ? In-Reply-To: <Xns97C5AE2C06CE8BaldHeadedJohn@216.196.109.145> References: <e4c59e$tqg$1@emma.aioe.org> <Xns97C5AE2C06CE8BaldHeadedJohn@216.196.109.145> Message-ID: <446A0363.5040205@mvista.com> John D Salt wrote: > Steve <lonetwin.nospam at yahoo.com> wrote in > news:e4c59e$tqg$1 at emma.aioe.org: > > >> umm, was just wondering, does the python mascot have a name ? >> > > I always assumed it was Monty, but I confess to not having the slightest > factual basis for this belief. > > To be honest, Monty really makes the most sense to me for a mascot name... now if we can only get past all that damn copyright infringement ;) -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From mrmakent at cox.net Wed May 17 11:18:33 2006 From: mrmakent at cox.net (Mike Kent) Date: 17 May 2006 08:18:33 -0700 Subject: List behaviour References: <1147878414.819145.88580@i40g2000cwc.googlegroups.com> Message-ID: <1147879113.255149.26560@g10g2000cwb.googlegroups.com> When you did: b = a[:] b was then a copy of a, rather than just a reference to the same a. But what does a contain? It contains two sublists -- that is, it contains references to two sublists. So b, which is now a copy of a, contains copies of the two references to the same two sublists. What you need to do instead is: b = copy.deepcopy(a) to get you what you actually want. From peter.maas at somewhere.com Wed May 10 16:53:21 2006 From: peter.maas at somewhere.com (Peter Maas) Date: Wed, 10 May 2006 22:53:21 +0200 Subject: Can Python installation be as clean as PHP? In-Reply-To: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> References: <KcednZWHS4CKc_3ZRVn-uw@comcast.com> Message-ID: <e3tjs2$663$1@online.de> Jack wrote: > With Python, things are really messy. I have to run the installer > to install dozens of directories and hundreds of files, and I don't > really know if all of them are necessary. PHP has LOTS of functions in a single namespace. I don't know wether they are in separate files or packed in the exexutable but I'm sure that you don't need them all ;) > Plus, lots of libraries > are in .py, which is of course not as efficient/clean as having all > of the core functions built-in in the C/C++ core, like in PHP. Python is faster than PHP in most situations (2-3x). Look at http://dada.perl.it/shooutout for win32 and http://shooutout.alioth.debian.org for linux. Peter Maas, Aachen From sjmachin at lexicon.net Thu May 25 08:30:57 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 May 2006 22:30:57 +1000 Subject: regex in python In-Reply-To: <1148551097.266423.141230@j55g2000cwa.googlegroups.com> References: <1148551097.266423.141230@j55g2000cwa.googlegroups.com> Message-ID: <4475A381.6050109@lexicon.net> On 25/05/2006 7:58 PM, gisleyt wrote: > I'm trying to compile a perfectly valid regex, but get the error > message: > > r = > re.compile(r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*') > Traceback (most recent call last): > File "<stdin>", line 1, in ? > File "/usr/lib/python2.3/sre.py", line 179, in compile > return _compile(pattern, flags) > File "/usr/lib/python2.3/sre.py", line 230, in _compile > raise error, v # invalid expression > sre_constants.error: nothing to repeat > > What does this mean? I know that the regex > ([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.* > is valid because i'm able to use it in Regex Coach. Say what??? From the Regex Coach website: (1) "can be used to experiment with (Perl-compatible) regular expressions" (2) "PCRE (which is used by projects like Python" -- once upon a time, way back in the dream-time, when the world was young, ... The problem is this little snippet near the end of your regex: >>> re.compile(r'(\d*)?') Traceback (most recent call last): File "<stdin>", line 1, in ? File "C:\Python24\lib\sre.py", line 180, in compile return _compile(pattern, flags) File "C:\Python24\lib\sre.py", line 227, in _compile raise error, v # invalid expression sre_constants.error: nothing to repeat The message is a little cryptic, should be something like "a repeat operator has an operand which may match nothing". In other words, you have said X? (optional occurrence of X) *BUT* X can already match a zero-length string. X in this case is (\d*) This is a theoretically valid regex, but it's equivalent to just plain X, and leaves the reader (and the re implementors, obviously) wondering whether you (a) have made a typo (b) are a member of the re implementation quality assurance inspectorate or (c) just plain confused :-) BTW, reading your regex was making my eyes bleed, so I did this to find out which piece was the problem: import re pat0 = r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*' pat1 = r'([^\d]*)' pat2 = r'(\d{1,3}\.\d{0,2})?' pat3 = r'(\d*)' pat4 = r'(\,\d{1,3}\.\d{0,2})?' pat5 = r'(\d*)?.*' for k, pat in enumerate([pat1, pat2, pat3, pat4, pat5]): print k+1 re.compile(pat) > But is Python's > regex syntax different that an ordinary syntax? Python aims to lift itself above the ordinary :-) > > By the way, i'm using it to normalise strings like: > > London|country/uk/region/europe/geocoord/32.3244,42,1221244 > to: > London|country/uk/region/europe/geocoord/32.32,42,12 > > By using \1\2\4 as replace. I'm open for other suggestions to achieve > this! > Well, you are just about on the right track. You need to avoid the eye-bleed (by using VERBOSE patterns) and having test data that doesn't have typos in it, and more test data. You may like to roll your own test harness, in *Python*, for *Python* regexes, like the following: C:\junk>type re_demo.py import re tests = [ ["AA222.22333,444.44555FF", "AA222.22,444.44"], ["foo/geocoord/32.3244,42.1221244", "foo/geocoord/32.32,42.12"], # what you meant ["foo/geocoord/32.3244,42,1221244", "foo/geocoord/32.32,42,12"], # what you posted ] pat0 = r'([^\d]*)(\d{1,3}\.\d{0,2})?(\d*)(\,\d{1,3}\.\d{0,2})?(\d*)?.*' patx = r""" ([^\d]*) # Grp 1: zero/more non-digits (\d{1,3}\.\d{0,2})? # Grp 2: 1-3 digits, a dot, 0-2 digits (optional) (\d*) # Grp 3: zero/more digits (\,\d{1,3}\.\d{0,2})? # Grp 4: like grp 2 with comma in front (optional) (\d*) # Grp 5: zero/more digits (.*) # Grp 6: any old rubbish """ rx = re.compile(patx, re.VERBOSE) for testin, expected in tests: print "\ntestin:", testin mobj = rx.match(testin) if not mobj: print "no match" continue for k, grp in enumerate(mobj.groups()): print "Group %d matched %r" % (k+1, grp) actual = rx.sub(r"\1\2\4", testin) print "expected: %r; actual: %r; same: %r" % (expected, actual, expected == actual) C:\junk>re_demo.py testin: AA222.22333,444.44555FF Group 1 matched 'AA' Group 2 matched '222.22' Group 3 matched '333' Group 4 matched ',444.44' Group 5 matched '555' Group 6 matched 'FF' expected: 'AA222.22,444.44'; actual: 'AA222.22,444.44'; same: True testin: foo/geocoord/32.3244,42.1221244 Group 1 matched 'foo/geocoord/' Group 2 matched '32.32' Group 3 matched '44' Group 4 matched ',42.12' Group 5 matched '21244' Group 6 matched '' expected: 'foo/geocoord/32.32,42.12'; actual: 'foo/geocoord/32.32,42.12'; same: True testin: foo/geocoord/32.3244,42,1221244 Group 1 matched 'foo/geocoord/' Group 2 matched '32.32' Group 3 matched '44' Group 4 matched None Group 5 matched '' Group 6 matched ',42,1221244' Traceback (most recent call last): File "C:\junk\re_demo.py", line 28, in ? actual = rx.sub(r"\1\2\4", testin) File "C:\Python24\lib\sre.py", line 260, in filter return sre_parse.expand_template(template, match) File "C:\Python24\lib\sre_parse.py", line 782, in expand_template raise error, "unmatched group" sre_constants.error: unmatched group === HTH, John From steve at holdenweb.com Fri May 26 06:33:39 2006 From: steve at holdenweb.com (Steve Holden) Date: Fri, 26 May 2006 11:33:39 +0100 Subject: how to clear up a List in python? In-Reply-To: <1148638555.440810.277540@i40g2000cwc.googlegroups.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <1148596003.879693.63250@i39g2000cwa.googlegroups.com> <mailman.6213.1148598607.27775.python-list@python.org> <1148600313.776440.61710@i39g2000cwa.googlegroups.com> <1148602972.946639.40220@38g2000cwa.googlegroups.com> <mailman.6221.1148634413.27775.python-list@python.org> <1148636521.026385.171410@y43g2000cwc.googlegroups.com> <e56iu7$g9j$1@news.albasani.net> <1148638555.440810.277540@i40g2000cwc.googlegroups.com> Message-ID: <e56lhs$5s2$1@sea.gmane.org> vbgunz wrote: >>You perhaps shouldn't become so excited. Next time, if you're not sure of >>the correctness of your solution, try to wait a bit before posting it, >>and see if someone other comes up with the same thing you would have posted. > > > George, if Frederik's first reply was replaced with yours chances are > this little waste of time would have never had taken place. I am not an > animal and I am capable of understanding my mistakes but trying to > embarass me and belittle me in front of all of my peers here when all I > tried to do was help is absolutely pathetic the first time around. > That's "Georg", by the way ... > I don't try to come off as a know it all here and I don't feel I should > post a gospel warning label on my help signature but Fredrik could have > delivered his message in a much better tone. I too am learning Python > and if maybe my answer was not evident enough of that then how smart is > Fredrik to persecute me for it? > Man, if you think *that* was persecution don't *ever* take up Lisp or Perl, where they will eat you alive just for not knowing something. > I don't wish to question Fredriks knowledge or his position in the > whole scheme of Python but to disrespect me in the name of arrogance > and call it just is a mislabel. I don't wish to carry on with this, I > don't... I just have no love for a bully and Fredrik is proving himself > to be just that. > No he isn't. Like Python itself this group is for consenting adults, and you are letting your emotions get in the way of an adult response. > Good day George! > regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From h.b.furuseth at usit.uio.no Mon May 15 10:42:13 2006 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Mon, 15 May 2006 16:42:13 +0200 Subject: Embedding python in package using autoconf Message-ID: <hbf.20060515phtn@bombur.uio.no> I want to use Python as an extension language in a package which uses autoconf. That means its and Python's autoconf #defines can conflict, so I can't safely #include both <Python.h> and the package's own include files:-( Do anyone have a safe way to #include at least <object.h> without <pyconfig.h>? E.g. copy the files (and <pyport.h>'s PyAPI_FUNC/PyAPI_DATA) and rename the autoconf macros - and fail compilation if that wouldn't work? Currently I have two sets of source files - one set which only #includes Python.h and one set which only #includes the package's files. They communicate through a single .h file with a bunch of enums for various functions and struct members, and wrapper functions to use these by their enum value. It has a few cheats like declaring "struct _object;" (that's PyObject) to make life simpler, but it's still rather tedious. -- Hallvard From Elric02 at rogers.com Tue May 16 14:17:36 2006 From: Elric02 at rogers.com (Elric02 at rogers.com) Date: 16 May 2006 11:17:36 -0700 Subject: Unable to extract Python source code using Windows In-Reply-To: <446a0229$1@nntp0.pdx.net> References: <1147793244.668439.266520@j55g2000cwa.googlegroups.com> <446a0229$1@nntp0.pdx.net> Message-ID: <1147803456.431686.258380@i39g2000cwa.googlegroups.com> >You can get Python sources from python.org I'm unable to locate a source file brings that will work with WinZip. Can anybody please point me to the exact URL that will get me to the source code? but it it is tar ball format or a gzip format, than that will work for me as WinZip is not open. From maxm at mxm.dk Tue May 30 04:16:26 2006 From: maxm at mxm.dk (Max M) Date: Tue, 30 May 2006 10:16:26 +0200 Subject: John Bokma harassment In-Reply-To: <Xns97D294C4D81FCcastleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <447ae549$1_5@news.bluewin.ch> <1148906778.530827.317000@g10g2000cwb.googlegroups.com> <Xns97D294C4D81FCcastleamber@130.133.1.4> Message-ID: <447bff02$0$38691$edfadb0f@dread12.news.tele.dk> John Bokma wrote: > ilitzroth at gmail.com wrote: > Your first question should be: Is it alright that Xah harasses 5 > newsgroups? Or maybe work on your spelling, harass is with one r, but > maybe you didn't read the subject, which wouldn't amaze me, since you > sound like you should be spending time on MySpace OMG!. I assume that the single l in alright is the courteous misspelling that should allways be in a posting, when correcting other peoples speling? -- hilsen/regards Max M, Denmark http://www.mxm.dk/ IT's Mad Science Phone: +45 66 11 84 94 Mobile: +45 29 93 42 96 From python at rcn.com Sun May 21 12:55:51 2006 From: python at rcn.com (Raymond Hettinger) Date: 21 May 2006 09:55:51 -0700 Subject: Feature request: sorting a list slice References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <mailman.5974.1148066477.27775.python-list@python.org> <1148073894.399040.242890@j73g2000cwa.googlegroups.com> <mailman.5983.1148077882.27775.python-list@python.org> Message-ID: <1148230551.278945.220130@i39g2000cwa.googlegroups.com> Getting a patch ready for checkin (corrected, documented, reviewed, and tested) is only part of the battle. The real challenge of language design is figuring out whether something should be done. Adding optional parameters to a method makes its invocation slower and makes the API harder to learn and remember. There has not yet been a thorough discussion of use cases. In particular, people should scan their existing, deployed codebase for examples of where a particular code fragment would have been improved. We should then compare the fragment with and without the feature -- how much more concise is it, how much is performance improved/harmed, is the code more or less readable, etc. If the perf gain is small and the use cases are infrequent, the addition is likely unwarranted. There is an entire class of feature requests that are more appropriate as recipes than for inclusion in the language. If python had accepted most requests like this, it would have become somewhat bloated and unattractive. From caseyhHAMMER_TIME at istar.ca Mon May 8 22:32:21 2006 From: caseyhHAMMER_TIME at istar.ca (Casey Hawthorne) Date: Tue, 09 May 2006 02:32:21 GMT Subject: which is better, string concatentation or substitution? References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <roy-A5FC8E.09284008052006@reader1.panix.com> <IWH7g.2053$No6.45672@news.tufts.edu> <e3nnv0$jbm$1@reader1.panix.com> Message-ID: <envv521lhcir4i9bpg2affcu2kg7gje41v@4ax.com> roy at panix.com (Roy Smith) wrote: >O(n^0), which is almost always written as O(1). This is a "constant >time" algorithm, one which takes the same amount of steps to execute >no matter how big the input is. For example, in python, you can >write, "x = 'foo'". That assignment statement takes the same amount >of time no matter how long the string is. All of these execute in the >same number of steps: > > x = '' > x = 'foo' > x = 'a very long string with lots and lots of characters' > >We can say that "assignment is constant time", or "assignment is >O(1)". Constant time if converted to byte code or compiled? O(n) in string length if being interpreted? -- Regards, Casey From ptmcg at austin.rr._bogus_.com Wed May 3 15:31:04 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 03 May 2006 19:31:04 GMT Subject: Recommended data structure for newbie References: <1146626916.066395.206540@y43g2000cwc.googlegroups.com> <7Z16g.1536$CH2.1053@tornado.texas.rr.com> Message-ID: <Yx76g.2251$CH2.1034@tornado.texas.rr.com> "Paul McGuire" <ptmcg at austin.rr._bogus_.com> wrote in message news:7Z16g.1536$CH2.1053 at tornado.texas.rr.com... > "manstey" <manstey at csu.edu.au> wrote in message > news:1146626916.066395.206540 at y43g2000cwc.googlegroups.com... > > Hi, > > > > I have a text file with about 450,000 lines. Each line has 4-5 fields, > > separated by various delimiters (spaces, @, etc). > > > > I want to load in the text file and then run routines on it to produce > > 2-3 additional fields. > > > > <snip> > > Matthew - > > If you find re's to be a bit cryptic, here is a pyparsing version that may > be a bit more readable, and will easily scan through your input file: > <snip> Lest I be accused of pushing pyparsing where it isn't appropriate, here is a non-pyparsing version of the same program. The biggest hangup with your sample data is that you can't predict what the separator is going to be - sometimes it's '[', sometimes it's '^'. If the separator character were more predictable, you could use simple split() calls, as in: data = "blah blah blah^more blah".split("^") elements = data[0].split() + [data[1]] print elements ['blah', 'blah', 'blah', 'more blah'] Note that this also discards the separator. Since you had something which goes beyond simple string split()'s I thought you might find pyparsing to be a simple alternative to re's. Here is a version that tries different separators, then builds the appropriate list of pieces, including the matching separator. I've also shown an example of a generator, since you are likely to want one, parsing 100's of thousands of lines as you are. -- Paul ================= data = """gee fre asd[234 ger dsf asd[243 gwer af as.:^25a""" # generator to process each line of data # call using processData(listOfLines) def processData(d): separators = "[^" #expand this string if need other separators for line in d: for s in separators: if s in line: parts = line.split(s) # return the first element of parts, split on whitespace # followed by the separator # followed by whatever was after the separator yield parts[0].split() + [ s, parts[1] ] break else: yield line # to call this for a text file, use something like # for lineParts in processData( file("xyzzy.txt").readlines() ) for lineParts in processData( data.split("\n") ): print lineParts print # rerun processData, augmenting extracted values with additional # computed values for lineParts in processData( data.split("\n") ): toks = lineParts tokens = toks[:] tokens.append( toks[0]+toks[1] ) tokens.append( toks[-1] + toks[-1][-1] ) #~ tokens.append( str( lineno(start, data) ) ) print tokens ==================== prints: ['gee', 'fre', 'asd', '[', '234'] ['ger', 'dsf', 'asd', '[', '243'] ['gwer', 'af', 'as.:', '^', '25a'] ['gee', 'fre', 'asd', '[', '234', 'geefre', '2344'] ['ger', 'dsf', 'asd', '[', '243', 'gerdsf', '2433'] ['gwer', 'af', 'as.:', '^', '25a', 'gweraf', '25aa'] From sam at nuevageorgia.com Mon May 22 16:23:54 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 22 May 2006 13:23:54 -0700 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <bhv172hbu1i37nqi3kp1rhnuaujj1qo208@4ax.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <slrne73loa.8pe.sybrenUSE@schuimige.stuvel.eu> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> <2lmcg.90657$dW3.29599@newssvr21.news.prodigy.com> <1148324738.039440.57700@j73g2000cwa.googlegroups.com> <7xwtcdc0qq.fsf@ruckus.brouhaha.com> Message-ID: <1148329434.692975.264510@g10g2000cwb.googlegroups.com> Nah, the world needs more Flashy WebSites, :) But I do renounce my uglier criticisms of HTML. I realize now it is just a completely different mindset, not a bad technology. Python is far easier than PHP IMO. Especially if there is minimal HTML, I mostly just want to get at a database and manipulate symbols. I know Python pretty well, PHP (or Ruby) would take some study. From kent at kentsjohnson.com Tue May 9 16:13:47 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Tue, 09 May 2006 16:13:47 -0400 Subject: Enumerating Regular Expressions In-Reply-To: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> References: <1147146518.622294.91970@j73g2000cwa.googlegroups.com> Message-ID: <4460f778$1_1@newspeer2.tds.net> blair.bethwaite at gmail.com wrote: > Hi all, > > Does anybody know of a module that allows you to enumerate all the > strings a particular regular expression describes? Make a generator that yields *all* strings in your chosen alphabet (see the monthly threads about permutations and combinations for hints). Filter with the regex. Halting is left as an exercise for the reader. (Halting when the length reaches a predetermined limit would be one way to do it.) Kent From fredrik at pythonware.com Mon May 29 04:46:19 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 29 May 2006 10:46:19 +0200 Subject: html 2 plain text In-Reply-To: <e5e580$1r5i$1@ns.felk.cvut.cz> References: <1148840205.741356.209310@i40g2000cwc.googlegroups.com> <e5e580$1r5i$1@ns.felk.cvut.cz> Message-ID: <e5ecco$vp6$1@sea.gmane.org> garabik-news-2005-05 at kassiopeia.juls.savba.sk wrote: > text=re.sub(r'(?s)\<.+?\>', '', html_text) > (this will keep html entities, though) here's a variation that handles that too: http://effbot.org/zone/re-sub.htm#strip-html </F> From elpX at adsihqX.com Sat May 27 14:31:32 2006 From: elpX at adsihqX.com (Dr. Pastor) Date: Sat, 27 May 2006 18:31:32 GMT Subject: Array? Please help. Message-ID: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> I need a row of 127 bytes that I will use as a circular buffer. Into the bytes (at unspecified times) a mark (0<mark<128) will be written, one after the other. After some time the "buffer" will contain the last 127 marks. (A pointer will point to the next byte to write to.) What would be the Pythonic way to do the above? Thanks for any guidance. From pthibault33 at yahoo.ca Thu May 4 12:20:11 2006 From: pthibault33 at yahoo.ca (Pierre Thibault) Date: 4 May 2006 09:20:11 -0700 Subject: Mutable String In-Reply-To: <44592d5f$1@nntp0.pdx.net> References: <1146680841.991313.248410@i40g2000cwc.googlegroups.com> <44592d5f$1@nntp0.pdx.net> Message-ID: <1146759610.956628.98950@i39g2000cwa.googlegroups.com> Ok, That will do the job. Thank you. From andrew.arobert at gmail.com Wed May 17 11:33:06 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 17 May 2006 11:33:06 -0400 Subject: Process forking on Windows Message-ID: <126mgi2j7fl4b4b@corp.supernews.com> Hi everyone, I have a python program that will need to interact with an MQSeries trigger monitor. It does this fine but it hogs the trigger monitor while it executes. I'd like to fork the program off and terminate the parent process so that the trigger monitor frees up. Does anyone how this can be accomplished on a Windows platform? I've looked at doing this via the subprocess module but this doesn't look like the correct approach. Any help you can provide would be greatly appreciated. Thanks From larry.bates at websafe.com Mon May 8 09:45:01 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 08 May 2006 08:45:01 -0500 Subject: A better way to split up a list In-Reply-To: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> References: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> Message-ID: <445F4B5D.5060009@websafe.com> fidtz at clara.co.uk wrote: > The code below works fine, but it is less than nice to look at and > somewhat long winded. Is there a better way to do the docstring task? > This is the first working version, and can proabably be "compacted" a > bit (list comprehensions etc) but I am looking for a better basic > approach. Any help much appreciated :) > > from itertools import islice > def chopupmoves(movelist): > '''creates a list of 3 lists from one list, that should all have > (length of movelist)/3 length, with any remainder getting added to the > third list''' > outputlist = [[],[],[]] > > parlen = int(len(movelist)/3) > if parlen < 3: > parlen = 3 > > stoplist=[0];exit = 0 > while exit < len(movelist): > stoplist.append(exit+parlen) > exit = exit + parlen > while len(stoplist) > 4: > stoplist.pop(len(stoplist)-1) > stoplist[-1]=len(movelist) > > for x in range(len(stoplist)-1): > for i in islice(movelist,stoplist[x],stoplist[x+1],1): > outputlist[x].append(i) > return outputlist > movelist = [1,2,3,4,5,6,7,8,9,10,11] > print chopupmoves(movelist) > Try something like this: def chopupmoves(movelist): return [movelist[0:3], movelist[3:6], movelist[6:]] -Larry Bates From loeschmichngomsl at yahoo.com Fri May 12 03:37:53 2006 From: loeschmichngomsl at yahoo.com (=?ISO-8859-15?Q?Daniel_Kl=FCnder?=) Date: Fri, 12 May 2006 09:37:53 +0200 Subject: pythoncode in matlab In-Reply-To: <4cgogmF15ljumU1@news.dfncis.de> References: <4cgogmF15ljumU1@news.dfncis.de> Message-ID: <4cisamF11ma9pU1@news.dfncis.de> Hi Sven, I don't have Matlab on my computer so the following is just a wild guess: As far as I know you can include C code into Matlab or at least into Simulink. Maybe you could try to execute your Python script in that C code? Daniel From scott.daniels at acm.org Mon May 8 21:02:06 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Mon, 08 May 2006 18:02:06 -0700 Subject: group for pure startups... In-Reply-To: <mailman.5490.1147131903.27775.python-list@python.org> References: <mailman.5490.1147131903.27775.python-list@python.org> Message-ID: <445fe653$1@nntp0.pdx.net> bruce wrote: > can someone tell me if there's a group where people who are interested in > starting/contributing to embryoninc startup concepts can get together/meet, > exchange ideas, etc... > i'm not referring to meetings where you do VC/Funding presentations, I'm > basically talking about meetings where you could form your team, join a > team, etc... Every startup I've been involved in began by recruiting trusted people; Forming a team involves several people risking each other's livelihoods, and is almost always begun with an "old boy's network." --Scott David Daniels scott.daniels at acm.org From steve at holdenweb.com Wed May 17 05:03:56 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 May 2006 10:03:56 +0100 Subject: Time to bundle PythonWin In-Reply-To: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> References: <Pine.LNX.4.63.0605111701370.10983@lackingtalent.com> Message-ID: <e4eou4$bu7$3@sea.gmane.org> Dave Benjamin wrote: > Hey folks, > > Why is PythonWin (win32all) still a separate download from a third party? > Is it legal, technical, or what? I think it's about time it be part of the > standard distribution. > Something that the other responders seem to have ignored is the separation of development of the two systems. If Python for Windows were to bundle win32all then there'd be less chance of Mark Hammond releasing bugfixes separately from the Python distribution, and he would have to synchronise his release cycles with those of the Python core. It can be done (witness the forthcoming introduction of elementtree as a standard library module), but I see little benefit in this case, especially as there's little evidence that the majority of Windows Python users need win32all. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From steve at holdenweb.com Wed May 17 04:56:16 2006 From: steve at holdenweb.com (Steve Holden) Date: Wed, 17 May 2006 09:56:16 +0100 Subject: Replace In-Reply-To: <039001c675e0$30b796e0$0201a8c0@mcuf7> References: <R40975357.427.5217.1@mx-extra.net><mailman.5419.1146921316.27775.python-list@python.org><u757g.202$NB6.173@trndny03><jssp529kre6g83fso3clj3ndf1s6t2dua2@4ax.com><ng1q52hgo2bjkp471d1jkbd52u7odfep47@4ax.com> <wpa7g.3081$923.1771@trndny02> <039001c675e0$30b796e0$0201a8c0@mcuf7> Message-ID: <e4eofn$bu7$2@sea.gmane.org> Anthra Norell wrote: > se = SE.SE (r' "~=.~=\=#') > >>>>se ('tyrtrbd =ffgtyuf == =tyryr =u=p ttttff') > > 'tyrtrbd =#fgtyuf =# =#yryr =#=# ttttff' > > > I am in the final stages of documenting my stream editor SE. There are quite > a few problems raised on this list which SE would handle elegantly. Where do > I propose it for distribution? > The Cheese Shop (how I dislike that name :), otherwise known as the Python Packahe Index, is the usual place to offer code in Python nowadays. See http://www.python.org/pypi regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From arv.nntp at gmail.com Wed May 3 09:39:08 2006 From: arv.nntp at gmail.com (Alexis Roda) Date: Wed, 03 May 2006 15:39:08 +0200 Subject: ConfigParser and multiple option names In-Reply-To: <e381dg$dk2$1@news.in.tum.de> References: <e37rji$c46$1@news.in.tum.de> <e37v3o$30b$1@nsnmpen2-gest.nuria.telefonica-data.net> <e381dg$dk2$1@news.in.tum.de> Message-ID: <e3abop$n0n$1@nsnmpen2-gest.nuria.telefonica-data.net> Not tested by me, but according to docs it does support list values: http://cheeseshop.python.org/pypi/ConfigObj Regards From eric_brunel at despammed.com Thu May 18 10:56:13 2006 From: eric_brunel at despammed.com (Eric Brunel) Date: Thu, 18 May 2006 16:56:13 +0200 Subject: Tkinter Dialog Management problems: References: <mailman.5875.1147956085.27775.python-list@python.org> Message-ID: <ops9q43zmcrqur0o@eb.pragmadev> On Thu, 18 May 2006 08:41:20 -0400, Michael Yanowitz <m.yanowitz at kearfott.com> wrote: > Hello: > > Below I have included a stripped down version of the GUI I am working > on. > It contains 2 dialog boxes - one main and one settings. It has the > following > problems, probably all related, that I am hoping someone knows what I am > doing wrong: > > 1) Pressing the Settings.. Button multiple times, brings up many > instances > of the Settings Panel. I just want it to bring up one. Is there an > easy > way to do that? In fact, the two windows you created are not dialogs; they're just windows. To turn a window into an actual "dialog", i.e basically to make it modal, you have to do the following operations (supposing your dialog window is named dlg and your main window in named root): ## Ensure only window can receive user events dlg.grab_set() ## Force Dialog to stay on top of main window dlg.transient(root) ## Wait for dialog to be destroyed root.wait_window(dlg) > 2) Pressing the Done button in the Settings Panel, just erases the Done > button > (and any other widgets in the Panel). It does not dismiss the Panel. > Pressing > the X button does work. What callback is that? Can I make the Done > button > call > that instead? How? This is not the way it works. In fact, what you did wrong is something that has been around for years in some Tkinter tutorial(s): you made your classes inherit from Frame. This is a Bad Idea: a Frame is not a window, but only a generic container. There are 2 classes for windows: Tk for the main window and Toplevel for all others. They both also act as containers, so you can do in them everything you do in Frames. So make your ScriptDialog inherit from Tk, your SettingsDialog inherit from Toplevel, remove all explicit creations of Tkinter.Tk or Tkinter.Toplevel and instantiate your classes instead. Then calling destroy on either on the dialogs will actually close the window. > 3) Pressing the Done button from the Main Panel has no effect? Why not? > It > used > to work (self.quit()). Again, I would like to call whatever is called > when the > X button (top Right corner) is pressed. This should work. BTW, your "done" method is not needed: creating the Button with command=self.quit works without problem. HTH -- python -c "print ''.join([chr(154 - ord(c)) for c in 'U(17zX(%,5.zmz5(17l8(%,5.Z*(93-965$l7+-'])" From johnjsal at NOSPAMgmail.com Wed May 10 11:50:38 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 15:50:38 GMT Subject: multiline strings and proper indentation/alignment In-Reply-To: <5iv3629eodhhq7g8hp42n5eclusli2r5qo@4ax.com> References: <Ms48g.2070$No6.45827@news.tufts.edu> <mailman.5527.1147204632.27775.python-list@python.org> <44613e5d$0$9438$c3e8da3@news.astraweb.com> <4461c445$0$14031$626a54ce@news.free.fr> <Eim8g.2075$No6.45677@news.tufts.edu> <5iv3629eodhhq7g8hp42n5eclusli2r5qo@4ax.com> Message-ID: <iZn8g.2078$No6.45875@news.tufts.edu> Dave Hansen wrote: >>>> print textwrap.dedent(s).strip().replace('\n',' ') > this is a multiline triple-quted string with indentation for nicer > code formatting But I have some newlines that are already embedded in the string, and I wouldn't want those replaced. From nobody at 127.0.0.1 Tue May 2 13:29:58 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 17:29:58 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> Message-ID: <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> bruno at modulix wrote: >> that 1) b is an object not a module*, and 2) objects pass references to >> themselves as the first argument to their methods. > > Nope. It's the MethodType object (a descriptor) that wraps the function > that do the job. The object itself is totally unaware of this. It's shorthand, not to be taken literally. >> Making people pass 'self' > > s/self/the instance/ > >> explicitly is stupid > > No. It's actually a feature. potato, potahto. >> the first argument, leading to these kinds of mistakes. The compiler >> should handle it for you > > I don't think this would be possible if we want to keep the full > dynamism of Python. How then could the compiler handle the following code > ? > > class MyObj(object): > def __init__(self, name): > self.name = name class MyObj(object): def __init__(name): self.name = name And the rest should work fine. When the interpreter sees a method declaration, it can automatically 1) add the object instance parameter to the signature, and 2) automatically bind the name self to the object instance on dispatch. Everything else is just as before. >> but in practice you don't declare >> self as a parameter to module functions > > def someOtherFunc(): > print "hello there" > > m.someFunc = someOtherFunc > m.someFunc() Complete non-sequitor, what does this have to do with self? From jstroud at ucla.edu Sun May 28 17:38:43 2006 From: jstroud at ucla.edu (James Stroud) Date: Sun, 28 May 2006 14:38:43 -0700 Subject: Using a package like PyInstaller In-Reply-To: <0rieg.1829$hv1.972@trnddc01> References: <FyYdg.2216$As2.860@trnddc02> <e5ab5l$tkm$1@daisy.noc.ucla.edu> <DD4eg.2432$As2.2216@trnddc02> <e5amec$64m$1@daisy.noc.ucla.edu> <ZX5eg.287$xO5.197@trnddc03> <e5bf4k$of9$1@daisy.noc.ucla.edu> <0rieg.1829$hv1.972@trnddc01> Message-ID: <e5d593$v4p$1@daisy.noc.ucla.edu> LittlePython wrote: > "Im 99.999% confident that this will not happen from the .exe file > generated by pyinstaller (unless you specify--see link above)." > > Well I guess that's about as close as any one can get in this business. I > have been trying to introduce py into our environment, and have opened a few > eyes, however I have been given one restriction. I can not install anything, > leave behind anything or alter anything on a systems ...... period, You can always hard-code external resources. For example, first write a script that makes a module out of one or several jpegs (assuming jpeg extension is consitently 'jpg': import binascii def append_to_jpeg_module(modulename, jpegs): myjpegs = open('%s.py' % modulename, 'wa') for jpegname in jpegs: afile = open('%s.jpg' % jpegname, 'rb') ajpeg = afile.read() afile.close() jpegascii = binascii.b2a_base64(ajpeg) print jpegascii myjpegs.write('%s = """%s"""\n\n' % (jpegname, jpegascii)) myjpegs.close() append_to_jpeg_module('myjpegs', ['logo_sm']) #heres how you use it append_to_jpeg_module('myjpegs', ['coolpik1', 'coolpik2', 'anotherpik']) Now, in your file that needs the jpegs, you can pretend these strings are files with the cStringIO module, e.g. (pretending 'modulename' above is 'myjpegs'): import binascii import myjpegs import cStringIO def get_jpeg_as_opened_file(jpegname, module): jpegascii = module.__dict__[jpegname] jpegbin = binascii.a2b_base64(jpegascii) return cStringIO.StringIO(jpegbin) # getting that pik get_jpeg_as_opened_file('coolpik1', myjpegs) And your company can go on making widgets feeling secure in the fact that you have not required any extra entries in their file allocation tables. James -- James Stroud UCLA-DOE Institute for Genomics and Proteomics Box 951570 Los Angeles, CA 90095 http://www.jamesstroud.com/ From wleftwich at gmail.com Sun May 14 12:10:11 2006 From: wleftwich at gmail.com (Wade Leftwich) Date: 14 May 2006 09:10:11 -0700 Subject: Aggregate funuctions broken in MySQLdb? References: <lorenzo-33D2D1.20511013052006@hedley.internal.thethurmans.com> Message-ID: <1147623011.319336.11820@v46g2000cwv.googlegroups.com> Works fine for me, and I certainly hope MySQLdb is ready for prime time, because I use the heck out of it. Maybe you're getting fooled by the fact that cursor.execute() returns the count of result rows. To actually see the result rows, you have to say cursor.fetchone() or fetchall() -- In [34]: cur.execute("select article_id from articles limit 10") Out[34]: 10L In [35]: cur.fetchall() Out[35]: ((3L,), (4L,), (5L,), (6L,), (7L,), (8L,), (9L,), (10L,), (11L,), (12L,)) In [36]: cur.execute("select count(article_id) from articles where article_id < 13") Out[36]: 1L In [37]: cur.fetchall() Out[37]: ((10L,),) In [38]: cur.execute("select sum(article_id) from articles where article_id < 13") Out[38]: 1L In [39]: cur.fetchone() Out[39]: (75.0,) In [40]: cur.execute("select avg(article_id) from articles where article_id < 13") Out[40]: 1L In [41]: cur.fetchone() Out[41]: (7.5,) From ironfroggy at gmail.com Sun May 7 23:22:26 2006 From: ironfroggy at gmail.com (Calvin Spealman) Date: Sun, 7 May 2006 23:22:26 -0400 Subject: Image SIG ML Moderator does not respond Message-ID: <76fd5acf0605072022l46d331b4v413b1a4da7a7b0c8@mail.gmail.com> I have tried repeatedly to make a post to the Image SIG ML, and get nothing but automated responses that I must wait for word from the moderator to approve my posting on the list. I have gotten no reply, positive or not, in over a month. I am assuming the Image SIG moderator is currently MIA. What channels do I have to get my messages on the ML, and how is responsible for installing a new moderator if that is needed? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060507/faca5618/attachment.html> From chris.uppal at metagnostic.REMOVE-THIS.org Tue May 9 06:22:41 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Tue, 9 May 2006 11:22:41 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1147148036.512676.288190@i39g2000cwa.googlegroups.com> <slrne60jsm.dac.apardon@rcpc42.vub.ac.be> <1147165989.106261.164090@j33g2000cwa.googlegroups.com> Message-ID: <44606dd0$0$651$bed64819@news.gradwell.net> Pisin Bootvong wrote: > Slippery Slope:: > "Argumentation that A is bad, because A might lead to B, and B > to C, and we all know C is very bad." For the Slippery Slope criticism to be applicable, there would have to be some suggestion that removing anonymous functions /would actually/ (tend to) lead to removing anonymous values in general. There was no such suggestion. The form of the argument was more like reasoning by analogy: if context A has features like context B, and in B some feature is known to be good (bad) then the analogous feature in A is also good (bad). In that case an attack on the validity of the argument would centre on the relevance and accuracy of the analogy. Alternatively the argument might be seen as a generalisation/specialisation approach. Functions are special cases of the more general notion of values. We all agree that anonymous values are a good thing, so anonymous functions should be too. If you parse the argument like that, then the attack should centre on showing that functions have relevant special features which are not shared by values in general, and so that we cannot validly deduce that anonymous functions are good. -- chris From sybrenUSE at YOURthirdtower.com.imagination Fri May 12 04:35:26 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 12 May 2006 10:35:26 +0200 Subject: Threads References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <jq8862dcirmmj5atp7tdv2q7t032ansquh@4ax.com> <1147417744.770080.11490@q12g2000cwa.googlegroups.com> <slrne68ddu.qon.sybrenUSE@schuimige.stuvel.eu> <1147419709.500563.120190@i39g2000cwa.googlegroups.com> Message-ID: <slrne68i6e.4h6.sybrenUSE@schuimige.stuvel.eu> placid enlightened us with: > its always said that (in programming) that the easiest solution to a > problem is hard to find Yeah, that's true allright! Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From kentilton at gmail.com Wed May 10 12:04:33 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 10 May 2006 12:04:33 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <ubn362tg2ft4la26hq4so0ron8lsj7fvqe@4ax.com> References: <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> <kBn7g.3$4q2.1@fe12.lga> <6pfu521h1gtq1v3rb3g4he5pi6fr6u4g67@4ax.com> <1LJ7g.17$u17.10@fe08.lga> <xcv3bfke1ju.fsf@conquest.OCF.Berkeley.EDU> <s0cv52d14nvs8iftt5hvj5d98poceoqald@4ax.com> <NUP7g.17$G22.12@fe11.lga> <36q062ts4fu6f5bpd2sinmfv906k7ls5eq@4ax.com> <ubn362tg2ft4la26hq4so0ron8lsj7fvqe@4ax.com> Message-ID: <mao8g.5$CQ6.4@fe11.lga> [Sorry, I missed this one originally.] David C. Ullrich wrote: > On Tue, 09 May 2006 05:35:47 -0500, David C. Ullrich > <ullrich at math.okstate.edu> wrote: > > >>On Mon, 08 May 2006 18:46:57 -0400, Ken Tilton <kentilton at gmail.com> >>wrote: >>[...] >> >>If you, um, look at the code you see that "cells.a = 42" triggers >>cells.__setattr__, which fires a's callback; the callback then >>reaches inside and sets the value of b _without_ going through >>__setattr__, hence without triggering b's callback. >> >>In Cells you can't have A depend on B and also B depend on A? >>That seems like an unfortunate restriction - I'd want to be >>able to have Celsius and Farenheit, so that setting either >>one sets the other. Set Kelvin, and make Celsius and Fahrneheit functions of that. ie, There is only one datapoint, the temperature. No conflict unless one creates one. > > > Realized later that I hadn't thought this through. > > I'd been assuming that of course we should be allowed to > have A and B depend on each other. Hence if a change in > A propagates to a change in B that change in B has to > be a non-propagating change - thought I was just so > clever seeing a way to do that. I think it could be arranged, if one were willing to tolerate a little fuzziness: no, there would be no strictly correct snapshot at which point everyone had their "right value". Instead, A changes so B recomputes, B changes so A recomputes... our model has now come to life, we just have to poll for OS events or socket data, and A and B never get to a point where they are self-consistent, because one or the other always needs to be recalculated. I sometimes wonder if the physical universe is like that, explaining why gravity slows time: it is not the gravity, it is the mass and we are seeing system degradation as the matrix gets bogged down recomputing all that matter. [Cue Xah] > > But duh, if that's how things are then we can't have > transitive dependencies working out right; surely we > want to be able to have B depend on A and then C > depend on B... > > (And also if A and B are allowed to depend on each > other then the programmer has to ensure that the > two rules are inverses of each other, which seems > like a bad constraint in general, something non-trivial > that the programmer has to get right.) Right, when I considered multi-way dependencies I realized I would have to figure out some new syntax to declare in one place the rules for two slots, and that would be weird because in Cells it is the instance that gets a rule at make-instance time, so i would really have to have some new make-instance-pair capability. Talk about a slippery slope. IMO, the big constraints research program kicked off by Steele's thesis withered into a niche technology because they sniffed at the "trivial" spreadsheet model of linear dataflow and tried to do partial and multi-way dependencies. I call it "a bridge too far", and in my experience of Cells (ten years of pretty intense use), guess what?, all we need as developers is one-way, linear, fully-specified dependencies. > > So fine, no loops. If anything, if we know that > there are no loops in the dependencies that simplifies > the rest of the programming, no need for the sort of > finagling described in the first paragraph above. Actually, I do allow an on-change callback ("observer" in Cells parlance) to kick off a toplevel, imperative state change to the model. Two cells who do that to each other will run until one decides not to do so. I solve some GUI situations (the classic being a scrollbar thumb and the text offset, which each at different times control the other, by having them simply set the other in an observer. On the second iteration, B is setting A to the value A has already, so propagation stops (a longstanding Cells feature). These feel like GOTOs, by the way, and are definitely to be avoided because they break the declarative paradigm of Cells in which I can always look at one (anonymous!) rule and see without question from where any value it might hold comes. (And observers define where they take effect outside the model, but those I have to track down by slot name using OO browsing tools.) > But this raises a question: > > Q: How do we ensure there are no loops in the dependencies? Elsewhere I suggested the code was: (let ((*dependent* this-cell)) (funcall (rule this-cell) (object this-cell))) It is actually: (let ((*dependents* (list* this-cell *dependents*))) (funcall (rule this-cell) (object this-cell))) So /before/ that I can say: (assert (not (find this-cell *dependents*))) > > Do we actually run the whole graph through some algorithm > to verify there are no loops? > > The simplest solution seems like adding the cells one > at a time, and only allowing a cell to depend on > previously added cells. It's clear that that would > prevent loops, but it's not clear to me whether or > not that disallows some non-looping graphs. As you can see, the looping is detected only when there is an actual circularity, defined as a computation requiring its own computation as an input. btw, a rule /does/ have access to the prior value it computed, if any, so the cell can be value-reflective even though the rules cannot be reentrant. > A > math question the answer to which is not immediately > clear to me (possibly trivial, the question just > ocurred to me this second): > > Say G is a (finite) directed graph with no loops. Is it always > possible to order the vertices in such a way that > every edge goes from a vertex to a _previous_ vertex? I am just a simple application programmer, so I just wait till Cells breaks and then I fix that. :) kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From tim.leeuwvander at nl.unisys.com Wed May 24 07:29:09 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 24 May 2006 04:29:09 -0700 Subject: John Bokma harassment In-Reply-To: <1148468447.577714.203450@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> Message-ID: <1148470149.596188.18500@j55g2000cwa.googlegroups.com> ilitzroth at gmail.com wrote: > I agree there are limits to you right to free speech, but I believe Xah > Lee is not crossing > any boundaries. If he starts taking over newspapers and TV stations be > sure to notify me, > I might revise my position. > Immanuel Perhaps he's not crossing boundaries of free speech, but he's repeatedly crossing boundaries on usenet nettiquette, even though repeatedly he's being asked not to do so. (Extensive crossposting to various usenetgroups / mailing lists, for instance). If he would just post his stuff on a blog and find a why to get people to visit hist blog, without crossposting to 10 usenest groups for each post he makes to his blog, then nobody would mind him expressing his opinions, and those interested could discuss them wildly on the blog. But I've repeatedly seen people telling him not to crosspost his essays to so many newsgroups, yet he continues doing it. If that's enough to quit his subscription with his ISP I don't know, but since I've stopped following threads originated by him I don't know what other grounds there would be. Cheers, --Tim From iainking at gmail.com Wed May 17 05:37:27 2006 From: iainking at gmail.com (Iain King) Date: 17 May 2006 02:37:27 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147853776.367091.254700@u72g2000cwu.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <Xns97C5D095513C4duncanbooth@127.0.0.1> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <Xns97C5E15CACA5Cduncanbooth@127.0.0.1> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <Xns97C65986E948Dduncanbooth@127.0.0.1> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> Message-ID: <1147858647.488974.92230@j73g2000cwa.googlegroups.com> Ant wrote: > I think Duncan has hit the nail on the head here really. I totally > agree that conceptually using tabs for indentation is better than using > spaces. Pragmatically though, you can't tell in an editor where spaces > are used and where tabs are used. > Um, I don't follow this. If you can't tell the editor where tabs/spaces are used, who does? > Perhaps if editors colored the background of tab characters differently > from spaces this wouldn't be a problem, Some editors do. > or if Python was more > restrictive and did not actually allow a mix of tabs and spaces for > indentation there would be no problem - the compiler could throw out an > exception for mixed characters. python -tt > In reality, neither of these are likely > to be implemented any time soon! um Iain From deets at nospam.web.de Sun May 21 18:23:26 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 22 May 2006 00:23:26 +0200 Subject: Iterators: Would "rewind" be a good idea? In-Reply-To: <vM4cg.20452$Lm5.11170@newssvr12.news.prodigy.com> References: <4470C2E5.1020004@earthlink.net> <mailman.6042.1148244425.27775.python-list@python.org> <vM4cg.20452$Lm5.11170@newssvr12.news.prodigy.com> Message-ID: <4dc7ivF19lqquU1@uni-berlin.de> > My knowledge of Python's iterators is kind of sketchy, so I may have missed > something. The only thing a python iterator really is is something that supports a next()-method and will raise a StopIteration-Exception in case of exhaustion. So - nobody stops you from introducing an object like class Foo: def next(self): pass def prev(self): pass and work with it as you like - the same way as in C++. But the syntactic sugaring and support in lots of classes that makes the iterator concept especially interesting in python makes only sense in one-way-iterators. Or do you really have a use-case for an reverting-in-the-middle for . in . - syntax? And as Heiko explained (and you yourself mentioned too): forward/backward iteration makes only sense in case of a memory-backed implementation, namely containers. But the much more general concept of iterators of python applies to generators/generator expressions, itertools and so on. Diez From johnjsal at NOSPAMgmail.com Sat May 13 14:52:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sat, 13 May 2006 14:52:12 -0400 Subject: Sending mail with attachment... In-Reply-To: <1147515213.695066.5740@u72g2000cwu.googlegroups.com> References: <1147508571.532690.292650@v46g2000cwv.googlegroups.com> <1147515213.695066.5740@u72g2000cwu.googlegroups.com> Message-ID: <44662b51$0$1949$c3e8da3@news.astraweb.com> Merrigan wrote: > mesg['To'] = recievelist It's already been pointed out that this is a problem, but I just wanted to mention also that 'recieve' is misspelled, in case that affects anything, or others who might read/use the code. From mrmakent at cox.net Wed May 31 09:21:55 2006 From: mrmakent at cox.net (Mike Kent) Date: 31 May 2006 06:21:55 -0700 Subject: problem with google api / xml In-Reply-To: <1149066648.521045.152480@h76g2000cwa.googlegroups.com> References: <1149066648.521045.152480@h76g2000cwa.googlegroups.com> Message-ID: <1149081715.924998.46430@f6g2000cwb.googlegroups.com> robin wrote: > from SOAPpy import WSDL > WSDLFILE = '/pathtomy/googleapi/GoogleSearch.wsdl' > APIKEY = '....' > _server = WSDL.Proxy(WSDLFILE) Robin, note this part of the URI set in WSDLFILE: '/pathtomy/googleapi'. Get it? 'path to my google api'. You must set this part to the actual path where the file 'GoogleSearch.wsdl' is found. In addition, doesn't APIKEY = '....' look a bit odd to you? Hmm, what could this mean. APIKEY. Perhaps you need to get an API key from Google in order to use their search API, and fill it in there? ;-) From s99999999s2003 at yahoo.com Thu May 25 07:27:59 2006 From: s99999999s2003 at yahoo.com (s99999999s2003 at yahoo.com) Date: 25 May 2006 04:27:59 -0700 Subject: a good explanation Message-ID: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> hi my friend has written a loop like this cnt = 0 files = [a,b,c,d] while cnt < len(files) : do_something(files[cnt]) i told him using for fi in files: do_something(fi) is better, because the while loop method makes another call to len..which is slower.. am i partly right? or is there a better explanation for using the for method.? thanks From johnjsal at NOSPAMgmail.com Fri May 12 18:04:34 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 12 May 2006 18:04:34 -0400 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <jz09g.2091$No6.46071@news.tufts.edu> References: <jz09g.2091$No6.46071@news.tufts.edu> Message-ID: <4465079d$0$11703$c3e8da3@news.astraweb.com> John Salerno wrote: > If more information is needed, I will try my local DB when I get home > later. Ok, here we go: import MySQLdb db = MySQLdb.connect(host='localhost', user='johnjsal', passwd='seinfeld', db='bbdatabank') cursor = db.cursor() cursor.execute('SELECT * FROM Master') data = cursor.fetchall() cursor.close() db.close() print data And the output: >>> Traceback (most recent call last): File "C:\Python24\myscripts\db_test.py", line 6, in -toplevel- db='bbdatabank') File "C:\Python24\lib\site-packages\MySQLdb\__init__.py", line 66, in Connect return Connection(*args, **kwargs) File "C:\Python24\lib\site-packages\MySQLdb\connections.py", line 134, in __init__ super(Connection, self).__init__(*args, **kwargs2) OperationalError: (2003, "Can't connect to MySQL server on 'localhost' (10061)") >>> The situation is this: I installed MySQL 5.0, created a database called bbdatabank using the MySQL prompt. Within the database there is a table called Master, which I'm testing on. Obviously something is happening with the connect method. Perhaps I'm doing something wrong. Is there a way to get more info about what's happening? Thanks. From http Fri May 26 01:53:36 2006 From: http (Paul Rubin) Date: 25 May 2006 22:53:36 -0700 Subject: genexp surprise (wart?) References: <7xpsi14drb.fsf@ruckus.brouhaha.com> <1148620982.393630.250970@i40g2000cwc.googlegroups.com> <7xfyixe3x6.fsf@ruckus.brouhaha.com> Message-ID: <7xbqtle3hb.fsf@ruckus.brouhaha.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > Yeah, it's just counterintuitive is all. I guess the natural way to > express this would have been with tail recursion instead of a while > loop. FWIW, here's a listcomp version: def s2(n=100): stream = range(2,n) while stream: p = stream[0] yield p stream = [s for s in stream if s%p != 0] print list(s2(100)) This should have the same space consumption and approx. running time as the classic sieve. The genexp version actually used O(n/log(n)) space instead of linear space, I think. From gdamjan at gmail.com Mon May 22 10:36:28 2006 From: gdamjan at gmail.com (Damjan) Date: Mon, 22 May 2006 16:36:28 +0200 Subject: enumerate() question References: <1148308146.493287.323770@38g2000cwa.googlegroups.com> Message-ID: <4471cc6c$0$15785$14726298@news.sunsite.dk> > I have a question for the developer[s] of enumerate(). Consider the > following code: > > for x,y in coords(dots): > print x, y > > When I want to iterate over enumerated sequence I expect this to work: > > for i,x,y in enumerate(coords(dots)): > print i, x, y for i, (x, y) in enumerate(coords(dots)): print i, x, y -- damjan From craighse888 at googlemail.com Sat May 27 04:44:58 2006 From: craighse888 at googlemail.com (craighse888 at googlemail.com) Date: 27 May 2006 01:44:58 -0700 Subject: monkeypatching NamedTemporaryFile In-Reply-To: <mailman.6216.1148614516.27775.python-list@python.org> References: <mailman.6216.1148614516.27775.python-list@python.org> Message-ID: <1148719498.352149.251740@38g2000cwa.googlegroups.com> Maybe that should be the default behaviour. Presumably the file has been deleted by some other process? From bignose+hates-spam at benfinney.id.au Fri May 19 20:31:40 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 May 2006 10:31:40 +1000 Subject: calling python functions using variables References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <e4k443$el5$02$1@news.t-online.com> <mailman.5934.1148032680.27775.python-list@python.org> <446da180$0$10184$636a55ce@news.free.fr> Message-ID: <87wtchk043.fsf@benfinney.id.au> bruno at modulix <onurb at xiludom.gro> writes: > Ben Finney wrote: > > You'll also need to anticipate the situation where the value bound > > to VARIABLE is not the name of an attribute in 'commands'. > > > > Either deal with the resulting NameError exception (EAFP[0]) > > try: > getattr(commands, VARIABLE)() > except NameError: > print >> sys.stderr, "Unknown command", VARIABLE No. As another poster points out, that will mistakenly catch NameError exceptions raised *inside* the function. When catching exceptions, be sure that your 'try' block is only doing the minimum of stuff that you want exceptions from, so you know what they mean when they occur. try: this_command = getattr(commands, VARIABLE) except NameError: print >> sys.stderr, "Unknown command '%s'" % VARIABLE this_command() > > or test first whether the attribute exists (LBYL[1]). > > command = getattr(commands, VARIABLE, None) > if command is None: > print >> sys.stderr, "Unknown command", VARIABLE > else: > command() > > I'd go for the first solution. With the caveats mentioned above, yes, I agree. -- \ "I was arrested today for scalping low numbers at the deli. | `\ Sold a number 3 for 28 bucks." -- Steven Wright | _o__) | Ben Finney From andre.roberge at gmail.com Sun May 28 19:18:08 2006 From: andre.roberge at gmail.com (=?iso-8859-1?B?QW5kcuk=?=) Date: 28 May 2006 16:18:08 -0700 Subject: pygame and wxpython In-Reply-To: <1148854384.549915.135950@j73g2000cwa.googlegroups.com> References: <1148854384.549915.135950@j73g2000cwa.googlegroups.com> Message-ID: <1148858288.668368.246720@j55g2000cwa.googlegroups.com> DK wrote: > I'm somewhat new to Python but not to programming. > > I just want to know if it's possible to have a SINGLE wxPython frame > containing two sections where one will contain widgets and the other > will host an animation done using PyGame. > > More specifically, I want to have a list of names of animations on the > left and depending on what is selected, run the PyGame animation in the > main area. I have not seen this done but you should note that both wxPython and Pygame run their own event loops - which can cause some serious problems. However, here's a link that may help you get started on trying to do what you're looking for. http://wiki.wxpython.org/index.cgi/IntegratingPyGame?highlight=%28pygame%29 Andr? From bignose+hates-spam at benfinney.id.au Fri May 19 21:35:05 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 20 May 2006 11:35:05 +1000 Subject: Creating a new file object; open() vs file() (was: Re: altering an object as you iterate over it?) References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> <WNpbg.2142$No6.46279@news.tufts.edu> <y2qbg.46875$CH2.9602@tornado.texas.rr.com> <qbqbg.2145$No6.46426@news.tufts.edu> Message-ID: <87wtchiily.fsf_-_@benfinney.id.au> John Salerno <johnjsal at NOSPAMgmail.com> writes: > Paul McGuire wrote: > > > I think it is just part of the objectification trend - "f = > > open('xyzzy.dat')" is sort of a functional/verb concept, so it has > > to return something, and its something non-objecty like a file > > handle - urk! Instead, using "f = file('xyzzy.dat')" is more of > > an object construction concept > > I see what you mean, but I think that's why I like using open, > because I like having my functions be verbs instead of nouns. Note though that you're calling a class (in this case, type) constructor, to return a new object. Do you find int(), dict(), set() et al to be strange names for what they do? -- \ "I was sleeping the other night, alone, thanks to the | `\ exterminator." -- Emo Philips | _o__) | Ben Finney From lorenzo at excitement.com Sat May 13 21:51:10 2006 From: lorenzo at excitement.com (Lorenzo) Date: Sat, 13 May 2006 20:51:10 -0500 Subject: Aggregate funuctions broken in MySQLdb? Message-ID: <lorenzo-33D2D1.20511013052006@hedley.internal.thethurmans.com> I'm trying to use some of the agg functions in MySQLdb (avg, min, max), but they're just not working as I would expect. They all return the value 1 when executed as part of Python scripts, but work as expected when used in mysql 4.1. Does anyone have any experience using Python with MySQLdb? Quite frankly, the more I use it, the more MySQLdb seems to be not quite ready for prime time. -- "My Break-Dancing days are over, but there's always the Funky Chicken" --The Full Monty From nick at craig-wood.com Thu May 25 11:30:05 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Thu, 25 May 2006 10:30:05 -0500 Subject: a good explanation References: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> <4dlmsqF1abojeU1@uni-berlin.de> <1148561036.982387.316920@j33g2000cwa.googlegroups.com> Message-ID: <slrne7bhrs.rhj.nick@irishsea.home.craig-wood.com> mik3 <mik3l3374 at hotmail.com> wrote: > So he has written his first program in python and i have roughly toook > a glance at it and saw what he did.. i pointed out his "mistakes" but > couldn't convince him otherwise. Anyway , i am going to show him your > replies.. You might want to show him this too...if you happen to need cnt in the loop, this is what you write files = [a,b,c,d] for cnt, fi in enumerate(files): do_something(cnt, fi) -- Nick Craig-Wood <nick at craig-wood.com> -- http://www.craig-wood.com/nick From bdesth.quelquechose at free.quelquepart.fr Mon May 29 19:39:37 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Tue, 30 May 2006 01:39:37 +0200 Subject: create a text file In-Reply-To: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> References: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> Message-ID: <447b56c9$0$19539$636a55ce@news.free.fr> Stan Cook a ?crit : > I'm writing a script to list all of my music files' id3 tags to a comma > delimited file. The only part I'm missing seems like it should be the > simplest. I haven't used Python for the last couple of years. My > question is this: > > When I use os.open(<file_variable>,"w"), I get an error message, > TypeError: an integer is required. Has something changed? Did I miss > something??? You want open() (the builtins one), not os.open(). Also, if you want to deal with csv files, you may want to check the csv module (if you don't use it already). From kentilton at gmail.com Sun May 7 10:36:00 2006 From: kentilton at gmail.com (Ken Tilton) Date: Sun, 07 May 2006 10:36:00 -0400 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1146989302.961178.91070@y43g2000cwc.googlegroups.com> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <87psiq48sm.fsf@rpi.edu> <1146989302.961178.91070@y43g2000cwc.googlegroups.com> Message-ID: <kBn7g.3$4q2.1@fe12.lga> Serge Orlov wrote: > Bill Atkins wrote: > >>"Serge Orlov" <Serge.Orlov at gmail.com> writes: >> >> >>>Ken Tilton wrote: >>> >>>>It is vastly more disappointing that an alleged tech genius would sniff >>>>at the chance to take undeserved credit for PyCells, something probably >>>>better than a similar project on which Adobe (your superiors at >>>>software, right?) has bet the ranch. This is the Grail, dude, Brooks's >>>>long lost Silver Bullet. And you want to pass????? >>>> >>>>C'mon, Alex, I just want you as co-mentor for your star quality. Of >>>>course you won't have to do a thing, just identify for me a True Python >>>>Geek and she and I will take it from there. >>>> >>>>Here's the link in case you lost it: >>>> >>>> http://www.lispnyc.org/wiki.clp?page=PyCells >>>> >>>>:) >>>> >>>>peace, kenny >>>> >>>>ps. flaming aside, PyCells really would be amazingly good for Python. >>>>And so Google. (Now your job is on the line. <g>) k >>> >>>Perhaps I'm missing something but what's the big deal about PyCells? >>>Here is 22-lines barebones implementation of spreadsheet in Python, >>>later I create 2 cells "a" and "b", "b" depends on a and evaluate all >>>the cells. The output is >>> >>>a = negate(sin(pi/2)+one) = -2.0 >>>b = negate(a)*10 = 20.0 >>> >>>=================== spreadsheet.py ================== >>>class Spreadsheet(dict): >>> def __init__(self, **kwd): >>> self.namespace = kwd >>> def __getitem__(self, cell_name): >>> item = self.namespace[cell_name] >>> if hasattr(item, "formula"): >>> return item() >>> return item >>> def evaluate(self, formula): >>> return eval(formula, self) >>> def cell(self, cell_name, formula): >>> "Create a cell defined by formula" >>> def evaluate_cell(): >>> return self.evaluate(formula) >>> evaluate_cell.formula = formula >>> self.namespace[cell_name] = evaluate_cell >>> def cells(self): >>> "Yield all cells of the spreadsheet along with current values >>>and formulas" >>> for cell_name, value in self.namespace.items(): >>> if not hasattr(value, "formula"): >>> continue >>> yield cell_name, self[cell_name], value.formula >>> >>>import math >>>def negate(x): >>> return -x >>>sheet1 = Spreadsheet(one=1, sin=math.sin, pi=math.pi, negate=negate) >>>sheet1.cell("a", "negate(sin(pi/2)+one)") >>>sheet1.cell("b", "negate(a)*10") >>>for name, value, formula in sheet1.cells(): >>> print name, "=", formula, "=", value >>> >> >>I hope Ken doesn't mind me answering for him, but Cells is not a >>spreadsheet (where did you get that idea?). > > > It's written on the page linked above, second sentence: "Think of the > slots as cells in a spreadsheet, and you've got the right idea". I'm > not claiming that my code is full PyCell implementation. Well it's the Miller Analogy Test, isn't it? <g> Very easy to leave out a level of abstraction. Like I said in my other reply, /everyone/ leaves this level out. Your spreadsheet does not have slots ruled by functions, it has one slot for a dictionary where you store names and values/formulas. Go back to your example and arrange it so a and b are actual slots (data members? fields?) of the spreadsheet class. You can just stuff numbers in a: sheet1.a = 42 but b should be somehow associated with a rule when sheet1 is created. As I said in the other post, also associate an on-change callback with slots a and b. When you create sheet1: sheet1 = Spreadsheet(a=42,b=pow(self.a,2)) You should see the callbacks for a and b fire. Then when you: sheet1.a = 7 You should see them fire again (and each should see old and new values as one would hope). The fun part is when the rule associated with b is just: self.b = somefunction(self) and somefunction happens to access slot a and it all still works. One important feature above is that the rule is associated with the slot when the instance is created, and different instances can have different ruls for the same slot. In effect, classes become programmable, hence more reusable -- without this one is forever subclassing to satisfy different functional requirements. > > > >>It does apply the basic >>idea of a spreadsheet to software - that is, instead of updating value >>when some event occurs, you specify in advance how that value can be >>computed and then you stop worrying about keeping it updated. > > > The result is the same. Hopefully I have made clear the different levels. With your example, all variables exist only in the universe of the Spreadsheet class. So you have a good start on an /interpreter/ that works like the /extension/ Cells provide to Common Lisp. Do you see the difference? Apologies for all the pseudo-Python above, btw. btw, I am not saying Python cannot do PyCells. I got pretty far on a port from CL to Python before losing interest. You just take your code above and move it to the metaclass level and, yes, track dependencies, etc etc etc. When that is done we can look at a working example and see how well Python fared without macros and full-blown lambda. hth, kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From tdelaney at avaya.com Wed May 24 19:19:05 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 25 May 2006 09:19:05 +1000 Subject: PEP-xxx: Unification of for statement and list-comp syntax Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E71F@au3010avexu1.global.avaya.com> Heiko Wundram wrote: > Am Mittwoch 24 Mai 2006 06:12 schrieb Tim Roberts: >> At one time, it was said that the "%" operator was the fastest way to >> concatenate strings, because it was implemented in C, whereas the + >> operator was interpreted. However, as I recall, the difference was >> hardly measurable, and may not even exist any longer. > > The difference doesn't exist anymore for CPython (if you join a lot of > strings) Actually, the string concatenation optimisations only work in certain specific cases (although they are the most common cases). It is still definitely advised to append to a list, then join the list. Tim Delaney From Bulkan at gmail.com Fri May 12 03:09:04 2006 From: Bulkan at gmail.com (placid) Date: 12 May 2006 00:09:04 -0700 Subject: Threads In-Reply-To: <jq8862dcirmmj5atp7tdv2q7t032ansquh@4ax.com> References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <jq8862dcirmmj5atp7tdv2q7t032ansquh@4ax.com> Message-ID: <1147417744.770080.11490@q12g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > On 11 May 2006 17:02:51 -0700, "placid" <Bulkan at gmail.com> declaimed the > following in comp.lang.python: > > > > I have a thread that has a job Queue, it continuosly polls this queue > > to see if there are any jobs for it, what i really wont to be able to > > do is, when the queue is empty, i want the thread to pause (or more > > technical, i want the thread to block) until the queue gets populated > > again. Is this possible ? > > > Did you read the documentation for Queue methods? there is no need to be patronizing about this dude, im just learning Python in my spare time, as im a Intern Software Engineer > > x = q.get(true) #blocks until data is available this is even better, thanks dude > -- > 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 http Sun May 7 15:05:52 2006 From: http (Paul Rubin) Date: 07 May 2006 12:05:52 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <87mzdurayc.fsf@rpi.edu> <1hexcwa.1vmhfkv1w40r36N%aleaxit@yahoo.com> <87ac9ubsfg.fsf@rpi.edu> <1hexfi8.12h5pp9vaj4rwN%aleaxit@yahoo.com> <87bquaskap.fsf@rpi.edu> <1146988487.941796.32550@j73g2000cwa.googlegroups.com> <1heyqab.a8408z1thjmadN%aleaxit@yahoo.com> Message-ID: <7x7j4xeju7.fsf@ruckus.brouhaha.com> aleaxit at yahoo.com (Alex Martelli) writes: > I do hate it that > [ x for x in container if predicate(x) ] > is an exact synonym of the more legible > list( x for x in container if predicate(x) ) Heh, I hate it that it's NOT an exact synonym (the listcomp leaves 'x' polluting the namespace and clobbers any pre-existing 'x', but the gencomp makes a new temporary scope). > and the proposed > {1, 2, 3} > is an exact synonym of > set((1, 2, 3)) There's one advantage that I can think of for the existing (and proposed) list/dict/set literals, which is that they are literals and can be treated as such by the parser. Remember a while back that we had a discussion of reading expressions like {'foo': (1,2,3), 'bar': 'file.txt'} from configuration files without using (unsafe) eval. Aside from that I like the idea of using constructor functions instead of special syntax. From linuxnow at gmail.com Sun May 7 18:46:36 2006 From: linuxnow at gmail.com (linuxnow at gmail.com) Date: 7 May 2006 15:46:36 -0700 Subject: why _import__ only works from interactive interpreter? Message-ID: <1147041996.232232.165820@i39g2000cwa.googlegroups.com> I don't know what I'm doing wrong, but the result is that _import_ only works from a python shell, but not when I call a python script. $ cat test.py mod = __import__("/home/me/tests/test_imp") Called from a script it does not work: $ python /home/me/test.py Traceback (most recent call last): File "/home/pau/test.py", line 1, in ? mod = __import__("/home/me/tests/test_imp") ImportError: No module named /home/me/tests/test_imp But if I import it from a python shell, then no problem: $ python >>> import test >>> What am I doing wrong? From carlosperezs at alumnos.uvigo.es Mon May 22 06:02:59 2006 From: carlosperezs at alumnos.uvigo.es (carlosperezs at alumnos.uvigo.es) Date: Mon, 22 May 2006 12:02:59 +0200 Subject: Menu's problem Message-ID: <1148292179.44718c538177e@correoweb.uvigo.es> Hello together : I have programmed that: a listCtrl with binding functions. self.ListCtrlMarks = wx.ListCtrl(self.panel, -1, style = wx.LC_REPORT) self.Bind(wx.EVT_LIST_ITEM_SELECTED,self.OnSelectedItem,self.ListCtrlMarks) self.ListCtrlMarks.Bind(wx.EVT_RIGHT_DOWN, self.OnRightDown) self.ListCtrlMarks.Bind(wx.EVT_COMMAND_RIGHT_CLICK, self.OnRightClick) self.ListCtrlMarks.Bind(wx.EVT_RIGHT_UP, self.OnRightClick) The respectives handler are: def OnRightDown(self, event): self.x = event.GetX() self.y = event.GetY() item, flags = self.ListCtrlMarks.HitTest((self.x, self.y)) fDep.write("Item :"+str(item)+" "+str(self.x)+" "+str(self.y)+"\n") fDep.flush() if flags & wx.LIST_HITTEST_ONITEM: self.ListCtrlMarks.Select(item) event.Skip() def OnRightClick(self, event): """ The mouse right button has been pressed into a mark""" fDep.write("Despois \n") fDep.flush() # only do this part the first time so the events are only bound once if not hasattr(self, "popupID1"): self.popupID1 = wx.NewId() self.popupID2 = wx.NewId() self.popupID3 = wx.NewId() self.popupID4 = wx.NewId() self.Bind(wx.EVT_MENU, self.OnPopupOne, id=self.popupID1) self.Bind(wx.EVT_MENU, self.OnPopupTwo, id=self.popupID2) self.Bind(wx.EVT_MENU, self.OnPopupThree, id=self.popupID3) self.Bind(wx.EVT_MENU, self.OnPopupFour, id=self.popupID4) # make a menu menu = wx.Menu() # add some items menu.Append(self.popupID1, "Edit (Name and Note)") menu.Append(self.popupID2, "Init") menu.Append(self.popupID3, "End") menu.Append(self.popupID4, "Delete") # Popup the menu. If an item is selected then its handler # will be called before PopupMenu returns. self.PopupMenu(menu, (self.x, self.y)) menu.Destroy() the problem i have is thaht menu do not popup at the mouse cursor position. I do not know what goes wrong? Thank you --oOo-----------------------------------------------------------------oOo-- Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo Servicios Inform?ticos [ http://si.uvigo.es ] Universidade de Vigo [ http://www.uvigo.es ] URL: https://correoweb.uvigo.es From kent at kentsjohnson.com Fri May 26 06:12:20 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Fri, 26 May 2006 06:12:20 -0400 Subject: Speed up this code? In-Reply-To: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> Message-ID: <4476d3ac_2@newspeer2.tds.net> aomighty at gmail.com wrote: > I'm creating a program to calculate all primes numbers in a range of 0 > to n, where n is whatever the user wants it to be. I've worked out the > algorithm and it works perfectly and is pretty fast, but the one thing > seriously slowing down the program is the following code: > > def rmlist(original, deletions): > return [i for i in original if i not in deletions] > > original will be a list of odd numbers and deletions will be numbers > that are not prime, thus this code will return all items in original > that are not in deletions. For n > 100,000 or so, the program takes a > very long time to run, whereas it's fine for numbers up to 10,000. > > Does anybody know a faster way to do this? (finding the difference all > items in list a that are not in list b)? - Make deletions a set, testing for membership in a set is much faster than searching a large list. - Find a better algorithm ;) Kent From nnorwitz at gmail.com Sat May 27 21:53:31 2006 From: nnorwitz at gmail.com (nnorwitz at gmail.com) Date: 27 May 2006 18:53:31 -0700 Subject: linking errors with debug build of Python2.4.3 In-Reply-To: <mailman.6150.1148482197.27775.python-list@python.org> References: <mailman.6150.1148482197.27775.python-list@python.org> Message-ID: <1148781211.487215.260090@j73g2000cwa.googlegroups.com> Martin Wiechert wrote: > Hi list, > > I've created a fresh build of Python 2.4.3 using the following configuration > > $ ./configure --with-pydebug --prefix=/usr/local/debug --enable-shared > --with-fpectl --with-signal-module > > What did I do wrong? Try with just: ./configure --with-pydebug --prefix=/usr/local/debug I think the problem is --enable-shared. I'm not sure what you are doing, but you probably don't need the other options. The signal module should always be built, I've never even seen the --with-signal-module option. :-) n From nobody at 127.0.0.1 Sat May 20 22:16:59 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 02:16:59 GMT Subject: misleading prefix ++ References: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> <e4n4i6$s26$03$1@news.t-online.com> Message-ID: <v4Qbg.19956$Lm5.5678@newssvr12.news.prodigy.com> Peter Otten wrote: >>>> class Int(object): [snip] > ... def __pos__(self): > ... if self.half: > ... self.value += 1 > ... self.half = not self.half > ... return self [snip] >>>> i = Int() which leads us to: >>>> i > 0 >>>> +i > 0 >>>> +i > 1 >>>> +i > 1 >>>> +i > 2 Now that is absolutely lovely. Looks like it's time to join the ranks of Perl and C with an Obfuscated Python Contest. ;) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From rpdooling at gmail.com Tue May 16 08:26:53 2006 From: rpdooling at gmail.com (BartlebyScrivener) Date: 16 May 2006 05:26:53 -0700 Subject: Using python for a CAD program In-Reply-To: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> Message-ID: <1147782413.357660.202480@j55g2000cwa.googlegroups.com> Art Haas posts from time to time regarding a program called PythonCad that he maintains: http://tinyurl.com/o36t8 Also, here is a search of this forum on "Cad": http://tinyurl.com/nuobe From aisaac0 at verizon.net Wed May 17 08:14:38 2006 From: aisaac0 at verizon.net (David Isaac) Date: Wed, 17 May 2006 12:14:38 GMT Subject: Tabs are *MISUNDERSTOOD*, end of discussion. (Re: Tabs versus Spaces in Source Code) References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> Message-ID: <OsEag.7446$mU6.4353@trnddc07> > Andy Sy wrote: > >Don't be evil - always configure your editor to > >convert tabs to true spaces. "achates" <aylwyn at cantab.net> wrote in message news:1147863377.329823.162990 at j73g2000cwa.googlegroups.com... > Yet another space-indenter demonstrates that problem actually lies with > people who think that tab == some spaces. Exactly. Cheers, Alan Isaac From tomerfiliba at gmail.com Sun May 21 14:52:24 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 21 May 2006 11:52:24 -0700 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <mailman.6034.1148237188.27775.python-list@python.org> References: <200605211711.25043.me+python@modelnine.org> <mailman.6034.1148237188.27775.python-list@python.org> Message-ID: <1148237544.579470.43420@i40g2000cwc.googlegroups.com> > Today you can archive the same effect (but not necessarily with the same > performance) with: > > for node in (x for x in tree if x.haschildren()): > <do something with node> true, but it has different semantic meanings -tomer From benji at benjiyork.com Fri May 5 15:38:53 2006 From: benji at benjiyork.com (Benji York) Date: Fri, 05 May 2006 15:38:53 -0400 Subject: unittest.main-workalike that runs doctests too? In-Reply-To: <Pine.LNX.4.64.0605051925460.8449@localhost> References: <uvesklpyi.fsf@pobox.com> <445BA5EB.2090506@benjiyork.com> <Pine.LNX.4.64.0605051925460.8449@localhost> Message-ID: <445BA9CD.9050706@benjiyork.com> John J Lee wrote: > Is there a page that describes the Zope SVN layout? Not that I know of. It basically goes like this: if it's not a top-level project (like zope.testing), it's either in Zope (for Zope 2 stuff) or Zope3 (for Zope 3 stuff). -- Benji York From xah at xahlee.org Sun May 21 05:15:31 2006 From: xah at xahlee.org (Xah Lee) Date: 21 May 2006 02:15:31 -0700 Subject: Software Needs Philosophers Message-ID: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Software Needs Philosophers by Steve Yegge, 2006-04-15. Software needs philosophers. This thought has been nagging at me for a year now, and recently it's been growing like a tumor. One that plenty of folks on the 'net would love to see kill me. People don't put much stock in philosophers these days. The popular impression of philosophy is that it's just rhetoric, just frivolous debating about stuff that can never properly be answered. ?Spare me the philosophy; let's stick to the facts!? The funny thing is, it's philosophers who gave us the ability to think rationally, to stick to the facts. If it weren't for the work of countless philosophers, facts would still be getting people tortured and killed for discovering and sharing them. Does it ever strike you as just a teeny bit odd that after a brief period where philosophy flourished, from maybe 400 B.C.E. to ~100 C.E., we went through a follow-on period of well over one thousand five hundred years during which the Roman Catholic Church enslaved everyone's minds and killed anyone who dared think differently? What's weirder is that we tend to pretend it didn't really happen. We like to just skip right over the dominance of religion over our minds for a hundred generations, and think of religion today as a kindly old grandpa who's just looking out for us kids. No harm, no foul. Let bygones be bygones. Sure, there were massacres and crusades and genocides and torture chambers with teeth grinding and eyes bleeding and intestines torn out in the name of God. But we were all just kids then, right? Nobody does that kind of thing today, at least not in civilized countries. We try not to think about the uncivilized ones. It was philosophers that got us out of that Dark Ages mess, and no small number of them lost their lives in doing so. And today, the philosophy majors are the butts of the most jokes, because after the philosophers succeeded in opening our minds, we forgot why we needed them. And if we stop to think about it at all, we think that it was other people, people who are very unlike us, who committed those atrocities in the name of Faith (regardless of whether it's faith in a god, or in a political party, or any other form of mind control carried out by force). We like to think we live in an enlightened age, but we don't. Humans haven't changed significantly in 10,000 years. We're still killing and torturing each other. It's apparently incredibly easy to decide to kill someone and then do it. Happens every day, all around the world. Torture, too. But those people are just people. If they had been born down the street from you, they'd have gone to school with you, been friends with you, learned to program with you, written blogs and comments, never tortured or killed anyone in the name of an idea. They'd have been you. Which means they are you; you just got lucky in where you were born. One of the commenters on my last blog entry expressed the fervent wish that I drop dead. To be sure, they qualified it with ?on the internet?. But if they really feel that way, especially about something as hilariously and absurdly unimportant in the Grand Scheme as whether the Lisp programming language has any acceptable implementations, then what does it say about us? Everyone who commented angrily on that blog entry was caught. I caught you, anonymous or not, being a religious fanatic. The only ?negative? commenter who doesn't appear to be a religious zombie was Paul Costanza (ironic, since he claims to be the opinionated one), who relegated his comments to pedantic technical corrections. They're welcome, of course; I'm always looking to correct any technical misconceptions I harbor. But they're moot, since even if I was wrong about every single technical point I brought up in that entry, my overall point ? Lisp is not an acceptable Lisp ? remains largely uncontested by the commenters. Some of them just don't get it, which is fine; no harm in that. If you've been using Lisp for years and years, and you've written books and articles and zillions of lines of Lisp code, then you're unlikely to remember anything about what it's like coming to Lisp for the first time. They're religious because they've forgotten what it's like to be a skeptic. But make no mistake; a substantial percentage of people who take a side in any programming language discussion that devolves into a flamewar know exactly what the other side means, and they want to invoke the Ultimate Censorship: drop dead! Killing someone, after all, is one of the best ways to silence them. You also have to burn all their writings, which is getting harder these days; hence the increased vehemence on the 'net. Those of you who've followed what I've written over the past year or so know where I'm going. I'm taking a stand, all right, and it's a very definite one. I'm finding myself drawn inexorably towards a single goal: stamping out technological religion, because I'm frigging tired of not being able to stick to the facts. FACT: Java has no first-class functions and no macros. This results in warped code that hacks around the problem, and as the code base grows, it takes on a definite, ugly shape, one that's utterly unique to Java. Lisp people can see this clear as day. So can Python folks, so can Ruby folks. Java people flip out, and say ?macros are too much power?, or ?what do u mean i dont understand u? or ?fuck you, you jerk, Lisp will NEVER win?. You think I don't hear ALL that, and much more, in the hate mail I get every day? I sure wouldn't want to be alone with a Java fanatic in a medieval torture chamber, because God only knows what they're capable of. Turn the mirror towards Python, and what happens? Funny, but the Java folks will mail me saying: ?yeah, I've always known I detested Python, and you really nailed exactly why. Thanks!? Meanwhile, Python folks are literally frothing at the mouth, looking for the ?Kill That Bastard? key on their 101-key keyboards. I turned the mirror towards Lisp yesterday. Had to go to the bathroom like nobody's business, and my wife was expecting me home any minute, so I rushed it out: just a few thoughts here and there. So the Gorgon only caught the tiniest glimpse of itself, but hell evidently hath no fury like that of a Lisper scorned, and all that. It doesn't matter that I rushed it out. I'm glad I did; spending any more time on it, trying to get it ?right? by looking up useless factoids like how you can override length's non-polymorphicness with some weird setting (when it plainly should just be the default), would have had the exact same net effect: Lisp zealots would have found some way to turn it into a flamewar. And I'd have been out 2 or 3 more hours. Let's call it a troll, then, because it was poorly researched; it was just some months-old recollections of pain I'd gone through last year trying to commit to Common Lisp, after another year of trying the same with various flavors of Scheme and finding them all wanting. As far as I'm concerned, Lisp is unacceptable today; it's my opinion and just that, but I'll stick with it. I still need Lisp; after you learn enough of it, it becomes part of your soul. I get my fix hacking elisp, and I do a lot of it. The commenters are quite right; I've never written anything substantial in Common Lisp, because in each of my serious attempts, there was too much friction. Risk/reward wasn't high enough, and believe me, I wanted it. But after many attempts, I've given up on Common Lisp. They won't let me use it where I work, and there are probably more Lispers per capita where I work, including some famous ones, than at any other big company in the world. If we can't use it where I work, then it's frigging unacceptable; that's the shortest proof I can offer. What I'm far more interested today is the situation that arises if you consider my post a troll. I'm far more interested in the social consequences of working in a world filled with religious fanatics of different religious persuasions. Especially given that it's a world in which ?natural religion? has, by and large, been marginalized through the work of philosophers. [ ? Peter Siebel is the author of the book Practical Common Lisp, 2005. ( http://gigamonkeys.com/book/).] Let's look at this world in a little more detail, starting with Peter Siebel's comment, which I believe is the most interesting. Peter said: I was trying to figure out why on earth you spent so much time writing about something that you apparently don't like. Then it hit me: HCGS?. So thanks for your help. His first sentence speaks volumes about the sociology. His viewpoint is exactly what they teach us all as kids: If you don't have anything nice to say, don't say anything at all. We like to think people have a right to believe whatever they want, and that it's not nice to say mean things about other people's beliefs, especially when their livelihoods are at stake. That's where philosophers come in, folks. They pick your beliefs apart and show you in unforgettable ways the consequences of what you believe in. I'm no philosopher; I know basically nothing about it, but I can tell you I wish fervently that some great philosophers would come along and effect change in our technical society. Because if nothing else, I can see the consequences of the way we're thinking about things. One of many such consequences is that languages aren't getting any better, and the worst offenders are Lisp and Scheme, which by rights should be racing along the innovation curve faster than their supposedly less capable peers. But they've stagnated worse than any other non-dead language I can think of.[1] Programming languages are religions. For a long while now I've been mildly uncomfortable calling it ?religion?, but I don't feel bad about it anymore. They're similar enough. At the top of the language religion is the language itself; it serves as the deity and the object of worship. Like any other organized religion, there's always a Pope (or a politburo chairman, in countries where the government has brutally set itself up as what is for all intents the religion of choice): a spiritual leader that gives the religion the human touch. This person is almost always the language designer, of course. In Lisp's case it's complicated, because McCarthy, Sussman and Steele aren't very active as spiritual leaders for their languages anymore. Every major organized religion is a heirarchical government, and programming languages are no exception. You'll find equivalents of cardinals, bishops, priests and laity in programming language camps: the closer you are to the fire, to the spiritual center, the higher your rank. It's a great way to quantify your perceived self-importance: a high-score list, in effect. Great for the ego, but it makes you a piss-poor debater, because you're so emotionally invested in your status. You'd think your rank would be accrued by virtue of your technical and/or documentation contributions, but in practice it's usually more of a function of how many converts you've gained, how many followers you have, how much you've been spreading the Word. [? Paul Graham is a lisp dignitary. He is well known for having sold his ecommerce software written in lisp to Yahoo.com for $49.9 million, among other things. See Paul Graham? and http://www.paulgraham.com/ ] That's why Paul Graham isn't the Pope of Lisp. He's eminently qualified, but unfortunately he's a heretic. Notice that almost none of the commenters on my last blog mentioned the PG argument I made. The only one who did (as of this writing) tried to make it an argument for Common Lisp. Let's face it: you can't give those heretics too much press; people might start listening to them! Peter, are you beginning to understand why I write so much about something I apparently don't like? It's because I wanted to like it but found it fatally flawed, technically and culturally. It's as if I were a would-be convert to Roman Catholicism, but I can't bring myself to commit because I've seen too much of their role in creating a history that ironically we all wish we could rewrite. I was born and raised a Roman Catholic, and I renounced it when I was thirteen years old, after my Uncle Frank (a devout terrorist Catholic if there ever was one) told me to stop reading the Bible, that it would ?really screw a person up? to do that, that you needed someone to interpret it for you. That wasn't the only reason I renounced it, but it'll suffice for our purposes. Technologically I was born and raised an assembly-language programmer; at least that's what my first real job was, for 5 years after I got my CS degree. Assembly is just flagellation, though, and damned uncomfortable at that, so I joined the Church of Java for fully seven years. And practically at the very moment I'd finally tired of chafing at Java's limitations, Paul Graham came along and through his early essays, showed me Lisp. What a great new religion! Problem is, each time you switch religions, the next one has less impact on you. Once a Catholic, always a Catholic, they say. I don't know what that means for me, since I was raised by the assembly-language wolf, but it appears to mean that I'm never going to be enthralled with another programming language. And now that I've swallowed the red pill, what choice do I have? I need to try to show people what's out there. Interestingly, it was Peter Siebel's most excellent book, Practical Common Lisp?, that played the role of Uncle Frank and killed my desired to continue with Common Lisp. Peter was the first person to show me beast's underbelly. Every other Lisp book had pretended it was pure and beautiful and uncorrupted, because they left all the nastiness out as ?implementation-defined?. Once I saw what you really need to do in order to build something resembling a portable Lisp code base, and then had a few runs at it myself, I threw in the towel. I much prefer Lisp the idea to Lisp the implementation.[2] [ ? Fyodor_Dostoyevsky?, David_Hume?, Aristotle?, Jean-Paul_Sartre?, Ben_Franklin?, Galileo_Galilei?, Bertrand_Russell?, Albert_Einstein? ] I can tell you this: I've tried writing this essay for a year. I've tried fully a dozen times. I've tackled it from a dozen angles. I've wanted to say it ? software needs philosophers! ? so many times, in so many ways. We need great thinkers ? the Fyodor Dostoyevskys and David Humes and Aristotles and Jean-Paul Sartres and Ben Franklins and Galileo Galileis and Bertrand Russells and Albert Einsteins to show us the way through the Software Dark Ages we're in today: a time that will doubtless be remembered as every bit as mired in darkness and ignorance as the Dark Ages themselves. But I've failed. This isn't the essay I wanted to write, because I'm neither a great thinker nor a great writer. However, you might be: if not now, then perhaps someday. So I think it's better to get the idea out now than to hoard it in the hopes of someday writing a world-changing essay. For those of you who were surprised at the suddenness and vehemence of the Lisp community's backlash to my little rant, I hope I've helped shed a little light, helped you see its inevitability. Basically they've had a lot of practice. Lisp is one of the oldest technology religions, and they've both experienced and doled out their share of religious persecution. But that's not the lesson you should take away. The lesson is that they are you. Whenever you hear someone ranting about something you take for granted as wonderful and praiseworthy, and you're wondering why they don't leave well enough alone so we can all get back to our incestuous cheerleading, just remember: we went from the Dark Ages to our reeeeasonably enlightened society today by questioning our most cherished beliefs. So keep questioning them. [ ? R6RS refers to the Scheme Lisp language's upcoming specification. See Scheme programming language? ] [1] Yes, I've read all of R6RS. It's a lukewarm compromise that punts on most of the important issues. It's not going to make Scheme any more successful than it is today, which to me feels practically criminal; it was their one big chance to break out of the rut they're in. But it doesn't matter. Let's pretend this footnote is just a troll. If your hackles went up, then you're a techno-religious zombie, and I hope in my lifetime to find you a cure. Try your best to think about that long and hard before responding. [ ? SLIME is a emacs mode for lisp programing. See http://common-lisp.net/project/slime/. ] [2] For the record, the commenter I agree the most with is the one who said the problem basically boils down to an IDE issue. SLIME doesn't cut it, either, as beautiful as SLIME is. Can't use it on Windows to save your life, for instance. But that's one of a thousand problems with the Lisp IDE situation; it's pointless to try to discuss them all in blogger. It's probably pointless to discuss them at all, because it's just going to make me more miserable that no decent IDE exists for Lisp, except for Emacs-as-Elisp-IDE. Which is why I get my Lisp fix by hacking elisp these days. ---- This post is archived at: http://steve-yegge.blogspot.com/2006/04/software-needs-philosophers.html and http://xahlee.org/Periodic_dosage_dir/_p/software_phil.html This essay is reported with permission. Xah xah at xahlee.org ? http://xahlee.org/ From simon at brunningonline.net Wed May 10 14:49:33 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 10 May 2006 19:49:33 +0100 Subject: syntax for -c cmd In-Reply-To: <e3tatm$8oa$1@sea.gmane.org> References: <1147284798.136873.237730@i40g2000cwc.googlegroups.com> <e3tatm$8oa$1@sea.gmane.org> Message-ID: <8c7f10c60605101149k1e843204l3886d27e4e1f04b6@mail.gmail.com> On 5/10/06, Fredrik Lundh <fredrik at pythonware.com> wrote: > James wrote: > > > Wrong syntax is shown below. What should be the delimiter before else? > > > > python -c 'if 1==1: print "yes"; else print "no"' > > there is no such delimiter. Python's syntax doesn't allow you to put multiple > clauses on a single line. if your shell supports it, use a "here document", or > embedded newlines. if not, use a script. Or there's always this; cool in a "The Dark Side is strong" kind of a way: <http://www.unixuser.org/~euske/pyone/> -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From srikar2097 at gmail.com Wed May 3 08:40:39 2006 From: srikar2097 at gmail.com (sri2097) Date: 3 May 2006 05:40:39 -0700 Subject: Playability of a file in windows media player Message-ID: <1146660038.890159.167130@j73g2000cwa.googlegroups.com> Basically, I want to check if a URL is playable or not (without actually playing it). i.e. given a URL I want to write an automation script to figure it out for me if it's playable or not. If you give a bad/invalid URL for windows media player to play a pop-up window shows us that it cannot be played. So I would want to catch that event. I have found 2 ways to do this - 1) import win32com.client, win32api, sre, time data = file("webclips.txt") web_clips = data.readlines () shell = win32com.client.Dispatch("WScript.Shell") shell.Run("wmplayer.exe") shell.AppActivate("Windows Media Player") win32api.Sleep(100) print "Total :", len(web_clips) for webclip in web_clips: shell.SendKeys("^u", 0) shell.AppActivate("Open URL") shell.SendKeys("{DEL}") shell.SendKeys(webclip) shell.SendKeys("~") time.sleep(25) if shell.AppActivate("Windows Media Player"): webclip = webclip not_there.append(webclip) shell.SendKeys("~") print len(not_there) print "Not here: ", not_there ~ In this way I manually fire Windows media player and do the checking. But It's a brute force way of solving the problem (since for every URL I keep a time-out of 25 seconds). As a result it takes a lot of time.I had to look for a better solution. My second solution uses Windows much hyped ActiveX controls. 2) from win32com.client import Dispatch,DispatchWithEvents class WMPEvents: def OnVisible(self,evt): print "OnVisible changed:",evt def OnError(self,evt=None): print "OnError",evt def OnMediaError(self,evt=None): print "OnMediaError",evt def OnDisconnect(self,evt): print "OnDisconnect",evt def OnStatusChange(self): print "OnStatusChange" def OnDisconnect(self,evt): print "Disconnect",evt def OnBuffering(self,evt): print "OnBuffering changed:",evt def OnOpenStateChange(self,evt=None): print "OnOpenStateChange" ,evt mp = DispatchWithEvents("WMPlayer.OCX", WMPEvents) mp.settings.autoStart = True webclip_playlist = mp.newPlaylist('Web_Clips', "") raw_web_clips = [] data = file("webclips.txt") web_clips = data.readlines() for url in web_clips: tune = mp.newMedia(url) mp.currentPlaylist.appendItem(tune) mp.controls.playItem (tune) mp.controls.play() mp.controls.stop() raw_input("Press enter to stop playing") mp.controls.stop() mp.close() This solution is much faster. But still I'm not able to solve it. Initially I had planned to use the "OnOpenStateChange" event to detect if a given URL is in a state just about to be opened. That's good enough for me to declare that a URL can be played. But as written in MSDN, they suggest not to rely on state changes as a definitive way to find details. So, I had to find an alternative. There is an event called "OnBuffering", i.e. when a link is found and is just about to be buffered this event (Boolean value) is triggered. But it never seem to happen. I would be truly grateful if you can help in any way. From vinogri at mcmaster.ca Fri May 5 16:37:22 2006 From: vinogri at mcmaster.ca (Ivan Vinogradov) Date: Fri, 5 May 2006 16:37:22 -0400 Subject: NaN handling In-Reply-To: <125hplqmppfeq29@corp.supernews.com> References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> Message-ID: <01B15AD0-0C7D-4498-B6FD-02651217557C@mcmaster.ca> > <snip> > NaNs are handled. Throwing an exception would be nice in regular Python (non-scipy). This works to catch NaN on OSX and Linux: # assuming x is a number if x+1==x or x!=x: #x is NaN But is expensive as a precautionary measure. Assert can be used for testing, if production code can be run with -0 or -OO. From robert.kern at gmail.com Sun May 21 22:42:38 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 May 2006 21:42:38 -0500 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <4471228D.4020100@serveisw3.net> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <44710145.6040603@serveisw3.net> <e4r4va$711$2@sea.gmane.org> <4471228D.4020100@serveisw3.net> Message-ID: <e4r8eu$em0$1@sea.gmane.org> Gonzalo Monz?n wrote: > I see there are both libraries linked in my pyrex modules... However, > when one should expect to have problems with this "dll nightmare", if > you always provide the right msvcr71.dll bundled within your project -I > mean, using py2exe by example- ? > > Of course if you didn't bundle the right crt, it does depend on the > available crt on target system... then you would be in trouble if user > doesn't have msvcrt71, or anyway, could be in trouble linking the > "right" library? If you use std::cout in a C++ extension module that was built with the stock Python 2.4 distutils and the stock MinGW, you will crash the interpreter. "Bundling the right CRT" is not the issue. *Building* with the right CRT 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 ben at nonegiven.test Tue May 9 02:06:56 2006 From: ben at nonegiven.test (Ben) Date: Tue, 09 May 2006 01:06:56 -0500 Subject: Problem - Serving web pages on the desktop (SimpleHTTPServer) Message-ID: <6kW7g.62729$aD6.4202@newsfe18.lga> Hi there, Perhaps someone can help me. For some reason, when my Python script runs and loads an HTML page in a new browser window at the local host (desktop), the links to my stylesheet and all the images are broken. I did check the HTML file by itself...everything loaded fine ;) Here's my script: -------------------- # File: webbrowser-test.py import webbrowser, SimpleHTTPServer from StringIO import StringIO f=open('testpage.html', 'rb') myPage = f.read() class MyRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler): def send_head(self): self.send_response(200) self.send_header("Content-type", "text/html") self.end_headers() return StringIO(myPage) webbrowser.open("http://127.0.0.1:8000", new=0, autoraise=1) SimpleHTTPServer.test(MyRequestHandler) -------------------- Here's my sample directory: --------------------------------- webbrowser-test.py testpage.html m_files/ |_____stylesheet.css |_____logo.gif -------------------------------- Thanks for having a look. My next step is to process form input using AJAX. I'll post working snippets of code here as I progress. Ben From bborcic at gmail.com Tue May 2 15:20:48 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 21:20:48 +0200 Subject: simultaneous assignment In-Reply-To: <pan.2006.05.02.18.46.39.714313@hastings.org> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> Message-ID: <4457b115$1_6@news.bluewin.ch> Steve R. Hastings wrote: > So, don't test to see if something is equal to True or False: > > if 0 == False: > pass # never executed; False and 0 do not directly compare of course they do - ie isinstance(False,int) is True and False == 0 > > > You *could* do this, but I don't really recommend it: > > if bool(0) == False: > pass # always executed > > > Do this: > > if not 0: > pass # always executed > > if 1: > pass # always executed > > > To convert a random value into a boolean value, you could use either > "bool()" or you could use "not not": > > a = not not 0 > b = bool(0) > > > "not not" will work on older versions of Python that didn't have an > explicit boolean type; "not 0" would return 1 in that case. "bool()" > will work in Python 2.2 and newer. From onurb at xiludom.gro Wed May 10 06:43:47 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 10 May 2006 12:43:47 +0200 Subject: multiline strings and proper indentation/alignment In-Reply-To: <44613e5d$0$9438$c3e8da3@news.astraweb.com> References: <Ms48g.2070$No6.45827@news.tufts.edu> <mailman.5527.1147204632.27775.python-list@python.org> <44613e5d$0$9438$c3e8da3@news.astraweb.com> Message-ID: <4461c445$0$14031$626a54ce@news.free.fr> John Salerno wrote: > Gary Herron wrote: > >> Gary John Salerno wrote: >> >>> How do you make a single string span multiple lines, but also allow >>> yourself to indent the second (third, etc.) lines so that it lines up >>> where you want it, without causing the newlines and tabs or spaces to >>> be added to the string as well? >>> >>> Example (pretend this is all on one line): >>> >>> self.DTD = '<!DOCTYPE html PUBLIC "-//W3C//DTD HTML >>> 4.01//EN"\n"http://www.w3.org/TR/html4/strict.dtd">\n\n' >>> >>> I want it to read: >>> >>> self.DTD = '''<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01//EN"\n >>> "http://www.w3.org/TR/html4/strict.dtd">\n\n''' >>> >>> Or anything like that, but I don't want the extra newline or tabs to >>> be a part of the string when it's printed. >>> >>> Thanks. >>> >>> >> The textwrap module has a function to do just the thing you want. >> *dedent*( text) >> >> Remove any whitespace that can be uniformly removed from the left of >> every line in text. >> >> This is typically used to make triple-quoted strings >> line up with the left edge of screen/whatever, while still >> presenting it in the source code in indented form. >> >> Gary Herron >> >> > > But does this do anything to the newline character that gets added to > the end of the first line? Why not trying by yourself ?-) >>> import textwrap >>> s = """ ... this is a multiline ... triple-quted string with ... indentation for nicer code formatting ... """ >>> print s this is a multiline triple-quted string with indentation for nicer code formatting >>> print textwrap.dedent(s) this is a multiline triple-quted string with indentation for nicer code formatting >>> Obviously, you have to strip newlines yourself. Let's try: >>> print textwrap.dedent(s.strip()) this is a multiline triple-quted string with indentation for nicer code formatting Mmm. Not good. Let's try again: >>> print textwrap.dedent(s).strip() this is a multiline triple-quted string with indentation for nicer code formatting >>> Well, seems like we're done. About 2'30'' to solve the problem. FWIW, reading textwrap's doc may be useful to - no need to reinvent the SquaredWheel(tm) if the rounded version already exists !-) HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From gpd at gpdnet.co.uk Fri May 12 17:34:45 2006 From: gpd at gpdnet.co.uk (Gary Doades) Date: Fri, 12 May 2006 22:34:45 +0100 Subject: Python Translation of C# DES Encryption References: <mailman.5620.1147425991.27775.python-list@python.org> Message-ID: <tgv962lccs7j2blbao7v16m750ero16b8v@4ax.com> On Fri, 12 May 2006 11:00:23 +0200, Andreas Pauley <andreasp+python at qbcon.com> wrote: >Hi all, > >I'm trying to implement a Python equivalent of a C# method that encrypts >a string. >My Python attempt is in the attached file, but does not return the same >value as the C# method (see below). > >Any hints? > >Thanks, >Andreas > Check out PyDES I have had great success in decrypting strings that have been encrypted with .NET TripleDES. Although it does not appear to encrypt the string to the same value it does work perfectly decrypting and encrypting in a way compatible with thwe C# methods. http://twhiteman.netfirms.com/des.html Regards, Gary. From sjmachin at lexicon.net Thu May 11 18:58:16 2006 From: sjmachin at lexicon.net (John Machin) Date: Fri, 12 May 2006 08:58:16 +1000 Subject: find all index positions In-Reply-To: <1147374826.341124.129260@g10g2000cwb.googlegroups.com> References: <1147360857.232317.149810@j33g2000cwa.googlegroups.com> <1147374826.341124.129260@g10g2000cwb.googlegroups.com> Message-ID: <4463C188.3030202@lexicon.net> On 12/05/2006 5:13 AM, vbgunz wrote: > I thought this to be a great exercise so I went the extra length to > turn it into a function for my little but growing library. I hope you > enjoy :) > Oh, indeed ;-) > > def indexer(string, target): Consider not shadowing the name of the string module. > '''indexer(string, target) -> [list of target indexes] > > enter in a string and a target and indexer will either return a > list of all targeted indexes if at least one target is found or > indexer will return None if the target is not found in sequence. Consider returning [] if the target is not found in the sequence. That would enable callers to "do nothing gracefully": for posn in indexer(... # do something and it doesn't require a gross rewrite ... merely dedent the last line. > > >>> indexer('a long long day is long', 'long') > [2, 7, 19] > > >>> indexer('a long long day is long', 'day') > [12] > > >>> indexer('a long long day is long', 'short') > None > ''' > > res = [] > Consider evaluating string.count(target) *ONCE*. > if string.count(target) >= 1: > res.append(string.find(target)) > > if string.count(target) >= 2: > for item in xrange(string.count(target) - 1): > res.append(string.find(target, res[-1] + 1)) > > return res > > > if __name__ == '__main__': > print indexer('a long long day is long', 'long') # -> [2, 7, 19] > print indexer('a long long day is long', 'day') # -> [12] > print indexer('a long long day is long', 'short') # -> None > When called with the args('abababababababa', 'aba'), it returns [0, 2, 4, 6]. If you *intend* to allow for overlaps, it should return [0, 2, 4, 6, 8, 10, 12]; otherwise it should return [0, 4, 8, 12]. Consider doing something straightforward and understandable, like the following (tested): def findallstr(text, target, overlapping=0): result = [] startpos = 0 if overlapping: jump = 1 else: jump = max(1, len(target)) while 1: newpos = text.find(target, startpos) if newpos == -1: return result result.append(newpos) startpos = newpos + jump HTH, John From mariano.difelice at gmail.com Thu May 11 10:42:29 2006 From: mariano.difelice at gmail.com (mardif) Date: 11 May 2006 07:42:29 -0700 Subject: Python memory deallocate In-Reply-To: <4463462a$0$297$626a54ce@news.free.fr> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> <-yy*V4mgr@news.chiark.greenend.org.uk> <1147355266.189030.131420@y43g2000cwc.googlegroups.com> <4463462a$0$297$626a54ce@news.free.fr> Message-ID: <1147358549.473182.89950@i40g2000cwc.googlegroups.com> In python 2.5 this was resolved, ok, but i can't use any python version then 2.3.5. This project was initializated with this version, and now it can be dangerous change version, even because I use McMillan installer for compile e build an executable. So, my initial window is a "menu window", when i can choose, for example, upload foto for print, or create an object as PhotoAlbum. If i'will choose PhotoAlbum, it will allocate 200Mb. well! if i decide to abort this work, i will return to initial window. and if i will click in PhotoAlbum ago, the memory will increase to 350-400Mb. It's that!!! I don't understand why!!! when i abort the work the first time, i call app.Destroy() del app Why Python ( or GarbageCollector, or.... ) don't deallocate memory?? If it's not possibile, why python don't reuse the memory "cached"? thx a lot From Serge.Orlov at gmail.com Fri May 19 07:58:49 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 19 May 2006 04:58:49 -0700 Subject: Encode exception for chinese text References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> Message-ID: <1148039929.462581.51770@i40g2000cwc.googlegroups.com> Vinayakc wrote: > Hi all, > > I am new to python. > > I have written one small application which reads data from xml file and > tries to encode data using apprpriate charset. > I am facing problem while encoding one chinese paragraph with charset > "gb2312". > > code is: > > encoded_str = str_data.encode("gb2312") > > The type of str_data is <type 'unicode'> > > The exception is: > > "UnicodeEncodeError: 'gb2312' codec can't encode character u'\xa0' in > position 0: illegal multibyte sequence" Hmm, this is 'no-break space' in the very beginning of the text. It look suspiciously like a plain text utf-8 signature which is 'zero width no-break space'. If you strip the first character do you still have encoding errors? From kkylheku at gmail.com Fri May 19 15:19:08 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 19 May 2006 12:19:08 -0700 Subject: number of different lines in a file In-Reply-To: <1148063935.859890.173230@u72g2000cwu.googlegroups.com> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> <1148063935.859890.173230@u72g2000cwu.googlegroups.com> Message-ID: <1148066348.761868.322570@g10g2000cwb.googlegroups.com> Paddy wrote: > If the log has a lot of repeated lines in its original state then > running uniq twice, once up front to reduce what needs to be sorted, > might be quicker? Having the uniq and sort steps integrated in a single piece of software allows for the most optimization opportunities. The sort utility, under -u, could squash duplicate lines on the input side /and/ the output side. > uniq log_file | sort| uniq | wc -l Now you have two more pipeline elements, two more tasks running, and four more copies of the data being made as it travels through two extra pipes in the kernel. Or, only two more copies if you are lucky enough to have a "zero copy" pipe implementation whcih allows data to go from the writer's buffer directly to the reader's one without intermediate kernel buffering. From bdesth.quelquechose at free.quelquepart.fr Tue May 23 21:24:21 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 24 May 2006 03:24:21 +0200 Subject: how to change sys.path? In-Reply-To: <1148399102.963320.129230@u72g2000cwu.googlegroups.com> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> Message-ID: <4473867f$0$7721$626a54ce@news.free.fr> Ju Hui a ?crit : > yes, I mean I want change the sys.path value and save it for next > using. > > I can change the value of sys.path, but I can't "save" it permanently. No. > There is no python_path environment on my pc, sorry, I meant PYTHONPATH (all caps, no underscore). Like all environnement variable, it can be set up. > what the relationship > between it and the sys.path? Don't you guess ? From cvanarsdall at mvista.com Fri May 12 13:52:13 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Fri, 12 May 2006 10:52:13 -0700 Subject: Discussion: Python and OpenMP Message-ID: <4464CB4D.70106@mvista.com> Hey everyone, I know I've posted several questions regarding python and python's parallel capabilities so bear with me as I've never attempted to incite discussion. However, today I'm interested in sparking discussion over having an OpenMP style of interface in python. For those of you familiar with OpenMP, its a pragmatic api for parallelizing software. For more information I invite anyone to do some google searches, there's a plethora of information available. Just to give a simple example of what i'm talking about, in OpenMP you would insert a pragma above a section of code you want to parallelize. In C it might look something like: int main(int argc, char* argv[]) { #pragma omp parallel printf("Hello, world.\n"); return 0; } In which case threads are spawn and handled. OpenMP of course has more than this available for developers, but I'm just trying to paint a picture before I start asking questions. Anyhow, onto the meat of the discussion. Would the python community be interested in parallel programming this way? Although I understand python already supports threading I thought that this was a real interesting (and easy) way of writing parallel code. For example, new keywords could be added to the python interpreter, such as parallel: Ex: ####### #!usr/bin/python parallel: print "I am a thread" ####### Taking this a step further, OpenMP or an OpenMP style implementation could be added to python. In addition easy to use/read, one possible benefit I could see of writing parallel python code this way would be providing a layer of abstraction between parallel code and threading constructs. For example, as a developer or community standards change threading in python code would not have to be re-written. Developers would create an interface between python's OpenMP style code and whatever their new threading libraries may be (this is one of many ways it could happen). Ultimately providing more code portability between people using different threading standards (should they ever become available). I see other use cases as well, but I just wanted to throw a couple ideas to see if this was worth thinking about further. Thanks for reading this one, I know it was long but I'd really appreciate your comments! -Carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From fb at frank-buss.de Sun May 7 07:31:47 2006 From: fb at frank-buss.de (Frank Buss) Date: Sun, 7 May 2006 13:31:47 +0200 Subject: algorithmic mathematical art References: <1146996866.280944.313050@y43g2000cwc.googlegroups.com> Message-ID: <9nelgqhh0dxf.thq8flk8fold$.dlg@40tude.net> Xah Lee wrote: > The one most prominent mention of it is in chapter 2 of the book > Structure and Interpretation of Computer Programs by Hal Abelson et al. Thanks for the interesting book tip, it is available online: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#%_sec_2.2.4 > anyway, today i ran into this page by Frank Bu? > http://www.frank-buss.de/lisp/functional.html > which used the idea in the book to render a traditional Escher's tiling > piece. I should note that I've used the original paper from Peter Henderson, which is cited in the book, too: http://mitpress.mit.edu/sicp/full-text/book/book-Z-H-15.html#footnote_Temp_202 -- Frank Buss, fb at frank-buss.de http://www.frank-buss.de, http://www.it4-systems.de From kay.schluehr at gmx.net Tue May 16 08:10:47 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 16 May 2006 05:10:47 -0700 Subject: Far from complete In-Reply-To: <mailman.5746.1147773496.27775.python-list@python.org> References: <1147758802.408740.131700@u72g2000cwu.googlegroups.com> <mailman.5746.1147773496.27775.python-list@python.org> Message-ID: <1147781447.205393.19820@u72g2000cwu.googlegroups.com> Steve Holden wrote: > Kay Schluehr wrote: > > Section 2.3 of the Python 2.5. tutorial > > > > "The following sections describe the standard types that are built into > > the interpreter. Historically, Python's built-in types have differed > > from user-defined types because it was not possible to use the built-in > > types as the basis for object-oriented inheritance. With the 2.2 > > release this situation has started to change, although the intended > > unification of user-defined and built-in types is as yet far from > > complete. " > > > > "Far from complete"? Have I missed something? > > > Releases 2.3 through 2.5, by the look of it :) > > Of course the "classic" classes still remain, and probably won't > disappear until 3.0, so that could be regarded as "completion" of the > change described. Then *everything* will ultimately be based on "object". Of course I can live with the fact that "classic classes" are not considered as legacy and being "supported for backwards compatibility" but are the reason why the object system is "far from complete". It is just a little harder to argue that the object system is not immature and early alpha since Python 2.2 when the Python tutorial states it differently. Fortunately I'm not responsibe for "marketing" the language and explain this to beginners with the juridical sensititvity like you do it here for me. From nospam at nospam.nospam Tue May 16 12:59:39 2006 From: nospam at nospam.nospam (Nic) Date: Tue, 16 May 2006 18:59:39 +0200 Subject: Python and Combinatorics Message-ID: <446a0501$0$14778$4fafbaef@reader4.news.tin.it> Thanks a bunch. Both the codes are fine. Only one question, if you allow. In my example I've chosen the number 3. How should I change the Python code in order to select another number (e.g. 7)? Thanks. Nic From nobody at 127.0.0.1 Tue May 2 16:15:26 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 20:15:26 GMT Subject: ConfigParser and multiple option names References: <e37rji$c46$1@news.in.tum.de> Message-ID: <y5P5g.11068$Lm5.4284@newssvr12.news.prodigy.com> Florian Lindner wrote: > I think the best solution would be to use a seperation character: > > dir="/home/florian, /home/john, home/whoever" > > What character would be best to work on various operating systems? (of > what names may a path consist is the question) I don't think there are any universally-disallowed chars for path names. But I also haven't seen anyone mention os.pathsep yet. Seems like the best choice for a separator char. If you need to run on multiple platforms, your choices seem to be: 1. pick a legal-on-some-systems-but-uncommon-on-all char for dir names as a separator (iirc osx uses : in paths so ; might have to do) 2. use os.pathsep to write platform-specific config files 3. do it another way From Serge.Orlov at gmail.com Wed May 10 05:42:20 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 10 May 2006 02:42:20 -0700 Subject: ascii to latin1 In-Reply-To: <4460dec2$0$15791$14726298@news.sunsite.dk> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <mailman.5504.1147171291.27775.python-list@python.org> <4460831e$0$15794$14726298@news.sunsite.dk> <1147180014.685659.325830@i39g2000cwa.googlegroups.com> <4460dec2$0$15791$14726298@news.sunsite.dk> Message-ID: <1147254139.954024.273040@j33g2000cwa.googlegroups.com> Luis P. Mendes wrote: > Errors occur when I assign the result of ''.join(cp for cp in de_str if > not unicodedata.category(cp).startswith('M')) to a variable. The same > happens with de_str. When I print the strings everything is ok. > > Here's a short example of data: > 115448,DA??O > 117788,DA 1? DE MO N? 2 > > I used the following script to convert the data: > # -*- coding: iso8859-15 -*- > > class Latin1ToAscii: > > def abreFicheiro(self): > import csv > self.reader = csv.reader(open(self.input_file, "rb")) > > def converter(self): > import unicodedata > self.lista_csv = [] > for row in self.reader: > s = unicode(row[1],"latin-1") > de_str = unicodedata.normalize("NFD", s) > nome = ''.join(cp for cp in de_str if not \ > unicodedata.category(cp).startswith('M')) > > linha_ascii = row[0] + "," + nome # * > print linha_ascii.encode("ascii") > self.lista_csv.append(linha_ascii) > > > def __init__(self): > self.input_file = 'nome_latin1.csv' > self.output_file = 'nome_ascii.csv' > > if __name__ == "__main__": > f = Latin1ToAscii() > f.abreFicheiro() > f.converter() > > > And I got the following result: > $ python latin1_to_ascii.py > 115448,DACAO > Traceback (most recent call last): > File "latin1_to_ascii.py", line 44, in ? > f.converter() > File "latin1_to_ascii.py", line 22, in converter > print linha_ascii.encode("ascii") > UnicodeEncodeError: 'ascii' codec can't encode character u'\xba' in > position 11: ordinal not in range(128) > > > The script converted the ?? from the first line, but not the ? from the > second one. Still in *, I also don't get a list as [115448,DA??O] but a > [u'115448,DA??O'] element, which doesn't suit my needs. > > Would you mind telling me what should I change? Calling this process "latin1 to ascii" was a misnomer, sorry that I used this phrase. It should be called "latin1 to search key", there is no requirement that the key must be ascii, so change the corresponding lines in your code: linha_key = row[0] + "," + nome print linha_key self.lista_csv.append(linha_key.encode("latin-1") With regards to ?, Richie already gave you food for thoughts, if you want "1 DE MO" to match "1? DE MO" remove that symbol from the key (linha_key = linha_key.translate({u"?": None}), if you don't want such a fuzzy matching, keep it. From http Sat May 6 21:10:57 2006 From: http (Paul Rubin) Date: 06 May 2006 18:10:57 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <8764kive9g.fsf@rpi.edu> Message-ID: <7x64kihc66.fsf@ruckus.brouhaha.com> Bill Atkins <NOatkinwSPAM at rpi.edu> writes: > Fair enough. But what does Python offer above any garbage-collected > language that makes it so scalable? I think what used to be Lisp culture now uses the *ML languages or Haskell. It's only throwbacks (which includes me sometimes) who still use Lisp. I've been wanting for a while to do something in ML but just haven't worked up enough steam for it. Python really does make small and medium-sized tasks easy, even compared with Lisp. I'm still reserving judgement about how it is at large tasks. From miki.tebeka at gmail.com Mon May 15 07:19:28 2006 From: miki.tebeka at gmail.com (Miki) Date: 15 May 2006 04:19:28 -0700 Subject: List and order References: <446842f7$0$14785$4fafbaef@reader4.news.tin.it> Message-ID: <1147691967.998184.285120@u72g2000cwu.googlegroups.com> Hello Nic, Python lists has a very powerfull buid-in "sort". edges = list(G.edges()) edges.sort(key = lambda u, v: (ddeg(u), ddeg(v))) for u, v in edges: print u,v, # Note the training comma to avoid newline print HTH, Miki http://pythonwise.blogspot.com From userprogoogle-139 at yahoo.co.uk Fri May 19 10:43:50 2006 From: userprogoogle-139 at yahoo.co.uk (rodmc) Date: 19 May 2006 07:43:50 -0700 Subject: Strange Memory Leaks Message-ID: <1148049830.472097.81130@j33g2000cwa.googlegroups.com> I have written an application which seems to work fine most of the time and takes up about 26k when run. However when the PC (Windows 2k) is put to sleep/locked and the application is left to run it starts eating up memory, indeed about 400mb was the recent record. Is there any automated way of finding out where the memory leak is arising? Or a method of suspending the application when the screen is locked and/or the PC goes to sleep? Best, rod From pwatson at redlinepy.com Tue May 2 08:55:16 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 02 May 2006 07:55:16 -0500 Subject: --version? In-Reply-To: <n2I5g.2683$Vn.323@newsread4.news.pas.earthlink.net> References: <4bp06lF1276vvU1@individual.net> <n2I5g.2683$Vn.323@newsread4.news.pas.earthlink.net> Message-ID: <4bp35kF12517kU1@individual.net> Adonis wrote: > Paul Watson wrote: > >> Is there any chance that Python would support the --version command >> line parameter? It seems that many open source programs use this >> switch to report their version number. > > > > try at a command prompt: > python -V > > Hope this helps. > > Adonis I am well aware of -V. Could --version be supported as well? From DustanGroups at gmail.com Thu May 18 18:19:13 2006 From: DustanGroups at gmail.com (Dustan) Date: 18 May 2006 15:19:13 -0700 Subject: Which is More Efficient? In-Reply-To: <1147974619.413812.112780@i39g2000cwa.googlegroups.com> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> <1147974619.413812.112780@i39g2000cwa.googlegroups.com> Message-ID: <1147990753.406649.80150@y43g2000cwc.googlegroups.com> John Machin wrote: > 1. Think about it. The first case will make a new list and copy "size" > *objects. When the assignment happens, the old list has its reference > count decremented. Not very memory-friendly. The second case merely > truncates the existing list in situ. Bit hard to imagine how the first > case could ever be faster than the second case. You might like to read > the source code. The file that you are looking for is listobject.c. That's what I thought. I wasn't sure exactly what del actually does. > 2. Measure it. Tell me how and I will; I'm not nearly that much of a geek unfortunately. > 3. Unless you are deliberately parodying b1ff at aol.com, don't use > "L".lower() as a variable name. Don't understand what you mean by this, but I didn't actually use 'l' as a variable name; that was just an example. > 4. Try reading this list / newsgroup more often I follow too many newsgroups as it is, when I've got plenty of other stuff to do. > -- (a) this topic (or a > closely related one) was covered within the last week or so (b) you > might notice abuse like (3) above being hurled at others and avoid > copping your share. > HTH, > John From aylwyn at cantab.net Tue May 16 14:46:01 2006 From: aylwyn at cantab.net (achates) Date: 16 May 2006 11:46:01 -0700 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147801895.830394.17130@v46g2000cwv.googlegroups.com> Message-ID: <1147805161.617753.141050@y43g2000cwc.googlegroups.com> Kaz Kylheku wrote: > If you want to do nice typesetting of code, you have to add markup > which has to be stripped away if you actually want to run the code. Typesetting code is not a helpful activity outside of the publishing industry. You might like the results of your typsetting; I happen not to. You probably wouldn't like mine. Does that mean we shouldn't work together? Only if you insist on forcing me to conform to your way of displaying code. You are correct in pointing out that tabs don't allow for 'alignment' of the sort you mention: (lisp (nested list with symbols and things)) But then neither does Python. I happen to think that's a feature. (And of course you can do what you like inside a comment. That's because tabs are for indentation, and indentation is meanigless in that context. Spaces are exactly what you should use then. I may or may not like your layout, but it won't break anything when we merge our code.) From john at castleamber.com Sat May 20 18:04:09 2006 From: john at castleamber.com (John Bokma) Date: 20 May 2006 22:04:09 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> Message-ID: <Xns97C9ADA375FCCcastleamber@130.133.1.4> Edward Elliott <nobody at 127.0.0.1> wrote: > A little out-of-order execution seems useful here. ;) No, not interested in a pissing contest. Your statement that the Perl community encourages importing is *encouraged* (over using OO without importing) is false. -- 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 michele.petrazzo at TOGLIunipex.it Mon May 8 04:18:19 2006 From: michele.petrazzo at TOGLIunipex.it (Michele Petrazzo) Date: Mon, 08 May 2006 08:18:19 GMT Subject: python 2.5a2, gcc 4.1 and memory problems In-Reply-To: <1146969449.567022.245750@u72g2000cwu.googlegroups.com> References: <UwZ6g.111186$A83.2617718@twister1.libero.it> <1146969449.567022.245750@u72g2000cwu.googlegroups.com> Message-ID: <f9D7g.113700$A83.2703541@twister1.libero.it> nnorwitz at gmail.com wrote: > Michele Petrazzo wrote: >> I haven't tried to recompile py 2.4 myself with gcc 4.1 because it >> is already compiled with it (4.0.3), so I think (only think) that >> is a py 2.5 problem. I'm right? or I have to compile it with >> something other switches? > > Sounds like a gcc problem to me. Try adding --with-pydebug in the > configure options. My guess is that it will work. This option > enables asserts, but more importantly disables optimization. Yes, with this option it work, but has very bad performances. > My guess is that this is an optimization problem with gcc. I assume > -fno-strict-aliasing is one of the gcc flags. It should be as this > is required for building python. > Yes, I specify that flag for compiling, but still the same... Always problems. Also tried with --without-pymalloc and no changes. > Cheers, n > I think that I'll wait for the firsts debian packages, or compile it with gcc 3.3. Thanks, Michele From me+python at modelnine.org Fri May 19 15:22:23 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Fri, 19 May 2006 21:22:23 +0200 Subject: Feature request: sorting a list slice In-Reply-To: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> Message-ID: <200605192122.24153.me+python@modelnine.org> Am Donnerstag 18 Mai 2006 19:27 schrieb George Sakkis: > It would be useful if list.sort() accepted two more optional > parameters, start and stop, so that you can sort a slice in place. I've just submitted: http://sourceforge.net/tracker/index.php?func=detail&aid=1491804&group_id=5470&atid=305470 to the bugtracker, which extends the (start, stop) keyword arguments to list.reverse() (which I've needed more than once). The patch updates the test suite, documentation, list object, and sorted() builtin to accept (or specify) the new arguments. Any comment/feedback would be appreciated. --- Heiko. From paul at boddie.org.uk Mon May 15 10:45:34 2006 From: paul at boddie.org.uk (Paul Boddie) Date: 15 May 2006 07:45:34 -0700 Subject: please help me is sms with python References: <mailman.5701.1147690409.27775.python-list@python.org> <4cr6deF17i9mpU1@uni-berlin.de> Message-ID: <1147704334.116926.70280@i40g2000cwc.googlegroups.com> Diez B. Roggisch wrote: > > Attach a Mobile to your computer using USB/Bluetooth, open it with a > terminal program and use these AT-commands. > > http://www.cellular.co.za/hayesat.htm#SMS Command Set > > You can do that in python too, by opening the COM-port the handset is > attached to and issuing the commands yourself. See the t616hack distribution for help on reading and writing messages, although I haven't bothered to implement message sending just yet - it shouldn't be as hard as implementing message writing, however. http://www.python.org/pypi/t616hack Nelson Minar did the original work by getting COM port communications working using PySerial and a Bluetooth dongle. I've since extended that work to use Bluetooth sockets, which are somewhat more convenient. Only certain Sony Ericsson telephones are known to work, but I imagine that other models provide similar command sets. With respect to the original query, it may be the case that the questioner was thinking of certain Internet gateways which accept requests and relay messages to the telephone network. Certain software packages like smssend may be the solution in that context. Paul From grante at visi.com Wed May 10 16:45:54 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 10 May 2006 20:45:54 -0000 Subject: hyperthreading locks up sleeping threads References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> <1147292178.325015.172460@y43g2000cwc.googlegroups.com> Message-ID: <1264k82rk3pvu26@corp.supernews.com> On 2006-05-10, OlafMeding at gmail.com <OlafMeding at gmail.com> wrote: > So to make sure that no other software is involved we took the > PC with the problem, reset the BIOS to its defaults (which > also enables hyper-threading) and installed Windows XP > Professional (SP2) on it (but no further driver software, > etc). We accepted all defaults during the installation. > > Once Windows XP was running we installed Python downloaded > from (and accepted all defaults during the installation): > http://www.python.org/ftp/python/2.4.3/python-2.4.3.msi > > And we then ran our Python test program and it hung after less > than 15 minutes! > > We are now contacting the company that puts that PC together > for further advice. You might want to run some memory tests. I don't see why hyperthreading would make a difference, but running the test is dead simple: download the ISO image, burn a CD, boot from the CD, come back in a day or two: http://www.memtest86.com/ -- Grant Edwards grante Yow! Does that mean at I'm not a well-adjusted visi.com person?? From http Tue May 9 21:52:01 2006 From: http (Paul Rubin) Date: 09 May 2006 18:52:01 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <m264kguu4c.fsf@Dagney.local> <1hf1hlk.uf6b5hc60js1N%aleax@mac.com> <w4cejz2ricn.fsf@bianca.cd.chalmers.se> Message-ID: <7xwtcuhcji.fsf@ruckus.brouhaha.com> rydis (Martin Rydstr|m) @CD.Chalmers.SE writes: > [Emacs] is written in Lisp, which is the only computer language that is > beautiful. -- Neal Stephenson, _In the Beginning was the Command Line_ I don't remember seeing these lyrics in the thread yet, but obviously it's a requirement: http://www.songworm.com/lyrics/songworm-parody/EternalFlame.html From h.b.furuseth at usit.uio.no Mon May 8 06:00:07 2006 From: h.b.furuseth at usit.uio.no (Hallvard B Furuseth) Date: Mon, 08 May 2006 12:00:07 +0200 Subject: Modifying PyObject.ob_type Message-ID: <hbf.20060508g4fv@bombur.uio.no> I've got some fixed-size types with identical object layout defind in C. The only differences are: Which methods they have, the name, and some are subtypes of others. Can I modify the ob_type of their instances, to switch between which of these types an object has? -- Hallvard From tomerfiliba at gmail.com Wed May 24 15:10:14 2006 From: tomerfiliba at gmail.com (gangesmaster) Date: 24 May 2006 12:10:14 -0700 Subject: PEP 3102 for review and comment In-Reply-To: <mailman.6145.1148470457.27775.python-list@python.org> References: <mailman.6145.1148470457.27775.python-list@python.org> Message-ID: <1148497814.727011.180150@i39g2000cwa.googlegroups.com> None is not currently a keyword From johnjsal at NOSPAMgmail.com Thu May 18 13:23:52 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Thu, 18 May 2006 17:23:52 GMT Subject: creating a new database with mysqldb In-Reply-To: <t87p6251ivsc99ho565qiv4kdo6gk8t887@4ax.com> References: <gcKag.2113$No6.46302@news.tufts.edu> <126nj7utnok7u6e@corp.supernews.com> <446be190$0$5024$c3e8da3@news.astraweb.com> <1147927982.322181.20880@i39g2000cwa.googlegroups.com> <Dd%ag.2119$No6.46425@news.tufts.edu> <t87p6251ivsc99ho565qiv4kdo6gk8t887@4ax.com> Message-ID: <I42bg.2121$No6.46279@news.tufts.edu> Dennis Lee Bieber wrote: > As a client on a shared host, I suspect the provider created a user > account and A (one) database for that account. The privilege tables for > that user account would have been set so that only that database is > available. The account would have full privileges within that database, > and no privileges to access any other database (including the mysql > master tables). Depending the strictness of the provider, the account > may or may not allow for connections from outside hosts, or only from > "localhost" (ie, CGI applications that are running on the provider's > machine, and not via "mysql -u user -h somewhere.out.there -p" or > programmatic equivalents) I know for sure I can't connect from anywhere else, only the server itself. But I *think* I have full privileges to do what I want with the database, but I need to do some further checking, I suppose. It says I have 'amdmin privilegs' but that might not be the same as what I need to create databases outside of the control panel. From nobody at 127.0.0.1 Tue May 2 04:38:04 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 08:38:04 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <mailman.5202.1146536914.27775.python-list@python.org> Message-ID: <MTE5g.64462$_S7.12078@newssvr14.news.prodigy.com> Steve Holden wrote: > Objects don't actually "pass references to themselves". The interpreter > adds the bound instance as the first argument to a call on a bound method. Sure, if you want to get technical For that matter, objects don't actually call their methods either -- the interpreter looks up the method name in a function table and dispatches it. I don't see how shorthand talk about objects as actors hurts anything unless we're implementing an interpreter. > Sorry, it's a wart on your brain. Fine it's a wart on my brain. It's still a wart. > Read Guido's arguments in favor of an > explicit self argument again before you assert this so confidently. I would if I could find it. I'm sure he had good reasons, they may even convince me. But from my current perspective I disagree. > It's > certainly confusing to beginners, but there are actually quite sound > reasons for it (see next paragraph). While confusion for beginners is a problem, that's not such a big deal. It's a trivial fix that they see once and remember forever. What I mind is its ugliness, that the language makes me do work declaring self when it knows damn well it won't like my code until I do what it wants (yes I'm anthropomorphizing interpreters now). The interpreter works for me, I don't work for it. Things it can figure out automatically, it should handle. > Hmm. I see. How would you then handle the use of unbound methods as > first-class objects? If self is implicitly declared, that implies that > methods can only be used when bound to instances. I fail to see the problem here. I'm taking about implicit declaration on the receiving end. It sounds like you're talking about implicit passing on the sending end. The two are orthogonal. I can declare def amethod (a, b): and have self received implicitly (i.e. get the object instance bound by the interpreter to the name self). The sender still explicitly provides the object instance, e.g. obj.amethod (a,b) or class.amethod (obj, a, b) IOW everything can still work exactly as it does now, only *without me typing self* as the first parameter of every goddamn method I write. Does that make sense? > How, otherwise, would > you have an instance call its superclass's __init__ method if it's no > longer valid to say > > myClass(otherClass): > def __init__(self): > otherClass.__init__(self) > ... > Like this: myClass(otherClass): def __init__(): otherClass.__init__(self) self is still there and still bound, I just don't have to type it out. The interpreter knows where it goes and what it does, automate it already! >> * technically modules may be objects also, but in practice you don't >> declare self as a parameter to module functions > > The reason you don't do that is because the functions in a module are > functions in a module, not methods of (some instance of) a class. > Modules not only "may be" objects, they *are* objects, but the functions > defined in them aren't methods. What, in Python, *isn't* an object? If it looks like a duck and it quacks like a duck... Functions and methods look different in their declaration but the calling syntax is the same. It's not obvious from the dot notation syntax where the 'self' argument comes from. Some interpreter magic goes on behind the scenes. Great, I'm all for it, now why not extend that magic a little bit further? From bravegag at gmail.com Fri May 19 08:36:59 2006 From: bravegag at gmail.com (bravegag) Date: 19 May 2006 05:36:59 -0700 Subject: problem with import autotest ... Message-ID: <1148042219.334648.183790@38g2000cwa.googlegroups.com> Hi all, Please beware I am new to Python and have little experience with it. I have a script that works just fine on linux but when I try to debug from Windows using Eclipse and PyDEV plugin then it does not work. The Python version is the same 2.3.x , and command line is roughly the same. from Unix: mymodule.py <my-params> >From Windows (Eclipse) python.exe mymodule.py <my-params> The point is that from Linux the "import autotest" works as intended i.e. just allow the importing module use some functions but from Windows it autoruns itself just by importing it, I do not get why or how? >From Windows it does: "Regression test. This will find all modules whose name is "test_*" in the test directory, and run them. Various command line options provide additional facilities" and then starts executing tests without ever getting to the main of my module ... Any clues? TIA, Best Regards, Giovanni From ptmcg at austin.rr._bogus_.com Mon May 15 14:15:14 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Mon, 15 May 2006 18:15:14 GMT Subject: Large Dictionaries References: <1147699064.107490@teuthos> <e49va0$m72$1@newsreader3.netcologne.de> Message-ID: <Sy3ag.25523$Qq.14668@tornado.texas.rr.com> "Claudio Grondi" <claudio.grondi at freenet.de> wrote in message news:e49va0$m72$1 at newsreader3.netcologne.de... > Chris Foote wrote: > > Hi all. > > > > I have the need to store a large (10M) number of keys in a hash table, > > based on a tuple of (long_integer, integer). The standard python > > dictionary works well for small numbers of keys, but starts to > > perform badly for me inserting roughly 5M keys: > > > > # keys dictionary metakit (both using psyco) > > ------ ---------- ------- > > 1M 8.8s 22.2s > > 2M 24.0s 43.7s > > 5M 115.3s 105.4s > > > > Has anyone written a fast hash module which is more optimal for > > large datasets ? > > > > p.s. Disk-based DBs are out of the question because most > > key lookups will result in a miss, and lookup time is > > critical for this application. > > > > Cheers, > > Chris > Python Bindings (\Python24\Lib\bsddb vers. 4.3.0) and the DLL for > BerkeleyDB (\Python24\DLLs\_bsddb.pyd vers. 4.2.52) are included in the > standard Python 2.4 distribution. > > "Berkeley DB was 20 times faster than other databases. It has the > operational speed of a main memory database, the startup and shut down > speed of a disk-resident database, and does not have the overhead of > a client-server inter-process communication." > Ray Van Tassle, Senior Staff Engineer, Motorola > > Please let me/us know if it is what you are looking for. > > Claudio sqlite also supports an in-memory database - use pysqlite (http://initd.org/tracker/pysqlite/wiki) to access this from Python. -- Paul From camfarnell at cogeco.ca Fri May 26 14:56:43 2006 From: camfarnell at cogeco.ca (Cam) Date: 26 May 2006 11:56:43 -0700 Subject: Don't wish to give up on a Tkinter GUI Builder :( References: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> <1148371674.932205.83160@j55g2000cwa.googlegroups.com> <1148382609.644438.267020@j55g2000cwa.googlegroups.com> <A6qdnQFPrLgDzO7ZnZ2dnUVZ_uidnZ2d@nmt.edu> <1148411169.830384.149330@g10g2000cwb.googlegroups.com> <1148446711.224119.53720@i39g2000cwa.googlegroups.com> Message-ID: <1148669803.616645.282490@i39g2000cwa.googlegroups.com> Ah, what I was referring to (somewhat in jest) was something to automatically *write* the code needed by the application. Simply executing it is easy enough and in fact Rapyd-Tk already does this via the save-build-run project-menu choice. vbgunz wrote: > > As for the code to actually make the application go, well, > > if there is some automatic way to make that happen it hasn't dawned on > > me yet. > > why not execute 'python -u /pathto/module.py' I could be wrong but hope > I am not :) From johnjsal at NOSPAMgmail.com Sun May 7 19:09:59 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Sun, 07 May 2006 19:09:59 -0400 Subject: md5 from python different then md5 from command line In-Reply-To: <7xd5epek9c.fsf@ruckus.brouhaha.com> References: <1146996448.577162.283480@j73g2000cwa.googlegroups.com> <445e3a3b$0$22630$c3e8da3@news.astraweb.com> <7xd5epek9c.fsf@ruckus.brouhaha.com> Message-ID: <445e7f40$0$13351$c3e8da3@news.astraweb.com> Paul Rubin wrote: > John Salerno <johnjsal at NOSPAMgmail.com> writes: >> Just a quick md5-related follow-up question: I was experimenting with >> it and making md5 sums for strings, but how do you use the md5 module >> to create a sum for an actual file, such as an .exe file? > > m = md5.new() > f = file('foo.exe', 'b') # open in binary mode > while True: > t = f.read(1024) > if len(t) == 0: break # end of file > m.update(t) > print m.hexdigest() Any reason you can't just read the whole file at once and update m? Also, doesn't the parameter for update have to be a string? If you're reading the file in binary mode, would t still be a string? Thanks. From lance at augustmail.com Mon May 15 12:23:10 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Mon, 15 May 2006 11:23:10 -0500 Subject: help with perl2python regular expressions Message-ID: <4468aaed$0$61164$ae4e5890@news.nationwide.net> Hey all, I am trying to convert some old perl scripts I have to python. Here is a snippit of the regex I used in perl. I am trying to figure out the equivalent code in python. Can someone help? my $file =$Word->ActiveDocument->Content->Text; $file =~ /TABLE\s+1.*?JCP.*?MEAN.*?(?:(\d{1,3}\.\d\d)\s+){1}/s; my $P05A008 = $1; Lance From michael at elehack.net Mon May 1 19:17:40 2006 From: michael at elehack.net (Michael Ekstrand) Date: Mon, 1 May 2006 18:17:40 -0500 Subject: set partitioning In-Reply-To: <1146523373.778624.142510@y43g2000cwc.googlegroups.com> References: <1146521357.483940.263490@u72g2000cwu.googlegroups.com> <1146522121.798317.206180@i39g2000cwa.googlegroups.com> <1146523373.778624.142510@y43g2000cwc.googlegroups.com> Message-ID: <20060501231740.GD29422@localhost.localdomain> On Mon, May 01, 2006 at 03:42:53PM -0700, hymort at hotmail.com wrote: > Not quite what I'm looking for. I would like a list of all partitions > with each partition having k or less elements, not just one instance. def partition(S, k): parts = [] ct = 0 cp = [] for elem in S: if ct > k: parts.append(cp) cp = [] ct = 0 cp.append(elem) ct += 1 parts.append(cp) return parts > > If this was a take home exam problem, > > you should be ashamed of yourself! > > -- Aaron Watters - Michael -- mouse, n: a device for pointing at the xterm in which you want to type. -- Fortune Visit me on the Web: http://www.elehack.net From nobody at 127.0.0.1 Sun May 14 01:05:39 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 14 May 2006 05:05:39 GMT Subject: copying files into one References: <874pztgsd5.fsf@localhost.localdomain> Message-ID: <DUy9g.5950$fb2.4026@newssvr27.news.prodigy.net> Gary Wessle wrote: > I am looping through a directory and appending all the files in one > huge file, the codes below should give the same end results but are > not, I don't understand why the first code is not doing it. > > combined = open(outputFile, 'wb') > for name in flist: > if os.path.isdir(file): continue > infile = open(os.path.join(file), 'rb') this shouldn't work. 'file' is a type object, not a filename. did you rebind 'file' without showing us? or should those 'file's be 'name's instead? in either case, calling os.path.join with one argument is pointless. > # CODE 1 this does not work > tx = infile.read(1000) > if tx == "": break > combined.write(tx) > infile.close() hint: where will break take you? therein lies your answer. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From andrew.arobert at gmail.com Sat May 20 17:42:34 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Sat, 20 May 2006 17:42:34 -0400 Subject: File encoding strategy question Message-ID: <126v3aufq22ip31@corp.supernews.com> Hi everyone, I am in the process of creating a file transmit/receiver program using MQSeries. The way it works is through creation of an XML message. Elements within the XML message contain things such as file name, size, and the file contents. The file contents are encoded, currently using Base64, for support of both binary and text data. This works great but there is a small rub to the problem. I would like to be able to view the contents of the file if it is text while still maintaining the ability to transmit binary data. Does anyone know of an encoding format that would make this possible? The viewing of the file contents does not need to be perfect, merely enough that a particular in-transit file could be identified. Thoughts on this would be greatly appreciated. Thanks, Andy From grante at visi.com Tue May 30 09:57:21 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 30 May 2006 13:57:21 -0000 Subject: wait() on Popen4 object from thread? References: <127ndd2pcisrr0c@corp.supernews.com> <uphn72t6utbme7u09u9e621e8o9f3tv3ei@4ax.com> <127ojedfa8inq56@corp.supernews.com> Message-ID: <127ojq18q6h90b5@corp.supernews.com> On 2006-05-30, Grant Edwards <grante at visi.com> wrote: doesn't V > However, the presence/absence of the global affect whether the > OSError happens or not. -- Grant Edwards grante Yow! I'm EMOTIONAL at now because I have visi.com MERCHANDISING CLOUT!! From chris at foote.com.au Mon May 15 08:43:00 2006 From: chris at foote.com.au (Chris Foote) Date: Mon, 15 May 2006 22:13:00 +0930 Subject: Large Dictionaries Message-ID: <1147699064.107490@teuthos> Hi all. I have the need to store a large (10M) number of keys in a hash table, based on a tuple of (long_integer, integer). The standard python dictionary works well for small numbers of keys, but starts to perform badly for me inserting roughly 5M keys: # keys dictionary metakit (both using psyco) ------ ---------- ------- 1M 8.8s 22.2s 2M 24.0s 43.7s 5M 115.3s 105.4s Has anyone written a fast hash module which is more optimal for large datasets ? p.s. Disk-based DBs are out of the question because most key lookups will result in a miss, and lookup time is critical for this application. Cheers, Chris From webraviteja at gmail.com Fri May 12 03:45:52 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 12 May 2006 00:45:52 -0700 Subject: python soap web services In-Reply-To: <R3T8g.84368$eR6.57426@bgtnsc04-news.ops.worldnet.att.net> References: <R3T8g.84368$eR6.57426@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <1147419952.459260.51990@u72g2000cwu.googlegroups.com> > Is there any reason why there isn't any python library that makes > using soap as easy as how microsoft .net makes it. SOAP with Python is easy too in a different sort of way. I don't know about the equivalent for autogenerating WSDL bit as in .NET. #!/usr/bin/env python def hello(): return "Hello, world" import ZSI ZSI.dispatch.AsCGI() And you have SOAP available on ANY web server. More here. http://pywebsvcs.sourceforge.net/zsi.html http://diveintopython.org/soap_web_services/index.html > When do you think someone will make this available for python web service?? When? Will let you know soon as my crystal ball gets delivered :-) Seriously, whenever someone gets that itch to scratch since that's how things get done in OSS usually. From chaosquant at tele2.fr Thu May 11 05:16:52 2006 From: chaosquant at tele2.fr (chaosquant at tele2.fr) Date: 11 May 2006 02:16:52 -0700 Subject: Calling C/C++ functions in a python script In-Reply-To: <1147300511.673435.72630@i39g2000cwa.googlegroups.com> References: <1147299778.630583.83380@q12g2000cwa.googlegroups.com> <1147300511.673435.72630@i39g2000cwa.googlegroups.com> Message-ID: <1147339012.474084.327540@q12g2000cwa.googlegroups.com> Ravi Teja a ?crit : > > For more advanced needs, take a look at some of the extending options > available. > http://www.suttoncourtenay.org.uk/duncan/accu/integratingpython.html Thanks for your answer. It is just what I'm trying to do. Unfortunately, apparently I need a "pyhton24_d.lib" to link to that does not seem to exists. Do you know a solution for this? Thanks a lot, Jean-Claude From grante at visi.com Fri May 12 10:27:30 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 12 May 2006 14:27:30 -0000 Subject: Threads References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <e414h9$f8g$01$1@news.t-online.com> <1147424692.502720.206970@j73g2000cwa.googlegroups.com> Message-ID: <12696qik3in4k9a@corp.supernews.com> On 2006-05-12, antred <NutJob at gmx.net> wrote: Nerver knew what? Please quote for context. > Aww shoot, I never knew that!! http://docs.python.org/lib/QueueObjects.html get([block[, timeout]]) Remove and return an item from the queue. If optional args block is true and timeout is None (the default), block if necessary until an item is available. [...] -- Grant Edwards grante Yow! VICARIOUSLY at experience some reason visi.com to LIVE!! From michele.simionato at gmail.com Tue May 9 04:41:09 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 9 May 2006 01:41:09 -0700 Subject: Is this a good use of __metaclass__? In-Reply-To: <e3pilo$9l8$1@news.lysator.liu.se> References: <e3f96d$3oi$1@news.lysator.liu.se> <1147079642.732317.210890@i40g2000cwc.googlegroups.com> <e3pilo$9l8$1@news.lysator.liu.se> Message-ID: <1147164069.329056.312650@i39g2000cwa.googlegroups.com> Joel Hedlund wrote: > It's not that I'm hellbent on using > metaclasses - I'm just curious how people think they should be used. There are very few good use cases for metaclasses. *You should use a metaclass only when you want the additional metaclass-induced behavior to be inherited in the children classes.* Here is a made up example (it assume you know the cmd.Cmd class in the standard library). Suppose you want to use a metaclasses to add aliases to the "do_*" methods of a subclass of cmd.Cmd. You can do it in this way: import cmd class make_oneletter_aliases_for_commands(type): """Typically used in Cmd classes.""" def __init__(cls, name, bases, dic): for name,func in dic.iteritems(): if name.startswith("do_"): firstletter = name[3] setattr(cls, "do_" + firstletter, func) class Cmd(cmd.Cmd, object): # make it a new-style class, so that super works __metaclass__ = make_oneletter_aliases_for_commands def preloop(self): """Done once at the beginning.""" cmd.Cmd.preloop(self) self.do_greetings("World!") def do_greetings(self, arg): """Display a greeting message.""" print "Hello, %s!" % arg def do_help(self, arg): """Print this help message.""" super(Cmd, self).do_help(arg) def do_quit(self,arg): """Exit the command-loop.""" return 'quit' # anything != None will do if __name__ == '__main__': Cmd().cmdloop() Here is how you use it: $ python cmd_with_aliases.py Hello, World!! (Cmd) h Documented commands (type help <topic>): ======================================== g greetings h help q quit (Cmd) g World Hello, World! (Cmd) q The metaclass has generated the methods 'do_h', 'do_g' and 'do_q' as aliases for 'do_help', 'do_greetings', 'do_quit' respectively. You could have done the same without a metaclass, with a function modifying the class. However every time you subclass Cmd (or a subclass of it), you would have to invoke the function again to generate the aliases corresponding to the new methods in the subclass. The metaclass performs this step automagically, simplifying the life of your users. If you don't care about giving magic abilities to the subclasses of subclasses you don't need a metaclass. For real use of metaclasses, see the Zope framework code. Michele Simionato From nobody at 127.0.0.1 Thu May 4 01:54:19 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 04 May 2006 05:54:19 GMT Subject: stripping unwanted chars from string References: <tFe6g.21715$4L1.10250@newssvr11.news.prodigy.com> <44598a93$1@news.eftel.com> Message-ID: <fGg6g.81576$dW3.51580@newssvr21.news.prodigy.com> John Machin wrote: > [expletives deleted] and it was wrong anyway (according to your > requirements); > using \w would keep '_' which is *NOT* alphanumeric. Actually the perl is correct, the explanation was the faulty part. When in doubt, trust the code. Plus I explicitly allowed _ further down, so the mistake should have been fairly obvious. > >>> alphabet = 'qwertyuiopasdfghjklzxcvbnm' # Look, Ma, no thought > required!! Monkey see, monkey type. I won't dignify that with a response. The code that is, I could give a toss about the comments. If you enjoy using such verbose, error-prone representations in your code, god help anyone maintaining it. Including you six months later. Quick, find the difference between these sets at a glance: 'qwertyuiopasdfghjklzxcvbnm' 'abcdefghijklmnopqrstuvwxyz' 'abcdefghijklmnopprstuvwxyz' 'abcdefghijk1mnopqrstuvwxyz' 'qwertyuopasdfghjklzxcvbnm' # no fair peeking And I won't even bring up locales. > >>> keepchars = set(alphabet + alphabet.upper() + '1234567890-.') > >>> fixer = lambda x: ''.join(c for c in x if c in keepchars) Those darn monkeys, always think they're so clever! ;) if "you can" == "you should": do(it) else: do(not) >> Sadly I can find no such beast. Anyone have any insight? As of now, >> regexes look like the best solution. > > I'll leave it to somebody else to dredge up the standard riposte to your > last sentence :-) If the monstrosity above is the best you've got, regexes are clearly the better solution. Readable trumps inscrutable any day. > One point on your requirements: replacing unwanted characters instead of > deleting them may be better -- theoretically possible problems with > deleting are: (1) duplicates (foo and foo_ become the same) (2) '_' > becomes '' which is not a valid filename. Which is why I perform checks for emptiness and uniqueness after the strip. I decided long ago that stripping is preferable to replacement here. > And a legibility problem: if > you hate '_' and ' ' so much, why not change them to '-'? _ is allowed. And I do prefer -, but not for legibility. It doesn't require me to hit Shift. > Oh and just in case the fix was accidentally applied to a path: > > keepchars.update(os.sep) > if os.altsep: keepchars.update(os.altsep) Nope, like I said this is strictly a filename. Stripping out path components is the first thing I do. But thanks for pointing out these common pitfalls for members of our studio audience. Tell him what he's won, Johnny! ;) From lard at tardis.ed.ac.molar.uk Sun May 7 14:53:12 2006 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Sun, 07 May 2006 18:53:12 GMT Subject: algorithmic mathematical art In-Reply-To: <1146996866.280944.313050@y43g2000cwc.googlegroups.com> References: <1146996866.280944.313050@y43g2000cwc.googlegroups.com> Message-ID: <smr7g.118834$xt.109591@fe3.news.blueyonder.co.uk> Xah Lee wrote: > i've long time been interested in algorithmic mathematical art. That > is, mathematical or algorithmic visual art works that are generated by > computer such that the program's source code reflects the algorithmic > essence of the visual quality in the art work. (for detail, see > Algorithmic Mathematical Art at > http://xahlee.org/Periodic_dosage_dir/t1/20040113_cmaci_larcu.html Hi Xah thanks for the interesting links! I sometimes dabble in computer art. Nearest example of my stuff to hand are these: http://ohmslaw.org.uk/images/newtonRaphsonArt/ Those images are based on a variant of the Newton-Raphson root finding equation (and used on complex numbers - the pictures represents the Argand plane, i.e. x => real, => imaginary). I need to find more of my stuff and give it a proper home! cheerio lex From per9000 at gmail.com Thu May 25 04:06:48 2006 From: per9000 at gmail.com (per9000) Date: 25 May 2006 01:06:48 -0700 Subject: how to change sys.path? References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> Message-ID: <1148544408.348803.190320@j33g2000cwa.googlegroups.com> also se topic named 'problem(s) with import from parent dir: "from ../brave.py import sir_robin" ' I use this every day now: sys.path.append("../../py_scripts") best wishes, Per From fdu.xiaojf at gmail.com Mon May 8 09:06:45 2006 From: fdu.xiaojf at gmail.com (Xiao Jianfeng) Date: Mon, 08 May 2006 21:06:45 +0800 Subject: How can I do this with python ? In-Reply-To: <1147078986.624152.14770@u72g2000cwu.googlegroups.com> References: <mailman.5460.1147060043.27775.python-list@python.org> <1147078986.624152.14770@u72g2000cwu.googlegroups.com> Message-ID: <445F4265.9080503@gmail.com> Tim N. van der Leeuw wrote: > Your question is insufficiently clear for me to answer. > > Do you want to know how to read from standard-input in a Python > program? > > Do you want to know how to start an external program from Python, and > then connect something to that programs standard input? > > Do you want to know something else? > > Please specify! > > Cheers, > > --Tim > > Thanks. For example, I can call vim and do something like this in a shell script, #!/bin/sh vim a.file<<-EOF :some_vim_command :some_vim_command :w :q EOF I want to know how to call vim and to the same thing with python. Regrads, From __peter__ at web.de Fri May 19 05:47:46 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 May 2006 11:47:46 +0200 Subject: calling python functions using variables References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> Message-ID: <e4k443$el5$02$1@news.t-online.com> creo wrote: > i invoke an 'ls' command like this > commands.ls() > where commands.py is a file in the same directory > > what i want to do is > commands.VARIABLE() > where VARIABLE holds the name of the function which i want to execute > and depends on what the user has typed You want getattr(commands, VARIABLE)() Peter From tim.leeuwvander at nl.unisys.com Fri May 12 10:25:31 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 12 May 2006 07:25:31 -0700 Subject: New tail recursion decorator In-Reply-To: <Xns97C19C18C76A4duncanbooth@127.0.0.1> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <Xns97BF8E839A8D1duncanbooth@127.0.0.1> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> <1147437656.779139.54840@d71g2000cwd.googlegroups.com> <1147441799.331677.88460@d71g2000cwd.googlegroups.com> <Xns97C19C18C76A4duncanbooth@127.0.0.1> Message-ID: <1147443931.003427.240370@y43g2000cwc.googlegroups.com> Duncan Booth wrote: > Tim N. van der Leeuw wrote: > [...] > @tail_recursion > def factorial2(n): > # do the stuff > pass > > your 'do the stuff' actually had an erroneous call to 'factorial'. If you > are going to rename the function you have to rename the recursive calls as > well. (At least, that's what I forgot to do when I first tried it and > couldn't understand why it gave me an answer instead of crashing.) [...] Duncan, You're totally right. Somehow, I had managed to completely overlook this. Oops! My apologies! :) --Tim From jeff at schwabcenter.com Mon May 22 00:03:35 2006 From: jeff at schwabcenter.com (Jeffrey Schwab) Date: Mon, 22 May 2006 04:03:35 GMT Subject: Software Needs Less Idiots In-Reply-To: <878xou5303.fsf@david-steuber.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148204984.990918.237770@u72g2000cwu.googlegroups.com> <878xou5303.fsf@david-steuber.com> Message-ID: <rKacg.13304$Lg.416@tornado.southeast.rr.com> David Steuber wrote: > "PofN" <7abc at sogetthis.com> writes: > >> Xah Lee wrote: >>> Software needs philosophers. >> No, software neds less idiots. So please take your medication and >> change profession. > > Perhaps fewer would do. Thank you. I didn't want to be "that guy." From kent at kentsjohnson.com Wed May 10 08:14:03 2006 From: kent at kentsjohnson.com (Kent Johnson) Date: Wed, 10 May 2006 08:14:03 -0400 Subject: regular expressions, substituting and adding in one step? In-Reply-To: <AY58g.2072$No6.45671@news.tufts.edu> References: <yEI7g.2056$No6.45379@news.tufts.edu> <4460e0d7$1_1@newspeer2.tds.net> <AY58g.2072$No6.45671@news.tufts.edu> Message-ID: <4461d885$1_3@newspeer2.tds.net> John Salerno wrote: > Call > me crazy, but I'm interested in regular expressions right now. :) Not crazy at all. REs are a powerful and useful tool that every programmer should know how to use. They're just not the right tool for every job! Kent From bearophileHUGS at lycos.com Thu May 18 15:52:12 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 18 May 2006 12:52:12 -0700 Subject: Sorting of list containing tuples In-Reply-To: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> References: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> Message-ID: <1147981931.982962.80330@g10g2000cwb.googlegroups.com> >>> l = [(2,3),(3,2),(6,5)] >>> from operator import itemgetter >>> sorted(l, key=itemgetter(1), reverse=True) [(6, 5), (2, 3), (3, 2)] Bye, bearophile From chris.cavalaria at free.fr Wed May 17 09:40:17 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 17 May 2006 15:40:17 +0200 Subject: IDLE confusion In-Reply-To: <mailman.5769.1147812265.27775.python-list@python.org> References: <1147767977.928350.261650@i39g2000cwa.googlegroups.com><e4c34c$5l6$1@newsreader3.netcologne.de> <446991de$0$7690$626a54ce@news.free.fr> <mailman.5769.1147812265.27775.python-list@python.org> Message-ID: <446b27eb$0$5316$626a54ce@news.free.fr> Terry Reedy a ?crit : > "Christophe" <chris.cavalaria at free.fr> wrote in message > news:446991de$0$7690$626a54ce at news.free.fr... > >>Try in the IDLE menu [Shell] "Restart Shell" (Ctrl+F6) each time you >>have changed something in your files - this "resets" anything previously >>imported, which stays the same way otherwise. > > > And I though that "bug" was fixed already :) > > On my system, the current 2.4.3 version of Python+IDLE *does* auto restart > with each run (F5). So either the OP is using a much older version (did > not specify) or the respondant mis-diagnosed the problem. I was looking at some idlefork info not long ago and I found something which might get those different behaviours with a recent version of idle : if idle cannot open it's RPC socket, it'll execute all python code in it's own interpreter. There's an option for that in fact. From oliphant.travis at ieee.org Wed May 24 14:24:36 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Wed, 24 May 2006 12:24:36 -0600 Subject: Scipy: vectorized function does not take scalars as arguments In-Reply-To: <1148480844.817338.69230@u72g2000cwu.googlegroups.com> References: <1148480844.817338.69230@u72g2000cwu.googlegroups.com> Message-ID: <e528d4$960$1@sea.gmane.org> ago wrote: > Once I vectorize a function it does not acccept scalars anymore. Es > > def f(x): return x*2 > vf = vectorize(f) > print vf(2) > > AttributeError: 'int' object has no attribute 'astype' > > Is this the intended behaviour? > Vectorize handles scalars in recent versions of NumPy. Which version do you have? -Travis From dcrosta at sccs.swarthmore.edu Tue May 9 11:06:33 2006 From: dcrosta at sccs.swarthmore.edu (Dan Crosta) Date: Tue, 09 May 2006 11:06:33 -0400 Subject: distutils In-Reply-To: <loom.20060509T164814-180@post.gmane.org> References: <loom.20060509T161902-311@post.gmane.org> <4460A9D0.50503@sccs.swarthmore.edu> <loom.20060509T164814-180@post.gmane.org> Message-ID: <4460AFF9.6040407@sccs.swarthmore.edu> David S. wrote: > Thank you. This introduces a new problem for me. I have other scripts that I > want to install likewise. But now I have to overwrite setup.py for each install. > > Alternatively, I can create script1setup.py, script2setup.py, etc. That would > be fine except that there are other files, ie. MANIFEST.IN and README, that need > to be there too. I have not found a way to similarly rename these. > > Finally, it seems odd that I should have so many XXXsetup.py scripts in my > package root directory. I don't understand -- you can install multiple scripts with a single setup.py. Do you want finer-grained control over which are installed by a single invocation of setup.py? In that case, you should re-read the distutils docs about sub-classing portions of the setup process. The documentation for the Python 2.4.2 distribution is more complete than in 2.3.5. dsc From carlosperezs at alumnos.uvigo.es Mon May 8 03:14:44 2006 From: carlosperezs at alumnos.uvigo.es (carlosperezs at alumnos.uvigo.es) Date: Mon, 8 May 2006 09:14:44 +0200 Subject: List Ctrl Message-ID: <1147072484.445eefe44a4f7@correoweb.uvigo.es> Hello together !!!!!! I have programmed a List Control and I introduced information in several rows. What I want to do is, modify this information when i select a row and press a button. There two options: - when i do this, a window appears and asks me to introduce the information. - or in the selected row , the last information is removed and lets me to overwrite. Thank you --oOo-----------------------------------------------------------------oOo-- Servicio de acceso ? correo electr?nico v?a web da Universidade de Vigo Servicio de acceso al correo electr?nico v?a web de la Universidad de Vigo Servicios Inform?ticos [ http://si.uvigo.es ] Universidade de Vigo [ http://www.uvigo.es ] URL: https://correoweb.uvigo.es From giles_brown at hotmail.com Wed May 24 05:29:52 2006 From: giles_brown at hotmail.com (Giles Brown) Date: 24 May 2006 02:29:52 -0700 Subject: hi,every body. a problem with PyQt. In-Reply-To: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> References: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> Message-ID: <1148462992.083939.209920@38g2000cwa.googlegroups.com> The tool to create a python script from a Qt designer .ui file is called pyuic. I suggest you have a google for "pyqt tutorial" pages. I found this one for example: http://wiki.python.org/moin/JonathanGardnerPyQtTutorial Regards, Giles From chris.cavalaria at free.fr Thu May 18 11:13:59 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 17:13:59 +0200 Subject: Question about exausted iterators In-Reply-To: <mailman.5886.1147964579.27775.python-list@python.org> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> <446c7346$0$7147$626a54ce@news.free.fr> <mailman.5879.1147959939.27775.python-list@python.org> <446c7f44$0$7128$626a54ce@news.free.fr> <4d3f10F18q0d9U1@uni-berlin.de> <446c88a2$0$7121$626a54ce@news.free.fr> <mailman.5886.1147964579.27775.python-list@python.org> Message-ID: <446c8f5e$0$7153$626a54ce@news.free.fr> Fredrik Lundh a ?crit : > Christophe wrote: > >> Maybe I've used more iterables than most of you. Maybe I've been doing >> that wrong. > > > your problem is that you're confusing iterables with sequences. they're > two different things. Yes, I know perfectly well that the bugs were my fault. But this doesn't prevent me from asking for a feature that will have ( in my opinion ) a negligible effect of current valid code and will help all of us catch errors earlier. From sRuEmMrOnVoEt at hotmail.com Thu May 25 14:09:51 2006 From: sRuEmMrOnVoEt at hotmail.com (Geoffrey Summerhayes) Date: Thu, 25 May 2006 14:09:51 -0400 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> <Xns97CE807F1ADC6castleamber@130.133.1.4> Message-ID: <Zpmdg.2874$%Z2.298786@news20.bellglobal.com> "John Bokma" <john at castleamber.com> wrote in message news:Xns97CE807F1ADC6castleamber at 130.133.1.4... > Dra?en Gemi? <usenet at local.machine> wrote: > >> There is a person on USENET, particularly in hr. hierarchy that >> posts under three different accounts. Sometimes he argues with >> himself, and sometimes event supports himself :-) >> >> Maybe we have the similar case here. > > Wouldn't amaze me if some of the buddies of Xah are actually Xah sitting > in some Internet cafe, enjoying this troll fest, and already thinking up > the next one. That's right, we're all Xah, you're the only other one here. After you kill Navarth, will it be nothing but gruff and deedle with a little wobbly to fill in the chinks? -- Geoff From http Thu May 4 10:25:19 2006 From: http (Paul Rubin) Date: 04 May 2006 07:25:19 -0700 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <imbf52doc8hop66o1idfb5amhjuu5to915@4ax.com> Message-ID: <7xhd45kgts.fsf@ruckus.brouhaha.com> Dave Hansen <iddw at hotmail.com> writes: > Well, if you want something minimalist, you could try > > def truth_test(seq): > return sum(1 for item in seq if item) == 1 def truth_test(seq): return sum(map(bool, seq)) == 1 From deets at nospam.web.de Fri May 12 07:40:45 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 12 May 2006 13:40:45 +0200 Subject: python soap web services References: <R3T8g.84368$eR6.57426@bgtnsc04-news.ops.worldnet.att.net> Message-ID: <4cjaj2F14ufcoU1@uni-berlin.de> Butternut squash wrote: > Is there any reason why there isn't any python library that makes > using soap as easy as how microsoft .net makes it. > > I mean I write rudimentary asmx files call them from a webbrowser. > The WSDL is generated and then there is documentation and a form to > invoke a function. The WSDL will never as easily be created as in .NET/JAVA, as Python lacks static typing annotations that are used by the WSDL-generators. So either someone defines his own type annotation theme for that purpose that can be used to infer the WSDL - or you write WSDL yourself. Which is a major PITA, as the whole SOAP mess. Ravi OTH has pointed out _running_ a SOAP service is easy as cake. Diez From robin at reportlab.com Tue May 9 05:11:56 2006 From: robin at reportlab.com (Robin Becker) Date: Tue, 09 May 2006 10:11:56 +0100 Subject: hyperthreading locks up sleeping threads In-Reply-To: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> References: <1147097624.645082.324420@i40g2000cwc.googlegroups.com> Message-ID: <44605CDC.30203@chamonix.reportlab.co.uk> OlafMeding at gmail.com wrote: > Below are 2 files. The first is a Python program that isolates the > problem within less than 1 hour (often just a few minutes). The second > is a C++ program that shows that the Win32 Sleep() function works as > expected (ran from Friday afternoon until Monday morning). > > Note, the Python programs hangs (stops responding) with hyper-threading > turned on (a BIOS setting), but works as expected with hyper-threading > turned off. ...... I ran this on winxp ht+python-2.4.3 for about 16 hours and no lockup. -- Robin Becker From rune.strand at gmail.com Mon May 1 09:31:16 2006 From: rune.strand at gmail.com (Rune Strand) Date: 1 May 2006 06:31:16 -0700 Subject: Measure memory usage in Python In-Reply-To: <1146455362.984926.216240@g10g2000cwb.googlegroups.com> References: <1146431890.904603.98620@i39g2000cwa.googlegroups.com> <1146455362.984926.216240@g10g2000cwb.googlegroups.com> Message-ID: <1146490276.060838.63870@i40g2000cwc.googlegroups.com> gene tani wrote: > Rune Strand wrote: > > Is there a way to measure how much memory a data structure use? For > > instance, what is the footprint of a particular list object like > > [0,1,2,3,4,5,6,7,8,9]? > > i have a note to try this, but haven't got around to it, if you want to > blog/post > > http://pysizer.8325.org/ Thank you! That seems to be what I was looking for. From duncan.booth at invalid.invalid Fri May 5 08:47:01 2006 From: duncan.booth at invalid.invalid (Duncan Booth) Date: 5 May 2006 12:47:01 GMT Subject: Method acting on arguements passed References: <1146832062.017259.265700@y43g2000cwc.googlegroups.com> Message-ID: <Xns97BA8C3303947duncanbooth@127.0.0.1> Panos Laganakos wrote: > I want a class method to take action depending on the type of the > arguement passed to it. > > ie: > getBook(id) # get the book by ID > getBook(name) # get the book by name > ... > > Other languages use the term function/method overloading to cope with > this. And when I googled about it seems that GvR is testing it for 3.0 > inclusion or so. > > I was thinking of right after the function declaration check for the > parameter passed by isinstance() or type() and use if..elif..else to > act. > > Is this the pythonic way/best practice to apply here? > I think the most Pythonic way is probably to have separate methods. You presumably know at the point when you are calling getBook whether you have an id or a name. So be explicit: getBookById(id) getBookByName(name) This has the advantage that id and name could both be strings and the code will still do the right thing. No amount of function overloading will resolve arguments which have the same type but mean different things. Another reasonable way to go is to use keyword arguments: getBook(id=id) getBook(name=name) which keeps down the number of different methods but could be confusing as you have mutually exclusive keyword arguments. Another option you might have here, if getBook does a lookup in a dictionary, or database query, is simply to index the books by both id and name. Then the definition might be: def getBook(self, idorname): return self._books[idorname] and there is still no typechecking. If you do feel you need typechecking, consider pulling it out into a separate method so you are actually testing for the meaning of the parameter rather than explicitly testing its type everywhere: def getBook(self, idorname): if self.isvalidid(idorname): .... elif self.isvalidname(idorname): .... else: raise Oops() From imdognuts at yahoo.com Thu May 11 12:49:50 2006 From: imdognuts at yahoo.com (imdognuts at yahoo.com) Date: 11 May 2006 09:49:50 -0700 Subject: linking with math.so Message-ID: <1147366190.436903.315380@g10g2000cwb.googlegroups.com> hi, My application that contains the .o's that were generated from using "freeze" needs to import math. The point of using freeze was to make a static application that can be shipped as a single entity (it contains the dot o's from libpython2.4.a), vs having to worry about external python dependencies. "importing math" as far as I can tell right now, invokes a shared library (math.so). Now I have a shared library dependency that I dont want. Is there a way to get the math functionality from a dot a or a dot o, so I dont have to make my app dependent on a shared library? cos, sin, and pi which is what I need do not live in the libpython2.4.a - I did an nm on it.... I'm on linux. thanks, Nancy From nospam at foo.com Fri May 12 19:09:27 2006 From: nospam at foo.com (jayessay) Date: 12 May 2006 19:09:27 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> <m38xp7p7el.fsf@rigel.goldenthreadtech.com> <yfs3bffuqj7.fsf@oc.ex.ac.uk> <r559g.16$Id.14@fe10.lga> Message-ID: <m3zmhmon6g.fsf@rigel.goldenthreadtech.com> Ken Tilton <kentilton at gmail.com> writes: > Alexander Schmolck wrote: > > jayessay <nospam at foo.com> writes: > > > >>"Michele Simionato" <michele.simionato at gmail.com> writes: > >> > >> > >>>I was interested in a proof of concept, to show that Python can > >>>emulate Lisp special variables with no big effort. > >> > >>OK, but the sort of "proof of concept" given here is something you can > >> hack up in pretty much anything. > > Care to provide e.g. a java equivalent? > > I think the point is that, with the variable actually being just a > string and with dedicated new explicit functions required as > "accessors", well, you could hack that up in any language with > dictionaries. It is the beginnings of an interpreter, not Python > itself even feigning special behavior. Exactly. Of course this is going to be totally lost on the intended audience... /Jon -- 'j' - a n t h o n y at romeo/charley/november com From grante at visi.com Sat May 27 09:11:23 2006 From: grante at visi.com (Grant Edwards) Date: Sat, 27 May 2006 13:11:23 -0000 Subject: Looking for triangulator/interpolator References: <127f313dbhl7gf4@corp.supernews.com> <mailman.6267.1148697006.27775.python-list@python.org> <127fp09e6v176a5@corp.supernews.com> <mailman.6270.1148714558.27775.python-list@python.org> Message-ID: <127gjvrhk7udbcc@corp.supernews.com> On 2006-05-27, Travis E. Oliphant <oliphant.travis at ieee.org> wrote: > Not that you made a bad choice. I do wonder, how much of your > difficulty was with the interface to the underlying fitpack > routines. I've no idea. I had never done anything with splines before, so it's quite possible I just wasn't doing things right. I never got it to work at all for non-gridded data (which is what I needed). Since it wasn't stable even for gridded data, I more or less gave up. > The interface is pretty involved as there are lots of > parameter choices to the underlying routine. It's very > possible the interface is broken in some strange way. I took a look at underlying Fortran code, but that made my dizzy. > Given how many people want to do interpolation. I'm surprised > nobody has looked into fixing up the fitpack routines that do > it. I suppose it's possible that the underlying fitpack > routines are faulty in 2-d. > > Your examples will help in that study. > > Pearu made some nice class-based interfaces to fitpack in > 2003. They are in SciPy, but, it appears that people aren't > making much use of them. Did you try them? Not that I remember. For that particular application, the interpolation had to be done in real time, so a triangulation scheme turned out to be a lot faster [with some constraints on the input data to make the triangle search O(sqrt(N))]. -- Grant Edwards grante Yow! Are the STEWED PRUNES at still in the HAIR DRYER? visi.com From Symantec_Mail_Security_for_SMTP at hu.edu.jo Wed May 10 08:12:01 2006 From: Symantec_Mail_Security_for_SMTP at hu.edu.jo (Symantec_Mail_Security_for_SMTP at hu.edu.jo) Date: Wed, 10 May 2006 14:12:01 +0200 (CEST) Subject: =?utf-8?B?RGVsaXZlcnkgZmFpbHVyZSBub3RpZmljYXRpb25=?= Message-ID: <20060510121201.5013F1E4002@bag.python.org> Your message with Subject: could not be delivered to the following recipients: kevin at yahoo.co.uk Please do not resend your original message. Delivery attempts will continue to be made for 5 day(s). From http Thu May 18 15:38:55 2006 From: http (Paul Rubin) Date: 18 May 2006 12:38:55 -0700 Subject: Sorting of list containing tuples References: <7iip62h92vtjvrp8qcv3380oni8k7k5721@4ax.com> Message-ID: <7x1wurcecw.fsf@ruckus.brouhaha.com> Ronny Mandal <ronnyma at math.uio.no> writes: > And now I want to sort l reverse by the second element in the tuple, > i.e the result should ideally be: > > l = [(6,5),(2,3),(3,2)] sorted(l, key = lambda a: -a[1]) From lonetwin.nospam at yahoo.com Tue May 16 13:06:06 2006 From: lonetwin.nospam at yahoo.com (Steve) Date: Tue, 16 May 2006 22:36:06 +0530 Subject: [silly] Does the python mascot have a name ? References: <e4c59e$tqg$1@emma.aioe.org> <Xns97C5AE2C06CE8BaldHeadedJohn@216.196.109.145> Message-ID: <e4d0l4$dju$1@emma.aioe.org> John D Salt wrote: > Steve <lonetwin.nospam at yahoo.com> wrote in > news:e4c59e$tqg$1 at emma.aioe.org: > >> umm, was just wondering, does the python mascot have a name ? > > I always assumed it was Monty, but I confess to not having the slightest > factual basis for this belief. Well, so Monty it is ! ...btw, did you know, the Camel (http://dev.perl.org/perl6/rfc/343.html) doesn't have a name either ? ...looks like Duke (http://www.java.com/en/dukeszone/) is the only dude with a name ...but then duke is not an animal (wtf is it ?), so it had to be called something ! Regards Steve From emami at knmi.nl Tue May 16 09:13:27 2006 From: emami at knmi.nl (Nader Emami) Date: Tue, 16 May 2006 14:13:27 +0100 Subject: a question Message-ID: <4d91a$4469cff7$9117fe9b$21343@news1.tudelft.nl> L.S., I have read all replays about web development with python. I would agree with somebody who have said that web design is depends on specific requirements. I would like to develop some in which the animation is well important. It will be an animation of a radar file. I have looked for a lot of alternative but I do not which of them I can choose for my application. I will appreciate everyone if he/she would give me some advice in this case. With regards, Nader From johnjsal at NOSPAMgmail.com Wed May 24 11:29:11 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 24 May 2006 15:29:11 GMT Subject: Python Programming Books? In-Reply-To: <1148483986.822220.287590@i39g2000cwa.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <mn.c36f7d65ac4090ff.43626@yahoo.fr.invalid> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> <dr_cg.2164$No6.46749@news.tufts.edu> <1148483986.822220.287590@i39g2000cwa.googlegroups.com> Message-ID: <bZ_cg.2168$No6.46909@news.tufts.edu> herraotic at googlemail.com wrote: > I borrowed Learning Python 2nd edtion from a library once and it felt > condensed with information and I didn't think I could start with it > "yet" as I want a book made for a beginner programmer and I don't think > Learning Python 2nd edtion is made for my audience. > > I want something that explains programming fundamentals and explains it > in general while also showing the reason in practise and from reading > some free PDF's of "Python Programming: An Introduction to Computer > Science" I think it fit the bill perfectly, I would have it already but > i'm only 15 and my dad is a bit weary of using his credit card online > :-). > Well, I *would* say that Learning Python does assume a little knowledge of programming in general, so in your case it might not be a good start. On the same note, neither is Beginning Python. If your problem is limited access to books, you might want to try this site: http://www.ibiblio.org/obp/thinkCSpy/index.htm From jantod at gmail.com Sun May 28 14:14:57 2006 From: jantod at gmail.com (jantod at gmail.com) Date: 28 May 2006 11:14:57 -0700 Subject: itertools.count() as built-in Message-ID: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> Is there any chance of itertools.count() ever becoming one of the built-in functions? It's a wonderful little function and I find myself importing it in every module I write. -Janto From agr at fq.uniovi.es Mon May 8 06:56:29 2006 From: agr at fq.uniovi.es (=?UTF-8?B?w4FuZ2VsIEd1dGnDqXJyZXogUm9kcsOtZ3Vleg==?=) Date: Mon, 08 May 2006 12:56:29 +0200 Subject: List of lists of lists of lists... Message-ID: <e3n81d$9o0$1@emma.aioe.org> I would like to have a list of lists N times deep, and my solution is (in pseudocode): def deep(x): a=[x] return a mylist=[] for N: mylist=deep(mylist) Is there a more elegant way to do it? The maine idea is: from a list having the numbre of steps along N dimensions, generate a list with an item at each possible point. Example 1: N=2 list=[2,3] result=[[1,2],[1,2],[1,2]] Example 2: N=3 list=[3,1,2] result=[[[1,2,3]],[[1,2,3]]] -- ?ngel Guti?rrez Rodr?guez - agr at fq.uniovi.es Instituto de Ciencia de los Materiales de Madrid - CSIC SpLine - European Syncrothorn Radiation Facility - Grenoble - France Postal adress: Departamento de Qu?mica F?sica y Anal?tica Universidad de Oviedo - c/Juli?n Claver?a 8 33006 - Oviedo Asturias - Spain E-mail: agr at fq.uniovi.es Telf.: +34-985103687 From bnblazer at gmail.com Wed May 24 09:59:26 2006 From: bnblazer at gmail.com (Brian) Date: 24 May 2006 06:59:26 -0700 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <mn.c36f7d65ac4090ff.43626@yahoo.fr.invalid> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> Message-ID: <1148479166.809729.85880@j33g2000cwa.googlegroups.com> herraotic at googlemail.com wrote: > Thanks, if you don't mind could I have a small <b>personal</b> > description on the quality of the books (pros, cons). > > I also am interested if anyone has used "Python Programming: An > Introduction to Computer Science" and if I could be given a detailes > evaluation about it. > I have a copy of this book on my shelf. I think it may be a good choice since you are new to programming. One thing to keep in mind is that is it a Computer Science book that uses Python to teach CS. As a result, you do not get too deep into the language. One book that I think you should definitely look at is Beginning Python from Novice to Professional. I think that it is one of the best books out there on the subject, is an easy read, has clear and concise examples, and does a great job of explaining the whys without making you think you are reading a PhD thesis. On a final note, I think that Python Essential Reference is a good reference book on the language. One thing you might want to look at is Safari Bookshelf by O'Reilly http://safari.oreilly.com/ . They have all of their books online for your to read. It costs $14/month, but you get a 2 week free trial to decide if you want it. You can even download whole chapters as pdf's. In my mind it is a great place to test drive a book, or to have one that you only need to see one or two things in. HTH, Brian From just at xs4all.nl Thu May 4 13:08:44 2006 From: just at xs4all.nl (Just) Date: Thu, 04 May 2006 19:08:44 +0200 Subject: Tuple assignment and generators? References: <mailman.5334.1146755400.27775.python-list@python.org> <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> Message-ID: <just-6A9E96.19084404052006@news1.news.xs4all.nl> In article <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d at comcast.com>, Larry Bates <larry.bates at websafe.com> wrote: > While I have never needed anything like this in my 5 years of Python > programming, here is a way: > > a,b,c = 3*[0] > q,r,s,t,u,v = 6*[0] This is (IMO) fairly idiomatic: a = b = c = 0 q = r = s = t = u = v = 0 Just From bdesth.quelquechose at free.quelquepart.fr Tue May 2 22:13:44 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 03 May 2006 04:13:44 +0200 Subject: simultaneous assignment In-Reply-To: <mailman.5224.1146604977.27775.python-list@python.org> References: <8dM5g.2031$No6.43874@news.tufts.edu> <RAN5g.2037$No6.43926@news.tufts.edu> <e38ghu$he1$1@avnika.corp.mot.com> <mailman.5224.1146604977.27775.python-list@python.org> Message-ID: <4457e327$0$12849$626a54ce@news.free.fr> Heiko Wundram a ?crit : (snip) > If you're looking for things to code in Python, I'd rather suggest you look at > number theory than at logic problems. > > Basically, every logic problem can be > solved by exhaustive search (which is always the same algorithm), whereas a > number theory problem requires that you implement a certain algorithm from > scratch for each problem you're trying to tackle. Well... I do see the point, but still boolean logic is a mandatory part of programming, and one that wannabee programmers should get right. From onurb at xiludom.gro Fri May 12 04:25:32 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 12 May 2006 10:25:32 +0200 Subject: Reg Ex help In-Reply-To: <S4P8g.69868$_S7.2226@newssvr14.news.prodigy.com> References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> <4463a7be$0$290$626a54ce@news.free.fr> <S4P8g.69868$_S7.2226@newssvr14.news.prodigy.com> Message-ID: <446446df$0$289$636a55ce@news.free.fr> Edward Elliott wrote: (snip) >>don a ?crit : >> >>>Also if there is a better way than using regex, please let me know. >> (snip) > > I wouldn't call these better (or worse) than regexes, but a slight variation > on the above: > > marker = s.index('/CHECKEDOUT') > branch = s [s.rindex('/', 0, marker) + 1 : marker] Much cleaner than mine. I shouldn't try to code when it's time to bed !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From xyzzyx23 at yahoo.com Mon May 15 05:53:29 2006 From: xyzzyx23 at yahoo.com (NoNickName) Date: 15 May 2006 02:53:29 -0700 Subject: where do you run database scripts/where are DBs 'located'? In-Reply-To: <1147497059.393293.182010@j73g2000cwa.googlegroups.com> References: <jz09g.2091$No6.46071@news.tufts.edu> <1147497059.393293.182010@j73g2000cwa.googlegroups.com> Message-ID: <1147686809.145019.306180@i40g2000cwc.googlegroups.com> Gerard Flanagan wrote: > Interactive SQL tutorial: http://www.sqlcourse.com/ ; > http://sqlcourse2.com/ > > Indirectly helpful maybe: > http://initd.org/tracker/pysqlite/wiki/basicintro > > HTH > > Gerard There's also the TechBookReport SQL tutorial - which is geared to MySQL (and, shudder, Access). Take a look at http://www.techbookreport.com/sql-tut1.html From tim.peters at gmail.com Tue May 2 02:23:37 2006 From: tim.peters at gmail.com (Tim Peters) Date: Tue, 2 May 2006 02:23:37 -0400 Subject: Popping from the middle of a deque + deque rotation speed In-Reply-To: <1146527606.361060.211630@i39g2000cwa.googlegroups.com> References: <1146264164.488782.96770@g10g2000cwb.googlegroups.com> <mailman.5120.1146281831.27775.python-list@python.org> <1146527606.361060.211630@i39g2000cwa.googlegroups.com> Message-ID: <1f7befae0605012323v7e7aaa97n488e143f5ef1e672@mail.gmail.com> [Russell Warren] > ... > As to indexing into a deque being O(index)... I didn't realize that. > It is certainly something to keep in mind, though... looping through > the contents of a deque would obviously be a bad idea with this being > the case! I wonder if the generator for the deque helps reduce this? > Will check later. FYI, deque implements efficient forward and reverse iterators. So, e.g., for x in a_deque: pass and for x in reversed(a_deque): pass takes time proportional to len(a_deque). In contrast, for i in xrange(len(a_deque)): x = a_deque[i] take time quadratic in len(a_deque). The iterators don't use __getitem__ under the covers; explicitly indexing does, and that's the difference here. From alf at merlin.fayauffre.org Fri May 5 04:17:20 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Fri, 5 May 2006 08:17:20 +0000 (UTC) Subject: Job opportunity in France References: <mn.2a417d6545f2820b.43626@yahoo.fr.invalid> Message-ID: <slrne5m2g6.4l1.alf@merlin.fayauffre.org> Le 05-05-2006, Rony <bucodi at yahoo.fr.invalid> nous disait: > We have a vacancy for a python programmer for a 6 months assignement. Hi Rony, You may find interested people on fr.comp.lang.python and on the python-fr mailing list (python at aful dot org), if you post your announce (in French) on these forums. -- Alexandre Fayolle 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 kay.schluehr at gmx.net Mon May 22 18:00:02 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 22 May 2006 15:00:02 -0700 Subject: ANN: EasyExtend Message-ID: <1148335202.505830.142620@i40g2000cwc.googlegroups.com> After fixing some more severe bugs last weekend I decided to go online with EasyExtend and its homepage yet. EasyExtend was my Python hobby-horse and fun project the last months. It was exactly the kind of programming from which I wanted to become surprised myself. EasyExtend is essentially a system for extending the Python language in pure Python i.e. without the use of C extensions. While it is devoted to Python and its machinery it is also a clear break with Pythons traditional and I believe principle resistance against macro systems and such alike. As a pure Python program that performs meta-programming on Python I would consider it as the little brother of PyPy - and indeed I reused some PyPy code which could be well separated. Now it is open to you for look, play, experiment, criticism and usage. http://www.fiber-space.de/EasyExtend/doc/EE.html Regards, Kay From tkpmep at hotmail.com Mon May 8 15:33:14 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 8 May 2006 12:33:14 -0700 Subject: Using StopIteration In-Reply-To: <e3o3i0$4le$00$1@news.t-online.com> References: <1147112608.374083.99030@u72g2000cwu.googlegroups.com> <e3o3i0$4le$00$1@news.t-online.com> Message-ID: <1147116794.649517.263040@i39g2000cwa.googlegroups.com> This is just what the doctor ordered. Thanks, as always, everyone! > By breaking out of the while loop as shown above. > > Peter From nephish at xit.net Wed May 24 09:12:32 2006 From: nephish at xit.net (nephish at xit.net) Date: 24 May 2006 06:12:32 -0700 Subject: problem with writing a simple module In-Reply-To: <upm7721j452sm69ocb4auovqaot96pajhs@4ax.com> References: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> <dlq372dauhaigrhsd54rbadf7geklbkbop@4ax.com> <1148390743.600334.227460@j73g2000cwa.googlegroups.com> <p9b672l1nf5pat4kts5ltdp2nv8e1h86kg@4ax.com> <1148401441.799070.111030@j33g2000cwa.googlegroups.com> <upm7721j452sm69ocb4auovqaot96pajhs@4ax.com> Message-ID: <1148476352.804352.222750@j73g2000cwa.googlegroups.com> cool, thanks, i was running on some thinner examples i found on the net. From john at castleamber.com Thu May 25 13:37:55 2006 From: john at castleamber.com (John Bokma) Date: 25 May 2006 17:37:55 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <v7qdnYGD9bbdcenZnZ2dnUVZ_sydnZ2d@comcast.com> <e54crf$5lp$1@magcargo.vodatel.hr> Message-ID: <Xns97CE807F1ADC6castleamber@130.133.1.4> Dra?en Gemi? <usenet at local.machine> wrote: > There is a person on USENET, particularly in hr. hierarchy that > posts under three different accounts. Sometimes he argues with > himself, and sometimes event supports himself :-) > > Maybe we have the similar case here. Wouldn't amaze me if some of the buddies of Xah are actually Xah sitting in some Internet cafe, enjoying this troll fest, and already thinking up the next one. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From bignose+hates-spam at benfinney.id.au Thu May 18 09:08:15 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 23:08:15 +1000 Subject: How to customize getattr(obj, prop) function ? References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> <446c3785$0$6981$626a54ce@news.free.fr> <1147944267.585786.82730@i40g2000cwc.googlegroups.com> Message-ID: <87y7wzlbuo.fsf@benfinney.id.au> [Please provide some context in your reply, so we know what questions or comments you're replying to.] "Pierre" <meyer.p at gmail.com> writes: > I don't want to use getattr(object, property, default_value) because > I'm using external code and I don't want to modify or patch it. You can subclass the class you want to modify, and override its behaviour. class ScaryExternalThing(object): """ The external class we don't want to modify. """ class OurModifiedFriendlyThing(ScaryExternalThing): """ Class for use by our code. """ attr_defaults = { 'foo': "eggs", 'bar': "beans", } def __getattr__(self, name): """ Method invoked when getting an unknown attribute """ value = attr_defaults.get(name, "spam") return value -- \ "Welchen Teil von 'Gestalt' verstehen Sie nicht? [What part of | `\ 'gestalt' don't you understand?]" -- Karsten M. Self | _o__) | Ben Finney From grflanagan at yahoo.co.uk Sun May 28 16:27:34 2006 From: grflanagan at yahoo.co.uk (Gerard Flanagan) Date: 28 May 2006 13:27:34 -0700 Subject: Serializing / Unserializing datetime References: <1148751427.204676.238100@g10g2000cwb.googlegroups.com> <4478E634.8060001@lexicon.net> <1148844232.605364.192760@i40g2000cwc.googlegroups.com> Message-ID: <1148848054.531695.115160@j55g2000cwa.googlegroups.com> Brendan wrote: > Thanks John. I've discovered that datetime.strptime will be available > in 2.5, (http://docs.python.org/dev/whatsnew/modules.html) but your > example will work in the meantime. > > BJ I don't think it's what you want but I had the following on file - it uses time.strptime() which I didn't know there was a problem with. Not tested beyond what you see. -------------------------------------------------------------------------------- import time import datetime DDMMYY = ['%d %m %Y', '%d %m %y', '%d/%m/%Y', '%d/%m/%y', '%d-%m-%Y', '%d-%m-%y' ] def yearmonthday(datestring, fmts=DDMMYY): ymd = None for f in fmts: try: ymd = time.strptime( datestring, f ) break except ValueError: continue if ymd is None: raise ValueError return ymd[0], ymd[1], ymd[2] def is_valid_date(datestring, fmts=DDMMYY): try: yearmonthday(datestring, fmts) return True except ValueError: return False def string_to_date(datestring, fmts=DDMMYY): return datetime.date( *yearmonthday(datestring, fmts) ) assert string_to_date( '1/2/01', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '1 2 01', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '01/02/01', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '1/02/2001', DDMMYY) == datetime.date(2001,2,1) assert string_to_date( '29/02/2008', DDMMYY) == datetime.date(2008,2,29) assert string_to_date( '01/2/99', DDMMYY) == datetime.date(1999,2,1) for d in [ '', '32/1/01', '01/13/01', '29/2/07', '1/2', 'abcdef' ]: assert not is_valid_date(d, DDMMYY) ------------------------------------------------------------------------------------ Gerard From bjourne at gmail.com Sun May 7 19:00:12 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Mon, 8 May 2006 01:00:12 +0200 Subject: Swaying A Coder Away From Python In-Reply-To: <9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <W40839200.311.1532.1@mx-extra.net> <9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> Message-ID: <740c3aec0605071600t514dc575i3bcf977ae5d55216@mail.gmail.com> On 5/4/06, Tim Williams <tdw at tdw.net> wrote: > > (and why do you > > seem to think that this matters, btw ?) > > I actually think it is complete twaddle, for the same reasons as you. I think this article has something to do with this article: http://www.paulgraham.com/submarine.html Maybe or maybe not. -- mvh Bj?rn From SODIA17 at aol.com Fri May 19 10:28:15 2006 From: SODIA17 at aol.com (SODIA17 at aol.com) Date: Fri, 19 May 2006 10:28:15 EDT Subject: CLAIM YOUR TWO FREE UNIVERSAL STUDIOS TICKETS! Message-ID: <220.c38a104.319f2fff@aol.com> -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060519/3b79b1c5/attachment.html> From paul.dubois at gmail.com Fri May 26 01:51:11 2006 From: paul.dubois at gmail.com (Paul Du Bois) Date: 25 May 2006 22:51:11 -0700 Subject: genexp surprise (wart?) In-Reply-To: <7xpsi14drb.fsf@ruckus.brouhaha.com> References: <7xpsi14drb.fsf@ruckus.brouhaha.com> Message-ID: <1148622671.835989.217780@i39g2000cwa.googlegroups.com> The generator is in its own scope. For proof, try accessing q outside the generator. There are two possibilities. The first is that you don't know what closures are and are complaining that python has them. That would be amusingly ironic, but I'm guessing you do know (if you don't, google "make_adder" and be enlightened) The second is that you don't like the late-binding behavior of generator expressions. PEP 289 has this to say: > After much discussion, it was decided that the first (outermost) > for-expression should be evaluated immediately and that the remaining > expressions be evaluated when the generator is executed. and: > After exploring many possibilities, a consensus emerged that [...] [for] > more complex applications, full generator definitions are always superior > in terms of being obvious about scope, lifetime, and binding And as an illustration of that last point, consider: def sieve_all(n = 100): # generate all primes up to n def filter_multiples(input, m): for q in input: if q % m != 0: yield q stream = iter(xrange(2, n)) while True: p = stream.next() yield p # this is now a redundant comment. # filter out all multiples of p from stream stream = filter_multiples(stream, p) p From bill.scherer at verizonwireless.com Wed May 31 13:15:03 2006 From: bill.scherer at verizonwireless.com (Bill Scherer) Date: Wed, 31 May 2006 13:15:03 -0400 Subject: Oracle Data Access in Python In-Reply-To: <NYOBGCEXSMTP20oghBe002072bb@nyobgcexsmtp20.uswin.ad.vzwcorp.com> References: <NYOBGCEXSMTP20oghBe002072bb@nyobgcexsmtp20.uswin.ad.vzwcorp.com> Message-ID: <447DCF17.7070100@verizonwireless.com> A.M wrote: > Hi, > > > > I am familiar with Perl's DBI programming. > > > > In Python, do we access to Oracle by using DBI? > No. > Is Oracle DBD driver included with Python distributions? > No. > What is the most common strategy for accessing to Oracle data through > Python? > cx_Oracle seems to be the leading module for Oracle access today. It works well. http://www.cxtools.net/default.aspx?nav=cxorlb You'll need the apropriate Oracle client installed for it to work, of course. Oracle's "Instant Client" is probably the easiest way to get what you need for that. Hope that helps, Bill From tdelaney at avaya.com Sun May 14 18:47:10 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Mon, 15 May 2006 08:47:10 +1000 Subject: count items in generator Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6EC@au3010avexu1.global.avaya.com> Delaney, Timothy (Tim) wrote: > Actually len(itertools.count()) would as well - when a couple of long > instances used up everything available - but it would take a *lot* > longer. Actually, this would depend on whether len(iterable) used a C integral variable to accumulate the length (which would roll over and never end) or a Python long (which would eventually use up all memory). Tim Delaney From deets at nospam.web.de Fri May 19 09:33:53 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 19 May 2006 15:33:53 +0200 Subject: noob import question References: <mailman.5945.1148045097.27775.python-list@python.org> Message-ID: <4d5vqaF18i4l1U1@uni-berlin.de> > I have tried to look up what is going on, but I have not found > anything. Would it be possible for someone to take a minute and give > an explanation? The from <module> import <*|nameslist> syntax imports some or all names found in <module> into the current modules namespace. Thus you can access your class. But if you do import <module> you only get <module> in your current namespace. So you need to access anything inside <module> by prefixing the expression. In your case, it is Student.Student If you only write Student, that in fact is the MODULE Student, which explains the error message. Now while this sounds as if the from <module> import * syntax is the way to go, you should refrain from that until you really know what you are doing (and you currently _don't_ know), as this can introduce subtle and difficult to debug bugs. If you don't want to write long module-names, you can alias them: import <moduel-with-long-name> as <shortname> And it seems as if you have some JAVA-background, putting one class in one file called the same as the class. Don't do that, it's a stupid restriction in JAVA and should be avoided in PYTHON. Diez From junkytownMAKNI at gmail.com Wed May 31 14:48:08 2006 From: junkytownMAKNI at gmail.com (SuperHik) Date: Wed, 31 May 2006 20:48:08 +0200 Subject: wx: PyNoAppError In-Reply-To: <447dc033$1@nntp0.pdx.net> References: <e5k664$bq$1@ss408.t-com.hr> <447dc033$1@nntp0.pdx.net> Message-ID: <e5kod9$i3f$1@ss408.t-com.hr> Scott David Daniels wrote: > SuperHik wrote: > > (1) A wxPython question. Better to ask on the wxPython newsgroup > (listed as comp.python.wxpython on gmane). I'm aware it's a wxPython question but I wasn't aware of the group you mentioned. Thank you! > >> Using XP SP2, PythonWin 2.4.3, any trying to use wx 2.6.3.2 >> When using wx, the first time I run a script it runs fine. >> Second time, it rasises an error: .... > Up here you should have mentioned you are doing this in IDLE, that is > your problem. > > Later in your message you say: >> ... *Says that runnig the script outside of IDLE fixes the problem. >> That works for me too but if there is a way to run it from IDLE >> that would be much easier. > > This is the inevitable result of running a pair of GUIs simultaneously: > They both want control of the main program to run their idle loop, and > only can win. I wasn't running them simultaneously. I ended the first (and only) one and then tried to start it again. > > --Scott David Daniels > scott.daniels at acm.org From sjmachin at lexicon.net Fri May 26 17:43:33 2006 From: sjmachin at lexicon.net (John Machin) Date: Sat, 27 May 2006 07:43:33 +1000 Subject: Speed up this code? In-Reply-To: <1148677047.168686.42580@g10g2000cwb.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <4476d3ac_2@newspeer2.tds.net> <1148647447.804097.228580@j33g2000cwa.googlegroups.com> <1148649951.816182.134210@g10g2000cwb.googlegroups.com> <1148656566.089446.159470@y43g2000cwc.googlegroups.com> <1148677047.168686.42580@g10g2000cwb.googlegroups.com> Message-ID: <44777685.80105@lexicon.net> On 27/05/2006 6:57 AM, bearophileHUGS at lycos.com wrote: > I have tried this comparison, with a version I've modified a bit, I > have encoutered a problem in sieve_all, for example with n=10000, I > don't know why: It might have been better use of bandwidth to give details of the problem instead of all that extraneous source code. Did you get this: """RuntimeError: maximum recursion depth exceeded"""? You don't know why? From brianc at temple.edu Fri May 12 14:25:30 2006 From: brianc at temple.edu (Brian Cole) Date: Fri, 12 May 2006 14:25:30 -0400 Subject: Broken essays on python.org Message-ID: <54b165660605121125h4faf9f7agadb0f2ee3db4683d@mail.gmail.com> I'm not sure if this is the proper place to post this... A lot of the essays at http://www.python.org/doc/essays/ have a messed up layout in Firefox and IE. -Brian From onurb at xiludom.gro Fri May 19 10:19:12 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 19 May 2006 16:19:12 +0200 Subject: [OT] noob import question In-Reply-To: <mailman.5946.1148046277.27775.python-list@python.org> References: <mailman.5945.1148045097.27775.python-list@python.org> <4d5vqaF18i4l1U1@uni-berlin.de> <mailman.5946.1148046277.27775.python-list@python.org> Message-ID: <446dd449$0$7616$636a55ce@news.free.fr> Brian Blazer wrote: <ot> please, dont top-post, and edit out irrelevant material </ot> > You are right, I do come from a Java background. Then you may want to read this: http://dirtsimple.org/2004/12/python-is-not-java.html HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From zlatko.matic1 at sb.t-com.hr Sat May 27 10:15:05 2006 From: zlatko.matic1 at sb.t-com.hr (tatamata) Date: Sat, 27 May 2006 16:15:05 +0200 Subject: starting some Python script from C# References: <e58ta7$jns$1@fegnews.vip.hr> <1148728940.440692.166330@i39g2000cwa.googlegroups.com> Message-ID: <e59mtc$rbi$1@fegnews.vip.hr> thanks. "Gerard Flanagan" <grflanagan at yahoo.co.uk> je napisao u poruci interesnoj grupi:1148728940.440692.166330 at i39g2000cwa.googlegroups.com... > tatamata wrote: >> Hello. >> >> How can I run some Python script within C# program? >> > > --------------------------------------------------------------------------------- > ProcessStartInfo startInfo; > Process process; > string directory; > string pyArgs; > string script; > > startInfo = new ProcessStartInfo("python"); > startInfo.WorkingDirectory = directory; > startInfo.Arguments = script + " " + pyArgs; > startInfo.UseShellExecute = false; > startInfo.CreateNoWindow = true; > startInfo.RedirectStandardOutput = true; > startInfo.RedirectStandardError = true; > > process = new Process(); > process.StartInfo = startInfo; > process.Start(); > > string s; > while ((s = process.StandardOutput.ReadLine()) != null) > { > //do something with s > } > --------------------------------------------------------------------------------- > > HTH > > Gerard > From onurb at xiludom.gro Tue May 9 04:17:00 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 10:17:00 +0200 Subject: Is this a good use of __metaclass__? In-Reply-To: <1146936973.992372.275310@u72g2000cwu.googlegroups.com> References: <e3f96d$3oi$1@news.lysator.liu.se> <445baf1a$0$2386$626a54ce@news.free.fr> <1146936973.992372.275310@u72g2000cwu.googlegroups.com> Message-ID: <4460505d$0$8317$626a54ce@news.free.fr> Joel.Hedlund at gmail.com wrote: > I played around with my old code before I saw your post, and I believe > I've found a solution that's a bit neater than what I had before. I > thought I could just as well post it if you're interested and have the > time. This one uses multiple inheritance, but it's legal and there's > only one metaclass. > (snip code) Seems quite clean. -- 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 May 31 08:36:09 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 May 2006 22:36:09 +1000 Subject: [OT] whitespace (was Re: stupid perl question) In-Reply-To: <6uA*vT1hr@news.chiark.greenend.org.uk> References: <44778C05.9020701@grads.ece.mcmaster.ca> <4477A74C.6080605@lexicon.net> <slrne7p8p8.2t1.grahn+nntp@frailea.sa.invalid> <447cdc3d@news.eftel.com> <6uA*vT1hr@news.chiark.greenend.org.uk> Message-ID: <447D8DB9.8070705@lexicon.net> On 31/05/2006 8:17 PM, Sion Arrowsmith wrote: > John Machin <sjmachin at lexicon.net> wrote: >> Whitespace is a silly term, anyway (IMHO); is there such a >> thing as a space that is not white? > > Yes, if you go back to the term's origins in printshops. A solid > block of ink is space, not print, but it's not whitespace. We've > kept the word alive, even if the meaning's drifted (see also "tab"). > And if we didn't say "whitespace", how would we distinguish between > "space characters" meaning " " and "whitespace characters" > meaning " \t\r\n\v"? (OK, has anyone met a "\v" in the wild?) > I've found a not-always-white space: U+1680 OGHAM SPACE MARK -- the glyph is non-blank in "stemmed" fonts. I'm surprised that one of the billions of people who use Ogham for day-to-day correspondence hasn't pointed this out to me already :-) Cheers, John From claird at lairds.us Mon May 8 15:10:27 2006 From: claird at lairds.us (Cameron Laird) Date: Mon, 8 May 2006 19:10:27 +0000 Subject: Python's DSLs (was: A critic of Guido's blog on Python's lambda) References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> Message-ID: <3mh4j3-9pm.ln1@lairds.us> In article <1hewvsx.11x9f301gbjrhqN%aleaxit at yahoo.com>, Alex Martelli <aleaxit at yahoo.com> wrote: . . . >Of course, the choice of Python does mean that, when we really truly >need a "domain specific little language", we have to implement it as a >language in its own right, rather than piggybacking it on top of a >general-purpose language as Lisp would no doubt afford; see ><http://labs.google.com/papers/sawzall.html> for such a DSLL developed >at Google. However, I think this tradeoff is worthwhile, and, in >particular, does not impede scaling. > > >Alex You lost me, Alex. I recognize that most of this thread has been far away, in the land of the anonymity of function definitions, and so on. I've redirected follow-ups to clp. On this one isolated matter, though, I'm confused, Alex: I sure think *I* have been writing DSLs as specializations of Python, and NOT as "a language in its own right". Have I been fooling myself, or are you making the point that Lisp-based DSLs live in a larger syntactic universe than Python's, or ...? From kentilton at gmail.com Wed May 24 10:22:28 2006 From: kentilton at gmail.com (Ken Tilton) Date: Wed, 24 May 2006 10:22:28 -0400 Subject: John Bokma harassment In-Reply-To: <e51kh4$t18$1@ml.accsnet.ne.jp> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> Message-ID: <R_Zcg.248$LO3.40@fe11.lga> Ben Bullock wrote: > "Xah Lee" <xah at xahlee.org> wrote in message > news:1148459377.384317.100730 at j73g2000cwa.googlegroups.com... > >> If you believe this lobbying to my webhosting provider is unjust, >> please write to my web hosting provider abuse at dreamhost.com > > > Why don't you just change your provider? It would take less time than this. Are you joking. "Just change your provider?" Do you have a little button on your computer that says "Change provider"? Cool! :) C'mon, John Bokma (and everyone else dumb enough to crosspost their shushing to every group on the crosspost list -- why do they do that? So Xah will hear them six times? No, they want everyone to see how witty they are when they tell Xah off. Now /that/ is spam) is the problem. kenny -- Cells: http://common-lisp.net/project/cells/ "Have you ever been in a relationship?" Attorney for Mary Winkler, confessed killer of her minister husband, when asked if the couple had marital problems. From cito at online.de Sun May 7 08:50:04 2006 From: cito at online.de (Christoph Zwerschke) Date: Sun, 07 May 2006 14:50:04 +0200 Subject: pygresql - bytea In-Reply-To: <44500ede$1@griseus.its.uu.se> References: <44500ede$1@griseus.its.uu.se> Message-ID: <e3kqdq$6ff$1@online.de> Jan Danielsson wrote: > I'm trying to use pygresql to insert binary data (type: bytea) into a > column (using postgresql, obviously). > ... > Does _anyone_ have a working example? A simple insertion, and a > simple select is all I'm looking for. You should better ask such questions on the PyGreSQL mailing list. Actually, you can insert and delete bytea data just as you would insert and select ordinary string data, with the exception that you have to escape the data before the insert, and unescape after select. For instance, the string 'a\x00b' must be inserted as 'a\\000b'. As a result from a select, you will get 'a\000b'. The next PyGreSQL version will have functions for escaping and unescaping on board (they are already checked in to CVS). -- Christoph From tim.leeuwvander at nl.unisys.com Thu May 11 07:40:01 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 11 May 2006 04:40:01 -0700 Subject: Python memory deallocate In-Reply-To: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> Message-ID: <1147347601.597292.15220@j73g2000cwa.googlegroups.com> Hi, 'del a' should remove 'a', as a reference to the tuple created by the 'range' function. If that is also the last reference, it can now be garbage-collected. Of course, the question is if you really need to allocate such a big amount of memory. If you just need to iterate over some numbers, it's better to use 'xrange' instead of 'range': 'xrange' will not create the whole list of numbers in advance, but will create an iterator, producing the desired numbers one by one. With such large ranges, this will reduce memory consumption significantly. Cheers, --Tim From merrigan at merrigan.za.net Mon May 1 15:53:10 2006 From: merrigan at merrigan.za.net (Merrigan Took) Date: Mon, 01 May 2006 21:53:10 +0200 Subject: How do I take a directory name from a given dir? In-Reply-To: <mailman.5190.1146513086.27775.python-list@python.org> References: <1146512578.301649.319050@j33g2000cwa.googlegroups.com> <mailman.5190.1146513086.27775.python-list@python.org> Message-ID: <e35ouk$j9$1@ctb-nnrp2.saix.net> Daniel Nogradi wrote: >> Hi, >> >> I am trying to write a script to backup all my company's server configs >> weekly. The script will run in a cronjob, on whatever I set it. >> >> The issue I am currently having isto "extract" the directory name from >> a given directory string. For example: from the string >> "/home/testuser/projects/" I need to extract the "projects" part. The >> problem is that the directory names that needs to be used will never be >> the same lenght, so as far as my (very limited) knowledge stretches, >> slicing and indicing is out of the question. >> >> Can anybody help me, or give me an idea of what I should look at, >> seeing as I'm seriously stuck. I only started coding at the beginnig of >> the year, and was never interested before that, so my knowlege is >> basically non-existent. > > You can try this: > >>>> '/home/testuser/projects/'.strip( '/' ).split( '/' ) > ['home', 'testuser', 'projects'] > > strip gets rid of the first and last / and split splits the remaining > part and puts the results into a list. > > HTH :) AAAAh, ok, Thank you, I will definitely look into this and play with it! From deets at nospam.web.de Thu May 11 08:28:55 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Thu, 11 May 2006 14:28:55 +0200 Subject: Python memory deallocate References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com> Message-ID: <4cgp12F15jpmlU1@uni-berlin.de> mariano.difelice at gmail.com wrote: > Hi, > I've a big memory problem with my application. > > First, an example: > > If I write: > > a = range(500*1024) > > I see that python process allocate approximately 80Mb of memory. > What can i do for DEALLOCATE this memory, or good part of this? > > My really problem is that my program work with more photos, which I > open with PIL package. > When I start it, my program allocate approximately 200Mb memory. > > If I want abort actual work and restart without restarting python > process, the memory usage will go up approximately 380-400 Mb. > > I would like find something that DEallocate the memory not used. > > I've tried with gc python module, but don't work fine (it deallocate > approximately 20-30 Mb) > I've tried with Destroy, del command, but the memory don't show down. > > Thx > > I'm very desperate No need to. Just because the process seems to be that large doesn't mean that there is so much memory consumed by python. It's just that modern OSs will not correctly display the amount of memory really consumed, as they aren't too eager to remove once allocated virtual memory a process has been granted. I guess it's an optimization scheme. For example if I do >>> a = range(500*1024 * 50) the VmSize of the python process grows to 500MB. If I issue an >>> del a it shrinks to 300MB. The reissuing >>> a = range(500*1024 * 50) will make it grow - but only to about 400MB. Then I do >>> del a >>> a = [chr(i % 255) for i in xrange(500*1024 * 50)] This time I used strings, to circumvene some internal caching python might do on numbers. Yet still - the overall VmSize is 400MB Bottomline: don't get confused by tsakmanagers memory size display. You only have to be concerned when the consumption steadily grows - which indicates a memory leak. Diez From john at castleamber.com Sat May 6 01:44:47 2006 From: john at castleamber.com (John Bokma) Date: 6 May 2006 05:44:47 GMT Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <pan.2006.05.06.01.59.38.15904@gmail.com> <o%U6g.2569$VV2.182325@news20.bellglobal.com> Message-ID: <Xns97BB7985CF1Ccastleamber@130.133.1.4> "Rhino" <no.offline.contact.please at nospam.com> wrote: > What does any of this have to do with Java? Xah Lee is well known for abusing Usenet for quite some time, report his posts as excessive crossposts to: abuse at bcglobal dot net abuse at dreamhost dot com IIRC this is his third ISP account in 2 weeks, so it *does* work. Moreover, his current hosting provider, dreamhost, might drop him soon. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From danb_83 at yahoo.com Mon May 1 04:13:32 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 1 May 2006 01:13:32 -0700 Subject: ending a string with a backslash References: <445546c8$0$13341$c3e8da3@news.astraweb.com> Message-ID: <1146471212.817684.258290@j73g2000cwa.googlegroups.com> John Salerno wrote: > I have this: > > subdomain = raw_input('Enter subdomain name: ') > > path = r'C:\Documents and Settings\John Salerno\My Documents\My > Webs\1and1\johnjsalerno.com\' + subdomain > > Obviously the single backslash at the end of 'path' will cause a > problem, and escaping it with a backslash seems to fix this problem, but > how does escaping work when I already have it as a raw string? When I > test it out and then print string, I get something like this: > > C:\Documents and Settings\John Salerno\My Documents\My > Webs\1and1\johnjsalerno.com\\test > > But I don't see how this is valid, since all the backslashes are single > (which is correct) except the last one. Somehow this still works when I > tried to create the new directory -- os.mkdir(path) -- but I wasn't sure > if this is the right way to go about it, or if there is some other, > better way to handle the final backslash. As others have stated, you can use a forward slash. Alternatively, you can write: >>> r'This\string\contains\backslashes' '\\' 'This\\string\\contains\\backslashes\\' From Serge.Orlov at gmail.com Fri May 19 02:04:09 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 18 May 2006 23:04:09 -0700 Subject: import woe References: <1148016083.020020.40660@u72g2000cwu.googlegroups.com> Message-ID: <1148018649.414492.60490@j55g2000cwa.googlegroups.com> gsocks at gmail.com wrote: > hello, > > i have a problem. i would like to import python files above and below > my current directory. > > i'm working on /home/foo/bar/jar.py > > i would like to import /home/foo/car.py and > /home/foo/bar/far.py > > how can i do this? $ cat >>~/.bashrc export PATH=/home/foo/:$PATH $ cat >/home/foo/application #!/usr/bin/env python import bar.jar $ chmod +x /home/foo/application $ cd /home/foo/bar $ application .... all imports work fine ... > ps: i want to scale, so i do not want to edit the python path In what sense do you want to scale, working with multiple projects or multiple versions of one project at the same time? Anyway you are to quick to jump to conclusions, if you don't want to edit python path who will do it for you? Python path won't appear out of thin air if your file layout is not supported out of the box. From dacut at kanga.org Mon May 22 03:15:54 2006 From: dacut at kanga.org (David Cuthbert) Date: Mon, 22 May 2006 00:15:54 -0700 Subject: Using python for a CAD program In-Reply-To: <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <446a557b$0$22979$c83e3ef6@nn1-read.tele2.net> <e4ham3$1td$1@sea.gmane.org> <446C8950.3070107@anansispaceworks.com> <mailman.6000.1148109587.27775.python-list@python.org> <4470ce0e$0$22978$c83e3ef6@nn1-read.tele2.net> Message-ID: <e4rofb$kcq$1@sea.gmane.org> baalbek wrote: > No, concurrent access is highly relevant; for example, on a team of > about 50 architects working on design and production drawings for a new > hospital, each floor was one 'drawing' (dwg file), and thus stored on > disk as a separate entity from the other floors. > > Now, only one architect could work on one floor at any time! And as info > from the project goes (sums and statistics of data, for example areas), > the only reliable (an efficient) way to gather this was to hack an > in-house application that collected the desired info from the various > binary dwgs stored on disk, and saved this data this to a RDBMS, for > further report processing. You have two orthogonal thoughts going here. It makes sense to collect statistics from a given drawing into an RDBMS in such a way that, whenever a design is checked in, the statistics are synched with the RDBMS. Further, such a system could (and should) make sure that no previous checkin has been clobbered. This is a classic source control system. I'd be surprised if there aren't plenty of add-ons which do this. At Cadence, we provided hooks for such systems to automatically collect necessary information. This does not mean the design itself should be stored as an RDBMS. As I've stated previously, CAD data (both electrical and, it appears, mechanical) does not lend itself to RDBMS relationship modeling. What you want is an easy way to manage the information, not dictate the storage format of the information. > And just to work on one small area of a huge floor, the architect has to > load the whole freaking floor... I don't have any architectural experience, so I can't say whether this makes sense or not. However, I think of this as being akin to complaining, "Just to edit a single function, I have to load the entire source file/check out the entire module/rebuild and rerun all the tests!" Not that this is necessarily an invalid idea. However, my experience with Cadence's tools makes me believe the existing behavior might just be the lesser of two evils. CDBA has a strict library/cell/view hierarchy; the checkout granularity here is (usually) at the view level (that is, when you lock a design, you're locking the view). Two designers could edit two different cells or views in the same library. This leads to all kinds of data inconsistency problems -- cell borders aren't lining up in a layout, for example, or the cached data isn't valid, etc. It's a nightmare. The newer OpenAccess system has an option to manage this at the library level. Unfortunately, this is rarely enabled due to backwards compatibility. From chris.uppal at metagnostic.REMOVE-THIS.org Tue May 9 05:46:13 2006 From: chris.uppal at metagnostic.REMOVE-THIS.org (Chris Uppal) Date: Tue, 9 May 2006 10:46:13 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <m2iroiupef.fsf@Dagney.local> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <m2ac9tvcm1.fsf@Dagney.local> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> Message-ID: <44606502$2$645$bed64819@news.gradwell.net> Alex Martelli wrote: > I think it's reasonable to make a name a part of functions, classes and > modules because they may often be involved in tracebacks (in case of > uncaught errors): to me, it makes sense to let an error-diagnosing > tracebacks display packages, modules, classes and functions/methods > involved in the chain of calls leading to the point of error _by name_. It seems to me that there's something of a circularity here. Either in your logic if applied to language design in general, or as a self-perpetuating habit when applied to Python in particular. The assumption is that functions are in some sense rather "big" things -- that each function performs a well-defined action which can be understood in isolation. That may well be true in idiomatically written Python (I've never cared for the look of the language myself, so I don't know what's considered "normal"), but it isn't true in general. With the assumption, it makes sense to say that every function /could/ have a name, and so, why not /give/ it a name ? But without the assumption, when many little anonymous functions are used, the idea of giving them all names appears pettifogging to the point of idiocy. If the language and/or culture expects that all/most functions will be named, then "little" functions (in my sense) won't be used; hence the self-perpetuating habit. But I don't think that the underlying logic supports that habit independently of its own self-perpetuating nature. E.g. consider the Smalltalk code (assumed to be the body of a method): aCollection do: [:each | each > 0 ifTrue: [^ true]]. ^ false. which iterates over a collection checking to see if any element is > 0. If so then the method answers true ("^" -- spelled "return" in Java), otherwise it answers false. In that code, [^ true] is syntactically and semantically an anonymous function, which is only invoked if the antecedent is true (in point of fact the compiler inlines that function away but I don't think that's relevant here). The passage beginning [:each | ... and reaching to the matching ] is also an anonymous function with one parameter (each) which is applied to each element of the collection in turn. (In this case it really is an anonymous function, even at the implementation level.) What "name" would you give to either of them ? I don't believe that /any/ name is possible, and certainly that no name is desirable. In my working Smalltalk environment today, there are 60099 methods defined across 3369 classes. In that codebase there are 38112 anonymous functions. Do you really want to have to find names for them all ? -- chris From rick446 at NOSPAM.usa.net Wed May 17 12:58:04 2006 From: rick446 at NOSPAM.usa.net (Richard Copeland) Date: Wed, 17 May 2006 12:58:04 -0400 Subject: How to customize getattr(obj, prop) function ? In-Reply-To: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> References: <1147884283.009533.300350@j33g2000cwa.googlegroups.com> Message-ID: <9bKdnakiGs9Cy_bZRVn-qw@comcast.com> Try this: class Class: a='aa' b='bb' def __getattr__(self, ppt): return 'custom computed result' __getattr__ is only called when "normal" attribute lookup fails, so there's no need for the "hasattr" test. Also, I believe that __getattribute__ only applies to new-style classes (classes derived from "object"), and it will override *all* attribute accesses, anyway (meaning you'd have infinite recursion if you used it since you look up "self.ppt") Pierre wrote: > Hi, > > Sorry in advance, english is not my main language :/ > > I'd like to customize the result obtained by getattr on an object : if > the object has the requested property then return it BUT if the object > doesn't has actually this property return something else. > > In my case, I can't use getattr(object, property, default_value). > > I tried to write a class with a __getattr__ method and even a > __getattribute__ method but this doesn't do what I want.... > > Maybe I didn't correctly understand this : > http://docs.python.org/ref/attribute-access.html > > Here is a piece of my code : > ===================================== > class myclass: > """docstring""" > > a = 'aa' > b = 'bb' > > def __getattr___(self, ppt): > """getattr""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" > > def __getattribute__(self, ppt): > """getattribute""" > if hasattr(self, ppt): > return self.ppt > else: > return "my custom computed result" > > if __name__ == "__main__": > > d = myclass() > p1 = getattr(d, "a") > print p1 > p2 = getattr(d, "b") > print p2 > p3 = getattr(d, "c") > print p3 > ================================ > > I get an AttributeError when accessing to the property named "c". > > Any explanation/solution to my problem ? > From telesphore4 at gmail.com Wed May 17 11:22:26 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 17 May 2006 08:22:26 -0700 Subject: A better way of making subsclassing of built-in types stick for attributes? References: <1147839432.816504.318290@38g2000cwa.googlegroups.com> <mailman.5805.1147875117.27775.python-list@python.org> Message-ID: <1147879346.938720.239850@y43g2000cwc.googlegroups.com> Maric Michaud wrote: > Le Mercredi 17 Mai 2006 06:17, telesphore4 at gmail.com a ?crit : > > I want the fact that the fields are > > not strings to be invisible to the client programmers. > You should use properties then. I started with that idea, using the recipie 20.2 from the cookbook. However, this caused a fair amount of code bloat... Err the way I implemented it did at least. I may be missing a way to regularize the process and make the whole process cleaner too. The problem was that I needed to set the properties for all of the object fields with boilerplate code that looks very much the same. Even if the boilerplate was small, it was still bigger than the one-line descriptor definitions at the bottom of the module. Shrinking the descriptor definitions to a one-liner shrunk the code by a fair bit. There are many classes (100+ when I'm done) and some of them have a fair number of fields (up to 50) and all of them have to have the snazzyStr abilities. Another problem was esthetics; it forces me to place the main class at the bottom of the module after the definition of the supporting classes. Putting the descriptors after the bottom of the module left the important parts at the top where they should be, IMO. I wanted to use supporting classes for the field definitions because it allowed me to use mix-ins. This was the biggest win in the design. Thanks t4 From Zac.Daniel at gmail.com Tue May 2 20:17:54 2006 From: Zac.Daniel at gmail.com (Jack) Date: 2 May 2006 17:17:54 -0700 Subject: Binary File Reading : Metastock Message-ID: <1146615474.410864.52950@g10g2000cwb.googlegroups.com> Hi I am having a little trouble trying to read a binary file, I would like to write an ascii to Metastock converter in python but am not having a lot of success. The file formats are http://sf.gds.tuwien.ac.at/00-pdf/m/mstockfl/MetaStock.pdf If any one can point me in the right direction it would be much appreciated. So far I have tried opening file "rb" then trying to use struct and then binascii but I am not too sure what I should be doing and fuction I should be using in binascii ? TIA From tjgolden at gmail.com Sun May 14 09:35:22 2006 From: tjgolden at gmail.com (Tim Golden) Date: 14 May 2006 06:35:22 -0700 Subject: any plans to make pprint() a builtin? In-Reply-To: <Xns97C3667B2DA19duncanbooth@127.0.0.1> References: <44669e46$0$5337$c3e8da3@news.astraweb.com> <Xns97C3667B2DA19duncanbooth@127.0.0.1> Message-ID: <1147613722.812929.23760@j73g2000cwa.googlegroups.com> Duncan Booth wrote: > John Salerno wrote: > > > Just wondering if this will ever happen, maybe in 3.0 when print becomes > > a function too? It would be a nice option to have it available without > > importing it every time, but maybe making it a builtin violates some > > kind of pythonic ideal? > > There are so many things which *could* be builtins, and it really is better > not to pollute the global namespace with more than absolutely necessary. > > Personally I'd just like to see 'python' a builtin shorthand for importing > a name you aren't going to use much > e.g. > > python.pprint.pprint(x) I think that's what the py.lib people have done with their py.std module: http://codespeak.net/py/current/doc/misc.html#the-py-std-hook (At least, it looks like it; I've never used it myself). TJG From onurb at xiludom.gro Wed May 3 05:06:58 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 11:06:58 +0200 Subject: Zope Guru... In-Reply-To: <mailman.5251.1146641484.27775.python-list@python.org> References: <mailman.5251.1146641484.27775.python-list@python.org> Message-ID: <4458730d$0$16424$626a54ce@news.free.fr> bruce wrote: > Hi.. > > In doing some research into Workflow apps regarding document management, I > came across Zope. Given that it's Python Based, I figured I'd shout to the > group here... Zope is Python based, but it's a world in itself, and probably not the most pythonic app around (which doesn't implie it's a bad app !-). > Are there any Zope gurus that I can talk to regarding Zope, Zope's mailing lists would be a better choice. > and what it > does/how it works? http://www.zope.org For short : Zope is an object-oriented web application server. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From johnjsal at NOSPAMgmail.com Mon May 8 10:52:01 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 14:52:01 GMT Subject: regular expressions, substituting and adding in one step? In-Reply-To: <yEI7g.2056$No6.45379@news.tufts.edu> References: <yEI7g.2056$No6.45379@news.tufts.edu> Message-ID: <lWI7g.2057$No6.45709@news.tufts.edu> John Salerno wrote: > So the questions are, how do you use regular expressions to add text to > the end of a line, even if you aren't matching the end of the line in > the first place? Or does that entail using separate regexes that *do* do > this? If the latter, how do I retain the value of the groups taken from > the first re? Here's what I have so far: ----------- import re txt_file = open(r'C:\Python24\myscripts\re_test.txt') new_string = re.sub(r"' \+ ([a-z]+) \+ '", '%s', txt_file.read()) new_string = re.sub(r'$', ' % paragraph', new_string) txt_file.close() ----------- re_test.txt contains: self.source += '<p>' + paragraph + '</p>\n\n' Both substitutions work, but now I just need to figure out how to replace the hard-coded ' % paragraph' parameter with something that uses the group taken from the first regex. I'm guessing if I don't use it at that time, then it's lost. I suppose I could create a MatchObject and save group(1) as a variable for later use, but that would be a lot of extra steps, so I wanted to see if there's a way to do it all at one time with regular expressions. Thanks. From mblume at socha.net Fri May 5 11:16:36 2006 From: mblume at socha.net (Martin Blume) Date: Fri, 5 May 2006 17:16:36 +0200 Subject: Is this a legal / acceptable statement ? References: <2AI6g.10201$9c6.5375@dukeread11> Message-ID: <445b6bca$0$13576$5402220f@news.sunrise.ch> "Philippe Martin" schrieb > Hi, > > This code works, but is it "appropriate" ? > > l_init = False > > if True == l_init and 1234 = l_value: > print 'l_value is initialized' > > I know I can do this with a try but ... > I am a Python newbie, but I think working with l_value = None would be the most pythonic way. C:\>c:\programme\python\python Python 2.4 (#60, Nov 30 2004, 11:49:19) [MSC v.1310 32 bit (Intel)] on win32 Type "help", "copyright", "credits" or "license" for more information. >>> v = None >>> x = 2 >>> x 2 >>> v >>> v_default=3 >>> y = x + (v or v_default) >>> y 5 >>> v = 6 >>> y = x + (v or v_default) >>> y 8 >>> v = None >>> y = x + (v or v_default) >>> y 5 >>> Of course in a function you can use: def travel_time(from, to, speed=60): pass and if travel_time is called travel_time(a,b,1000) the speed will be 1000 and if travel_time is called travel_time(a,b) the speed will be 60 IMHO. Martin From tim.peters at gmail.com Fri May 5 00:24:43 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 5 May 2006 00:24:43 -0400 Subject: Using time.sleep() in 2 threads causes lockup when hyper-threading is enabled In-Reply-To: <1146707567.506771.327490@i40g2000cwc.googlegroups.com> References: <1146681728.015020.26050@i39g2000cwa.googlegroups.com> <1146689031.533474.320570@v46g2000cwv.googlegroups.com> <1146689930.600243.65340@v46g2000cwv.googlegroups.com> <mailman.5282.1146692801.27775.python-list@python.org> <1146707567.506771.327490@i40g2000cwc.googlegroups.com> Message-ID: <1f7befae0605042124k504ba721r787045e172da4880@mail.gmail.com> [Tim Peters] >> I didn't run it for hours ;-) [OlafMeding at gmail.com] > Please try. OK, I let the first test program run for over 24 hours by now. It never hung. Overnight, the box did go into sleep mode, but the test woke itself up after sleep mode ended, and the threads reported they were sleeping for about 8 hours then. I did this under a debug build of Python, so that if it did hang I'd have _some_chance of getting useful info from the VC 7.1 debugger. It's possible (but unlikely) that using a debug-build Python prevented a hang that would have occurred had I used a release-build Python. > The sleep statement does not return! And this should not happen. The > code above does nothing special or unusual. The problem only occurs if > 2 threads use the sleep statement and hyper-threading is enabled. > > We discovered this bug perhaps a year ago. The only solution was to > tell our customers to disable hyper-threading (you can imagine they did > not like our "solution" very much). It then took many days of hard > work to isolate the problem down to the code I posted above. As before, since Python merely calls the Win32 API Sleep() function, it's extremely unlikely that the problem is due to Python. It's quite possible that the problem is due to a tiny timing hole in MS's implementation of Sleep(). Since I don't have the source code for that, and disassembling is prohibited by my license ;-), I can't pursue that. I've seen software with honest-to-God thread-race bugs that were never reported across years of heavy production use, until a user tried the code on a hyper-threaded or multi-core box. Tiny timing holes can be _extremely_ shy, and running on a box with true, or even just finer-grained (like HT), concurrency can make them much more likely to appear. I've never seen a software failure with (eventually) known cause occur on an HT box that could not have happened on a non-HT box. The statistics of extremely unlikely events aren't a natural fit to the unabused human mind ;-) > ... > Once the application locks up (getting stuck in a sleep statement) all > comes back to live if I pull the network cable out. So perhaps the > socket thread returns from the sleep statement and other threads return > to live because they were waiting for the socket thread. That's peculiar. time.sleep() called from a thread other than the main thread on Windows is non-interruptable (because the Windows Sleep() function is non-interruptable). time.sleep() called from the main thread on Windows _is_ interruptable: the main thread uses the Win32 API WaitForSingleObject() instead, passing a handle to a custom interrupt event; the _intent_ is so that a time.sleep() in the main thread can be aborted by a keyboard interrupt. But it shouldn't be possible for anything other than a keyboard interrupt or a normal (timeout) return to knock that loose. So if unplugging the cable knocks things lose, that just points even stronger at a bug in the Windows kernel. > Our software runs on both Windows and Linux. We are not sure if the > problem also happens on Linux. Well, I ran your test for a day on my Windows box -- you try running it for a week on your Linux box ;-) > ... > We have searched the Internet far and wide and were not able to find > any information that indicates that someone else has reported a similar > problem (neither Python nor Windows Sleep related). I'm pretty sure I would have known about it if anyone reported such a Python bug in the last 15 years. But this is the first time I've heard it. I don't keep up with Microsoft bug reports at all. From ttdevelop at gmail.com Tue May 2 20:51:54 2006 From: ttdevelop at gmail.com (Tim) Date: 2 May 2006 17:51:54 -0700 Subject: 345 free programming books In-Reply-To: <mailman.4996.1146021905.27775.python-list@python.org> References: <1146020222.383927.319890@i40g2000cwc.googlegroups.com> <e2moue$vaa$1@sea.gmane.org> <mailman.4996.1146021905.27775.python-list@python.org> Message-ID: <1146617514.168901.31540@i40g2000cwc.googlegroups.com> Thanks for notification... I am still working on to find new books...................... Time....time...so little time.... From robert.kern at gmail.com Tue May 9 15:25:27 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 May 2006 14:25:27 -0500 Subject: installing numpy In-Reply-To: <20060509120715.GB20063@torf.workaround.org> References: <877j4v5ukc.fsf@localhost.localdomain> <mailman.5505.1147174470.27775.python-list@python.org> <873bfj5sp5.fsf@localhost.localdomain> <20060509120715.GB20063@torf.workaround.org> Message-ID: <e3qqb8$vpk$1@sea.gmane.org> Christoph Haas wrote: > P.S.: Your mail client seems break the references. Your reply doesn't show > up as a proper followup to my posting. This probably has nothing to do with his mail/news client but rather the mail-news gateway that links python-list and comp.lang.python . -- 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 tjreedy at udel.edu Fri May 26 14:43:48 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Fri, 26 May 2006 14:43:48 -0400 Subject: chop() and empty() functions References: <1148662460.2149.20.camel@localhost.localdomain> Message-ID: <e57i93$gd0$1@sea.gmane.org> "Jeremy L. Moles" <jeremy at emperorlinux.com> wrote in message news:1148662460.2149.20.camel at localhost.localdomain... > Furthermore, what do people think about the idea of adding a truly > empty, no-op global lambda somewhere in Python? In an important sense, there is no such object as a 'lambda' in Python. There are only function objects created with lambda expressions, which are pretty much abbreviations of simple def statements. > I use them a lot For what? > (usually defining a: empty = lambda *a, **k: None somewhere at the > topmost module space), Better to write 'def empty(*a,**k): pass' since this requires fewer keystrokes, attached the specific name 'empty' to the function object instead of the generic pseudoname '<lambda>', and does not feed the misunderstanding of lambda expressions. > but if enough people did too, it might be worth > adding an empty() builtin to much later versions of Python. This seems to be a rare need, at least as expressed on clp. Terry Jan Reedy From bignose+hates-spam at benfinney.id.au Sun May 21 19:20:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Mon, 22 May 2006 09:20:20 +1000 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <slrne6rran.mt4.sybrenUSE@schuimige.stuvel.eu> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <mailman.6024.1148200750.27775.python-list@python.org> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <R75cg.439214$5F6.11691037@phobos.telenet-ops.be> <1148251070.320923.65710@38g2000cwa.googlegroups.com> Message-ID: <877j4f3qyz.fsf@benfinney.id.au> "SamFeltus" <sam at nuevageorgia.com> writes: > I keep trying to understand why people like HTML/JS, I don't think I > am gonna understand. It's fairly simple: HTML, CSS and JavaScript have all been standardised independent of any single corporation, and are freely implementable, resulting in competing free software implementations. We can choose or improve upon the implementation we like, or make our own, and share the result with others. > I guess for better or worse, Flash is a very different mindset and > approach to the web. One that shares none of the above qualities. -- \ "If you ever teach a yodeling class, probably the hardest thing | `\ is to keep the students from just trying to yodel right off. | _o__) You see, we build to that." -- Jack Handey | Ben Finney From peace.is.our.profession at gmx.de Sat May 13 09:17:41 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Sat, 13 May 2006 15:17:41 +0200 Subject: reusing parts of a string in RE matches? In-Reply-To: <mailman.5618.1147423740.27775.python-list@python.org> References: <YMm8g.2077$No6.45935@news.tufts.edu><mailman.5557.1147274047.27775.python-list@python.org><M2o8g.2080$No6.45875@news.tufts.edu><1147283334.610613.220770@j33g2000cwa.googlegroups.com><whq8g.2082$No6.45965@news.tufts.edu><1147287162.914661.237370@i39g2000cwa.googlegroups.com><E6r8g.2083$No6.45931@news.tufts.edu><eir8g.2084$No6.45965@news.tufts.edu><1147291197.423570.242440@g10g2000cwb.googlegroups.com><e3v387$9tt$1@mlucom4.urz.uni-halle.de><GGH8g.2085$No6.45839@news.tufts.edu><e3vikl$ecv$1@mlucom4.urz.uni-halle.de><eRI8g.2087$No6.45924@news.tufts.edu> <e408o5$kta$1@mlucom4.urz.uni-halle.de> <mailman.5618.1147423740.27775.python-list@python.org> Message-ID: <e44mgc$2hl$1@mlucom4.urz.uni-halle.de> Hi Fredrik you brought up some terse and somehow expressive lines with their own beauty ... > [this] is best done by a list comprehension: > l = [m[1] for m in re.findall(r, t)] > > or, [...] a generator expression: > g = (m[1] for m in re.findall(r, t)) > > or > process(m[1] for m in re.findall(r, t)) > > ... avoid creating the tuples, ... finditer instead: > l = [m.group(2) for m in re.finditer(r, t)] > g = (m.group(2) for m in re.finditer(r, t)) > > finditer is also a good tool to use > for m in re.finditer(r, t): > s = m.group(2) > ... process s in some way ... ... which made me wish to internalize such wisdom too ;-) This looks almost beautiful, it made me stand up and go to some large book stores in order to grab a good book on python. Sadly, there were none (except one small 'dictionary', ISBN: 3826615123). I live in a fairly large city in Germany w/three large bookstores in the center, where one can get loads of PHP and Java books, lots of C/C++ and the like - even some Ruby books (some "Rails" too) on display (WTF). Not that I wouldn't order books (I do that all the time for 'original versions') but it makes one sad-faced to see the small impact of the Python language here today on bookstore-tournarounds ... Thanks & regards Mirco From onurb at xiludom.gro Fri May 5 08:31:07 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 14:31:07 +0200 Subject: String Exceptions (PEP 352) In-Reply-To: <7xhd4ckl3n.fsf@ruckus.brouhaha.com> References: <pan.2006.04.27.14.18.41.758387@thomas-guettler.de> <4450d844$0$27293$626a54ce@news.free.fr> <7xhd4ckl3n.fsf@ruckus.brouhaha.com> Message-ID: <445b45e8$0$30081$636a55ce@news.free.fr> Paul Rubin wrote: > bruno at modulix <onurb at xiludom.gro> writes: > >>What's wrong with: >> >>assert foo and bar and i > 10, \ >> "if foo and bar i must not be greater than 10" > > > It doesn't necessarily do anything. With optimization enable, assert > is a no-op. quoting the OP (emphasis is mine): """ I use string exceptions if the condition for an *assertion* is to complex: """ -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From antroy at gmail.com Wed May 24 05:43:03 2006 From: antroy at gmail.com (Ant) Date: 24 May 2006 02:43:03 -0700 Subject: John Bokma harassment In-Reply-To: <1148459377.384317.100730@j73g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> Message-ID: <1148463783.812253.248100@u72g2000cwu.googlegroups.com> >From my point of view, this issue has two sides: 1) Xah is posting to the newgroups valid topics for discussion - if some find these controversial, then all the better: it means that the topic has provoked some thought. You only need to look at the quantity of Xah's threads to see how popular they are (even if you filter out the "you're in my kill file", or "plonk" style spam that some people feel the need to post) 2) Xah cross posted the posts to several newsgroups he has an interest in. Now this second point should be the only factor for reporting him to his ISP. Given that it has gone this far, wouldn't it be fair to give the guy a break on the condition that if he wants to post to a variety of newgroups, that he does it individually rather than as a cross post? -- Ant... From roy at panix.com Wed May 24 07:59:05 2006 From: roy at panix.com (Roy Smith) Date: Wed, 24 May 2006 07:59:05 -0400 Subject: Best way to handle exceptions with try/finally References: <mailman.6122.1148413632.27775.python-list@python.org> Message-ID: <roy-C36BC1.07590524052006@reader1.panix.com> "Carl J. Van Arsdall" <cvanarsdall at mvista.com> wrote: > class Shared: > def __init__(self): > self.__userData= {} > self.__mutex = threading.Lock() #lock object > > def getVar(self, variableName): > temp = None > error = 0 > self.__mutex.acquire() #accessing shared dictionary > try: > try: > temp = self.__userData[variableName] > except: > print "Variable doesn't exist in shared space" > raise ValueError > finally: > self.__mutex.release() > return temp A few comments on this. First, it's almost always a bad idea to have a bare "except:", because that catches *every* possible exception. You want to catch as specific an exception as you can (in this case, I suspect that's KeyError). Second, I'm not sure if your intent was to return from the function or to raise an exception on an unknown variableName. You can't do both! Quoting from http://docs.python.org/ref/try.html.. > When an exception occurs in the try clause, the exception is temporarily > saved, the finally clause is executed, and then the saved exception is > re-raised. If the finally clause raises another exception or executes a > return or break statement, the saved exception is lost. so with the code you posted (from sight; I haven't tried running it), what will happen is: 1) __userData[variableName] raises KeyError 2) The KeyError is caught by the inner try block and the except block runs, which in turn raises ValueError 3) The ValueError is caught by the outer try block and the finally block runs, releasing the mutex, discarding the ValueError exception, and returning temp 4) Whoever called getVar() will see a normal return, with a return value of None (because that's what temp was set to in the first line of getVar() From bdesth.quelquechose at free.quelquepart.fr Sat May 27 19:17:34 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 May 2006 01:17:34 +0200 Subject: Go "help" the perl list instead Fredrik Lundh In-Reply-To: <jbednXMRKL1RgOvZRVn-qQ@comcast.com> References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> <mailman.6205.1148585963.27775.python-list@python.org> <jbednXMRKL1RgOvZRVn-qQ@comcast.com> Message-ID: <4478aead$0$21272$626a54ce@news.free.fr> D H a ?crit : > Fredrik Lundh wrote: > >> vbgunz wrote: >> >>>> I have new a list , when it hava large number of values, I wonna to >>>> delete all the values in it,how to do? >>> >>> >>> something like this will probably help. >>> >>> x = [1,2,3,4,5,6,7,8,9] >>> y = x >>> >>> list([x.pop() for z in xrange(len(x))]) >>> >>> print x, y # [] [] >> >> >> if you don't know how to do things, you don't need to post. >> >> if you know why this is about the dumbest way to do what you're doing, >> and you're posted this on purpose, you really need to grow up. >> >> </F> > > > He already posted before your post that he made a mistake. Not the same one. Or there are missing posts on my provider's usenet service. > You obviously ignored that and invented some argument that he > posted with malicious intentions. Fredrik may have been a bit harsh, but the fact is that vbgunz's solution for clearing a list *is* the dumbest possible - and it should be obvious for anyone past CS101. Now since a lot of Python newbies read this newsgroup, uncorrected bad answers are far worse than no answer at all. > That better describes most of > your thousands of annoying posts. Fredrik - aka the effbot - is a Python expert, and a major contributor here. He's known to be usually very helpful, even for questions that are in the Fine Manual or in the FAQs. I'm afraid you can say so. You may not like the way he corrected vbgunz - and I'll wholefully agree on this - but this last sentence is total bullshit. From mc79 at cse.buffalo.edu Mon May 1 10:28:14 2006 From: mc79 at cse.buffalo.edu (Madhusudhanan Chandrasekaran) Date: Mon, 1 May 2006 10:28:14 -0400 Subject: regd efficient methods to manipulate *large* files Message-ID: <Pine.SOL.4.56.0605011012270.13646@pollux.cse.buffalo.edu> Hi: This question is not directed "entirely" at python only. But since I want to know how to do it in python, I am posting here. I am constructing a huge matrix (m x n), whose columns n are stored in smaller files. Once I read m such files, my matrix is complete. I want to pass this matrix as an input to another script of mine (I just have the binary.) Currently, the script reads a file (which is nothing but the matrix) and processes it. Is there any way of doing this in memory, without writing the matrix onto the disk? Since I have to repeat my experimentation for multiple iterations, it becomes expensive to write the matrix onto the disk. Thanks in advance. Help appreciated. -Madhu From sybrenUSE at YOURthirdtower.com.imagination Fri May 12 03:14:07 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 12 May 2006 09:14:07 +0200 Subject: Threads References: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> <mailman.5609.1147391624.27775.python-list@python.org> <1147392171.914234.48260@q12g2000cwa.googlegroups.com> <jq8862dcirmmj5atp7tdv2q7t032ansquh@4ax.com> <1147417744.770080.11490@q12g2000cwa.googlegroups.com> Message-ID: <slrne68ddu.qon.sybrenUSE@schuimige.stuvel.eu> placid enlightened us with: >> Did you read the documentation for Queue methods? > > there is no need to be patronizing about this dude, im just learning > Python in my spare time, as im a Intern Software Engineer There is nothing patronizing about the question, it's merely an enquiry to a possible fact. If you're going to be a techie, you should learn stuff like that. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From ptmcg at austin.rr._bogus_.com Sun May 21 17:45:17 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Sun, 21 May 2006 21:45:17 GMT Subject: Slicing Issues References: <fca207170605211352k5c707688u63102558898dfe57@mail.gmail.com> <mailman.6047.1148245219.27775.python-list@python.org> Message-ID: <Nb5cg.50746$CH2.48101@tornado.texas.rr.com> "Heiko Wundram" <me+python at modelnine.org> wrote in message news:mailman.6047.1148245219.27775.python-list at python.org... > Am Sonntag 21 Mai 2006 22:52 schrieb BJ Swope: > > district_combo=line[85:3] > > This returns the slice from character 85 to character 3 in the string, read > forwards. Basically, as Python slices are forgiving (because the borders are > actually "illogical"), this amounts to nothing, but could also amount > to: "your indexing boundaries are invalid." > > Basically, what you want is: > > district_combo = line[85:88] > > where 88 = 85 + 3 (3 being the length). Read up on Python slices... > > --- Heiko. How about: district_combo=line[85:][:3] ? -- Paul From deets at nospam.web.de Wed May 24 06:56:36 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Wed, 24 May 2006 12:56:36 +0200 Subject: referrers References: <1148463646.603330.275000@i40g2000cwc.googlegroups.com> <4dio43F1aju6aU1@uni-berlin.de> <1148465462.360499.172450@y43g2000cwc.googlegroups.com> Message-ID: <4disgnF1aanr3U1@uni-berlin.de> raghu wrote: > Diez, > > I did look into gc, specifically gc.get_referrers(), but it seemed to > give me something that I cant decipher. > > I added the following line. > > print "referrers ",gc.get_referrers(x0) > > This is what I got. > > referrers [{'__builtins__': <module '__builtin__' (built-in)>, > '__file__': './tst1.py', 'pdb': <module 'pdb' from > '/home/raghavan/Python-2.4/my_install/lib/python2.4/pdb.pyc'>, 'sys': > <module 'sys' (built-in)>, 'y': 24012, 'gc': <module 'gc' (built-in)>, > 'myfuncs': <module 'myfuncs' from '/home/Raghavan/tst/myfuncs.dll'>, > '__name__': '__main__', 'x0': 24012, 'z': 24012, 'os': <module 'os' > from '/home/raghavan/Python-2.4/my_install/lib/python2.4/os.pyc'>, > '__doc__': None, 'types': <module 'types' from > '/home/raghavan/Python-2.4/my_install/lib/python2.4/types.pyc'>}, > (None, '/home/Raghavan/tst', 'my pid is ', 24012, 'ref count ', > 'referrers ')] > > Also the len of this is 2, while I got refcount=5. So I dont know > whether this can be used in the same way. The refcount is always precise - as it is a simple integer that happens to be part of every python object. But the 1:n-relation to its referres is computed and not necessarily complete, as the docs state very clear. Additionally, they state that this method is only to be used for debugging-purposes. I'm not sure what you are after here - if it is about solving a mem-leak, gc might help. If it is some application logic, the advice must be clearly to explicitly model the object graph bi-directional. Diez From robert.kern at gmail.com Tue May 9 21:26:47 2006 From: robert.kern at gmail.com (Robert Kern) Date: Tue, 09 May 2006 20:26:47 -0500 Subject: List of lists of lists of lists... In-Reply-To: <e3reik$seq$1@daisy.noc.ucla.edu> References: <e3n81d$9o0$1@emma.aioe.org> <e3reik$seq$1@daisy.noc.ucla.edu> Message-ID: <e3rfgn$var$1@sea.gmane.org> James Stroud wrote: > Numarray does this sort of thing, but you have to familiarize yourself > with its indexing conventions: > > py> import numarray > py> numarray.ones((3,2)) > array([[1, 1], > [1, 1], > [1, 1]]) > py> numarray.ones((1,2,3)) > array([[[1, 1, 1], > [1, 1, 1]]]) numpy is the successor to numarray, so if you are just starting with arrays, please get started with numpy. It should also be noted that numpy can create arrays of objects as well as arrays of numbers. In [1]: from numpy import * In [2]: empty((1,2,3), dtype=object) Out[2]: array([[[None, None, None], [None, None, None]]], dtype=object) http://numeric.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 bignose+hates-spam at benfinney.id.au Sat May 6 02:49:07 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sat, 06 May 2006 16:49:07 +1000 Subject: Newbie question on code vetting References: <yvT5g.132$yh.117@trnddc04> <mailman.5299.1146719004.27775.python-list@python.org> <_%w6g.44217$C63.42016@trnddc06> <cBz6g.67490$F_3.12273@newssvr29.news.prodigy.net> <TGV6g.112$W83.13@trnddc07> Message-ID: <87hd43sl5o.fsf@benfinney.id.au> <william.boquist at gte.net> writes: > The overall goal is to remove a barrier to more widespread use of > Open Source - growing the mindshare dedicated to it and potentially > shrinking the mindshare dedicated to commercially-produced software. While I don't agree with the dichotomy you present -- much of the free software available, especially among the mature and popular projects, is commercially produced, so the two evidently aren't opposed -- I laud your goal of attempting to spread the use of free software at the expense of non-free software. > A couple of responders to my earlier notes wrote something like "do > you ask the same thing of closed source vendors?" The answer is "no, > not at present" The obvious thing to note at that point, then, is that an organisation which applies such a double standard to its vendors -- existing software vendors can continue to have appallingly obscure processes and not be held accountable, but free software's outstandingly open processes need to spend volunteer effort to become even *more* open to become worthy of attention -- needs to evolve or die. A less obvious thing to note is that the free software model allows anyone to get involved and do the work they perceive needs doing, or to sponsor it to make it happen. If an organisation needs a whole lot of work put in to create or improve the types of documents it likes to see, what is stopping that organisation from doing so, or offering compensation for others to do so? -- \ "For mad scientists who keep brains in jars, here's a tip: why | `\ not add a slice of lemon to each jar, for freshness?" -- Jack | _o__) Handey | Ben Finney From gmc at serveisw3.net Fri May 26 11:47:18 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Fri, 26 May 2006 17:47:18 +0200 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1148650554.256471.141510@j55g2000cwa.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <mailman.6052.1148256588.27775.python-list@python.org> <1148650554.256471.141510@j55g2000cwa.googlegroups.com> Message-ID: <44772306.1090402@serveisw3.net> Hi, sturlamolden escribi?: Gonzalo Monz?n wrote: > > >>I use Python 2.4.3 (msvcrt71) and I succesfully installed the last >>version of binutils, pyrex and MinGW, some weeks ago, using Julien Fiore >>step-by-step guide, so "my" MinGW is linking with msvcrt71.dll, with the >>default configuration. >> >> > >A successful build (compile and linkage) does not imply that you are >linking with the same crt as Python. It just means that there are no >syntax errors (successful compile) or unresolved external symbols >(successful linkage) in your code. > > > > >>I don't understand why do you say MinGW links with msvcrt.dll... perhaps >>you've got an older version than the ones Julien posted? >> >> > >Because it does not! What happens is that MinGW links with the import >library for msvcrt.dll. The compiler does not complain bacause there >are no syntax errors. The linker does not complain bacuase there are no >unresolved external symbols (after all, msvcrt is a standard crt). When >you run your program, Windows search the search path for msvcrt.dll, >finds the dll in c:\windows\system32, and loads it into your process >image. This produces no errors either. So intitially everything seems >to be ok. > > Does this happen if you're releasing, i.e. a built exe with py2exe, where you supply the right crt? or if you do supply the right crt on the application folder? ... I see my pyrex extension imports with both, msvcrt and msvcrt71, and when I do execute the python program, I see with dependency tool that only msvcr71 gets loaded and I suppose no more crt's are loaded at runtime, as it is shared by my extension and the Python interpreter & std. extensions. In a posterior email on this thread i asked about this issue: I see there are both libraries linked in my pyrex modules... However, when one should expect to have problems with this "dll nightmare", if you always provide the right msvcr71.dll bundled within your project -I mean, using py2exe by example- ? Of course if you didn't bundle the right crt, it does depend on the available crt on target system... then you would be in trouble if user doesn't have msvcrt71, or anyway, could be in trouble linking the "right" library? Thanks for any explanation. Regards, Gonzalo >But... The process image for your Pyrex extension is shared with the >Python interpreter. Previously, msvcrt71.dll was loaded into into the >porcess image when Python started. Now both crts reside in the process, >and Python and your Pyrex extension starts to call their respective >crts. The crts interfere with each other and you get very unpredictable >results. > > Why msvcrt is being loaded later than msvcrt71? why both dll are being loaded it migw links to both and one is already loaded by python interpreter? perhaps the only way to achieve total reliability is to compile using the same where Python & standard extensions where compiled? In the case, does any sense to compile using mingw for standard python >= 2.4 custom extensions? >This is not just a Python problem. Microsoft created this problem when >they started to publish multiple versions of their crt. Whenever a >process has imported different crts, there will inevitably be run-time >conflicts. Windows is a "component" based operating system. If you are >e.g. using in proc COM objects (also known as "ActiveX Components"), >you can only pray to God that the author did not use a different crt >than you. If you are loading a precompiled DLLs, you can only pray to >God that the author did not use a different crt than you. Previously >this was not an issue, as Windows had exactly one shared crt. Now this >is all messed up. Why did Microsoft decide to create "C runtime DLL >Hell"? I have no idea. > > > I'm aware of this, but I am not about every detail. Regards, Gonzalo From onurb at xiludom.gro Thu May 18 09:47:21 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 15:47:21 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147958226.200557.264850@j33g2000cwa.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <1147947048.303912.109150@38g2000cwa.googlegroups.com> <446c5a80$0$7024$636a55ce@news.free.fr> <mailman.5873.1147952119.27775.python-list@python.org> <1147958226.200557.264850@j33g2000cwa.googlegroups.com> Message-ID: <446c7b51$0$7040$636a55ce@news.free.fr> glomde wrote: >>What about writing a mini-language that gets translated to Python? Think of >>Cheetah, which does exactly this (albeit not being limited to templating HTML >>data). > > I have implemented my proposal as preprocessor. And it works fine. But > my > proposal in not only for HTML Nor is Cheetah. Nor is Django's templating system. Nor are some other Python templating systems. > it can be used for all hieracical data. > Example: > > myList = [] > *+* myList: > *+* []: > for i in range(10): > *+* i > *+* {}: > for i in range(10): > *=* i = i Sweet Lord, have mercy ! > Which should create myList = [[0..9], {0:0, ... 9:9}] myList = [ range(10), dict((i, i) for i in range(10)) ] Let's talk about readability.... > I do think I solve something and make it more > readable. Lol. Any Perl coder around ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From raathm at gmail.com Wed May 3 02:14:17 2006 From: raathm at gmail.com (Mike) Date: 2 May 2006 23:14:17 -0700 Subject: ImportError: No module named HTMLParser Message-ID: <1146636851.237957.92470@v46g2000cwv.googlegroups.com> Hi I'm getting the above message on a server installation (2.4) of Python. I don't get the error using my script on my own machine. I'm trying to use the non-sgmllib one - the standard HTMLParser but it won't import on the server. How can I go about checking which file should reside where? I'm a Python newbie so please bear with me. Thanks, Mike From sjmachin at lexicon.net Tue May 30 19:58:52 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 May 2006 09:58:52 +1000 Subject: stupid perl question In-Reply-To: <slrne7p8p8.2t1.grahn+nntp@frailea.sa.invalid> References: <44778C05.9020701@grads.ece.mcmaster.ca> <mailman.6264.1148687520.27775.python-list@python.org> <4477A74C.6080605@lexicon.net> <slrne7p8p8.2t1.grahn+nntp@frailea.sa.invalid> Message-ID: <447cdc3d@news.eftel.com> On 31/05/2006 5:55 AM, Jorgen Grahn wrote: > On Sat, 27 May 2006 11:11:40 +1000, John Machin <sjmachin at lexicon.net> wrote: > ... >> Yes, you could write out the whitespace characters for the 8-bit >> encoding of your choice, or you could find them using Python (and get >> some possibly surprising answers): >> >>>>> mkws = lambda enc, sz=256: "".join([chr(i) for i in range(sz) if >> chr(i).decode(enc, 'ignore').isspace()]) > ... >>>>> mkws('latin1') >> '\t\n\x0b\x0c\r\x1c\x1d\x1e\x1f \x85\xa0' > ^^^^ > That surprised me, at least. Should NO-BREAK SPACE really count as > whitespace? NO-BREAK SPACE is a space. Of course it should return True when fed to isspace(). Whitespace is a silly term, anyway (IMHO); is there such a thing as a space that is not white? > I thought that the whole purpose with it was to have a blank > character which programs automatically treated as non-whitespace, for > line-breaking, word-counting and similar purposes. Yes, but the concept of things like split() splitting on ASCII "whitespace" evidently predated (or ignored!) the concept of a no-break space appearing in various word-processors. Automatically?? Sure it counts for line-breaking, but some applications might want to treat it as a word-separator. It pays to look at what's in one's data, and find out what the tools and functions are actually doing with it. Cheers, John From sybrenUSE at YOURthirdtower.com.imagination Fri May 12 03:13:13 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Fri, 12 May 2006 09:13:13 +0200 Subject: Decorator References: <1147416658.204175.193480@i39g2000cwa.googlegroups.com> Message-ID: <slrne68dc9.qon.sybrenUSE@schuimige.stuvel.eu> Lad enlightened us with: > I use Python 2.3. > I have heard about decorators in Python 2.4. > What is the decorator useful for? A whole lot of stuff. I've used them for: - Logging all calls to a function, including its arguments. - Ensuring there is a database connection before the function is called. - Casting the arguments to certain types before passing them to the function. And there is much more possible... Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From wahab at chemie.uni-halle.de Thu May 11 16:12:48 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Thu, 11 May 2006 22:12:48 +0200 Subject: Reg Ex help In-Reply-To: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> References: <1147369153.397802.61040@v46g2000cwv.googlegroups.com> Message-ID: <e4062s$jog$1@mlucom4.urz.uni-halle.de> Hi don > I have a string from a clearcase cleartool ls command. > /main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT > from /main/parallel_branch_1/release_branch_1.0/4 > I want to write a regex that gives me the branch the file was > checkedout on ,in this case - 'dbg_for_python' > Also if there is a better way than using regex, please let me know. This is a good situation where Regex come into play, because all other solutions won't catch on different string structures easily. If you know that you will need the string before CHECKEDOUT, you can, for example use some nice positive lookahead (mentioned today here) pseudo: take all strings between / ... / and return 'em if the next thing is CHECKEDOUT (or something else): / ([^/]+) / (?=CHECKEDOUT) The ([^/]+) means ^/ (not /) in a character class, [^/]+ one or more than one times and ([^/]+) capture it by (..) The code: import re t = '/main/parallel_branch_1/release_branch_1.0/dbg_for_python/CHECKEDOUT from /main/p...' r = r'/([^/]+)/(?=CHECKEDOUT)' # print re.search(r, t).group(1) would do the job, independent of the structure of string - except the /CHECKEDOUT thing (which has to be there) If there are 'better ways' - that depends on 'better ways for whom?'. If you can handle the Railgun, why bother with the Pistols ;-) Regards M. From daniel.neilson at gmail.com Wed May 17 12:02:07 2006 From: daniel.neilson at gmail.com (dhn) Date: 17 May 2006 09:02:07 -0700 Subject: Point-feature labeling in matplotlib Message-ID: <1147881727.179982.293920@g10g2000cwb.googlegroups.com> I am trying to automate the generation of scatterplots in matplotlib. The problem of where to put the labels is known as 'point-feature labeling' (a main application is in cartography, where cities and such are known as 'point features'). In general the problem is not easy. Some references: http://www.merl.com/reports/docs/TR96-04.pdf http://www.eecs.harvard.edu/shieber/Biblio/Papers/tog-final.pdf If anyone knows of any canned python algorithms to do this, please direct me to them. If not, I will need to implement one. My problem is not that hard, as I will not have more than 20 labels to place. As I see it, the steps that need to be taken are: 1. locate the points 2. compute the size of the text boxes for the labels 3. minimize a loss function reflecting one of the algorithms discussed in the papers cited to determine the optimal placement of the labels At the moment I was wondering if any matplotlib experts (I am a bit of a novice) could suggest a good way to accomplish 2. I have tried to do something like In [1]: from pylab import * In [2]: plot([0.5],[0.5],'bo') In [3]: axis([0,1,0,1]) In [4]: t = text(0.50,0.51,'Test') In [5]: t._get_layout(t._renderer)[1][0][1] Out[5]: (20.0, 6.0) Then I have tried to use t._transform to convert these dimensions back into axis coordinates. Unfortunately this method seems to require that the plot be rendered to be able to get the dimensions, which is not too efficient. I'm sure there is a better way to do this; does anyone have any ideas? From manstey at csu.edu.au Wed May 17 01:29:49 2006 From: manstey at csu.edu.au (manstey) Date: 16 May 2006 22:29:49 -0700 Subject: A Unicode problem -HELP In-Reply-To: <446AAFE6.4080008@v.loewis.de> References: <1147404879.711606.246090@i39g2000cwa.googlegroups.com> <44641baf$0$8865$9b622d9e@news.freenet.de> <1147832399.383507.155800@j55g2000cwa.googlegroups.com> <446AAFE6.4080008@v.loewis.de> Message-ID: <1147843788.969853.159420@g10g2000cwb.googlegroups.com> OK, I apologise for not being clearer. 1. Here is my input data file, line 2: gn1:1,1.2 R")$I73YT R")$IYT at ncfsa 2. Here is my output data file, line 2: u'gn', u'1', u'1', u'1', u'2', u'-', u'R")$I73YT', u'R")$IYT', u'R")$IYT', u'@', u'ncfsa', u'nc', '', '', '', u'f', u's', u'a', '', '', '', '', '', '', '', '', u'B.:R")$I^YT', u'b.:cv)cv^yc', '\xc9\x94' 3. Here is my main program: # -*- coding: UTF-8 -*- import codecs import splitFunctions import surfaceIPA # Constants for file location # Working directory constants dir_root = 'E:\\' dir_relative = '2 Core\\2b Data\\Data Working\\' # Input file constants input_file_name = 'in.grab.txt' input_file_loc = dir_root + dir_relative + input_file_name # Initialise input file input_file = codecs.open(input_file_loc, 'r', 'utf-8') # Output file constants output_file_name = 'out.grab.txt' output_file_loc = dir_root + dir_relative + output_file_name # Initialise output file output_file = codecs.open(output_file_loc, 'w', 'utf-8') # unicode i = 0 for line in input_file: if line[0] != '>': # Ignore headers i += 1 if i != 1: word_info = splitFunctions.splitGrab(line, i) parse=splitFunctions.splitParse(word_info[10]) gloss=surfaceIPA.surfaceIPA(word_info[6],word_info[8],word_info[9],parse) a=str(word_info + parse + gloss).encode('utf-8') a=a[1:len(a)-1] output_file.write(a) output_file.write('\n') input_file.close() output_file.close() print 'done' 4. Here is my problem: At the end of my output file, where my unicode character \u0254 (OPEN O) appears, the file has '\xc9\x94' What I want is an output file like: 'gn', '1', '1', '1', '2', '-', ..... '?' where ? is an open O, and would display correctly in the appropriate font. Once I can get it to display properly, I will rewrite gloss so that it returns a proper translation of 'R")$I73YT', which will be a string of unicode characters. Is this clearer? The other two functions are basic. splitGrab turns 'gn1:1,1.2 R")$I73YT R")$IYT at ncfsa' into 'gn 1 1 1 2 R")$I73YT R")$IYT @ ncfsa' and splitParse turns the final piece of this 'ncfsa' into 'n c f s a'. They have to be done separately as splitParse involves some translation and program logic. SurfaceIPA reads in 'R")$I73YT' and other data to produce the unicode string. At the moment it just returns two dummy strings and u'\u0254'.encode('utf-8'). All help is appreciated! Thanks From fairwinds at eastlink.ca Sat May 13 12:34:22 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Sat, 13 May 2006 13:34:22 -0300 Subject: Package that imports with name of dependent package In-Reply-To: <e44vvm$nvh$01$1@news.t-online.com> References: <mailman.5657.1147530941.27775.python-list@python.org> <e44vvm$nvh$01$1@news.t-online.com> Message-ID: <44660A8E.8060108@eastlink.ca> Hi Peter. I'd like to fix the imports, but this would impact the portability of portions of the code that currently work with the existing package from the framework. This solution does the trick and allows me to create the package I want using a good amount of new material. I don't have to worry about adding to the original package each time a release comes out. I'll only have to monitor code changes for an impact on my classes, subclasses, etc. Still a pain, but a smaller one :-) Many thanks. Regards David Peter Otten wrote: > from pkgutil import extend_path > import mypackage > __path__ = extend_path(mypackage.__path__, __name__) > > into dependentpackage/__init__.py might work. > > Peter > > > From fredrik at pythonware.com Sat May 20 08:58:50 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Sat, 20 May 2006 14:58:50 +0200 Subject: misleading prefix ++ In-Reply-To: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> References: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> Message-ID: <e4n3q9$uer$1@sea.gmane.org> LuciferLeo at gmail.com wrote: > Don't you think it is misleading when you expect a variable to > increment? no. and in my experience, most people know that they cannot just type random stuff into a computer and expect it to do what they want. (have you figured out *why* this is valid syntax, and what it does to your integer?) </F> From tkpmep at hotmail.com Mon May 8 14:23:28 2006 From: tkpmep at hotmail.com (tkpmep at hotmail.com) Date: 8 May 2006 11:23:28 -0700 Subject: Using StopIteration Message-ID: <1147112608.374083.99030@u72g2000cwu.googlegroups.com> I create list of files, open each file in turn, skip past all the blank lines, and then process the first line that starts with a number (see code below) filenames=glob.glob("C:/*.txt") for fn in filenames: f =file(fn) line = " " while line[0] not in digits: line = f.next() ProcessLine(line) If a file has only blank lines, the while loop terminates with a StopIteration. How can I just close this file andd skip to the next file if a StopIteration is raised? I tried the following: filenames=glob.glob("C:/*.txt") for fn in filenames: f =file(fn) line = " " while line[0] not in digits: try: line = f.next() except StopIteration: f.close() continue ProcessLine(line) but got only a ValueError: I/O operation on closed file for line = f.next(). It appears that the continue is taking me back to the top of the while loop. How can I get back to the top of the for loop? Thanks in advance Thomas Philips From micklee74 at hotmail.com Tue May 2 02:20:56 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 1 May 2006 23:20:56 -0700 Subject: stripping Message-ID: <1146550856.291511.5780@v46g2000cwv.googlegroups.com> hi i have a file test.dat eg abcdefgh ijklmn <-----newline opqrs tuvwxyz <---newline I wish to print the contents of the file such that it appears: abcdefgh ijklmn opqrs tuvwxyz here is what i did: f = open("test.dat") while 1: line = f.readline().rstrip("\n") if line == '': break #if not re.findall(r'^$',line): print line but it always give me first 2 lines, ie abcdefgh ijklmn What can i do to make it print all..? thanks From ziga.seilnacht at gmail.com Thu May 25 09:29:33 2006 From: ziga.seilnacht at gmail.com (Ziga Seilnacht) Date: 25 May 2006 06:29:33 -0700 Subject: how to change sys.path? References: <1148544408.348803.190320@j33g2000cwa.googlegroups.com> <mailman.6193.1148558462.27775.python-list@python.org> Message-ID: <1148563773.316226.229570@j33g2000cwa.googlegroups.com> Michael Yanowitz wrote: > Is there something like a .pythoninitrc which can run whenever we start > Python > that can load a file with many sys.path.append(), etc? > If not is there some way to modify the Python shell constructor and > destructor? > > Thanks in advance: > Michael yanowitz Yes, there is the user module: http://docs.python.org/lib/module-user.html which you have to explicitly import and which will look for .pythonrc.py file in user's home directory and execute it. The other option is a sitecustomize module, which should be put somewhere on the initial search path. It will be imported automatically during the interpreter initialization. See: http://docs.python.org/lib/module-site.html for details. Ziga From fuzzyman at gmail.com Tue May 23 04:07:55 2006 From: fuzzyman at gmail.com (Fuzzyman) Date: 23 May 2006 01:07:55 -0700 Subject: Don't wish to give up on a Tkinter GUI Builder :( In-Reply-To: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> References: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> Message-ID: <1148371674.932205.83160@j55g2000cwa.googlegroups.com> vbgunz wrote: > Hello world, > > I tried looking everywhere for a decent Tkinter GUI builder and the > closest I got to finding one before being horrified from looking at the > source was vtcl @ http://vtcl.sourceforge.net. The next closest thing > was page @ http://page.sourceforge.net/ > > Page just didn't cut it for me and I got several errors from it whereas > vtcl was almost a dream come true. it was not only perfect but I had a > full fledged gui design up and running at the click of a file in less > than ten minutes with so many widgets neatly placed... > > When I looked at the source, it was in Tcl... It was huge at about 477 > lines for a nice and complete interface... problem is I don't know Tcl > from chinese... I assume it is Tcl because the extension on the > generated file was Tcl... Man, what a let down... > Try Rapyd-Tk. It's new, which is why it isn't featured on the pages you looked at. (I'm not the author, but it looks interesting.) http://home.cogeco.ca/~rapyd/ Fuzzyman http://www.voidspace.org.uk/python/shareware.shtml From apgwoz at gmail.com Thu May 4 14:14:28 2006 From: apgwoz at gmail.com (Andrew Gwozdziewycz) Date: Thu, 4 May 2006 14:14:28 -0400 Subject: Python for Perl programmers In-Reply-To: <e3dait$4us$1@panix2.panix.com> References: <Xxp6g.1766$VV2.132570@news20.bellglobal.com> <e3dait$4us$1@panix2.panix.com> Message-ID: <400D9E7B-09CA-4074-B398-9235F5F946BA@gmail.com> On May 4, 2006, at 12:36 PM, Aahz wrote: > In article <Xxp6g.1766$VV2.132570 at news20.bellglobal.com>, > A.M <alanalan at newsgroup.nospam> wrote: >> >> Is there any efficient online resource or book that help >> experienced Perl >> programmers to Python? I'd recommend http://www.diveintopython.org since you know how to program already. It's free! --- Andrew Gwozdziewycz apgwoz at gmail.com http://ihadagreatview.org http://and.rovir.us From fredrik at pythonware.com Tue May 2 17:23:46 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 May 2006 23:23:46 +0200 Subject: data regex match References: <87r73cdtmk.fsf@localhost.localdomain> Message-ID: <e38il3$kbn$1@sea.gmane.org> Gary Wessle wrote: > I am having an issue with this match > > tx = "now 04/30/2006 then" > data = re.compile('(\d{2})/\1/\1\1', re.IGNORECASE) > d = data.search(tx) > print d > > Nono > I was expecting 04/30/2006 really? your pattern matches two digits, followed by a slash, followed by a byte with the ASCII value 1, followed by a slash, followed by two bytes with the ASCII value 1. >>> '(\d{2})/\1/\1\1' '(\\d{2})/\x01/\x01\x01' in case you meant to write r'(\d{2})/\1/\1\1' (which is the same thing as '(\\d{2})/\\1/\\1\\1') it's still not close; that pattern matches two digits, followed by a slash, followed by the *same* two digits, followed by a slash, followed by the same two digits, followed by the same two digits. in other words, dates like 20/20/2020 and 12/12/1212. try '\d\d/\d\d/\d\d\d\d' instead. > what went wrong? (insert obligatory jwz quote here) </F> From webraviteja at gmail.com Fri May 12 15:16:27 2006 From: webraviteja at gmail.com (Ravi Teja) Date: 12 May 2006 12:16:27 -0700 Subject: deleting texts between patterns In-Reply-To: <44645C03.3070500@lexicon.net> References: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> <1147421468.912908.271280@i39g2000cwa.googlegroups.com> <44645C03.3070500@lexicon.net> Message-ID: <1147461387.001875.117120@u72g2000cwu.googlegroups.com> >> I don't think that's what you really meant ^ 2 Right! That was very buggy. That's what I get for posting past 1 AM :-(. From Sebastien.Boisgerault at gmail.com Sat May 27 17:09:54 2006 From: Sebastien.Boisgerault at gmail.com (=?iso-8859-1?q?S=E9bastien_Boisg=E9rault?=) Date: 27 May 2006 14:09:54 -0700 Subject: (mostly-)POSIX regular expressions Message-ID: <1148764193.962418.192750@j73g2000cwa.googlegroups.com> Hi, I'm searching for a POSIX 1003.2 compatible regular expression engine. The Python binding "pregex" by Neal Becker may do the job, but I did not manage to download it as the original link ftp://ftp.ctd.comsat.com/pub/ seems dead. Does any old-timer (<wink>) have a copy of this package ? Cheers, SB From sjmachin at lexicon.net Tue May 16 20:43:21 2006 From: sjmachin at lexicon.net (John Machin) Date: 16 May 2006 17:43:21 -0700 Subject: Unable to extract Python source code using Windows References: <1147793161.867167.113480@g10g2000cwb.googlegroups.com> Message-ID: <1147826601.426636.4540@y43g2000cwc.googlegroups.com> Elric02 wrote: """ I'm currently trying to get access to the Python source code, however whenever I try to extract the files using the latest version of WinZip (version 10) I get the following error "error reading however after processing 0 entries """ I've managed to reproduce this behaviour: 1. Browser = Firefox 2. go to www.python.org 3. click on quick links / source code [on the left side of the home page] 4. Firefox pops up a box which says 'You have chosen to download blahblah.tar.bz2 which is a: WinZip File". [It is is gravely mistaken]. 5. The default presented is "open" (as opposed to save to disk). 6. If you click on OK, you get "Error reading header [not 'however'!!] after 0 entries." In defense/mitigation of FireFox: IE is equally mistaken at step 4. At step 6, it doesn't complain but starts off downloading [painfully slowly]. I didn't wait around to find out what sort of error message ensued. So: (1) like I said in an earlier post, go for the .tgz file -- look for the line gzip-compressed source code: python-2.4.3.tgz on the home page (2) download the file, don't open archives online, even from trusted sources like python.org (3) understand that WinZip *does* handle .tar, .gz, .tar.gz, and .tgz files. It doesn't handle .bz2 files. (4) When asking a question, try stating what you have been doing, with some precision -- like in this case, *WHICH* archive and *HOW* ... From Florian.Lindner at xgm.de Tue May 2 10:50:16 2006 From: Florian.Lindner at xgm.de (Florian Lindner) Date: Tue, 02 May 2006 16:50:16 +0200 Subject: ConfigParser and multiple option names Message-ID: <e37rji$c46$1@news.in.tum.de> Hello, since ConfigParser does not seem to support multiple times the same option name, like: dir="/home/florian" dir="/home/john" dir="/home/whoever" (only the last one is read in) I wonder what the best way to work around this. I think the best solution would be to use a seperation character: dir="/home/florian, /home/john, home/whoever" What character would be best to work on various operating systems? (of what names may a path consist is the question) What do you think? Any better ideas? Thanks, Florian From ptmcg at austin.rr._bogus_.com Fri May 19 16:18:05 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 20:18:05 GMT Subject: altering an object as you iterate over it? References: <1Mobg.2139$No6.46432@news.tufts.edu> <D%obg.2140$No6.46498@news.tufts.edu> Message-ID: <1Kpbg.42822$Qq.36241@tornado.texas.rr.com> "John Salerno" <johnjsal at NOSPAMgmail.com> wrote in message news:D%obg.2140$No6.46498 at news.tufts.edu... > John Salerno wrote: > > What is the best way of altering something (in my case, a file) while > > you are iterating over it? I've tried this before by accident and got an > > error, naturally. > > > > I'm trying to read the lines of a file and remove all the blank ones. > > One solution I tried is to open the file and use readlines(), then copy > > that list into another variable, but this doesn't seem very efficient to > > have two variables representing the file. > > > > Perhaps there's also some better to do it than this, including using > > readlines(), but I'm most interested in just how you edit something as > > you are iterating with it. > > > > Thanks. > > Slightly new question as well. here's my code: > > phonelist = open('file').readlines() > new_phonelist = phonelist > > for line in phonelist: > if line == '\n': > new_phonelist.remove(line) > > import pprint > pprint.pprint(new_phonelist) > > But I notice that there are still several lines that print out as '\n', > so why doesn't it work for all lines? Okay, so it looks like you are moving away from modifying a list while iterating over it. In general this is good practice, that is, it is good practice to *not* modify a list while iterating over it (although if you *must* do this, it is possible, just iterate from back-to-front instead of front to back, so that deletions don't mess up your "next" pointer). Your coding style is a little dated - are you using an old version of Python? This style is the old-fashioned way: noblanklines = [] lines = open("filename.dat").readlines() for line in lines: if line != '\n': noblanklines.append(lin) 1. open("xxx") still works - not sure if it's even deprecated or not - but the new style is to use the file class 2. the file class is itself an iterator, so no need to invoke readlines 3. no need for such a simple for loop, a list comprehension will do the trick - or even a generator expression passed to a list constructor. So this construct collapses down to: noblanklines = [ line for line in file("filename.dat") if line != '\n' ] Now to your question about why '\n' lines persist into your new list. The answer is - you are STILL UPDATING THE LIST YOUR ARE ITERATING OVER!!! Here's your code: new_phonelist = phonelist for line in phonelist: if line == '\n': new_phonelist.remove(line) phonelist and new_phonelist are just two names bound to the same list! If you have two consecutive '\n's in the file (say lines 3 and 4), then removing the first (line 3) shortens the list by one, so that line 4 becomes the new line 3. Then you advance to the next line, being line 4, and the second '\n' has been skipped over. Also, don't confuse remove with del. new_phonelist.remove(line) does a search of new_phonelist for the first matching entry of line. We know line = '\n' - all this is doing is scanning through new_phonelist and removing the first occurrence of '\n'. You'd do just as well with: numEmptyLines = lines.count('\n') for i in range( numEmptyLines ): lines.remove('\n') Why didn't I just write this: for i in range( lines.count('\n') ): lines.remove('\n') Because lines.count('\n') would be evaluated every time in the loop, reducing by one each time because of the line we'd removed. Talk about sucky performance! You might also want to strip whitespace from your lines - I expect while you are removing blank lines, a line composed of all spaces and/or tabs would be equally removable. Try this: lines = map(str.rstrip, file("XYZZY.DAT") ) -- Paul From belred at gmail.com Mon May 22 23:28:16 2006 From: belred at gmail.com (Bryan) Date: Mon, 22 May 2006 20:28:16 -0700 Subject: groupby Message-ID: <e4tvgf$bon$1@sea.gmane.org> can some explain why in the 2nd example, m doesn't print the list [1, 1, 1] which i had expected? >>> for k, g in groupby([1, 1, 1, 2, 2, 3]): ... print k, list(g) ... 1 [1, 1, 1] 2 [2, 2] 3 [3] >>> m = list(groupby([1, 1, 1, 2, 2, 3])) >>> m [(1, <itertools._grouper object at 0x00AAC600>), (2, <itertools._grouper object at 0x00AAC5A0>), (3, <itertools._grouper object at 0x00AAC5B0>)] >>> list(m[0][1]) [] >>> thanks, bryan From rNOSPAMon at flownet.com Thu May 18 17:23:04 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 May 2006 14:23:04 -0700 Subject: WTF? Printing unicode strings Message-ID: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> >>> u'\xbd' u'\xbd' >>> print _ Traceback (most recent call last): File "<stdin>", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 0: ordinal not in range(128) >>> From sonicpulse at gmail.com Thu May 25 17:56:01 2006 From: sonicpulse at gmail.com (sonicpulse at gmail.com) Date: 25 May 2006 14:56:01 -0700 Subject: how to open password protected PDF's in Python Message-ID: <1148594161.383636.182320@j73g2000cwa.googlegroups.com> Hello, I made a program that iterates through all the pdf's in a folder and opens them and prints them. However, all of these pdf's are password protected, so I have to manually type in the password many times. Is there any way to open a password-protected PDF with the password entered through python? Thanks From conor.robinson at gmail.com Wed May 10 19:22:46 2006 From: conor.robinson at gmail.com (conor.robinson at gmail.com) Date: 10 May 2006 16:22:46 -0700 Subject: segmentation fault in scipy? In-Reply-To: <mailman.5571.1147301063.27775.python-list@python.org> References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <mailman.5571.1147301063.27775.python-list@python.org> Message-ID: <1147303366.635169.305300@q12g2000cwa.googlegroups.com> Good point. Finding the SSE using an absolute error matrix of (25000 x 1) is insane. I pulled out the error function (for now) and I'm back in business. Thanks for all the great advise. From bignose+hates-spam at benfinney.id.au Sun May 14 09:24:20 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Sun, 14 May 2006 23:24:20 +1000 Subject: send an email with picture/rich text format in the body References: <1147605849.115176.293460@i39g2000cwa.googlegroups.com> <1147611942.057703.211760@j73g2000cwa.googlegroups.com> Message-ID: <87ody0rb7f.fsf@benfinney.id.au> "Miki" <miki.tebeka at gmail.com> writes: > See http://docs.python.org/lib/node597.html > IMO if you'll place the picture as 1'st MutliMime part the *some* email > readers will show it like you want. And most good spam filters will recognise it for the junk that it is, and flag it appropriately. Messages that contain little plain text get flagged as likely spam. If there's useful information for the recipient to see in an email, put it in as text. If you want to distribute files, put them online for fetching -- and then feel free to send an email containing the URL to the people who want those files, so they can get them at an appropriate time, with appropriate tools. -- \ Contentsofsignaturemaysettleduringshipping. | `\ | _o__) | Ben Finney From ullrich at math.okstate.edu Wed May 24 07:49:05 2006 From: ullrich at math.okstate.edu (David C. Ullrich) Date: Wed, 24 May 2006 06:49:05 -0500 Subject: Multiple Version Install? References: <gbtj52l54trlhekcht3mgdb8s60aa4k83d@4ax.com> <mailman.5338.1146763189.27775.python-list@python.org> <rjgm5299fp5pvostqlbnmi8gvipegl838s@4ax.com> Message-ID: <2qh8729tqvovgkqmj4u0fnsl2qk416q8n7@4ax.com> On Fri, 05 May 2006 07:44:45 -0500, David C. Ullrich <ullrich at math.okstate.edu> wrote: [...] >Just curious: How does pythonxx.dll determine things >like where to find the standard library? That's the >sort of thing I'd feared might cause confusion... Ok, it was a stupid question, cuz right there in the registry it says Python/PythonCore/1.5/PYTHONPATH = whatever. All I can say is the last few times I wondered about this question I did search the registry for PYTHONPATH and didn't find it. Maybe I spelled it wrong or somthing. ************************ David C. Ullrich From barbaros at ptmat.fc.ul.pt Sun May 21 17:09:12 2006 From: barbaros at ptmat.fc.ul.pt (barbaros) Date: 21 May 2006 14:09:12 -0700 Subject: dynamic drawing in web page Message-ID: <1148245752.728480.238540@u72g2000cwu.googlegroups.com> Hello everybody, I need to put some dynamic drawings on my web page. More precisely, I need to draw a number of geometric figures (circles, rectangles) which evolve into a graphics windows according to some law (a little bit like the solar system). I need also to have several fields aside the window, where the visitor can change values for several significant parameters (like the mass of each body). Could you please suggest a solution (preferably not involving hundreds of lines of code) ? The computations should be performed on the client machine. Thank you. Cristian Barbarosie http://cmaf.fc.ul.pt/~barbaros From bill.pursell at gmail.com Wed May 17 09:51:19 2006 From: bill.pursell at gmail.com (Bill Pursell) Date: 17 May 2006 06:51:19 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <1147873879.818361.10040@i40g2000cwc.googlegroups.com> Xah Lee wrote: > Tabs versus Spaces in Source Code > > Xah Lee, 2006-05-13 > > In coding a computer program, there's often the choices of tabs or > spaces for code indentation. <snip> > (2) Due to the first reason, they have created and > propagated a massive none-understanding and mis-use, to the degree that > many tools (e.g. vi) does not deal with tabs well :set ts=<n> Yeah, that's really tough. vi does just fine handling tabs. vim does an even better job, with mode-lines, = and :retab. In my experience, the people who complain about the use of tabs for indentation are the people who don't know how to use their editor, and those people tend to use emacs. From sven at popmodernism.org Sun May 28 09:44:21 2006 From: sven at popmodernism.org (sven koenig) Date: Sun, 28 May 2006 15:44:21 +0200 Subject: using FFTW3 with Numeric on Windows Message-ID: <6.2.3.4.2.20060528153411.02afc960@post.strato.de> hi list, as the subject says, I'm trying to find a way to use FFTW3 with Numeric arrays. I'm not very familiar with C(++) - I think ctypes is the way to go, but I don't really have a clue how to do it. Has somebody already tried this? thx, sven. From raathm at gmail.com Wed May 3 07:15:18 2006 From: raathm at gmail.com (Mike) Date: 3 May 2006 04:15:18 -0700 Subject: ImportError: No module named HTMLParser In-Reply-To: <mailman.5249.1146638626.27775.python-list@python.org> References: <1146636851.237957.92470@v46g2000cwv.googlegroups.com> <mailman.5249.1146638626.27775.python-list@python.org> Message-ID: <1146654918.146817.15710@i39g2000cwa.googlegroups.com> Thanks - it turned out that the Python installation on our vendor's server is a cut-down one. I have had to place the HTMLParser source in a package off the a sys.path directory and import it from there - it now works. From sturlamolden at yahoo.no Fri May 26 14:13:55 2006 From: sturlamolden at yahoo.no (sturlamolden) Date: 26 May 2006 11:13:55 -0700 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <mailman.6247.1148658449.27775.python-list@python.org> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <mailman.6052.1148256588.27775.python-list@python.org> <1148650554.256471.141510@j55g2000cwa.googlegroups.com> <mailman.6247.1148658449.27775.python-list@python.org> Message-ID: <1148667235.713542.220810@j33g2000cwa.googlegroups.com> Gonzalo Monz?n wrote: > Does this happen if you're releasing, i.e. a built exe with py2exe, > where you supply the right crt? or if you do supply the right crt on the > application folder? ... It does not matter which crt you "supply". The dynamic linker will attempt to load the crt specified by the import library that you linked when the extension was built. What will happen, is that Windows will search through its "search path" (i.e. the current folder and folder specified by the PATH environment variable) until it find the crt it wants. > I see there are both libraries linked in my pyrex modules... However, > when one should expect to have problems with this "dll nightmare", if > you always provide the right msvcr71.dll bundled within your project -I > mean, using py2exe by example- ? Windows will e.g. look in its own directories as well. You can bundle msvcr71.dll, but msvcrt.dll will always be available in c:\windows\system32. If you used an import library for msvcrt.dll, then msvcrt.dll will be loaded. Also you cannot legally bundle msvcr71.dll unless you hold a license for Visual Studio 2003. There are no other way to legally redistribute msvcr71.dll. Other versions of Visual Studio allows redistribution of other versions of the crt. Visual C++ Toolkit 2003 only allows a statically linked crt. > Of course if you didn't bundle the right crt, it does depend on the > available crt on target system... No it does not. It always depends on the CRT specified by the import library. If you linked against msvcr71.lib, then the extension needs to load msvcr71.dll. If Windows cannot find msvcr71.dll on the search path, the process will be killed. It is your responsibility to make sure msvcr71.lib reside on the search path. If it cannot be found, Windows will not load a different crt instead. Windows will pop up a warning message telling you that msvcr71.dll cannot be found, and then kill the process. If you linked against msvcrt.lib, then the extension will load msvcrt.dll. From mensanator at aol.com Tue May 23 03:51:16 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 23 May 2006 00:51:16 -0700 Subject: module confict? gmpy and operator References: <1148346626.184199.125740@38g2000cwa.googlegroups.com> <mailman.6095.1148354349.27775.python-list@python.org> Message-ID: <1148370675.969310.41660@38g2000cwa.googlegroups.com> Tim Peters wrote: > [mensanator at aol.com] > > Please try to give a complete program that illustrates the problem. > For example, this program shows no problem on my box (Windows Python > 2.4.3): Sorry about that. I thought the problem was more obvious. <working example snipped> > I don't see a problem of any kind, and there's no way to guess from > the above what you did that mattered. It's hard to believe that > merely importing any module (operator or otherwise) has any effect on > gmpy. That's what I was asking about. I don't know enough about low level stuff to know. I've been using gmpy for years with the only problem being the memory leak that was fixed in the latest version. I've never used operator before, so I just assumed that's where the problem was. But I don't see why the program behaves the way it does either. Here's the complete program: import gmpy import random import operator def product(a,b): return a*b def gcdlist(X): mingcd = 999999 for i in xrange(1,len(X)): g = gmpy.gcd(X[i-1],X[i]) if g<mingcd: mingcd = g return mingcd X = [8,16,20,24,40,72,84,92] g = gcdlist(X) s = sum(X) print ' X:',X print ' gcd:',g N = 0 while N<s: N = g * random.randint(s,3333) print ' N:',N if N>s: C = [1 for i in X] diff = N-s done = False i = -1 XL = -len(X) while not done: while diff>=X[i]: C[i] += 1 diff -= X[i] if diff==0: done = True else: i -= 1 if i<XL: done = True NN = sum(map(operator.__mul__,X,C)) print ' X:',X print ' C:',C print ' NN:',NN print ' diff:',diff print if diff>0: p = 0 q = 1 done = False while not done: gpq = gmpy.gcd(X[p],X[q]) if diff % gpq == 0: done = True else: q += 1 if q==len(X): p += 1 q = p + 1 print 'p: %d q: %d' % (p,q) a = gmpy.divm(diff,X[p],X[q]) b = (X[p]*a - diff)/X[q] print 'a: %d b: %d X[p]: %d X[q]: %d' % (a,b,X[p],X[q]) if C[q]==b: print 'non-zero adjustment' print 'a: %d b: %d' % (a + X[q],b + X[p]) C[p] += a + X[q] C[q] -= b + X[p] else: C[p] += a C[q] -= b NN = sum(map(operator.__mul__,X,C)) print ' X:',X print ' C:',C print ' NN:',NN print This is what the output should look like X: [8, 16, 20, 24, 40, 72, 84, 92] gcd: 4 N: 4492 X: [8, 16, 20, 24, 40, 72, 84, 92] C: [1, 1, 1, 1, 1, 1, 2, 45] NN: 4488 diff: 4 p: 0 q: 2 a: 3 b: 1 X[p]: 8 X[q]: 20 non-zero adjustment a: 23 b: 9 X: [8, 16, 20, 24, 40, 72, 84, 92] C: [24, 1, -8, 1, 1, 1, 2, 45] NN: 4492 X is a list of integers selected so that the GCD of the entire list is >2. N is selected to be greater than sum(X) and divisible by GCD(X). C is initialized to [1,1,1,1,1,1,1,1]. NN is the sum of each X element multiplied by its corresponding C element. The values of C are then adjusted until the difference between N and NN is 0. If a difference of 0 is unobtainable (in the example diff=4 is smaller than the smallest element of X), then the program solves a linear congruence by first finding a pair of X whose GCD divides diff (8 and 20). For the solution a=3, b=1, we add three to C[0] and subtract 1 from C[2] making C: [1, 1, 1, 1, 1, 1, 2, 45] into C: [4, 1, 0, 1, 1, 1, 2, 45] But I don't want any 0s in the list, only positive and negative integers. Thus, in this example, a 0 adjustment is made: C: [24, 1, -8, 1, 1, 1, 2, 45] Ok, now the problem. In the first three runs, diff was 0, so the linear congruence was skipped. But in the fourth run, b=0 which indicates the error (8*3 evaluated to 6 resulting in b=0). Note I tested gmpy after each run from the Idle prompt. Once the failure occured, the problem continues to exist. That's how I made that original demo, I wrote a simple test AFTER gmpy had gotten funny. >>> X: [8, 16, 20, 24, 40, 72, 84, 92] gcd: 4 N: 12192 X: [8, 16, 20, 24, 40, 72, 84, 92] C: [1, 1, 2, 1, 2, 1, 1, 129] NN: 12192 diff: 0 >>> print gmpy.mpz(8)*gmpy.mpz(3) 24 >>> ================================ RESTART ================================ >>> X: [8, 16, 20, 24, 40, 72, 84, 92] gcd: 4 N: 7340 X: [8, 16, 20, 24, 40, 72, 84, 92] C: [1, 1, 1, 1, 1, 1, 2, 76] NN: 7340 diff: 0 >>> print gmpy.mpz(8)*gmpy.mpz(3) 24 >>> ================================ RESTART ================================ >>> X: [8, 16, 20, 24, 40, 72, 84, 92] gcd: 4 N: 8072 X: [8, 16, 20, 24, 40, 72, 84, 92] C: [2, 1, 1, 1, 1, 2, 1, 84] NN: 8072 diff: 0 >>> print gmpy.mpz(8)*gmpy.mpz(3) 24 >>> ================================ RESTART ================================ >>> X: [8, 16, 20, 24, 40, 72, 84, 92] gcd: 4 N: 6296 X: [8, 16, 20, 24, 40, 72, 84, 92] C: [2, 1, 1, 1, 2, 1, 1, 65] NN: 6292 diff: 4 p: 0 q: 2 a: 3 b: 0 X[p]: 8 X[q]: 20 X: [8, 16, 20, 24, 40, 72, 84, 92] C: [mpz(5), 1, mpz(1), 1, 2, 1, 1, 65] NN: 6286 >>> print gmpy.mpz(8)*gmpy.mpz(3) 6 Hey, maybe the gmpy divm() function isn't fixed after all: IDLE 1.1a3 >>> import gmpy >>> print gmpy.mpz(8)*gmpy.mpz(3) 24 >>> a = gmpy.divm(4,8,20) >>> a mpz(3) >>> print gmpy.mpz(8)*gmpy.mpz(3) 6 Can you verify this? From iainking at gmail.com Fri May 26 09:54:28 2006 From: iainking at gmail.com (Iain King) Date: 26 May 2006 06:54:28 -0700 Subject: Trying to get FreeImagePy to work. Message-ID: <1148651668.578852.3160@i40g2000cwc.googlegroups.com> I've installed ctypes and FreeImagePy. When I do this: >>> import FreeImagePy >>> f = FreeImagePy.Image() I get: find Traceback (most recent call last): File "<stdin>", line 1, in ? File "C:\Python\Lib\site-packages\FreeImagePy\FreeImagePy.py", line 1952, in _ _init__ super(Image, self).__init__(libraryName) File "C:\Python\Lib\site-packages\FreeImagePy\FreeImagePy.py", line 376, in __ init__ self.__lib = self.__internlLibrary(libraryName) File "C:\Python\Lib\site-packages\FreeImagePy\FreeImagePy.py", line 313, in __ init__ self.lib = C.windll.find(libraryName) File "ctypes\__init__.py", line 370, in __getattr__ dll = self._dlltype(name) File "ctypes\__init__.py", line 296, in __init__ self._handle = _dlopen(self._name, mode) WindowsError: [Errno 126] The specified module could not be found I put a 'print self._name' in the ctypes __init__ file, just before line 296 - it's printing out the 'find' just before the error. So, in what specific way have I screwed up the install? Iain From 123 at 321.com Thu May 11 07:25:05 2006 From: 123 at 321.com (DeepBlue) Date: Thu, 11 May 2006 19:25:05 +0800 Subject: Matplotlib in Python vs. Matlab, which one has much better graphical pressentation? In-Reply-To: <e3rluu$5u3$2@enyo.uwa.edu.au> References: <e3rluu$5u3$2@enyo.uwa.edu.au> Message-ID: <44631f1f$0$16013$5a62ac22@per-qv1-newsreader-01.iinet.net.au> anyone? N/A wrote: > Hi all, > > Can I have your opinions on Matlab vs. Matplotlib in Python in terms of > 2D and 3D graphical presentation please. > > Matplotlib in Python vs. Matlab, which one has much better graphical > pressentation? From python.list at tim.thechases.com Fri May 26 08:48:51 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 26 May 2006 07:48:51 -0500 Subject: Can any body help me In-Reply-To: <1148621554.184942.155430@38g2000cwa.googlegroups.com> References: <1148621554.184942.155430@38g2000cwa.googlegroups.com> Message-ID: <4476F933.7000701@tim.thechases.com> > 1.Given a test file containing lines of words such as (abc, abb, > abd,abb, etc), write a script that prints, in order of frequency, how > many times each word appears in the file. solution 1) search the list archives...within the last week, someone wanted to count unique lines in an input file. Several solutions were given--one of which solved it by counting instances of each unique line using a set. The resulting dictionary can then be sorted (by key or value) to yield your desired results. Tweak accordingly. solution 2) using common *nix shell commands: bash$ sort in.txt | uniq -c | sort -nr -tkc From jorge.vargas at gmail.com Wed May 10 13:59:21 2006 From: jorge.vargas at gmail.com (Jorge Vargas) Date: Wed, 10 May 2006 13:59:21 -0400 Subject: help with Linker dependencies missing went compiling mysql-python on Windows without VisualStudio In-Reply-To: <32822fe60605080837i1e8f5781ua1e3904d6a0b878a@mail.gmail.com> References: <32822fe60605080837i1e8f5781ua1e3904d6a0b878a@mail.gmail.com> Message-ID: <32822fe60605101059l47fafd7ds712d74c2accfa9f2@mail.gmail.com> noone here has try this?? On 5/8/06, Jorge Vargas <jorge.vargas at gmail.com> wrote: > > Hi everyone I'm stuck at doing this and can't find the problem, maybe > someone with more experience then I compiling python can help me out. > > I google around and found some old articles, from them the one that seems > more accurate is http://www.vrplumber.com/programming/mstoolkit/ > > of couse I had to difer from that a little so this is what I have install > > - Microsoft Windows Platform SDK Collection for Windows Server 2003 > SP1 > - Microsoft Visual Studio 2005 Version 8.0.50727.42 ( > RTM.050727-4200) thats Microsoft Visual C++ 2005 > > I have try with either one install > > - Microsoft .NET framework SDK 1.1 > - Microsoft .NET Framework Version 2.0.50727 > > > On the other part I have > > - Python 2.4.2 > - mysql-4.1.18-win32.zip > - mysqlpython 1.2.0, 1.2.1 and 1.2.1_p2 > > ----------------------------------------- > Changes to the sources > > - I apply the patch posted on the website, for disutils > http://www.vrplumber.com/programming/mstoolkit/msvccompiler.patch > - I commented out the code related to version in _mysql.c ( wont > give the line numbers cause they differ from file to file. > > /*if (PyDict_SetItemString(dict, "version_info", > PyRun_String(version_info, Py_eval_input, > dict, dict))) > goto error; > if (PyDict_SetItemString(dict, "__version__", > PyString_FromString(__version_ _))) > goto error;*/ > > - I copy over the file my_config.h from the mysql sources (because > it's NOT distributed with the installer) > - and finally I edit site.cfg to this, the rest of the file is not > changed. > > [compiler] > mysqlroot: C:\mysql > library_dirs: %(mysqlroot)s\lib\opt > include_dirs: %(mysqlroot)s\include > libraries: mysqlclient zlib libcmt wsock32 advapi32 > # libcmt msvcrt > #extra_compile_args: > #extra_objects: > > > - I started the "Visual Studio 2005 Command Prompt" > - and setup.py build > - So far I belive I have compile a working copy of the code but i'm > stuck at the linker > > Right now my problem is with the linker the values in site.cfg seems to be > wrong. > > libraries: mysqlclient zlib msvcrt libcmt wsock32 advapi32 > > libs msvcrt libcmt seems to conflict with eachother and with MSVCR80.dll > > I have try using msvcrt and have /NODEFAULTLIB:libcrt > > C:\MySQL-python-1.2.1_p2.tar\MySQL-python-1.2.1_p2>"C:\Program > Files\Microsoft Visual Studio 8\VC\BIN\link.exe" /DLL /nologo > /INCREMENTAL:NO /LIBPATH:C:\mysql\lib\opt /LIBPATH:c:\python24\libs > /LIBPATH:c:\python24\PCBuild mysqlclient.lib zlib.lib msvcrt.lib > wsock32.lib advapi32.lib /EXPORT:init_mysql build\temp.win32- > 2.4\Release\_mysql.obj /OUT:build\lib.win32-2.4\_mysql.pyd/IMPLIB:build\temp.win32- > 2.4\Release\_mysql.lib /NODEFAULTLIB:libcrt > LIBCMT.lib(crtheap.obj) : error LNK2005: __malloc_crt already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(crt0dat.obj) : error LNK2005: __amsg_exit already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(crt0dat.obj) : error LNK2005: __initterm_e already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(crt0dat.obj) : error LNK2005: _exit already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(fflush.obj) : error LNK2005: _fflush already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(dosmap.obj) : error LNK2005: __errno already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(calloc.obj) : error LNK2005: _calloc already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(realloc.obj) : error LNK2005: _realloc already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(crt0init.obj ) : error LNK2005: ___xi_a already defined in > msvcrt.lib(cinitexe.obj) > LIBCMT.lib(crt0init.obj) : error LNK2005: ___xi_z already defined in > msvcrt.lib (cinitexe.obj) > LIBCMT.lib(crt0init.obj) : error LNK2005: ___xc_a already defined in > msvcrt.libcinitexe.obj) > LIBCMT.lib(crt0init.obj) : error LNK2005: ___xc_z already defined in > msvcrt.lib(cinitexe.obj) > LIBCMT.lib(winxfltr.obj) : error LNK2005: ___CppXcptFilter already defined > in msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(winsig.obj) : error LNK2005: _signal already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(tidtable.obj) : error LNK2005: __encode_pointer already defined > in msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(tidtable.obj ) : error LNK2005: __encoded_null already defined > in msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(tidtable.obj) : error LNK2005: __decode_pointer already defined > in msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(mlock.obj) : error LNK2005: __unlock already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(mlock.obj) : error LNK2005: __lock already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(setlocal.obj) : error LNK2005: _setlocale already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(tzset.obj) : error LNK2005: __tzset already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(_ctype.obj) : error LNK2005: _isspace already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(_ctype.obj) : error LNK2005: _iscntrl already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(atox.obj) : error LNK2005: _atoi already defined in msvcrt.lib( > MSVCR80.dll) > LIBCMT.lib(getenv.obj) : error LNK2005: _getenv already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(strtol.obj) : error LNK2005: _strtol already defined in > msvcrt.lib(MSVCR80.dll) > LIBCMT.lib(strtol.obj) : error LNK2005: _strtoul already defined in > msvcrt.lib(MSVCR80.dll) > Creating library build\temp.win32-2.4\Release\_mysql.lib and object > build\temp.win32-2.4\Release\_mysql.exp > LINK : warning LNK4098: defaultlib 'LIBCMT' conflicts with use of other > libs; use /NODEFAULTLIB:library > LIBCMT.lib(crt0.obj) : error LNK2019: unresolved external symbol _main > referenced in function ___tmainCRTStartup > build\lib.win32-2.4\_mysql.pyd : fatal error LNK1120: 1 unresolved > externals > > I have try using libcmt and have /NODEFAULTLIB:msvcrt > > C:\MySQL-python-1.2.1_p2.tar\MySQL-python-1.2.1_p2>"C:\Program > Files\Microsoft Visual Studio 8\VC\BIN\link.exe" /DLL /nologo > /INCREMENTAL:NO /LIBPATH:C:\mysql\l ib\opt /LIBPATH:c:\python24\libs > /LIBPATH:c:\python24\PCBuild mysqlclient.lib zlib.lib libcmt.lib > wsock32.lib advapi32.lib /EXPORT:init_mysql build\temp.win32-2 .4\Release\_mysql.obj > /OUT:build\lib.win32-2.4\_mysql.pyd /IMPLIB:build\temp.win > 32-2.4\Release\_mysql.lib /NODEFAULTLIB:msvcrt > Creating library build\temp.win32-2.4\Release\_mysql.lib and object > build\temp.win32-2.4\Release\_mysql.exp > _mysql.obj : warning LNK4217: locally defined symbol _sprintf imported in > function __mysql_ConnectionObject_repr > _mysql.obj : error LNK2019: unresolved external symbol __imp__strncat > referenced in function __mysql_row_to_dict > _mysql.obj : error LNK2019: unresolved external symbol __imp__strncpy > referenced in function __mysql_row_to_dict > build\lib.win32-2.4\_mysql.pyd : fatal error LNK1120: 2 unresolved > externals > > And I have also try using none. of them, please note this is the same as > the above > > C:\MySQL-python-1.2.1_p2.tar\MySQL-python-1.2.1_p2>"C:\Program > Files\Microsoft Visual Studio 8\VC\BIN\link.exe" /DLL /nologo > /INCREMENTAL:NO /LIBPATH:C:\mysql\lib\opt /LIBPATH:c:\python24\libs > /LIBPATH:c:\python24\PCBuild mysqlclient.lib zlib.lib wsock32.lib > advapi32.lib /EXPORT:init_mysql build\temp.win32-2.4\Release\_mysql.obj/OUT:build\lib.win32- > 2.4\_mysql.pyd /IMPLIB:build\temp.win32-2.4\Release\_mysql.lib/NODEFAULTLIB:msvcrt /NODEFAULTLIB:libcrt > Creating library build\temp.win32-2.4\Release\_mysql.lib and object > build\temp.win32-2.4\Release\_mysql.exp > _mysql.obj : warning LNK4217: locally defined symbol _sprintf imported in > function __mysql_ConnectionObject_repr > _mysql.obj : error LNK2019: unresolved external symbol __imp__strncat > referenced in function __mysql_row_to_dict > _mysql.obj : error LNK2019: unresolved external symbol __imp__strncpy > referenced in function __mysql_row_to_dict > build\lib.win32-2.4\_mysql.pyd : fatal error LNK1120: 2 unresolved > externals > > now the weird thing is that i'm missing some very common functions I even > try adding > > #include <windows.h> > #include <stdio.h> > #include <string.h> > #include <stddef.h> > #include <stdlib.h> > > to the mysql.c file and they are still missing. > > my site.cfg mysql section is > > [compiler] > mysql_root: C:\mysql > library_dirs: %(mysql_root)s\lib\opt > include_dirs: %(mysql_root)s\include > libraries: mysqlclient zlib libcmt wsock32 advapi32 > # libcmt msvcrt > #extra_compile_args: > #extra_objects: > > I have also notice I have multiple versions of libcmt.lib and msvcrt.lib > one in C:\Program Files\Microsoft Visual Studio 8\VC\lib and another in > C:\Program Files\Microsoft Visual Studio .NET 2003\Vc7\lib > > I have try with both and still having the same error. > > sorry for the long message but it's a complex problem so it needs big > files:) > > any ideas? > > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060510/c83e0d7d/attachment.html> From aleaxit at yahoo.com Sat May 6 15:43:02 2006 From: aleaxit at yahoo.com (Alex Martelli) Date: Sat, 6 May 2006 12:43:02 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> Message-ID: <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> Ken Tilton <kentilton at gmail.com> wrote: > Martin P. Hellwig wrote: > > Bill Atkins wrote: > > <cut> > > > >> > >> How do you define scalability? > >> > > http://www.google.com/search?hl=en&q=define%3Ascalability&btnG=Google+Search > > > > Damn! Google can do that?! Omigod!!! Not joking, I never knew that,a You're welcome; we do have several little useful tricks like that. > lways used dictionary.com. Thx! I meant: > > > The ability to add power and capability to an existing system without > > significant expense or overhead. www.yipes.com/care/cc_glossary.shtml Excellent -- just the definition of "scalability" that Google and its competitor live and die by ((OK, OK, I'm _not_ implying that such issues as usability &c don't matter, by no means -- but, I live mostly in the world of infrastructure, where scalability and reliability reign)). > The number of definitions explains why most respondents should save > their breath. Natural language is naturally ambiguous. Meanwhile Usenet > is the perfect place to grab one meaning out of a dozen and argue over > the implications of that one meaning which of course is never the one > originally intended, as any reasonable, good faith reader would admit. However, you and I are/were discussing exactly the same nuance of meaning, either by a funny quirk of fate or because it's the one that really matters in large-scale programming (and more generally, large-scale systems). E.g., if your existing system can gracefully handle your current traffic of, say, a billion queries of complexity X, you want to be able to rapidly add a feature that will increase the average query's complexity to (X+dX) and attract 20% more users, so you'll need to handle 1.2 billion queries just as gracefully: i.e., you need to be able to add power and capability to your existing system, rapidly and reliably, just as that definition says. When this is the challenge, your choice of programming language is not the first order of business, of course -- your hardware and network architecture loom large, and so does the structuring of your applications and infrastructure software across machines and networks. Still, language does matter, at a "tertiary" level if you will. Among the potential advantages of Lisp is the fact that you could use Lisp across almost all semantic levels ("almost" because I don't think "Lisp machines" are a realistic option nowadays, so lower levels of the stack would remain in C and machine language -- but those levels may probably be best handled by a specialized squad of kernel-level and device-driver programmers, anyway); among the potential advantages of Python, the fact that (while not as suited as Lisp to lower-level coding, partly because of a lack of good solid compilers to make machine language out of it), it brings a powerful drive to uniformity, rather than a drive towards a host of "domain-specific" Little Languages as is encouraged by Lisp's admirably-powerful macro system. One key axis of scalability here is, how rapidly can you grow the teams of people that develop and maintain your software base? To meet all the challenges and grasp all the opportunities of an exploding market, Google has had to almost-double its size, in terms of number of engineers, every year for the last few years -- I believe that doing so while keeping stellar quality and productivity is an unprecedented feat, and while (again!) the choice of language(s) is not a primary factor (most kudos must go to our management and its approaches and methods, of course, and in particular to the strong corporate identity and culture they managed to develop and maintain), it still does matter. The uniformity of coding style and practices in our codebase is strong. We don't demand Python knowledge from all the engineers we hire: for any "engineering superstar" worth the adjective, Python is really easy and fast to pick up and start using productively -- I've seen it happen thousands of times, both in Google and in my previous career, and not just for engineers with a strong software background, but also for those whose specialties are hardware design, network operations, etc, etc. The language's simplicity and versatility allow this. Python "fits people's brains" to an unsurpassed extent -- in a way that, alas, languages requiring major "paradigm shifts" (such as pure FP languages, or Common Lisp, or even, say, Smalltalk, or Prolog...) just don't -- they really require a certain kind of mathematical mindset or predisposition which just isn't as widespread as you might hope. Myself, I do have more or less that kind of mindset, please note: while my Lisp and scheme are nowadays very rusty, proficiency with them was part of what landed me my first job, over a quarter century ago (microchip designers with a good grasp of lisp-ish languages being pretty rare, and TI being rather hungry for them at the time) -- but I must acknowlegde I'm an exception. Of course, the choice of Python does mean that, when we really truly need a "domain specific little language", we have to implement it as a language in its own right, rather than piggybacking it on top of a general-purpose language as Lisp would no doubt afford; see <http://labs.google.com/papers/sawzall.html> for such a DSLL developed at Google. However, I think this tradeoff is worthwhile, and, in particular, does not impede scaling. Alex From piet at cs.uu.nl Thu May 25 07:40:29 2006 From: piet at cs.uu.nl (Piet van Oostrum) Date: Thu, 25 May 2006 13:40:29 +0200 Subject: Request for comments on python distributed technologies References: <mailman.5972.1148064796.27775.python-list@python.org> Message-ID: <m28xoqjpsi.fsf@ordesa.cs.uu.nl> >>>>> "Carl J. Van Arsdall" <cvanarsdall at mvista.com> (CJVA) wrote: >CJVA> Hey everyone, another question for the list. In particular i'm >CJVA> looking for comments on some of the distributed technologies >CJVA> supported in python. Specifically, I'm looking at XML-RPC, RPyC, >CJVA> CORBA, and Twisted. Although it doesn't cover exactly the technologies mentioned above the following article may be interesting for you: Python Web services developer: Messaging technologies compared http://www.ibm.com/developerworks/library/ws-pyth9/ -- Piet van Oostrum <piet at cs.uu.nl> URL: http://www.cs.uu.nl/~piet [PGP 8DAE142BE17999C4] Private email: piet at vanoostrum.org From nephish at xit.net Tue May 23 09:25:43 2006 From: nephish at xit.net (nephish at xit.net) Date: 23 May 2006 06:25:43 -0700 Subject: problem with writing a simple module In-Reply-To: <dlq372dauhaigrhsd54rbadf7geklbkbop@4ax.com> References: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> <dlq372dauhaigrhsd54rbadf7geklbkbop@4ax.com> Message-ID: <1148390743.600334.227460@j73g2000cwa.googlegroups.com> ok, thanks everyone. The funny thing about the name conventions is, i was just two days ago looking around on the web for the best way to go about consistancy in variable names, class names, etc.. i have the module working now. thanks to you guys. And i think i understand the container name | object name paradigm. i did not get the suggestion to change all my database queries so the parameter substitution is performed by the .execute*() methods.. that one went over me head. thanks for all the help, guys From sjmachin at lexicon.net Sun May 28 21:36:40 2006 From: sjmachin at lexicon.net (John Machin) Date: Mon, 29 May 2006 11:36:40 +1000 Subject: itertools.count() as built-in In-Reply-To: <1148860241.048549.269330@j73g2000cwa.googlegroups.com> References: <1148840097.405460.42790@i39g2000cwa.googlegroups.com> <447A2C59.2040002@lexicon.net> <1148860241.048549.269330@j73g2000cwa.googlegroups.com> Message-ID: <447A5028.9070203@lexicon.net> On 29/05/2006 9:50 AM, jantod at gmail.com wrote: > I have a project of around 6000 lines where I used count() 20 times. It > has 14 modules, 10 of which I needed an explicit import. > > Many of the usages are of the form: > > for item, n in zip(items, count(N)): > dostuff > > Around half of these are due to using pylab.subplot(x,y.n), which > requires values for n>=1. So I want N=1. The enumerate builtin starts > from 0. Call me a Luddite if you will, but I'd suggest that instead of for item, n in zip(items, count(N)): dostuff(item, n) you try (1) for n, item in enumerate(items): dostuff(item, n+N) or (2) n = N-1 for item in items: n += 1 dostuff(item, n) > I also write out textual reports that start with n=1. > > I also have things like > for n, component, rotations in zip(count(), > sorted(tools.component_files().keys()), all_symbol_rotations) > where the enumerate version just looks even more confusing and easy to > mess up > for n, component, rotations in > enumerate(sorted(tools.component_files().keys()), all_symbol_rotations) As enumerate takes only 1 argument, I presume that is the messed-up version. Yes, the correct version is a pain: for n, (component, rotations) in enumerate(zip(yadda1, yadda2)): Perhaps you could use something like this: >>> def zipwithcount(N, *args): ... for x, guff in enumerate(zip(*args)): ... yield guff + (x + N,) ... >>> list(zipwithcount(666, 'abc', 'xyz')) [('a', 'x', 666), ('b', 'y', 667), ('c', 'z', 668)] >>> Cheers, John From nobody at 127.0.0.1 Wed May 3 19:15:03 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 23:15:03 GMT Subject: Python & SSL References: <e38c66$r2t$1@zinnia.noc.ucla.edu> <4457B74A.2000208@benjiyork.com> <mailman.5284.1146693115.27775.python-list@python.org> <slrne5i9oo.ijc.sybrenUSE@schuimige.stuvel.eu> Message-ID: <XPa6g.21456$4L1.14084@newssvr11.news.prodigy.com> Sybren Stuvel wrote: > I'm curious. Can you give me an example? AFAIK you need to know who > you're talking to before transmitting sensitive information, otherwise > you could be talking to anybody - and that's just what you wanted to > prevent with the encryption, right? Encryption has multiple meanings. In the general sense, it encompasses all of cryptography and the information security properties crypto provides. This meaning is rather imprecise and you run into problems using it to answer questions like yours. I won't encryption this way again in this post. In a more specific/technical sense, encryption protects the privacy of transmitted information, preventing third-party eavesdropping. It makes no guarantees who's on the other end of your encrypted pipe. Block cipher modes (CBC-DES, CTR-Rijndael/AES, etc) and asymmetric cipher modes (RSA-OAEP) are examples. Integrity guarantees that the data sent is the same as the data received. Authentication verifies the party on the other end of your pipe. This is the primary purpose of SSL certs, authenticating web sites to browsers (you get data encryption too, but that's somewhat less important). Note that it doesn't verify the party's identity or trustworthiness, only that they know a particular secret. The assumption is that if the certificate system is setup correctly, possession of that secret makes them trustworthy (or rather, you can trust the site because their secret proves that a cert authority somewhere trusts them in some fashion). Trustworthy for what is never defined. If that sounds convoluted or illogical, it is. "Ten Risk of PKI" is a good intro to why this chain of trust isn't all it's cracked up to be. It's good reading to understand exactly what you benefits you get from an SSL connection. http://www.schneier.com/paper-pki.html So in a long-winded way, I've answered your question. The short and sweet of it is, yes, SSL is meant to prevent you from "talking to anybody". In that it succeeds* -- but only so far as making sure the site you're talking to paid some money to one of the dozens of cert authorities for a minimal background check. You've gone from "anybody" to "anybody with a couple hundred bucks and spare time to blow". *at least, until the end user completely ignores the warning dialogs and accepts whatever invalid cert he's presented with. Of course if you control the server and serve a small clientele who already trust you, you can have clients import your own cert so they really can be sure who they're talking to -- as long as your master key remains secret. Watch out for hackers and disgruntled employees. The moral of this story is: computer security is an ugly, complex business. From Dorit.Gross at fao.org Fri May 12 14:11:22 2006 From: Dorit.Gross at fao.org (Gross, Dorit (SDRN)) Date: Fri, 12 May 2006 20:11:22 +0200 Subject: How to pass variables between scripts? Message-ID: <5290E77B1FE2FE40B82AA54158825F0602EF50F5@hqosex01.fao.org> Dear list, I am an absolute newbie to python and would appreciate your help very much :) I am trying to write a little python script that wraps a set of external scripts. The external scripts are either also written in python or are simple bash scripts. My wrapping script should be able to send an argument to the first script, to execute it, to read its results and to send them then as arguments into the next script. This is the first part that I have written so far: #! /usr/local/bin/python # test_exec.py import os, sys, glob fileList = glob.glob('/data/*.ZIP') for f in fileList: try: globvars = {'infile' : f} locvars = {} execfile('/scripts/second.py', globvars(), locvars) except IOError: exit(0) print locvars And this is what happens when calling test_exec.py ./test_exec.py Traceback (most recent call last): File "./test_exec.py", line 19, in ? execfile('/scripts/second.py', vars(), results) TypeError: 'dict' object is not callable I tried already to modify the script in different ways but wasn't successful so far to make it running. Could you maybe help what I am missing? Further, I am not sure how the second python has to look like to actually read what is given in "globvars" and to sent its results into "locvars". Or might os.popen* be a better option? -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060512/b1d8ddc2/attachment.html> From onurb at xiludom.gro Fri May 5 08:50:32 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 14:50:32 +0200 Subject: Method acting on arguements passed In-Reply-To: <1146832062.017259.265700@y43g2000cwc.googlegroups.com> References: <1146832062.017259.265700@y43g2000cwc.googlegroups.com> Message-ID: <445b4a75$0$5047$626a54ce@news.free.fr> Panos Laganakos wrote: > I want a class method to take action depending on the type of the > arguement passed to it. > > ie: > getBook(id) # get the book by ID > getBook(name) # get the book by name > ... > > Other languages use the term function/method overloading to cope with > this. And when I googled about it seems that GvR is testing it for 3.0 > inclusion or so. > > I was thinking of right after the function declaration check for the > parameter passed by isinstance() or type() and use if..elif..else to > act. > > Is this the pythonic way/best practice to apply here? For simple case and if there's no need for extensibility, this is usually quite enough - even if somewhat ugly. If the code for each case is really different, I'd split the whole thing into three separate methods : getBookById, getBookByName, and getBook that only do the dispatch. Else - and depending on the context, needs, specs and whatnot, I'd look either at the visitor pattern (or any custom double-dispatch) or at an existing multimethod implementation (like David Mertz's multimethod or Philip Eby's protocol.dispatch). 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 gmc at serveisw3.net Sun May 21 01:08:28 2006 From: gmc at serveisw3.net (=?ISO-8859-1?Q?Gonzalo_Monz=F3n?=) Date: Sun, 21 May 2006 07:08:28 +0200 Subject: Python update trouble (2.3 to 2.4): x<<y In-Reply-To: <cef393a0512232219w6fab1b09tfb10debd31fd12b7@mail.gmail.com> References: <cef393a0512232219w6fab1b09tfb10debd31fd12b7@mail.gmail.com> Message-ID: <446FF5CC.6020507@serveisw3.net> Hi all! I have been translating some Python custom C extension code into Python, as I need these modules to be portable and run on a PocketPC without the need of compile (for the purpose its a must 2.4 as it is the last PythonCE release with great improvements). But I've been stuck with a script wich does not work as expected once translated to python, 2.4 In the meantime, I thought I could test it with an old 2.3 version I have installed too on my computer, and found it run as expected, but see the FutureWarning, so googled a bit and found PEP 237 and long integer integration issue, but then can't find any workaround to fix the code for Python 2.4 Hope somebody could point some suggestion, or perhaps, the solution is pretty simple, but I missed it. As I said, the code works fine on 2.3. I attach the code below. The trouble is on the CalcCRC16 function, as you can see on the FutureWarning message. InitCRC16 function does some bitwise xor's too, but I checked it and works as expected. Thought because only happen to be with small values there. Thanks in advance for any help, Gonzalo ############################## Python 2.3.2: pytest1.py:90: FutureWarning: x<<y losing bits or changing sign will return a long in Python 2.4 and up crc = gCRC16Table[((crc >> 8) & 255)] ^ (crc << 8) ^ ord(str[x]) 67560050 ############################## Python 2.4.2: 22002496167782427386022437441624938050682666541682 *Expected result is 67560050* # ############################# # pytest1.py gCRC16Table = [] def InitCRC16(): global gCRC16Table for i in xrange(0,256): crc = i << 8 for j in xrange(0,8): if (crc & 0x8000) != 0: tmp = 0x1021 else: tmp = 0 crc = (crc << 1) ^ tmp gCRC16Table.append(crc) def CalcCRC16(str): global gCRC16Table crc = 0xFFFF for x in xrange(0,len(str)): crc = gCRC16Table[((crc >> 8) & 255)] ^ (crc << 8) ^ ord(str[x]) return crc test = "123456asdfg12345123" InitCRC16() print CalcCRC16(test) From bjourne at gmail.com Sun May 28 10:19:47 2006 From: bjourne at gmail.com (=?ISO-8859-1?Q?BJ=F6rn_Lindqvist?=) Date: Sun, 28 May 2006 16:19:47 +0200 Subject: iteration over non-sequence ,how can I resolve it? In-Reply-To: <1148822420.452617.79720@u72g2000cwu.googlegroups.com> References: <1148822420.452617.79720@u72g2000cwu.googlegroups.com> Message-ID: <740c3aec0605280719i31e225f5t1c1e373bac2ac5af@mail.gmail.com> On 28 May 2006 06:20:20 -0700, python <dongdonglove8 at hotmail.com> wrote: > at line "for j in linkReturned:" , raise an error: > File "C:\pythonProgram\test.py", line 308, in main > for j in linkReturned: > TypeError: iteration over non-sequence > how can I get a list from the return of thread.start() ? You can't. thread.start() always return None. > class PrintThread(threading.Thread): > def __init__(self, urlList): > threading.Thread.__init__(self) > urllist=[] > self.urllist=urlList > def run(self): > urllink=[] > ...... > return urllink > > > for i in range(0,2): > thread=PrintThread(links) > threadList.append(thread) > linkReturned=[] > for i in threadList: > linkReturned=i.start() > for j in linkReturned: > links.append(j) >From the looks of this code it seems like you want a sub-routine not a thread. You can simulate returning a value from a thread by adding a "return value" attribute to the PrintThread class that the run() method writes to. Then you would have to add some form of synchronizing so that your main program does not try to read the "return value" of the thread before the thread actually has written the "return value." -- mvh Bj?rn From panos.laganakos at gmail.com Thu May 4 17:31:35 2006 From: panos.laganakos at gmail.com (Panos Laganakos) Date: 4 May 2006 14:31:35 -0700 Subject: Python 2.4.2 to 2.4.3 transition issue In-Reply-To: <mailman.5346.1146773763.27775.python-list@python.org> References: <1146772876.641098.166110@g10g2000cwb.googlegroups.com> <mailman.5346.1146773763.27775.python-list@python.org> Message-ID: <1146778295.433948.188870@i39g2000cwa.googlegroups.com> Heh, Frederic, It seems that its Lilypond's (www.lilypond.org) fault. It registered its bin directory in the PATH variable, which seems to contain a python.exe too. So the result of: >>>import sys; sys.executable 'D:\\Program Files\\LilyPond\\usr\\bin\\python.exe' As for the instances of python24.dll, there are two: one in system32 and one in inkscape's directory. I 'fixed' it, by defining python's directory ahead of lilypond's. Now the right executable is called. Is there any other way instead of positioning in the PATH variable? From nobody at 127.0.0.1 Wed May 17 20:42:45 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 00:42:45 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> Message-ID: <9qPag.18370$Lm5.16748@newssvr12.news.prodigy.com> Michael Tobis wrote: > Edward also asked if others had similar experiences. If others did, the > assemblage of their opinions would in fact consttitute data. I have no > idea why people are giving him such grief over this request. Thank you, Michael. It was starting to feel like I'd asked about the best way to club baby seals in here. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From fredrik at pythonware.com Wed May 3 03:57:08 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 09:57:08 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com><1146634135.469447.54670@j73g2000cwa.googlegroups.com><mailman.5248.1146637412.27775.python-list@python.org> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> Message-ID: <e39nom$nc7$1@sea.gmane.org> tsaar2003 at yahoo.com wrote: > Yes, I know that "constant" A will also be modified as the b[0] points > to A. Obviously the [] should be marked as immutable, as A is declared > to be constant thus immutable. If somebody tries to modify this > immutable object an error would occur. so a constant declaration doesn't only affect the namespace, it also modifies the type of the object ? are you sure you know how Python's object model work ? if you do, please explain your proposal in terms of what needs to be changed, rather than in terms of wishful thinking. </F> From pydecker at gmail.com Wed May 24 20:52:33 2006 From: pydecker at gmail.com (Peter Decker) Date: Wed, 24 May 2006 20:52:33 -0400 Subject: John Bokma harassment In-Reply-To: <Xns97CD6F09CFD9Ecastleamber@130.133.1.4> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> <Xns97CD6F09CFD9Ecastleamber@130.133.1.4> Message-ID: <ca55a9900605241752v41c1cd61u9b2978f23f8387a9@mail.gmail.com> On 24 May 2006 15:54:56 GMT, John Bokma <john at castleamber.com> wrote: > And ain't it cool that reporting Xah's abuse might stop both? C'mon - admit it! you hafta be a Republican with a hardon for Bush! <rof,lmao!> -- # p.d. From c.gillespie at ncl.ac.uk Wed May 3 05:40:06 2006 From: c.gillespie at ncl.ac.uk (Colin Gillespie) Date: Wed, 03 May 2006 10:40:06 +0100 Subject: Calling a Postgres Function using CGI written in Python In-Reply-To: <1146648602.110172.191810@g10g2000cwb.googlegroups.com> References: <1146648602.110172.191810@g10g2000cwb.googlegroups.com> Message-ID: <e39tpn$ktk$1@ucsnew1.ncl.ac.uk> A quick google for "Python CGI" gives you lots of links. But if you intend to do much in the way of cgi, then I would recommend the spyce framework,http://spyce.sourceforge.net/ HTH Colin Fuzzydave wrote: > I need to call a function stored in Postgres which does a lot of the db > and calculation work > all the SQL queries are hardcoded in a file called cmi.py. What i need > to do is too to call > my function from postgres passing in my product_code variable into it > and returning the > value from the query into a variable i can print to screen as part of a > HTML page. > > I am sure its very easy but have never done anything in python as have > none of the guys > i work with making this a bit of a problem. > > Cheers Guys > David > From usenet at local.machine Mon May 22 19:18:41 2006 From: usenet at local.machine (=?ISO-8859-2?Q?Dra=BEen_Gemi=E6?=) Date: Tue, 23 May 2006 01:18:41 +0200 Subject: Software Needs Philosophers In-Reply-To: <44723437$0$11063$9b4e6d93@newsread4.arcor-online.net> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <e4q37v$ipo$2@magcargo.vodatel.hr> <44723437$0$11063$9b4e6d93@newsread4.arcor-online.net> Message-ID: <e4tg80$t1j$2@magcargo.vodatel.hr> Timo Stamm wrote: > Dra?en Gemi? schrieb: > >> Xah Lee wrote: >> >>> Software Needs Philosophers >>> >> >> Welcome to my junk filters !!!! > > > > Thanks for informing each and every reader of the newsgroups > comp.lang.perl.misc, comp.lang.python, comp.lang.java.programmer, > comp.lang.lisp, comp.lang.function about your junk filters. Anytime...... DG From fredrik at pythonware.com Wed May 3 10:34:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Wed, 3 May 2006 16:34:44 +0200 Subject: Sorting a list of dictionaries by dictionary key References: <mailman.19720.1146662103.27774.python-list@python.org> <4458B3B6.10606@gmail.com> Message-ID: <e3af26$a9q$1@sea.gmane.org> Nico Grubert wrote: > > assuming that DateTime returns something that compares correctly, you can > > do something like: > > > > def sortkey(item): > > return item.get("from_datetime") > > > > data.sort(key=sortkey) > > > > (assuming Python 2.4 or later) > > Thank you very much, Frederik. Unfortunately, I can only use > Python 2.3.5. under Python 2.3, you can either use a custom compare function (which may be slow if you have lots of items, because a sort has to do more com- pares than there are items): def compare(a, b): return cmp(sortkey(a), sortkey(b)) data.sort(compare) or do your own "decorate-sort-undecorate" (which is what the "key" option is doing for you): data = [ (sortkey(x), x) for x in data ] # decorate data.sort() data = [ x[1] for x in data ] # undecorate </F> From songyi012133 at gmail.com Wed May 17 23:13:24 2006 From: songyi012133 at gmail.com (hankssong) Date: 17 May 2006 20:13:24 -0700 Subject: how to make the program notify me explicitly Message-ID: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> Hi everyone, I'm writing a program that can retrieve some specified info from a web page, such as python topics I interested on a bbs. Now I had written the python script (run in the background), but I don't know how to make the program notify me explicitly, so I can be easily informed. I don't know whether python can warn me through beeping like C program(e.g.:printf("%c", '\07');) Thanks in advance! From corff at zedat.fu-berlin.de Sun May 21 10:13:17 2006 From: corff at zedat.fu-berlin.de (corff at zedat.fu-berlin.de) Date: 21 May 2006 14:13:17 GMT Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <4dbartF19cb9rU1@uni-berlin.de> In comp.lang.perl.misc Xah Lee <xah at xahlee.org> wrote: : the way through the Software Dark Ages we're in today: a time that will Wrong. We live in a paradise of ideas and possibilities well beyond the wildest dreams of only 20 years ago. : But I've failed. This isn't the essay I wanted to write, because I'm : neither a great thinker nor a great writer. Finally you got _something_ right. Anyway, unless ($your_text=m/\b[Pp]erl\b/) {print "Completely OT."} Sorry for feeding the unspeakable, Oliver. -- Dr. Oliver Corff e-mail: corff at zedat.fu-berlin.de From bearophileHUGS at lycos.com Fri May 26 16:57:27 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 26 May 2006 13:57:27 -0700 Subject: Speed up this code? In-Reply-To: <1148656566.089446.159470@y43g2000cwc.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <4476d3ac_2@newspeer2.tds.net> <1148647447.804097.228580@j33g2000cwa.googlegroups.com> <1148649951.816182.134210@g10g2000cwb.googlegroups.com> <1148656566.089446.159470@y43g2000cwc.googlegroups.com> Message-ID: <1148677047.168686.42580@g10g2000cwb.googlegroups.com> I have tried this comparison, with a version I've modified a bit, I have encoutered a problem in sieve_all, for example with n=10000, I don't know why: def sieve_all(n=100): # yield all primes up to n stream = iter(xrange(2, n)) while True: p = stream.next() yield p def s1(p, stream): # yield all non-multiple of p return (q for q in stream if q%p != 0) stream = s1(p, stream) def primes(n): "primes(n): return a list of prime numbers <=n." # Recipe 366178 modified and fixed if n == 2: return [2] elif n<2: return [] s = range(3, n+2, 2) mroot = n ** 0.5 half = len(s) i = 0 m = 3 while m <= mroot: if s[i]: j = (m*m - 3) / 2 s[j] = 0 while j < half: s[j] = 0 j += m i += 1 m = 2 * i + 3 if s[-1] > n: s[-1] = 0 return [2] + filter(None, s) from time import clock pmax = 21 for p in xrange(12, pmax): n = 2 ** p t1 = clock() primes(n) t2 = clock() list(sieve_all(n)) t3 = clock() print "primes(2^%s= %s):" % (p, n), round(t2-t1, 3), "s", round(t3-t2, 3), "s" import psyco psyco.bind(primes) psyco.bind(sieve_all) for p in xrange(12, pmax): n = 2 ** p t1 = clock() primes(n) t2 = clock() list(sieve_all(n)) t3 = clock() print "primes(2^%s= %s):" % (p, n), round(t2-t1, 3), "s", round(t3-t2, 3), "s" Bye, bearophile From nephish at xit.net Mon May 22 11:00:14 2006 From: nephish at xit.net (nephish at xit.net) Date: 22 May 2006 08:00:14 -0700 Subject: problem with writing a simple module In-Reply-To: <_s2dnXJvyY7vVezZnZ2dneKdnZydnZ2d@comcast.com> References: <1148305673.333321.9470@i40g2000cwc.googlegroups.com> <4471C4D9.8020806@websafe.com> <1148307297.076724.128310@j33g2000cwa.googlegroups.com> <_s2dnXJvyY7vVezZnZ2dneKdnZydnZ2d@comcast.com> Message-ID: <1148310013.952757.45720@j33g2000cwa.googlegroups.com> yeah, i have thought of picking that one up. That one, or nutshell. i got programming python, which was way over my head, then learning python, which has helped me a great deal. thanks From levub137 at wi.rr.com Fri May 5 06:50:52 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Fri, 05 May 2006 10:50:52 GMT Subject: CRC calculation In-Reply-To: <1146772014.264899.203740@j73g2000cwa.googlegroups.com> References: <1146772014.264899.203740@j73g2000cwa.googlegroups.com> Message-ID: <g6G6g.32851$Tf1.2501@tornado.rdc-kc.rr.com> mike7411 at gmail.com wrote: > Does anyone know where I can get python code to perform a CRC > calculation on an IP packet? > Check out http://crcmod.sourceforge.net/ From wrffruntre at tznvy.pbz.ROT13 Wed May 17 21:25:32 2006 From: wrffruntre at tznvy.pbz.ROT13 (Jesse Hager) Date: Wed, 17 May 2006 21:25:32 -0400 Subject: creating a new database with mysqldb In-Reply-To: <gcKag.2113$No6.46302@news.tufts.edu> References: <gcKag.2113$No6.46302@news.tufts.edu> Message-ID: <126nj7utnok7u6e@corp.supernews.com> John Salerno wrote: > Since the connect method of mysqldb requires a database name, it seems > like you can't use it without having a database already created. So is > there a way to connect to your mysql server (without a specified > database) in order to create a new database (i.e., the CREATE DATABASE > query)? > > Thanks. In every MySQL library I have ever seen, the database parameter is optional. You may either omit it or pass an empty string. It is just a shortcut so the application does not need to send a "USE" command to select the active database. >>>import MySQLdb >>>db = MySQLdb.connect("host","username","password") >>>c = db.cursor() To get the currently selected database: >>>c.execute("SELECT DATABASE()") 1L >>>c.fetchall() ((None,),) ^^^ None (NULL) indicates no currently selected database. To set the default database: >>>c.execute("USE mysql") 0L Getting the database again: >>>c.execute("SELECT DATABASE()") 1L >>>c.fetchall() (('mysql',),) ^^^ A string indicates that a database is currently selected. Hope this helps. -- Jesse Hager email = "wrffruntre at tznvy.pbz".decode("rot13") From belred at gmail.com Sun May 14 22:48:55 2006 From: belred at gmail.com (Bryan) Date: Sun, 14 May 2006 19:48:55 -0700 Subject: Tabs versus Spaces in Source Code In-Reply-To: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: <e48q8e$9si$1@sea.gmane.org> Xah Lee wrote: > Tabs versus Spaces in Source Code > > Xah Lee, 2006-05-13 > > In coding a computer program, there's often the choices of tabs or > spaces for code indentation. There is a large amount of confusion about > which is better. It has become what's known as ?religious war? ? > a heated fight over trivia. In this essay, i like to explain what is > the situation behind it, and which is proper. > > Simply put, tabs is proper, and spaces are improper. Why? This may seem > ridiculously simple given the de facto ball of confusion: the semantics > of tabs is what indenting is about, while, using spaces to align code > is a hack. > i agree, tabs is proper and i always use the tab key to indent... it puts in 4 spaces. From larry.bates at websafe.com Wed May 10 11:22:55 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 10 May 2006 10:22:55 -0500 Subject: PIL thumbnails unreasonably large In-Reply-To: <1147272829.719796.150680@y43g2000cwc.googlegroups.com> References: <1147272829.719796.150680@y43g2000cwc.googlegroups.com> Message-ID: <4462054F.2010502@websafe.com> Almad wrote: > Hello, > > I wonder how do I create reasonable thumbnails from JPEG with PIL. > My code: > > logging.debug('Downloading image %s' % id) > uri = ''.join([config['photo']['masterpath'], '?p=', > str(id)]) > uf = urlopen(uri).read() > f = tmpfile() > f.write(uf) > f.seek(0) > logging.debug('Resizing image %s' % id) > img = Image.open(f) > prev = img.copy() > img.thumbnail((180,180)) > if prev.size[0] > 640 or prev.size[1] > 640: > prev.thumbnail((640,640)) > # save resized to temporary files > f.seek(0) > img.save(f, "JPEG", quality=50) > fp = tmpfile() > prev.save(fp, "JPEG", quality=200) > > Well, works fine, but img size is about 0,5 MB (!), but strangely, prev > one is around 200 kb. > > How do I change this? I tried to play with various quality settings, > but with no effect. img thumbnail is supposed to be < 10 kb... > > Thank You, > > Almad > JPEG quality 200 is overkill, btw -- it completely disables JPEG's quantization stage, and "mainly of interest for experimental pur- poses", according to the JPEG library documentation, which continues: "Quality values above about 95 are NOT recommended for normal use; the compressed file size goes up dramatically for hardly any gain in output image quality." -Larry Bates From spamspam at spam.eggs Tue May 9 14:22:37 2006 From: spamspam at spam.eggs (Ben C) Date: 9 May 2006 18:22:37 GMT Subject: clear memory? how? References: <e3pjop$rqd$1@enyo.uwa.edu.au> <4cb49uF15811rU1@uni-berlin.de> <slrne61dve.e9e.spamspam@bowser.marioworld> Message-ID: <slrne61nlc.e9e.spamspam@bowser.marioworld> On 2006-05-09, Ben C <spamspam at spam.eggs> wrote: > def clearall(): > all = [var for var in globals() if "__" not in (var[:2], var[-2:])] > for var in all: > del globals()[var] > > since I think magic things always start and end with __. Oops, got that wrong anyway: should be: all = [var for var in globals() if (var[:2], var[-2:]) != ("__", "__")] From runlevelten at gmail.com Sat May 6 18:52:28 2006 From: runlevelten at gmail.com (Ten) Date: Sat, 6 May 2006 23:52:28 +0100 Subject: Swaying A Coder Away From Python In-Reply-To: <9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> References: <9afea2ac0605040209o79baa2d1o89be36d246bef38c@mail.gmail.com> <W40839200.311.1532.1@mx-extra.net> <9afea2ac0605040457p816a0d0ic05c08f412a6048f@mail.gmail.com> Message-ID: <200605062352.29062.runlevelten@gmail.com> On Thursday 04 May 2006 12:57, Tim Williams wrote: > > (and why do you > > seem to think that this matters, btw ?) > > I actually think it is complete twaddle For my part, I have to agree with you on this one. In terms of any subjective to-and-fro'ing regarding the languages themselves I did some small research projects using C# and realised I couldn't find any reason to favour it over other more suitable languages in most contexts. *As a language* it's not bad (even though python it ain't), but considering the number of hoops to be jumped through to adopt it, I'll be wanting my alpha waves parsed as I sleep into well-commented colloquial English and run by an English Language JITc with assembly-like speed before I'll consider using it over python, or php, or C++. In essence, not a big fan. >I usually refer to it as "VILE!". As in what Vile thing do I have >before me. > >Emacs all the way baby! ^IAWTP^ Couldn't agree more. -- There are 10 types of people in this world, those who understand binary, and those who don't. From tdelaney at avaya.com Mon May 8 17:57:04 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Tue, 9 May 2006 07:57:04 +1000 Subject: Using time.sleep() in 2 threads causes lockup whenhyper-threading is enabled Message-ID: <2773CAC687FD5F4689F526998C7E4E5F074375@au3010avexu1.global.avaya.com> OlafMeding at gmail.com wrote: > I am a bit surprised that nobody else has tried running the short > Python program above on a hyper-threading or dual core / dual > processor system. Does it happen every time? Have you tried it on multiple machines? Is it possible that that one machine is having problems? Does it take the same amount of time each run to replicate - and if so, how long is that (give or take a minute)? Until you can answer these questions with definite answers, people are not going to dedicate machines *that they use* for hours on end trying to replicate it. And from this thread, the time required appears to be "minutes to hours". That suggests you have a race condition which results in a deadlock - and of course, that is more likely to occur on a dual-core or dual-cpu machine, as you really have multiple threads executing at once. I'm surprised that so many people have been willing to dedicate as much time as they have, but then again considering the people involved it's not quite so surprising. Tim Delaney From tjreedy at udel.edu Sat May 27 18:07:53 2006 From: tjreedy at udel.edu (Terry Reedy) Date: Sat, 27 May 2006 18:07:53 -0400 Subject: iterator? way of generating all possible combinations? References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com><mailman.6269.1148709362.27775.python-list@python.org> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> Message-ID: <e5aijn$st2$1@sea.gmane.org> <akameswaran at gmail.com> wrote in message news:1148712466.299743.209350 at j73g2000cwa.googlegroups.com... > > Terry Reedy wrote: > >> >> Are the dice identical or distinguishable (marked). In other words, >> with 2 >> dice, is 1,2 the same as 2,1 or different? Note that in most dice >> games, >> such as craps, the dice are not distinguished, but probability >> calculations >> must treast them as if they were to get the elementary events. >> > they are distinct. This isn't necessarily about simulating a game. So > yes the dice are marked and I want to track those different > possibilties. Then your dice problem is equivalent to generating all n-digit base-d numbers, which is also the n-fold cartesian product of a set with itself. Sequential generation amounts to a 'plus-1' operation. tjr From simon at brunningonline.net Wed May 10 04:00:10 2006 From: simon at brunningonline.net (Simon Brunning) Date: Wed, 10 May 2006 09:00:10 +0100 Subject: Reading Soap struct type In-Reply-To: <4cdk7kF15h7qkU1@uni-berlin.de> References: <000d01c66e4c$af0be500$346ea8c0@tintz.co.nz> <1146620207.56.7672@mint-julep.mondoinfo.com> <002901c66e57$05a69090$346ea8c0@tintz.co.nz> <1146624295.41.7841@mint-julep.mondoinfo.com> <003501c66e64$316deb30$346ea8c0@tintz.co.nz> <1146677203.2.7870@mint-julep.mondoinfo.com> <mailman.5544.1147233358.27775.python-list@python.org> <4cdk7kF15h7qkU1@uni-berlin.de> Message-ID: <8c7f10c60605100100i55d8d14eq9a016086306f63d4@mail.gmail.com> On 5/10/06, Diez B. Roggisch <deets at nospam.web.de> wrote: > That is because it is no hash - AFAIK SOAP doesn't support hashes (or > dicts, in python-lingo) out of the box. What you see above essentially a > named tuple. Conceptionally like this: > > class MyStruct: > > def __init__(self, foo, bar): > self.foo = foo > self.bar = bar > > > Either you access the individual values by name - or maybe there is a > way to enumerate the names for you, but that depends on what the > SOAPpy.Types.structType is capable of. I suggest you look at it's source. IIRC, SOAPpy's structType has a _keys() function - so somethign like the following (untested) might work: struct_as_a_dict = dict((key, getattr(struct, key)) for key in struct._keys()) -- Cheers, Simon B, simon at brunningonline.net, http://www.brunningonline.net/simon/blog/ From grante at visi.com Fri May 19 15:03:05 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 19 May 2006 19:03:05 -0000 Subject: number of different lines in a file References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <1147991237.732146.29350@j55g2000cwa.googlegroups.com> <1148058125.773912.180080@i39g2000cwa.googlegroups.com> Message-ID: <126s5j9sgd0kt83@corp.supernews.com> On 2006-05-19, Kaz Kylheku <kkylheku at gmail.com> wrote: > There should be one huge utility which can do it all in a single > address space. Sure, as long as it can do all of everything you'll ever need to do, you're set! It would be the One True Program. Isnt' that what Emacs is supposed to be? -- Grant Edwards grante Yow! My mind is making at ashtrays in Dayton... visi.com From onurb at xiludom.gro Mon May 22 04:30:52 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Mon, 22 May 2006 10:30:52 +0200 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: <rz5cg.20468$Lm5.8909@newssvr12.news.prodigy.com> References: <200605211711.25043.me+python@modelnine.org> <mailman.6034.1148237188.27775.python-list@python.org> <1148237544.579470.43420@i40g2000cwc.googlegroups.com> <mailman.6035.1148237860.27775.python-list@python.org> <1148247633.377696.157820@38g2000cwa.googlegroups.com> <rz5cg.20468$Lm5.8909@newssvr12.news.prodigy.com> Message-ID: <44717726$0$10541$636a55ce@news.free.fr> Edward Elliott wrote: > George Sakkis wrote: > > >>Em Dom, 2006-05-21 ?s 17:11 +0200, Heiko Wundram escreveu: >> >>>for node in tree if node.haschildren(): >>><do something with node> >>> >>>as syntactic sugar for: >>> >>>for node in tree: >>>if not node.haschildren(): >>>continue >>><do something with node> > > [snip] > >>2) "There should be one and preferably only one way to do it." > > > You mean like this: > > s = "foo" + "bar" > s = 'foo' + 'bar' > s = 'foo' 'bar' > s = '%s%s' % ('foo', 'bar') > > This one and only one way stuff is overrated. I don't care how many ways > there are as long as: > 1. at least one way is intuitive > 2. every way is easily comprehendible (readable, no side effects, etc) The real mantra is actually : "There should be one-- and preferably only one --obvious way to do it" Please note the "should", "preferably", and "obvious". 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 nicogrubert at gmail.com Tue May 23 08:51:07 2006 From: nicogrubert at gmail.com (Nico Grubert) Date: Tue, 23 May 2006 14:51:07 +0200 Subject: How to open https Site and pass request? In-Reply-To: <4472F2E6.9040204@gmail.com> References: <4472F2E6.9040204@gmail.com> Message-ID: <4473053B.2010406@gmail.com> > >>> import urllib > >>> import urllib2 > >>> the_url = "https://myserver/application/login.do" > >>> user_agent = 'Mozilla/4.0 (compatible; MSIE 5.5; Windows NT)' > >>> headers = { 'User-Agent' : user_agent } > >>> values = { 'username' : 'myuser', 'password' : 'mypasswd' } > >>> data = urllib.urlencode(values) > >>> req = urllib2.Request(the_url, data) > >>> handle = urllib2.urlopen(req) > urllib2.URLError: <urlopen error unknown url type: https> To answer my question myself: My python installation does not have SSL support (from socket import ssl failed). I tested the same code on another machine and it's working. However, I am wondering how I can additionally enable SSL support for my python installation ? Regards, Nico From john at castleamber.com Wed May 24 11:54:56 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:54:56 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <e51kh4$t18$1@ml.accsnet.ne.jp> <R_Zcg.248$LO3.40@fe11.lga> <Xns97CD66F12561Fcastleamber@130.133.1.4> <87ejyjv40w.fsf@rpi.edu> Message-ID: <Xns97CD6F09CFD9Ecastleamber@130.133.1.4> Bill Atkins <NOatkinwSPAM at rpi.edu> wrote: > Life is short, John Bokma. There are more important things in the > world than tattling on Xah to his host. Maybe you can start > experiencing them Maybe check out my site first before you make another silly remark. Typically that (almost?) everybody defending Xah has so little clue. > if you learn to make use of the 'next message' key. Add up years of pressing that key, and add up the time it takes to send a few emails. If I considered Usenet a waste of time, I would have given up on it years ago. And finally, never thought about that it can be fun? >> So you haven't noticed that Xah does just hit & run posting? > > I've noticed it - but have you? Since I mentioned, what do you think? (now wait...) > It would be only one post that could easily be ignored, if not for all > this rubbish that you and people like you feel the need to post (sure, Yup, which is not going to stop. Posting "Don't feed the trolls" messages don't help. > I realize I'm contributing to the problem). Isn't "hit & run posting" > better than a thread full of nonsense? And ain't it cool that reporting Xah's abuse might stop both? -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From deets at nospam.web.de Tue May 9 07:04:47 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Tue, 09 May 2006 13:04:47 +0200 Subject: Is there any plan to port python to ACCESS Palm Linux Platform? References: <1147152028.828197.196790@j73g2000cwa.googlegroups.com> Message-ID: <4cbbanF14dkunU1@uni-berlin.de> heidan wrote: > Another quick question about python and palm? > > As we all have known that ACCESS has planned to build Palm OS on top of I didn't know. > Linux, is there any plan to port python to THIS future PALM OS? How is anybody going to plan something that requires something that is just planned? Python runs on lots of platforms, and linux-based ones certainly stand a good chance for becoming one - but only after the platform exists somebody can start working on that, don't you think? Diez From johnjsal at NOSPAMgmail.com Wed May 10 14:28:44 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 18:28:44 GMT Subject: reusing parts of a string in RE matches? In-Reply-To: <1147283334.610613.220770@j33g2000cwa.googlegroups.com> References: <YMm8g.2077$No6.45935@news.tufts.edu> <mailman.5557.1147274047.27775.python-list@python.org> <M2o8g.2080$No6.45875@news.tufts.edu> <1147283334.610613.220770@j33g2000cwa.googlegroups.com> Message-ID: <whq8g.2082$No6.45965@news.tufts.edu> BartlebyScrivener wrote: > I have to at least try :) > > s = "abababababababab" > > for x in range(len(s)): > ... try: > ... s.index("aba", x, x + 3) > ... except ValueError: > ... pass > > rd > yeah, looks like index() or find() can be used to do it instead of RE, but still, i'd like to know if there's a way you can write an RE expression to do it (and just an RE expression, without all the other for loops and extra nonsense...otherwise i might as well just use string methods) From vinay_sajip at yahoo.co.uk Thu May 25 13:14:00 2006 From: vinay_sajip at yahoo.co.uk (Vinay Sajip) Date: 25 May 2006 10:14:00 -0700 Subject: logging In-Reply-To: <mailman.6143.1148460752.27775.python-list@python.org> References: <mailman.6101.1148366215.27775.python-list@python.org> <1148426018.334087.124160@i40g2000cwc.googlegroups.com> <mailman.6143.1148460752.27775.python-list@python.org> Message-ID: <1148577240.250304.116360@j55g2000cwa.googlegroups.com> Baurzhan Ismagulov wrote: > Thanks for the idea! I think this should work for the example I sent. > However, I have more than one module, and I want to log only l01. How > can I do that? > I don't know what your logger hierarchy looks like: you could perhaps log to child loggers of l01 ("l01.XXX"), or set all other loggers you use to have a CRITICAL level, or filter them using a filter which filters out everything. Regards, Vinay From mhellwig at xs4all.nl Thu May 4 07:01:26 2006 From: mhellwig at xs4all.nl (Martin P. Hellwig) Date: Thu, 04 May 2006 13:01:26 +0200 Subject: This coding style bad practise? In-Reply-To: <4459bb6b$0$14029$626a54ce@news.free.fr> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> <44591be3$0$2626$636a55ce@news.free.fr> <445936fb$0$31642$e4fe514c@news.xs4all.nl> <4459bb6b$0$14029$626a54ce@news.free.fr> Message-ID: <4459df0c$0$31655$e4fe514c@news.xs4all.nl> bruno at modulix wrote: > Martin P. Hellwig wrote: >> Bruno Desthuilliers wrote: >> <cut> >> >>> Why not just use the call operator instead ? ie: >>> >>> >>> id = IDGenerator(...) >>> >>> id() >>> 01_20060424_151903_1 >>> >>> id() >>> 01_20060424_151905_2 >>> >> Because of: >> >>>>>> id = IDGenerator("01",99) >>>>>> id() >>> Traceback (most recent call last): >>> File "<pyshell#1>", line 1, in ? >>> id() >>> TypeError: 'IDGenerator' object is not callable >>> > > Of course - you have to overload the call operator for this to work. > Just rename IDGenerator.__repr__ to IDGenerator.__call__, and I garantee > this will work - and will be *much* more cleaner than abusing __repr__. > > > Thanks! That was the thing I was looking for! -- mph From fredrik at pythonware.com Tue May 2 17:34:26 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 May 2006 23:34:26 +0200 Subject: data regex match References: <87r73cdtmk.fsf@localhost.localdomain> <200605022327.57422.me+python@modelnine.org> Message-ID: <e38j93$md1$1@sea.gmane.org> Heiko Wundram wrote: > As always, use a raw string for regular expressions. \d is being interpreted > to mean an ascii character, and not to mean the character class you're trying > to reference here. \d isn't an ASCII character, but \1 is. >>> print '(\d{2})/\1/\1\1' (\d{2})/?/?? </F> From phddas at yahoo.com Tue May 2 19:13:08 2006 From: phddas at yahoo.com (Gary Wessle) Date: 03 May 2006 09:13:08 +1000 Subject: assignment in if Message-ID: <87iroodnqz.fsf@localhost.localdomain> Hi is there a way to make an assignment in the condition of "if" and use it later, e.g. nx = re.compile('regex') if nx.search(text): funCall(text, nx.search(text)) nx.search(text) is evaluated twice, I was hoping for something like nx = re.compile('regex') if x = nx.search(text): funCall(text, x)) thanks From grante at visi.com Wed May 24 17:11:52 2006 From: grante at visi.com (Grant Edwards) Date: Wed, 24 May 2006 21:11:52 -0000 Subject: how to use matplotlib contour()? Message-ID: <1279j0o8va1fq12@corp.supernews.com> I downloaded examples/contour_demo.py, and it doesn't run. I've searched both the user guide and the Wiki for "contour" and got zero hits. http://matplotlib.sourceforge.net/matplotlib.pylab.html#-contour appears to be a good reference if you already know how to use contour(), but I could glean zero clues from it on how to actually use contour(). For example, it doesn't explain what the actual formats/types of the parameters. It explains what the parameters do, but not what they _are_ For example one parameter is specied as "an array". No clue as to how many dimensions or what the axis are. In another place it says "the X,Y parameters specify the (x,y) coordinates of a surface". _How_ do they specify the surface? Are they just equal length lists of x and y coordinates that specify len(X) points. Or do they specify a len(X) x len(Y) grid of points? Since I can't find any documentation, I thought I'd just try a few things. I've got X,Y,Z values in an Nx3 array named "data" that looks like this: X Y Z [[ 4.94958000e+01 3.65706000e+00 1.84600000e-01] [ 4.94958000e+01 3.66447000e+00 1.82142000e-01] [ 4.94958000e+01 5.04936000e+00 1.90937000e-01] ..., [ 2.19844000e+03 9.74210000e+00 8.29735000e-01] [ 2.19844000e+03 9.93863000e+00 9.82307000e-01] [ 2.19844000e+03 1.03143000e+01 8.28844000e-01]] If I just pass the array to contour() by doing "pylab.contour(data)" I get this error: Traceback (most recent call last): File "./surfplot.py", line 11, in ? pylab.contour(data) File "/usr/lib/python2.4/site-packages/matplotlib/pylab.py", line 1659, in contour ret = gca().contour(*args, **kwargs) File "/usr/lib/python2.4/site-packages/matplotlib/axes.py", line 1244, in contour return self._contourHelper.contour(*args, **kwargs) File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 727, in contour x, y, z, lev = self._contour_args(False, badmask, origin, extent, *args) File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 544, in _contour_args lev = self._autolev(z, 7, filled, badmask) File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 471, in _autolev lev = linspace(zmin, zmax, N+2)[1:-1] File "/usr/lib/python2.4/site-packages/matplotlib/mlab.py", line 87, in linspace dx = (xmax-xmin)/(N-1) TypeError: unsupported operand type(s) for -: 'str' and 'str' I've no clue what that means. Well, I know what the TypeError means _literally_, but I've no idea how I'm supposed to interpret that particular error in regards to what I passed to contour(). Attempting to use one of the other forms found on the above web page I pass X,Y,Z vectors to contour() by doing "pylab.contour(data[:,0],data[:,1],data[:,2])": Traceback (most recent call last): File "./surfplot.py", line 13, in ? pylab.contour(data[:,0],data[:,1],data[:,2]) File "/usr/lib/python2.4/site-packages/matplotlib/pylab.py", line 1659, in contour ret = gca().contour(*args, **kwargs) File "/usr/lib/python2.4/site-packages/matplotlib/axes.py", line 1244, in contour return self._contourHelper.contour(*args, **kwargs) File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 727, in contour x, y, z, lev = self._contour_args(False, badmask, origin, extent, *args) File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 539, in _contour_args x,y,z = self._check_xyz(args[:3]) File "/usr/lib/python2.4/site-packages/matplotlib/contour.py", line 515, in _check_xyz raise TypeError("Input z must be a 2D array.") TypeError: Input z must be a 2D array. Which is almost as cryptic a result as my first attempt. Why would my Z values be a 2D array? -- Grant Edwards grante Yow! My NOSE is NUMB! at visi.com From sjmachin at lexicon.net Sat May 27 20:56:47 2006 From: sjmachin at lexicon.net (John Machin) Date: Sun, 28 May 2006 10:56:47 +1000 Subject: Pyrex speed In-Reply-To: <mailman.6275.1148739053.27775.python-list@python.org> References: <1148724988.265192.24140@j55g2000cwa.googlegroups.com> <4dqq38F1bi6btU1@uni-berlin.de> <1148728491.640293.298470@38g2000cwa.googlegroups.com> <1148728959.466305.23870@u72g2000cwu.googlegroups.com> <1148729670.982351.132060@j33g2000cwa.googlegroups.com> <e59eh9$hlk$1@nemesis.news.tpi.pl> <1148734724.933745.277830@j73g2000cwa.googlegroups.com> <mailman.6275.1148739053.27775.python-list@python.org> Message-ID: <4478F54F.90301@lexicon.net> On 28/05/2006 12:10 AM, Gonzalo Monz?n wrote: [good advice snipped] > > Example A: > This code is more than 80 times faster than a "easy" Python > implementation. For every call, it does some bitwise operations and does > an array lookup for every string character from argument. Its a lot > faster because in Python approach a list lookup is done and it is a lot > faster to do a C array lookup -thought that in these C loops no Python > type value conversions are needed, if it where the case, C approach > would not be so faster than python. I don't know how would perform an > array based Python code, but I expect it to be a lot faster than using a > list, so Python code can be speed up a lot if you know how to do it. > > // C code: > int CRC16Table[256]; // Filled elsewhere > int CalcCRC16(char *str) > { > int crc; > for(crc = 0xFFFF; *str != 0; str++) { > crc = CRC16Table [(( crc >> 8 ) & 255 )] ^ ( crc << 8 ) ^ *str; Gonzalo, just in case there are any C compilers out there which need to be told: > for(crc = 0xFFFF; *str != 0;) { > crc = CRC16Table [(( crc >> 8 ) & 255 )] ^ ( crc << 8 ) ^ *str++; > } > return crc; > } > > # Python code > gCRC16Table = [] # Filled elsewhere > def CalcCRC16(astr): > crc = 0xFFFFL Having that L on the end (plus the fact that you are pointlessly maintaining "crc" as an *unsigned* 32-bit quantity) will be slowing the calculation down -- Python will be doing it in long integers. You are calculating a *sixteen bit* CRC! The whole algorithm can be written simply so as to not need more than 16-bit registers, and not to pollute high-order bits in 17-or-more-bit registers. > for c in astr: > crc = gCRC16Table[((crc >> 8) & 255)] ^ ((crc & 0xFFFFFF) << 8) ^ > ord(c) Note that *both* the C and Python routines still produce a 32-bit result with 16 bits of high-order rubbish -- I got the impression from the previous thread that you were going to fix that. This Python routine never strays outside 16 bits, so avoiding your "& 255" and a final "& 0xFFFF" (which you don't have). def CalcCRC16(astr): crc = 0xFFFF for c in astr: crc = gCRC16Table[crc >> 8] ^ ((crc & 0xFF) << 8) ^ ord(c) return crc ============== To the OP: I'd just like to point out that C code and Pyrex code can gain signicantly (as the above example does) by not having to use ord() and chr(). As Gonzalo says, read the generated C code. Look for other cases of using Python built-ins that could be much faster with a minor bit of effort in Pyrex e.g. "max(a, b)" -> "(a) > (b) ? (a) : (b) " or if you don't like that, a cdef function to get the max of 2 ints will be *way* faster than calling Python's max() From defcon8 at gmail.com Fri May 19 02:35:23 2006 From: defcon8 at gmail.com (defcon8) Date: 18 May 2006 23:35:23 -0700 Subject: Getting URL's In-Reply-To: <1148020081.055817.281770@38g2000cwa.googlegroups.com> References: <1148019975.277742.253400@y43g2000cwc.googlegroups.com> <1148020081.055817.281770@38g2000cwa.googlegroups.com> Message-ID: <1148020523.195869.38340@u72g2000cwu.googlegroups.com> Thanks From fredrik at pythonware.com Fri May 19 02:07:41 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 19 May 2006 08:07:41 +0200 Subject: number of different lines in a file In-Reply-To: <iY7bg.3778$x4.261@newsread3.news.pas.earthlink.net> References: <C%5bg.122$K71.72@newsread1.news.pas.earthlink.net> <mailman.5913.1147991572.27775.python-list@python.org> <iY7bg.3778$x4.261@newsread3.news.pas.earthlink.net> Message-ID: <e4jnbd$vmg$1@sea.gmane.org> r.e.s. wrote: > BTW, the first thing I tried was Fredrik Lundh's program: > > def number_distinct(fn): > return len(set(s.strip() for s in open(fn))) > > which worked without the square brackets. Interesting that > omitting them doesn't seem to matter. a for loop inside square brackets is a "list comprehension", and the result is a list. if you use a list comprehension inside a function call, the full list is built *before* the function is called. in this case, this would mean that the entire file would be read into memory before the set was constructed. if you change the square brackets to ordinary parentheses, you get a generator expression instead: http://pyref.infogami.com/generator-expressions the generator expression results in an iterator object that calculates the values one by one. if you pass it to a function that expects an iterator, that function will end up "running the for loop itself", and no extra storage is needed. (in this case, you still need memory to hold the set, of course, so the difference between a list comprehension and a generator expression will only matter if you have lots of duplicates). finally, a syntax shortcut lets you remove the parentheses if the generator expression is the only argument in a function call, as in the above example. </F> From rridge at csclub.uwaterloo.ca Tue May 23 17:47:28 2006 From: rridge at csclub.uwaterloo.ca (Ross Ridge) Date: 23 May 2006 14:47:28 -0700 Subject: documentation for win32com? References: <hQHcg.2153$No6.46370@news.tufts.edu> Message-ID: <1148420848.766549.122480@j33g2000cwa.googlegroups.com> John Salerno wrote: > So does this mean that the code can be different each time, or is there > still a pre-determined way to refer to things, such as opening Excel, > reading a spreadsheet and working with it, etc.? For a given version of Excel, there's a "pre-determinied way" of doing those things. Different versions of Excel may do things the same way or differently depending on what exactly you're trying to do. > If so, where can I find a list of those objects and methods? In the documentation for the version of Excel you're using. Ross Ridge From nospamformeSVP at gmail.com Fri May 12 07:57:58 2006 From: nospamformeSVP at gmail.com (Don Taylor) Date: Fri, 12 May 2006 07:57:58 -0400 Subject: which windows python to use? In-Reply-To: <e407f7$pfa$1@sea.gmane.org> References: <mailman.5589.1147359382.27775.python-list@python.org> <e406rp$dvt$1@daisy.noc.ucla.edu> <e407f7$pfa$1@sea.gmane.org> Message-ID: <e41t8p$qpt$1@sea.gmane.org> Robert Kern wrote: > In what way? Does the mingw gcc that we distribute interfere with Cygwin's gcc? Robert: Which C compiler will you be using for the Enthought 2.4 Windows release? Don. From bborcic at gmail.com Tue May 2 15:28:58 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 21:28:58 +0200 Subject: simultaneous assignment In-Reply-To: <125fbbj4rfeah20@corp.supernews.com> References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> <125fbbj4rfeah20@corp.supernews.com> Message-ID: <4457b2fe$1_7@news.bluewin.ch> Grant Edwards wrote: > Python knows how to count. :) > > def countFalse(seq): > return len([v for v in seq if not v]) > > def countTrue(seq): > return len([v for v in seq if v]) > > def truth_test(seq): > return countTrue(seq) == 1 > I'd suggest the more direct def countFalse(seq) : return sum(1 for v in seq if not v) def countTrue(seq) : return sum(1 for v in seq if v) - not to speak of def countFalse(seq) : return sum(not v for v in seq) def countTrue(seq) : return sum(bool(v) for v in seq) From bignose+hates-spam at benfinney.id.au Thu May 18 05:49:44 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 19:49:44 +1000 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> Message-ID: <873bf7mzlz.fsf@benfinney.id.au> "SamFeltus" <sam at nuevageorgia.com> writes: > It seems most Python applications choose HTML/CSS/JS as the display > technology, These are open, freely-implementable, non-proprietary standards controlled by standards bodies. > yet Flash is a far more powerful and elegant display technology. This is a proprietary, closed format controlled by a single corporation. -- \ "He who allows oppression, shares the crime." -- Erasmus | `\ Darwin, grandfather of Charles Darwin | _o__) | Ben Finney From bigiain at mightymedia.com.au Thu May 25 09:05:03 2006 From: bigiain at mightymedia.com.au (Iain Chalmers) Date: Thu, 25 May 2006 23:05:03 +1000 Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <Xns97CD68305314Ccastleamber@130.133.1.4> <447479A1.8050809@hotORgooMAIL.invalid> <Xns97CD6AB19B4F3castleamber@130.133.1.4> <447485B6.4070507@hotORgooMAIL.invalid> <87verumr95.fsf@tiger.rapttech.com.au> Message-ID: <bigiain-5B7F44.23050325052006@nasal.pacific.net.au> In article <87verumr95.fsf at tiger.rapttech.com.au>, Tim X <timx at nospam.dev.null> wrote: > I also seem to remember a page on his website from a couple of years > back in which he admits enjoying trolling and starting flame wars - > but I can't find it now, so maybe I'm mistaken. http://web.archive.org/web/20050204172641/www.xahlee.org/Netiquette_dir/troll.html big -- "Everything you love, everything meaningful with depth and history, all passionate authentic experiences will be appropriated, mishandled, watered down, cheapened, repackaged, marketed and sold to the people you hate." Mr Jalopy quoting Hooptyrides (on jalopyjunktown.com) From jjl at pobox.com Thu May 4 13:44:02 2006 From: jjl at pobox.com (John J. Lee) Date: 04 May 2006 17:44:02 +0000 Subject: Python & SSL References: <e38c66$r2t$1@zinnia.noc.ucla.edu> <4457B74A.2000208@benjiyork.com> <mailman.5284.1146693115.27775.python-list@python.org> <slrne5i9oo.ijc.sybrenUSE@schuimige.stuvel.eu> Message-ID: <871wv9lm71.fsf@pobox.com> Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> writes: > John J. Lee enlightened us with: > > Of course, remembering that the first thing to ask in response to > > "is it secure?" is "against what?", for lots of purposes it just > > doesn't matter that it ignores certificates. > > I'm curious. Can you give me an example? AFAIK you need to know who > you're talking to before transmitting sensitive information, otherwise > you could be talking to anybody - and that's just what you wanted to > prevent with the encryption, right? If Edward hadn't answered I would have said something along the lines of what he said too, but more than that I just had in mind situations where, when fetching a web page, the risk (probability and consequences) of a man-in-the-middle attack doesn't feature much higher than the risk of getting hit by a piece of debris from outer space that day. Surprisingly often, it so happens that the people setting up the web site used https, even though as a user of the site I don't really care about the encryption or authentication. That doesn't mean proper certificate handling wouldn't be good to have (it would), just that installing m2crypto and finding the right docs isn't necessarily worth the bother. BTW, I assume the reason the OP (I forgot who that was) didn't have https support compiled in was just that they didn't have OpenSSL installed when they typed ./configure (since the Python build process on unix uses autoconf). Either that or they installed a system package to get Python (e.g. an .rpm) and the SSL support is is a separate package (seems unlikely). John From per9000 at gmail.com Tue May 30 06:06:01 2006 From: per9000 at gmail.com (per9000) Date: 30 May 2006 03:06:01 -0700 Subject: create a text file In-Reply-To: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> References: <2xIeg.88125$H71.14049@newssvr13.news.prodigy.com> Message-ID: <1148983561.469393.262430@j73g2000cwa.googlegroups.com> Hi, This is what I often do: somekindofoutput = '' somekindofoutput += somefunk(somearg) + '\n' # w is for writing myfile = open('theoutfile',w) myfile.write(somekindofoutput) myfile.close() also see http://www.python.org/doc/2.3.5/tut/node9.html or some other documentation /P9k From aleax at mac.com Tue May 9 11:14:02 2006 From: aleax at mac.com (Alex Martelli) Date: Tue, 9 May 2006 08:14:02 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <pan.2006.05.06.03.54.17.404055@hastings.org> <1147123648.914726.212680@i39g2000cwa.googlegroups.com> <1147156556.952331.29450@i39g2000cwa.googlegroups.com> Message-ID: <1hf291y.7wwy7na9f3orN%aleax@mac.com> Pisin Bootvong <joesb.coe9 at gmail.com> wrote: ... > Is there such language that allow scalability without any need for > design on the underlying architecture? Perhaps Erlang...? I have no specific experience with it, but according to the rumor mill it forces or cajoles you into an architecture that's quite appropriate for scaling -- i.e., sure that architecture needed to be designed, but (if I understand Erlang correctly) it's now built into the language and you're more or less going to use the right paradigm. Alex From martin.wiechert at gmx.de Wed May 24 10:48:22 2006 From: martin.wiechert at gmx.de (Martin Wiechert) Date: Wed, 24 May 2006 16:48:22 +0200 Subject: linking errors with debug build of Python2.4.3 Message-ID: <200605241648.22985.martin.wiechert@gmx.de> Hi list, I've created a fresh build of Python 2.4.3 using the following configuration $ ./configure --with-pydebug --prefix=/usr/local/debug --enable-shared --with-fpectl --with-signal-module in particular I used --with-pydebug. Now when I start the interpreter some dynamically loaded modules do not see debug-related symbols: $ /usr/local/debug/bin/python Python 2.4.3 (#1, May 12 2006, 05:35:54) [GCC 4.1.0 (SUSE Linux)] on linux2 Type "help", "copyright", "credits" or "license" for more information. Traceback (most recent call last): File "/etc/pythonstart", line 7, in ? import readline ImportError: /usr/local/debug/lib/python2.4/lib-dynload/readline.so: undefined symbol: _Py_RefTotal >>> I've attached a shell session with the outputs of ldd and nm on readline.so What did I do wrong? My System is SuSE Linux 10.1 on Intel. Any help would be much appreciated. Thanks, Martin. -------------- next part -------------- wiechert at bit:~> ldd /usr/local/debug/lib/python2.4/lib-dynload/readline.so linux-gate.so.1 => (0xffffe000) libreadline.so.5 => /lib/libreadline.so.5 (0xb7edd000) libncursesw.so.5 => /usr/lib/libncursesw.so.5 (0xb7e90000) libpthread.so.0 => /lib/libpthread.so.0 (0xb7e7c000) libc.so.6 => /lib/libc.so.6 (0xb7d5c000) libncurses.so.5 => /lib/libncurses.so.5 (0xb7d14000) libdl.so.2 => /lib/libdl.so.2 (0xb7d10000) /lib/ld-linux.so.2 (0x80000000) wiechert at bit:~> nm /usr/local/debug/lib/python2.4/lib-dynload/readline.so U add_history 00004e68 b begidx 00004e30 A __bss_start 00001780 t call_gmon_start 00002bb7 t call_readline U clear_history 00004e40 b completed.5751 00004e64 b completer U completion_matches 00004004 d __CTOR_END__ 00004000 d __CTOR_LIST__ w __cxa_finalize@@GLIBC_2.1.3 00004840 d doc_add_history 00004b60 d doc_clear_history 00004640 d doc_get_begidx 000049e0 d doc_get_completer 00004880 d doc_get_completer_delims 00004aa0 d doc_get_current_history_length 000046a0 d doc_get_endidx 00004a40 d doc_get_history_item 00004b00 d doc_get_line_buffer 00004ba0 d doc_insert_text 00004c60 d doc_module 00004260 d doc_parse_and_bind 00004340 d doc_read_history_file 000042c0 d doc_read_init_file 00004be0 d doc_redisplay 00004760 d doc_remove_history 000047c0 d doc_replace_history 000048e0 d doc_set_completer 00004700 d doc_set_completer_delims 00004580 d doc_set_startup_hook 000043c0 d doc_write_history_file 00002e10 t __do_global_ctors_aux 000017b0 t __do_global_dtors_aux 00004240 d __dso_handle 0000400c d __DTOR_END__ 00004008 d __DTOR_LIST__ 00004014 a _DYNAMIC 00004e30 A _edata U emacs_meta_keymap 00004f1c A _end 00004e6c b endidx U __errno_location@@GLIBC_2.0 00002e44 T _fini 0000286e t flex_complete 00001810 t frame_dummy 000031ac r __FRAME_END__ U free@@GLIBC_2.0 00001e6a t get_begidx 000022a1 t get_completer 00002242 t get_completer_delims 000023c1 t get_current_history_length 00001ea2 t get_endidx 0000231f t get_history_item 00001bf3 t get_history_length 00004500 d get_history_length_doc 00002404 t get_line_buffer 00004148 a _GLOBAL_OFFSET_TABLE_ w __gmon_start__ U history_get U history_get_history_state 0000433c d _history_length U history_truncate_file 00001847 t __i686.get_pc_thunk.bx 00002e09 t __i686.get_pc_thunk.cx 000013e8 T _init 00002da9 T initreadline 00002477 t insert_text 00004e80 b jbuf 00004010 d __JCR_END__ 00004010 d __JCR_LIST__ w _Jv_RegisterClasses U longjmp@@GLIBC_2.0 U malloc@@GLIBC_2.0 000026d7 t on_completion 00002542 t on_hook 00002ad8 t onintr 000026b1 t on_startup_hook 00004244 d p.5749 0000184c t parse_and_bind 000021c2 t py_add_history U PyArg_ParseTuple U PyCallable_Check 0000242c t py_clear_history U _Py_Dealloc U PyErr_Clear U PyErr_Format U PyErr_NoMemory U PyErr_Occurred U PyErr_SetFromErrno U PyErr_SetString U PyExc_IOError U PyExc_TypeError U PyExc_ValueError U Py_FatalError U PyGILState_Ensure U PyGILState_Release U Py_InitModule4TraceRefs U PyInt_AsLong U PyInt_FromLong U PyMem_Malloc U _Py_NegativeRefcount U _Py_NoneStruct U PyObject_CallFunction U PyOS_InputHook U PyOS_ReadlineFunctionPointer U PyOS_setsig U PyOS_snprintf U _Py_RefTotal 00001f74 t py_remove_history 00002090 t py_replace_history U PyString_AsString U PyString_FromString U read_history 000019db t read_history_file 00001929 t read_init_file U readline 00004cc0 d readline_methods 00002b00 t readline_until_enter_or_signal 000024f7 t redisplay U remove_history U replace_history_entry U rl_attempted_completion_function U rl_attempted_completion_over U rl_bind_key U rl_bind_key_in_map U rl_complete U rl_completer_word_break_characters U rl_completion_append_character U rl_event_hook U rl_initialize U rl_insert U rl_insert_text U rl_instream U rl_line_buffer U rl_outstream U rl_parse_and_bind U rl_prep_terminal U rl_read_init_file U rl_readline_name U rl_redisplay U rl_startup_hook 0000226a t set_completer 00001eda t set_completer_delims 00001b6c t set_history_length 00004440 d set_history_length_doc 00001c19 t set_hook U _setjmp@@GLIBC_2.0 U setlocale@@GLIBC_2.0 00001e33 t set_startup_hook 0000299d t setup_readline U sigrelse@@GLIBC_2.1 00004e60 b startup_hook U strcmp@@GLIBC_2.0 U strcpy@@GLIBC_2.0 U strdup@@GLIBC_2.0 U strncpy@@GLIBC_2.0 U using_history U write_history 00001a8d t write_history_file wiechert at bit:~> From chris.cavalaria at free.fr Thu May 18 09:14:07 2006 From: chris.cavalaria at free.fr (Christophe) Date: Thu, 18 May 2006 15:14:07 +0200 Subject: Question about exausted iterators In-Reply-To: <1147950956.161966.211630@u72g2000cwu.googlegroups.com> References: <446b48e2$0$5293$626a54ce@news.free.fr> <mailman.5834.1147891569.27775.python-list@python.org> <446c2dea$0$5306$626a54ce@news.free.fr> <1147950956.161966.211630@u72g2000cwu.googlegroups.com> Message-ID: <446c7346$0$7147$626a54ce@news.free.fr> looping a ?crit : > Christophe wrote: > >>Ok, call me stupid if you want but I know perfectly well the "solution" >>to that problem ! Come on, I was showing example code of an horrible >>gotcha on using iterators. >> > > > OK, your are stupid ;-) > Why asking questions when you don't want to listen answers ? Because I'm still waiting for a valid answer to my question. The answer "Because it has been coded like that" or is not a valid one. >>Instead of saying that all works as intended could you be a little >>helpful and tell me why it was intended in such an obviously broken way >>instead ? > > Why an exausted iterator must return an Exception (other than > StopIteration of course) ? Because it's exausted. Because it has been for me a frequent cause of bugs and because I have yet to see a valid use case for such behaviour. > Well an exausted iterator could be seen like an empty string or an > empty list (or tons of others things), so you expect the code > for car in "": > print car > to return an Exception because it's empty ??? Of course not. > It's your job to check the iterator when it need to be. It's my job to avoid coding bugs, it's the language job to avoid placing pitfalls everywhere I go. I must confess I have a strong opinion on that point. Not long ago I started working on some fresh code where I decided to use a lot of iterators and set instead of list if possible. That behaviour has caused me to lose quite some time tracking bugs. From __peter__ at web.de Fri May 19 02:09:42 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 May 2006 08:09:42 +0200 Subject: newb: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> Message-ID: <e4jnb8$rqr$01$1@news.t-online.com> manstey wrote: > Is there a clever way to see if two strings of the same length vary by > only one character, and what the character is in both strings. > > E.g. str1=yaqtil str2=yaqtel > > they differ at str1[4] and the difference is ('i','e') > > But if there was str1=yiqtol and str2=yaqtel, I am not interested. > > can anyone suggest a simple way to do this? > > My next problem is, I have a list of 300,000+ words and I want to find > every pair of such strings. I thought I would first sort on length of > string, but how do I iterate through the following: Not sure if it can handle 300000 words, but here is something to play with. import sys def find_similars(words, lookup=None, dupes=None): if lookup is None: lookup = {} if dupes is None: dupes = set() for word in words: low_word = word.lower() if low_word not in dupes: dupes.add(low_word) last = None for i, c in enumerate(low_word): if c == last: continue key = low_word[:i], low_word[i+1:] if key in lookup: lookup[key].append(word) else: lookup[key] = [word] last = c return (group for group in lookup.itervalues() if len(group) > 1) def main(): import optparse parser = optparse.OptionParser() parser.usage += " infile[s]" parser.add_option("-n", "--limit", type="int", help="process at most LIMIT words") options, args = parser.parse_args() if args: words = (w.strip() for fn in args for w in open(fn)) else: words = (w.strip() for w in sys.stdin) if options.limit is not None: from itertools import islice words = islice(words, max_len) for group in find_similars(words): print " ".join(sorted(group)) if __name__ == "__main__": main() Peter From sjmachin at lexicon.net Mon May 22 22:10:31 2006 From: sjmachin at lexicon.net (John Machin) Date: Tue, 23 May 2006 12:10:31 +1000 Subject: Too big of a list? and other problems In-Reply-To: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> References: <1148343552.037687.214420@j55g2000cwa.googlegroups.com> Message-ID: <44726f19$1@news.eftel.com> On 23/05/2006 10:19 AM, Brian wrote: > First off, I am sorry for cluttering this group with my inept > questions, but I am stuck again despite a few hours of hair pulling. > > I have a function (below) that takes a list of html pages that have > images on them (not porn but boats). This function then (supposedly) > goes through and extracts the links to those images and puts them into > a list, appending with each iteration of the for loop. The list of > html pages is 82 items long and each page has multiple image links. > When the function gets to item 77 or so, the list gets all funky. > Sometimes it goes empty, The list (not a tuple!!) found by findall is empty or smaller than expected when the webmaster has used .jpg instead of .jpeg. Pages 27, 77, and 79-82 at the moment have all .jpg as you would have found out had you inspected the actual data you are operating on instead of guessing. The print statement is your friend; use it. Your browser's "view source" functionality (ctrl-U in Firefox) is also handy. However if you mean that your foundPics list becomes empty, then either you haven't posted the code that you actually used, or the pixies from the bottom of the garden have been rearranging it for you :-) and others it is a much more abbreviated list > than I expect - it should have roughly 750 image links. > > When I looked at it while running, it appears as if my regex is > actually appending a tuple (I think) of the results it finds to the > list. No, read the manual. findall returns a list. *You* are appending that list to your list. > My best guess is that the list is getting too big and croaks. Very unlikely. In any case you would have seen evidence, like an exception and a traceback ... or maybe just your swap disk going into overdrive :-) > Since one of the objects of the function is also to be able to count > the items in the list, I am getting some strange errors there as well. And what were the strange errors that you perceived? > > Here is the code: [snip] Here is mine: import re, urllib def countPics(): foundPics = [] links_count = 0 pics_count = 0 pics = re.compile(r"images/.*\.jpeg") # for better results, change jpeg to jpe?g for link in ["cetaceaPage%02d.html" % x for x in range(1, 83)]: picPage = urllib.urlopen("http://continuouswave.com/whaler/cetacea/" + link) links_count += 1 html = picPage.read() picPage.close() findall_result = pics.findall(html) pics_count += len(findall_result) print links_count, pics_count, link, findall_result foundPics.append(findall_result) print("done") countPics() You may wish to change that append to extend, but then you will lose track of which pictures are on which page, if that matters to you. HTH, John From m.wilkinson at tideway.com Wed May 17 04:33:01 2006 From: m.wilkinson at tideway.com (Mark Wilkinson) Date: Wed, 17 May 2006 09:33:01 +0100 Subject: simultaneous reading and writing a textfile Message-ID: <B81183566FF73947875C3A207CD60AA6E5C448@LONEX01.tideway.com> Why this: > lines = iter(infile.readline, "") > # copy one line at a time > for line in lines: Rather than this? > for line in infile: ..Mark This email and any attachment may contain confidential, privileged information for the sole use of the intended recipient. If you are not the intended recipient, do not disclose, reproduce, disseminate or otherwise use this communication. If you received this communication in error, please immediately notify the sender via email and delete the communication from your system. From mwilson-to at sympatico.ca Thu May 18 13:49:45 2006 From: mwilson-to at sympatico.ca (Mel Wilson) Date: Thu, 18 May 2006 13:49:45 -0400 Subject: [silly] Does the python mascot have a name ? In-Reply-To: <e4i9hb$f1r$1@emma.aioe.org> References: <e4c59e$tqg$1@emma.aioe.org> <mailman.5791.1147860411.27775.python-list@python.org> <Xns97C6BF618E3A9BaldHeadedJohn@216.196.109.145> <Xns97C6ADE23FCAcastleamber@130.133.1.4> <Xns97C79C8584F71BaldHeadedJohn@216.196.109.145> <mailman.5890.1147966982.27775.python-list@python.org> <e4i9hb$f1r$1@emma.aioe.org> Message-ID: <_s2bg.8867$aa4.296233@news20.bellglobal.com> Steve wrote: > Carl J. Van Arsdall wrote: >> John D Salt wrote: >>>>>> hon-list/2003-September/185612.html >>>>> "Odi" must be the Dutch for "Monty". >>>> Nope. If it was Dutch it would probably be Odie >>> Damn. >>> >> Odi(e) was a punk. I'm gonna be a rebel without a cause and stay with >> Monty ;) > Yes ! Monty sounds much better ! ...also imagine the expression on the > PHB's face if this were to happen ... Just reinforces the central truth. The mascot doesn't *have* a name. Most things don't. You're welcome to assign it the name "Monty" if you want. Mel. From no at spam.com Tue May 9 13:44:42 2006 From: no at spam.com (DH) Date: Tue, 09 May 2006 12:44:42 -0500 Subject: Multi-line lambda proposal. In-Reply-To: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> Message-ID: <mMidnUCvoJmRSP3ZnZ2dnUVZ_vOdnZ2d@comcast.com> Kaz Kylheku wrote: > I've been reading the recent cross-posted flamewar, and read Guido's > article where he posits that embedding multi-line lambdas in > expressions is an unsolvable puzzle. To say that multi-line lambda is an unsolvable problem is completely absurd. Furthermore it has already been solved. http://wiki.python.org/moin/AlternateLambdaSyntax#head-c81743c0b461ab6812564785c7bc7ba581dec6fa So I agree with you, but I doubt you'll have any luck getting your proposal or any other multiline lambda proposal accepted into python anytime soon. From sjmaster at gmail.com Fri May 5 18:12:13 2006 From: sjmaster at gmail.com (Steve M) Date: 5 May 2006 15:12:13 -0700 Subject: How to get the target of a Windows shortcut file Message-ID: <1146867133.873710.235790@i39g2000cwa.googlegroups.com> Below is some code adapted from something I think was written by Mark Hammond. Originally I needed to create a Windows shortcut (link), and this code does the trick, requiring only the target filename and the desired shortcut name. Now, I find I need to open a shortcut and extract the target filename, and I don't have a clue how that is achieved. To be clear, I mostly don't understand the gory (Windows API) details of this code. So, can anyone show how to open an existing shortcut file (given its name) and discover the name of the file to which it is a shortcut? import os from win32com.shell import shell import pythoncom # Get the shell interface. sh = pythoncom.CoCreateInstance(shell.CLSID_ShellLink, None, \ pythoncom.CLSCTX_INPROC_SERVER, shell.IID_IShellLink) # Get an IPersist interface persist = sh.QueryInterface(pythoncom.IID_IPersistFile) target_of_link = os.path.abspath('target.doc') link_name = 'shortcut_to_target.doc.lnk' sh.SetPath(target_of_link) persist.Save(link_name, 1) From alexandre_irrthum at yahoo.com Wed May 17 09:10:24 2006 From: alexandre_irrthum at yahoo.com (alexandre_irrthum at yahoo.com) Date: 17 May 2006 06:10:24 -0700 Subject: SWIG: name 'new_doubleArray' is not defined Message-ID: <1147871424.647189.225600@i39g2000cwa.googlegroups.com> Hello, I am trying to use SWIG (1.3) to wrap some C code in Python (2.3.5) under Linux, but obviously I am missing something with arrays. This is my example.c file: double sum_array(double x[], int size) { int i; double sum = 0.0; for (i=0; i<size; i++) { sum += x[i]; } return sum; } This is example.i: %module example %include "carrays.i" %array_functions(double, doubleArray); %{ extern double sum_array(double x[], int size); %} extern double sum_array(double x[], int size); These three command seem to work fine: swig -python example.i gcc -fPIC -c example.c example_wrap.c -I/usr/include/python2.3 ld -shared example.o example_wrap.o -o _example.so In python, I can import the module: >>> import example But this fails: >>> a = new_doubleArray(10) Traceback (most recent call last): File "<stdin>", line 1, in ? NameError: name 'new_doubleArray' is not defined What am I doing wrong ? Thanks for your help. alex From scott.daniels at acm.org Sat May 6 19:13:11 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 06 May 2006 16:13:11 -0700 Subject: sort a list of files In-Reply-To: <mailman.5429.1146947502.27775.python-list@python.org> References: <877j4ysy29.fsf@localhost.localdomain> <mailman.5429.1146947502.27775.python-list@python.org> Message-ID: <445d29db$1@nntp0.pdx.net> Ryan Forsythe wrote: > Gary Wessle wrote: >> Hi >> >> I am trying to print out the contents of a directory, sorted. > ... >> if I remove ".sort()" at the end of line 6 I get an unsorted list of >> files, if I leave it I get None. who do I fix this? > > `blah.sort()` sorts in-place and returns None. You probably want > sorted(blah): > > >>> a = [3, 1, 4, 1, 5, 9] > >>> sorted(a) > [1, 1, 3, 4, 5, 9] > >>> a > [3, 1, 4, 1, 5, 9] > >>> a.sort() > >>> a > [1, 1, 3, 4, 5, 9] If you are using an old version of Python (2.3.X or before), the you just need to break your statement up: Instead of: 6 print os.listdir(sys.argv[1]).sort() use: 6 files = os.listdir(sys.argv[1]) 7 files.sort() 8 print files --Scott David Daniels scott.daniels at acm.org From micklee74 at hotmail.com Fri May 12 03:51:19 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 12 May 2006 00:51:19 -0700 Subject: deleting texts between patterns Message-ID: <1147420279.664699.181200@i40g2000cwc.googlegroups.com> hi say i have a text file line1 line2 line3 line4 line5 line6 abc line8 <---to be delete line9 <---to be delete line10 <---to be delete line11 <---to be delete line12 <---to be delete line13 <---to be delete xyz line15 line16 line17 line18 I wish to delete lines that are in between 'abc' and 'xyz' and print the rest of the lines. Which is the best way to do it? Should i get everything into a list, get the index of abc and xyz, then pop the elements out? or any other better methods? thanks From me+python at modelnine.org Tue May 2 17:31:24 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Tue, 2 May 2006 23:31:24 +0200 Subject: data regex match In-Reply-To: <e38il3$kbn$1@sea.gmane.org> References: <87r73cdtmk.fsf@localhost.localdomain> <e38il3$kbn$1@sea.gmane.org> Message-ID: <200605022331.24950.me+python@modelnine.org> Am Dienstag 02 Mai 2006 23:23 schrieb Fredrik Lundh: > Gary Wessle wrote: > > regular expression match: what went wrong? > (insert obligatory jwz quote here) QOTW! :-D --- Heiko. From lance at augustmail.com Mon May 15 20:41:39 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Mon, 15 May 2006 19:41:39 -0500 Subject: using target words from arrays in regex, pythons version of perls 'map' Message-ID: <44691fc2$0$61162$ae4e5890@news.nationwide.net> Hey all, in perl I was able to use the same regular expression multiple times changing one part of it via a previously defined array and put the results into a new array IN PERL: my @targets = ('OVERALL RATING', 'CLOTHING', ' ITEMS', 'ACCESSORIES', 'SHOES', 'FINE JEWELRY'); my @JA13 = map { $file2 =~/$_.*?(?:(\d{1,3}\.\d)\s+){3}/s; } @targets; So, in python instead of match2 = re.search('OVEWRALL RATING.*?(?:(\d{1,3}\.\d)\s+){3} ', file2);m01 = match2.group(1) ;print m01 match2 = re.search('CLOTHING.*?(?:(\d{1,3}\.\d)\s+){3} ', file2); m02 = match2.group(1) ;print m02 match2 = re.search('ITEMS.*?(?:(\d{1,3}\.\d)\s+){3} ', file2); m03 = match2.group(1) ;print m03 match2 = re.search('ACCESSORIES.*?(?:(\d{1,3}\.\d)\s+){3} ', file2); m04 = match2.group(1) ;print m04 match2 = re.search('SHOES.*?(?:(\d{1,3}\.\d)\s+){3} ', file2); m05 = match2.group(1) ;print m05 match2 = re.search('FINE JEWELRY.*?(?:(\d{1,3}\.\d)\s+){3} ', file2); m06 = match2.group(1) ;print m06 I would have something similar to perl above: targets = ['OVERALL RATING', 'CLOTHING', ITEMS', 'ACCESSORIES', 'SHOES', 'FINE JEWELRY'] PROPOSED CODE: match2 = re.search(targets[i].*?(?:(\d{1,3}\.\d)\s+){3} ', file2);m[i] = match2.group(1) Lance From benji at benjiyork.com Fri May 5 15:22:19 2006 From: benji at benjiyork.com (Benji York) Date: Fri, 05 May 2006 15:22:19 -0400 Subject: unittest.main-workalike that runs doctests too? In-Reply-To: <uvesklpyi.fsf@pobox.com> References: <uvesklpyi.fsf@pobox.com> Message-ID: <445BA5EB.2090506@benjiyork.com> John J. Lee wrote: > ...I wrote something to do this once, but didn't do as good a job as I > might have done and wondered if anybody else has done it properly. The Zope 3 project has zope.testing which has a very nice test runner (and isn't Zope-specific at all). You can get the code (via Subversion) at svn://svn.zope.org/repos/main/zope.testing/trunk and browse the code (including docs) at http://svn.zope.org/zope.testing/trunk/. -- Benji York From steven.bethard at gmail.com Thu May 11 16:06:36 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Thu, 11 May 2006 14:06:36 -0600 Subject: python equivalent of the following program In-Reply-To: <FbWdnZazBY8Aqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> References: <FbWdnZazBY8Aqf7ZnZ2dnUVZ_v2dnZ2d@comcast.com> Message-ID: <J-CdnRbdnJzNBP7ZnZ2dnUVZ_s-dnZ2d@comcast.com> AndyL wrote: > What would by a python equivalent of following shell program: > > #!/bin/sh > > prog1 > file1 & > prog2 > file2 & If you're just going for quick-and-dirty, Rob's suggestion of os.system is probably a reasonable way to go. If you want better error reporting, I suggest using open() and the subprocess module: import subprocess file1 = open('file1', 'w') prog1 = subprocess.Popen(['prog1'], stdout=file1) file2 = open('file2', 'w') prog2 = subprocess.Popen(['prog2'], stdout=file2) If at some point later you want to make sure that the processes completed, you simply call .wait() on prog1 or prog2. STeVe From aomighty at gmail.com Thu May 25 21:12:11 2006 From: aomighty at gmail.com (aomighty at gmail.com) Date: 25 May 2006 18:12:11 -0700 Subject: Speed up this code? Message-ID: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> I'm creating a program to calculate all primes numbers in a range of 0 to n, where n is whatever the user wants it to be. I've worked out the algorithm and it works perfectly and is pretty fast, but the one thing seriously slowing down the program is the following code: def rmlist(original, deletions): return [i for i in original if i not in deletions] original will be a list of odd numbers and deletions will be numbers that are not prime, thus this code will return all items in original that are not in deletions. For n > 100,000 or so, the program takes a very long time to run, whereas it's fine for numbers up to 10,000. Does anybody know a faster way to do this? (finding the difference all items in list a that are not in list b)? Thanks, Martin From lordlandon at gmail.com Wed May 3 17:42:34 2006 From: lordlandon at gmail.com (Lord Landon) Date: Wed, 3 May 2006 17:42:34 -0400 Subject: Defining class methods outside of classes Message-ID: <682277700605031442g14999257q7f98bf7c14b6d46@mail.gmail.com> Hi, I'm working on a bot written in python. It will consist of a mostly empty class that will then call a loader which in turn defines functions and adds them to the class. At the moment, I do this by using execfile(file,globals()) and calling a load(bot) method defined in every "module" which takes the functions defined in that perticular module and does bot.function=function. The problem with that is when I call bot.function() self doesn't get passed as an argument to the function. Is there anything I can do to sort this besides calling bot.function(bot, ...) everytime? -- Lord Landon rules over all! From brian at brianandkate.com Thu May 18 12:46:43 2006 From: brian at brianandkate.com (Brian Blazer) Date: Thu, 18 May 2006 11:46:43 -0500 Subject: Complex evaluation bug In-Reply-To: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> References: <446ca27d$0$14606$6c56d894@reader0.news.be.easynet.net> Message-ID: <4537B713-053A-4C7A-860B-E9247AB57EEB@brianandkate.com> I am not exactly sure what is going on, but I get the error: ValueError: complex() arg is a malformed string I think that it might be because the value of 'j' is not defined. But I am a newbie so I could very well be wrong. Brian Blazer brian at brianandkate.com On May 18, 2006, at 11:36 AM, of wrote: > a = 1+3j > complex(str(a)) > > Why does this not work ? It should > -- > http://mail.python.org/mailman/listinfo/python-list From unmiserable at gmail.com Mon May 22 01:18:35 2006 From: unmiserable at gmail.com (Petter Haggholm) Date: 21 May 2006 22:18:35 -0700 Subject: Python source sensitive to PyObject_HEAD layout? In-Reply-To: <44714081.2070308@v.loewis.de> References: <1148254892.114251.45770@j55g2000cwa.googlegroups.com> <44714081.2070308@v.loewis.de> Message-ID: <1148275115.566450.283160@i40g2000cwc.googlegroups.com> Boy, do I feel foolish! I hang my head in shame and thank you for your assistance---that solved it. From a.schmolck at gmail.com Tue May 16 14:22:07 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 16 May 2006 19:22:07 +0100 Subject: round numbers in an array without importing Numeric or Math? References: <446a1748$0$61168$ae4e5890@news.nationwide.net> Message-ID: <yfssln9q180.fsf@oc.ex.ac.uk> Lance Hoffmeyer <lance at augustmail.com> writes: > Is there an easy way to round numbers in an array? > > I have > Test = [1.1,2.2,3.7] > > and want to round so the values are > > print Test [1,2,4] [int(x+0.5) for x in Test] 'as From duncanm255 at hotmail.com Fri May 5 08:39:08 2006 From: duncanm255 at hotmail.com (D) Date: 5 May 2006 05:39:08 -0700 Subject: Active Directory Authentication Message-ID: <1146832748.087170.212860@j33g2000cwa.googlegroups.com> Is it possible to have Python authenticate with Active Directory? Specifically what I'd like to do is have a user enter a username/password, then have Python check the credentials with AD - if what they entered is valid, for example, it returns a 1, otherwise a 0.. Thanks! From johnjsal at NOSPAMgmail.com Fri May 19 13:29:24 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 17:29:24 GMT Subject: WTF? Printing unicode strings In-Reply-To: <mailman.5967.1148058991.27775.python-list@python.org> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <RFkbg.2124$No6.46433@news.tufts.edu> <e4kruq$19o$1@sea.gmane.org> <mailman.5967.1148058991.27775.python-list@python.org> Message-ID: <Ufnbg.2131$No6.46463@news.tufts.edu> skip at pobox.com wrote: > Robert> Because sys.stdout.encoding isn't determined by your Python > Robert> configuration, but your terminal's. > > Learn something every day. I take it "646" is an alias for "ascii" (or vice > versa)? Hmm, not that this helps me any :) >>> import sys >>> sys.stdout.encoding 'cp1252' >>> import codecs >>> codecs.lookup('cp1252') (<bound method Codec.encode of <encodings.cp1252.Codec instance at 0x009D6670>>, <bound method Codec.decode of <encodings.cp1252.Codec instance at 0x009D6698>>, <class encodings.cp1252.StreamReader at 0x009CF360>, <class encodings.cp1252.StreamWriter at 0x009CF330>) >>> From me+python at modelnine.org Wed May 3 10:01:02 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 3 May 2006 16:01:02 +0200 Subject: --version? In-Reply-To: <e37qgp$n44$1@sea.gmane.org> References: <4bp06lF1276vvU1@individual.net> <4bp35kF12517kU1@individual.net> <e37qgp$n44$1@sea.gmane.org> Message-ID: <200605031601.02909.me+python@modelnine.org> Am Dienstag 02 Mai 2006 16:31 schrieb Fredrik Lundh: > Paul Watson wrote: > > I am well aware of -V. Could --version be supported as well? > > http://www.python.org/dev/ > http://sourceforge.net/tracker/?group_id=5470&atid=355470 > > </F> I just submitted: https://sourceforge.net/tracker/index.php?func=detail&aid=1481112&group_id=5470&atid=305470 The patch implements long option support in _PyOS_GetOpt. --- Heiko. From barberomarcelo at gmail.com Wed May 17 11:36:32 2006 From: barberomarcelo at gmail.com (barberomarcelo at gmail.com) Date: 17 May 2006 08:36:32 -0700 Subject: List behaviour In-Reply-To: <1147879113.255149.26560@g10g2000cwb.googlegroups.com> References: <1147878414.819145.88580@i40g2000cwc.googlegroups.com> <1147879113.255149.26560@g10g2000cwb.googlegroups.com> Message-ID: <1147880192.717731.133210@g10g2000cwb.googlegroups.com> Thank you very much. It was clear. From m.yanowitz at kearfott.com Thu May 18 08:41:20 2006 From: m.yanowitz at kearfott.com (Michael Yanowitz) Date: Thu, 18 May 2006 08:41:20 -0400 Subject: Tkinter Dialog Management problems: In-Reply-To: <e41t8p$qpt$1@sea.gmane.org> Message-ID: <HGEOKIAPAMCIFPPBDALKMEJLCAAA.m.yanowitz@kearfott.com> Hello: Below I have included a stripped down version of the GUI I am working on. It contains 2 dialog boxes - one main and one settings. It has the following problems, probably all related, that I am hoping someone knows what I am doing wrong: 1) Pressing the Settings.. Button multiple times, brings up many instances of the Settings Panel. I just want it to bring up one. Is there an easy way to do that? 2) Pressing the Done button in the Settings Panel, just erases the Done button (and any other widgets in the Panel). It does not dismiss the Panel. Pressing the X button does work. What callback is that? Can I make the Done button call that instead? How? 3) Pressing the Done button from the Main Panel has no effect? Why not? It used to work (self.quit()). Again, I would like to call whatever is called when the X button (top Right corner) is pressed. Thanks in advance: """ TkInter Test """ #********** Imports ********************************************* import os import sys import Tkinter from Tkinter import Tk, Frame, Button, Label, Entry, Scrollbar from Tkinter import Text, Checkbutton, IntVar import tkFileDialog from tkMessageBox import askyesno, showerror # ******* runScript() ************************************* def runScript (strFilename): """ Executes Python script file """ if (VERBOSE): print strFilename, "is being imported" fileText = "" try: fptr = open (strFilename, 'r') fileText = fptr.read() fptr.close() except Exception, (errno): print "Exception in import of file:", strFilename, "- Errno = ", errno print (sys.exc_info()) showerror ('Error', 'Problem importing file - see console for details') else: fname = [strFilename[:-3].split('/')[-1]] for f in fname: __import__(f) # ******* getGUIFilename ******************************************* def getGUIFilename(): """ returns a tkInter File Selection Dialog """ strFilename = tkFileDialog.askopenfilename(initialdir='.', filetypes=[('Python files','*.py'), ('All Files','*.*')]) return strFilename # ******* ScenarioPlayerDialog class ************************************* class ScriptDialog(Frame): """ Script Dialog GUI class """ def __init__(self, parent=None): """ Script GUI class constructor """ Frame.__init__(self, parent) self.pack() self.commandRow = Frame(self) self.commandLabel = Label(self.commandRow, width=14, text="Python Command:") self.commandEnt = Entry(self.commandRow) self.commandRow.pack(side=Tkinter.TOP, fill=Tkinter.X) self.commandLabel.pack(side=Tkinter.LEFT) self.commandEnt.pack(side=Tkinter.RIGHT, expand=Tkinter.YES, fill=Tkinter.X) self.commandEnt.delete('0', Tkinter.END) self.commandEnt.pack(side=Tkinter.TOP, fill=Tkinter.X) buttonRow3 = Frame(self) doneBtn = Button(buttonRow3, text='Done', command=self.done) doneBtn.pack(side=Tkinter.RIGHT) buttonRow3.pack(side=Tkinter.BOTTOM, expand=Tkinter.YES, fill=Tkinter.X) buttonRow2 = Frame(self) runBtn = Button(buttonRow2, text='Run Script', command=self.playScript) runBtn.pack(side=Tkinter.LEFT) buttonRow2.pack(side=Tkinter.BOTTOM, expand=Tkinter.YES, fill=Tkinter.X) buttonRow1 = Frame(self) executeBtn = Button(buttonRow1, text='Execute Command') executeBtn.pack(side=Tkinter.LEFT) settingsBtn = Button(buttonRow1, text='Settings...', command=self.editSettings) settingsBtn.pack(side=Tkinter.LEFT) self.verbose = Tkinter.IntVar() Checkbutton(self,text="Verbose",variable=self.verbose, command=self.setVerbosity).pack(side=Tkinter.RIGHT) buttonRow1.pack(side=Tkinter.BOTTOM, expand=Tkinter.YES, fill=Tkinter.X) self.pack(expand=Tkinter.YES, fill=Tkinter.BOTH) self.theParent = parent def setVerbosity(self): """ Callback called when the 'Verbose' RadioButton is pressed """ global VERBOSE VERBOSE = self.verbose.get() def playScript(self): """ Callback called when the 'Run Script' button is pressed """ sFilename = getGUIFilename() if (VERBOSE): print "Running script file: ", sFilename runScript (sFilename) def editScript(self): """ Callback called when the 'Edit Script' button is pressed """ sFilename = getGUIFilename() editScript (sFilename) def executeCommand(self): """ Callback called when the 'Execute Command' button is pressed """ strCommand = self.commandEnt.get() if (VERBOSE): print strCommand, "is being executed" exec (strCommand) def editSettings(self): """ Callback called when the 'Edit Settings' button is pressed """ win = Tkinter.Toplevel() settingsDlg = SettingsDialog (win) def done(self): """ Callback called when the 'Done' button is pressed """ self.quit() # ******** start() ************************************************ def start(): """ Start the Script Dialog GUI """ rootWindow = Tkinter.Tk() rootWindow.title('Script Player - Version L1.0') ScriptDialog (rootWindow) rootWindow.mainloop() # ******* SocketSettingsDialog class ********************************* class SettingsDialog(Frame): """ Setttings Dialog GUI class """ def __init__(self, parent=None): """ Settings Dialog GUI class constructor """ Frame.__init__(self, parent) self.pack() buttonRow2 = Frame(self) self.theWidget = self doneBtn = Button(buttonRow2, text='Done', command=self.destroy) doneBtn.pack(side=Tkinter.RIGHT) buttonRow2.pack(side=Tkinter.TOP, expand=Tkinter.YES, fill=Tkinter.X) self.pack(expand=Tkinter.YES, fill=Tkinter.BOTH) def done(self): """ Callback called when the 'Done' button is pressed """ self.destroy() start() From chris at kateandchris.net Tue May 2 17:20:08 2006 From: chris at kateandchris.net (Chris Lambacher) Date: Tue, 2 May 2006 17:20:08 -0400 Subject: What is wrong with the Python home page? In-Reply-To: <1146602638.824774.264180@j33g2000cwa.googlegroups.com> References: <1146602638.824774.264180@j33g2000cwa.googlegroups.com> Message-ID: <20060502212008.GA12901@kateandchris.net> Works for me with FireFox 1.5.2, but I am on WinXP at the moment. -Chris On Tue, May 02, 2006 at 01:43:58PM -0700, fuzzylollipop wrote: > I am using FireFox 1.5.2 on OS X 10.4.6 and the www.python.org ends up > being only text with just the nasa picture with the guy in the space > suit. > > It looks like the CSS is hosed or something. > > And trying to go to the module docs for the current release is broken > as well > > -- > http://mail.python.org/mailman/listinfo/python-list From roy at panix.com Thu May 25 10:04:42 2006 From: roy at panix.com (Roy Smith) Date: Thu, 25 May 2006 10:04:42 -0400 Subject: Modify one character in a string References: <1148534239.471922.189520@i40g2000cwc.googlegroups.com> Message-ID: <roy-F85321.10044225052006@reader1.panix.com> "mp" <mailpitches at email.com> wrote: > X-No-Archive > How do I go about modifying one character in a string elegantly? > In other words, I want a function that will change 'aaaa' to 'aaza', > given the index 2 of the character in the string. Strings are immutable, so you can't change a string. The best you can do is create a new string from the old one. Something like: >>> old = 'aaaa' >>> new = old[:2] + 'z' + old[3:] >>> print new aaza or a few variations on that theme. > Also, how do I do this when dealing with a file ; which file mode > should I use and what function should I use to modify a single > character once in that file mode? This is a much more complicated question, because it depends on the details of the operating system you're using. On Unix, you can seek to a specific place in a file, write a single character, seek to EOF, and you've done an in-place single character edit of the file. I don't know if that works on other OS's or not. From http Sat May 6 10:52:51 2006 From: http (Paul Rubin) Date: 06 May 2006 07:52:51 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <87mzdvo2nm.fsf@rpi.edu> <445c8812$0$31639$e4fe514c@news.xs4all.nl> <7xhd43qkxq.fsf@ruckus.brouhaha.com> Message-ID: <7xd5erqk70.fsf@ruckus.brouhaha.com> Paul Rubin <http://phr.cx at NOSPAM.invalid> writes: > I don't know what good that hardware crypto is doing you, if you're > then writing out the shuffled deck to disk in the clear. Ehhh, I guess you want the crypto hardware to generate physical randomness for each shuffle. I'm skeptical of the value of this since a cryptographic PRNG seeded with good entropy is supposed to be computationally indistinguishable from physical randomness, and if it's not, we're all in big trouble; further, that hardware engine is almost certainly doing some cryptographic whitening, which is a problem if you don't think that cryptography works. Anyway, if it's just a 52-card deck you're shuffling, there's only about 226 bits of entropy per shuffle, or 52*6 = 312 bits if you write out the permutation straightforwardly as a vector. You could use that as the ticket but if you're generating it that way you may need to save the shuffle for later auditing. For practical security purposes I'd be happier generating the shuffles entirely inside the crypto module (HSM) by cryptographic means, with the "ticket" just being a label for a shuffle. E.g. let K1, K2 = secret keys T(n) = ticket #n = AES(K1, n) to prevent clients from guessing ticket numbers shuffle(n) = HMAC-SHA-384(K2, n) truncated to 312 bits, treated as permutation on 52 cards You could put some of the card dealing logic into the HSM to get the cards dealt out only as the game as played, to decrease the likelihood of any cards getting exposed prematurely. From vivainio at gmail.com Wed May 3 12:07:23 2006 From: vivainio at gmail.com (Ville Vainio) Date: 3 May 2006 09:07:23 -0700 Subject: IPython team needs a student for a google "Summer of Code" project. Message-ID: <1146672443.368154.234230@i39g2000cwa.googlegroups.com> This comes in a bit of a hurry (you only have time until next monday to sign up), but here's the deal: The next version of ipython (0.7.2, "out soon", pretty much done already) will include an extension for browsing and manipulating tabular data (e.g. file name, file size, permissions etc.) called "ipipe", contributed by Walter Doerwald. See http://projects.scipy.org/ipython/ipython/wiki/UsingIPipe to get an idea. The bad news is that, being built on curses, the browser only works on Linux/posix. That's where you'll step in. We need a similar tabular browser built on wxPython toolkit (possibly with the Wax wrapper library). Walter and me have already been accepted as mentors, but we need someone to do the work. As you probably know, there's money involved, see http://code.google.com/soc/studentfaq.html. No knowledge of IPython codebase is necessary (nor will you need to learn it), and the ipipe module itself is pretty manageable and small. So it's mostly about implementing new stuff from scratch. Please contact ipython-dev, me or (preferably) Walter Doerwald (walter at livinglogic.de) if you are interested, ASAP. From andy at neotitans.com Wed May 17 06:38:58 2006 From: andy at neotitans.com (Andy Sy) Date: Wed, 17 May 2006 18:38:58 +0800 Subject: Web framework to recommend (don't use one, use Spyce instead) In-Reply-To: <e495q1$1085$1@news.hgc.com.hk> References: <e495q1$1085$1@news.hgc.com.hk> Message-ID: <e4eu9j$20o$1@sea.gmane.org> Jacky wrote: > Hi all, > > I just started learning Python and would like to starting writing some > web-based applications with Python. > > I did have pretty much experience with doing so with PHP and Java, but > Python seems a bit different for me. > > Do you guys have some good web framework to recommend? (I don't want to > use CGI mode) > > Thanks a lot. > > -- > Jacky Spyce is probably the most underappreciated Python web solution out there. If you don't want the hassle of a framework's learning curve, Spyce lets you do PHP/JSP/ASP style coding using what you already know about Python and not much else. It is also more powerful than PHP because it supports features such as custom tags (ala JSP) and others. Check out the Wikipedia article below: http://en.wikipedia.org/wiki/Spyce The important thing to note is that you can transparently use traditional ASP, JSP style angled brackets <% and %> and not the confusing [[, ]] that Spyce documentation defaults to. I believe this is what may have turned many people (who are not aware of the more standard alternative) off from using Spyce. I however, disagree with the assertion in the wikipedia article that Spyce is easier to set up than PHP... PHP is just as easy to set up as Spyce, if not easier... -- It's called DOM+XHR and it's *NOT* a detergent! From larry.bates at websafe.com Wed May 31 13:21:34 2006 From: larry.bates at websafe.com (Larry Bates) Date: Wed, 31 May 2006 12:21:34 -0500 Subject: Are ActivePython scripts compatible with Linux? In-Reply-To: <Knjfg.1106$Su3.100610@news20.bellglobal.com> References: <Knjfg.1106$Su3.100610@news20.bellglobal.com> Message-ID: <SYCdnZBPbu0GTeDZnZ2dneKdnZydnZ2d@comcast.com> Short answer: yes Things to watch out for: 1) Versions on both Windows/Linux need to be compatible. If Linux has same or later version, you are normally OK. If Linux version is older, you will have to use only Python Libraries and functions that are in the oldest version. 2) Don't use OS-specific constructs. Things like backslashes in filenames, etc. Use os.path.join, os.path.basename, etc. to work with paths. Linux has OS-specific code that handles all the cross-OS problems for you if you use these methods. Don't hard code drive letters in your code, Linux/Mac don't have drive letters. 3) Obviously you can't use Python Windows extensions, which won't port. You can't move something that is written as COM object or as a Windows service (sorry those were probably too obvious ;-). 4) If you use GUI, use something that is cross-platform (like wxWindows, TK, etc.). You can't use Windows-specific GUI calls. 5) You can be affected by word length issues if you move from 32-bit Windows to 64-bit Linux. Normally this is only only a problem if you use struct module to pack/unpack buffers or if you do bit shift operations (e.g. <<, >>). 6) Don't depend on Windows line endings in files. Linux/Mac use different ones than Windows. 7) Some Linux machine have different endian storage of bytes. If you do bit shifting or struct pack/unpack you will need to take that into account. 8) If you have OS-specific "things" in your code, put them in a function or class that can easily be rewritten for the specific OS you are porting to. Don't spread them out all through your code. It is much easier to rewrite a couple of functions/classes that are OS-specific than it is to try to find problems all over your program. Hope info helps at least a little. -Larry A.M wrote: > Hi, > > > > I am planning to develop python applications on windows and run them on > Linux. Are ActivePython scripts compatible with Linux? Is there any > guideline that explains the compatibility issues between python in different > platforms? > > > > What would be the best approach for what I am trying to do? > > > > Any help would be appreciated, > > Alan > > From nszabolcs at gmail.com Tue May 23 15:54:10 2006 From: nszabolcs at gmail.com (Szabolcs Nagy) Date: 23 May 2006 12:54:10 -0700 Subject: Guide to using python for bash-style scripting In-Reply-To: <1148408959.230231.142460@i39g2000cwa.googlegroups.com> References: <1148405239.840908.120910@j33g2000cwa.googlegroups.com> <1148405325.101047.181370@j73g2000cwa.googlegroups.com> <1148408959.230231.142460@i39g2000cwa.googlegroups.com> Message-ID: <1148414050.770687.296150@j55g2000cwa.googlegroups.com> python subprocess module docs: http://docs.python.org/dev/lib/node517.html From me+python at modelnine.org Wed May 3 22:03:24 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Thu, 4 May 2006 04:03:24 +0200 Subject: This coding style bad practise? In-Reply-To: <445936fb$0$31642$e4fe514c@news.xs4all.nl> References: <44591463$0$31639$e4fe514c@news.xs4all.nl> <44591be3$0$2626$636a55ce@news.free.fr> <445936fb$0$31642$e4fe514c@news.xs4all.nl> Message-ID: <200605040403.24670.me+python@modelnine.org> Am Donnerstag 04 Mai 2006 01:04 schrieb Martin P. Hellwig: > Because of: > >>>> id = IDGenerator("01",99) > >>>> id() > > > > Traceback (most recent call last): > > File "<pyshell#1>", line 1, in ? > > id() > > TypeError: 'IDGenerator' object is not callable > > But i do appreciate your comment, thanks! You need to define a __call__(self)-method on your class so that instances are callable... Basically, what Bruno was saying, is that you rename your __repr__(self) to __call__(self), and see what happens. --- Heiko. From ajones1 at gmail.com Mon May 8 02:08:45 2006 From: ajones1 at gmail.com (Adam Jones) Date: 7 May 2006 23:08:45 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <O7A7g.59$sC4.54@fe09.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <1146982654.897283.293390@y43g2000cwc.googlegroups.com> <r8n7g.10$Q17.3@fe08.lga> <yfshd41yeaj.fsf@oc.ex.ac.uk> <O7A7g.59$sC4.54@fe09.lga> Message-ID: <1147068524.966560.52210@y43g2000cwc.googlegroups.com> Ken Tilton wrote: > Alexander Schmolck wrote: > > [trimmed groups] > > > > Ken Tilton <kentilton at gmail.com> writes: > > > > > >>yes, but do not feel bad, everyone gets confused by the /analogy/ to > >>spreadsheets into thinking Cells /is/ a spreadsheet. In fact, for a brief > >>period I swore off the analogy because it was so invariably misunderstood. > >>Even Graham misunderstood it. > > > > > > Count me in. > > <g> But looking at what it says: "Think of the slots as cells in a > spreadsheet (get it?), and you've got the right idea. ", if you follow > the analogy (and know that slot means "data member" in other OO models) > you also know that Serge's Spreadsheet example would have scored a big > fat zero on the Miller Analogy Test. Serge in no way made slots in > Python classes behave like cells in a spreadsheet. He simply started > work on a Spreadsheet application, using Python classes along the way. Bzzt. > > While everyone makes the mistake, it is only because few of us (me > included) read very carefully. Especially if they are more interested in > flaming than learning what someone is saying. > I don't really mean any disrespect here, but if an analogy is not interpreted correctly by a large group of people, the analogy is crap, not the people. Yes, I understood it, specifically because I have spent enough time dinking around with cell functions in a spreadhseet to understand what you meant. Maybe it would help to change the wording to "functions with cell references in a spreadsheet" instead of "cells in a spreadsheet". Yes, you lose the quippy phrasing but as it is most people use spreadsheets as "simple database with informal ad hoc schema" and mostly ignore the more powerful features anyways, so explicit language would probably help the analogy. I'm guessing if you made some vague allusions to how "sum(CellRange)" works in most spreadsheets people would get a better idea of what is going on. From seberino at spawar.navy.mil Thu May 18 12:05:13 2006 From: seberino at spawar.navy.mil (seberino at spawar.navy.mil) Date: 18 May 2006 09:05:13 -0700 Subject: Any pointers/advice to help learn CPython source? In-Reply-To: <1147936062.293223.233820@y43g2000cwc.googlegroups.com> References: <1147886150.819254.158880@i40g2000cwc.googlegroups.com> <1147936062.293223.233820@y43g2000cwc.googlegroups.com> Message-ID: <1147968313.861370.261250@g10g2000cwb.googlegroups.com> Wow thanks for your detailed reply. Mainly I just wanted to understand the theory and ideas needed to make an interpreter. Your directory description helped. Chris From russandheather at gmail.com Mon May 1 19:38:49 2006 From: russandheather at gmail.com (Russell Warren) Date: 1 May 2006 16:38:49 -0700 Subject: Popping from the middle of a deque + deque rotation speed References: <1146264164.488782.96770@g10g2000cwb.googlegroups.com> <mailman.5117.1146266004.27775.python-list@python.org> Message-ID: <1146526729.484401.314250@e56g2000cwe.googlegroups.com> Thanks for the responses. > It seems to work with my Python2.4 here. If you're > interested in efficiency, I'll leave their comparison as an > exercise to the reader... :) Ok, exercise complete! :) For the record, they are pretty much the same speed... >>> s = """ ... from collections import deque ... class mydeque(deque): ... def popmiddle(self, pos): ... self.rotate(-pos) ... ret=self.popleft() ... self.rotate(pos) ... return ret ... d = mydeque(xrange(1000000)) >>> timeit.Timer(stmt="x=d.popmiddle(1000)", setup = s).timeit(number=100000) 5.4620059253340969 >>> s2=""" ... from collections import deque ... class mydeque(deque): ... def popmiddle(self, pos): ... ret = self[pos] ... del(self[pos]) ... return ret ... d = mydeque(xrange(1000000)) ... """ >>> timeit.Timer(stmt="x=d.popmiddle(1000)", setup = s2).timeit(number=100000) 5.3937888754018104 Thanks for the alternative solution. Russ From majj81 at 163.com Wed May 31 03:10:53 2006 From: majj81 at 163.com (majj81) Date: Wed, 31 May 2006 15:10:53 +0800 (CST) Subject: Add file to zip, or replace file in zip Message-ID: <447D417D.000005.13553@bj163app13.163.com> hi: Good afternoon. Has this problem solved in the URL http://mail.python.org/pipermail/python-list/2006-April/338849.html . Now I have the same problem to deal with. If you have any suggestion please tell me. Thanks. Johnny Ma come from China -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060531/15b50f81/attachment.html> From runlevelten at gmail.com Sun May 14 10:03:21 2006 From: runlevelten at gmail.com (Ten) Date: Sun, 14 May 2006 15:03:21 +0100 Subject: copying files into one In-Reply-To: <874pztgsd5.fsf@localhost.localdomain> References: <874pztgsd5.fsf@localhost.localdomain> Message-ID: <200605141503.22030.runlevelten@gmail.com> On Sunday 14 May 2006 05:09, Gary Wessle wrote: > Hi > > I am looping through a directory and appending all the files in one > huge file, the codes below should give the same end results but are > not, I don't understand why the first code is not doing it. > > thanks > Hi there - I think you might need to give a more whole code sample when asking this question, as it's all a bit ambiguous - for instance "file" is a type, like "string" or "list" but... > > combined = open(outputFile, 'wb') > > for name in flist: > if os.path.isdir(file): continue ^If you can successfully get past this line, you must have reused "file" to describe a string (which is probably quite a *BAD* idea ;) ) and just not included some of the code... BUT > > infile = open(os.path.join(file), 'rb') > This line suggests it's a list, so I don't know. Argh. Anyway, I'm not being pernickety, just pointing out that it's a little too ambiguous - the code sample you gave alone would not work at all.. > # CODE 1 this does not work > tx = infile.read(1000) > if tx == "": break<<<<< > combined.write(tx) > infile.close()<<<<<<<<< > > # CODE 2 but this works fine > for line in infile: > combined.write(line) > infile.close() > > combined.close() Hope to help when you post back, Cheers, Ten -- There are 10 types of people in this world, those who understand binary, and those who don't. From bborcic at gmail.com Thu May 4 04:35:42 2006 From: bborcic at gmail.com (Boris Borcic) Date: Thu, 04 May 2006 10:35:42 +0200 Subject: pythonic way to sort In-Reply-To: <mailman.5298.1146718430.27775.python-list@python.org> References: <1146715940.923869.91730@u72g2000cwu.googlegroups.com> <mailman.5298.1146718430.27775.python-list@python.org> Message-ID: <4459bce3$1_2@news.bluewin.ch> Jay Parlar wrote: > > On May 4, 2006, at 12:12 AM, micklee74 at hotmail.com wrote: > [...] > Assume that you have the lines in a list called 'lines', > as follows: > > lines = [ > "1SOME STRING ~ABC~12311232432D~20060401~00000000", > "3SOME STRING ~ACD~14353453554G~20060401~00000000", > "2SOME STRING ~DEF~13534534543C~20060401~00000000"] > > > The more traditional way would be to define your own comparison function: > > def my_cmp(x,y): > return cmp( x.split("~")[1], y.split("~")[1]) > > lines.sort(cmp=my_cmp) > > > The newer, faster way, would be to define your own key function: > > def my_key(x): > return x.split("~")[1] > > lines.sort(key=my_key) and if the data is in a file rather than a list, you may write eg lines = sorted(file("/path/tofile"),key=mike) to create it sorted. From cyberco at gmail.com Mon May 1 17:05:30 2006 From: cyberco at gmail.com (cyberco) Date: 1 May 2006 14:05:30 -0700 Subject: python about mobile game? In-Reply-To: <mailman.4794.1145526339.27775.python-list@python.org> References: <mailman.4794.1145526339.27775.python-list@python.org> Message-ID: <1146517530.153809.126840@e56g2000cwe.googlegroups.com> http://sourceforge.net/projects/pys60 From brian at brianandkate.com Thu May 18 22:07:40 2006 From: brian at brianandkate.com (Brian Blazer) Date: Thu, 18 May 2006 21:07:40 -0500 Subject: Newbie append() question Message-ID: <179CD7BF-BBFD-4A37-AEA2-76F021A366F8@brianandkate.com> I promise that this is not homework. I am trying to self teach here and have run into an interesting problem. I have created a method that asks for a class name and then is supposed to add it to classes []. Here is a snippet: def getCurrentClasses(): classes = [] print 'Please enter the class name. When finished enter D.' while (c != "D"): c = raw_input("Enter class name") if (c != "D"): classes.append(c) I have been running this in the interactive interpreter and if I print the list I get the string "Enter class name" as the first entry in the list and what was supposed to be the first entry as the second element like this: Enter class name: cs1 ['Enter class name: cs1'] I guess that I assumed that c would be equal to the value entered by the user not the prompt string. It actually looks like it is taking the whole thing as one string. But then if I enter more classes I get this: Enter class name: cs2 ['Enter class name: cs1', 'cs2'] So with the second and successive inputs, it appends the entered string. Hopefully someone could enlighten me as to what is going on and maybe offer a suggestion to help me figure this one out. Thank you for your time, Brian brian at brianandkate.com From darkbard at gmail.com Tue May 16 09:15:13 2006 From: darkbard at gmail.com (Gabriele *darkbard* Farina) Date: 16 May 2006 06:15:13 -0700 Subject: Unicode digit to unicode string In-Reply-To: <slrne6jjn5.5af.alf@merlin.fayauffre.org> References: <1147784739.786522.234280@v46g2000cwv.googlegroups.com> <slrne6jjn5.5af.alf@merlin.fayauffre.org> Message-ID: <1147785312.783166.293780@v46g2000cwv.googlegroups.com> thank you, bye From grante at visi.com Tue May 30 10:27:22 2006 From: grante at visi.com (Grant Edwards) Date: Tue, 30 May 2006 14:27:22 -0000 Subject: Watching serial port activity. References: <1148955873.334359.47860@u72g2000cwu.googlegroups.com> <127ncut3mpadoc5@corp.supernews.com> <1148962019.355956.124420@38g2000cwa.googlegroups.com> <127oj612scnl8a0@corp.supernews.com> <1148998176.105881.156310@g10g2000cwb.googlegroups.com> Message-ID: <127olia8pnldl90@corp.supernews.com> On 2006-05-30, TheSeeker <duane.kaufman at gmail.com> wrote: > Have you looked into slsnif > (http://www.dakotacom.net/~ymg/software.html) FYI, slsnif won't work for any serial program that needs to use parity, 7 data bits, or any of the modem control/status lines. Since all of the serial applications I use need to use actual serial ports, I've never found slsnif to be useful. It's really a shame that pty devices don't support the same set of ioctl calls that tty devices do. -- Grant Edwards grante Yow! World War Three can at be averted by adherence visi.com to a strictly enforced dress code! From martin at v.loewis.de Sun May 21 06:07:12 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Sun, 21 May 2006 12:07:12 +0200 Subject: WTF? Printing unicode strings In-Reply-To: <mailman.5967.1148058991.27775.python-list@python.org> References: <rNOSPAMon-10BE57.14230418052006@news.gha.chartermi.net> <mailman.5904.1147987926.27775.python-list@python.org> <RFkbg.2124$No6.46433@news.tufts.edu> <e4kruq$19o$1@sea.gmane.org> <mailman.5967.1148058991.27775.python-list@python.org> Message-ID: <44703BD0.7030807@v.loewis.de> skip at pobox.com wrote: > Learn something every day. I take it "646" is an alias for "ascii" (or vice > versa)? Usage of "646" as an alias for ASCII is primarily a Sun invention. When ASCII became an international standard, its standard number became ISO/IEC 646:1968. It's not *quite* the same as ASCII, as it leaves a certain number of code points unassigned that ASCII defines (most notably, the dollar sign, and the square and curly braces). What Sun means is probably the "International Reference Version" of ISO 646, which is (now) identical to ASCII. Regards, Martin From nkammah at yahoo.fr Wed May 31 23:08:30 2006 From: nkammah at yahoo.fr (kepioo) Date: 31 May 2006 20:08:30 -0700 Subject: How to access the content of notepad with Python? Message-ID: <1149131310.763870.29250@j55g2000cwa.googlegroups.com> Hi, I have a software running on my computer that really looks like notepad ( same interface, different name). I need to write a script that will capture the content of this software --> the text written inside. Is it possible using win32 libs? any clue? Thanks! From bdesth.quelquechose at free.quelquepart.fr Sat May 27 19:49:09 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Sun, 28 May 2006 01:49:09 +0200 Subject: Software Needs Philosophers In-Reply-To: <7xirnwpnur.fsf@ruckus.brouhaha.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <Xns97CC91CC89166BaldHeadedJohn@216.196.109.145> <7xirnwpnur.fsf@ruckus.brouhaha.com> Message-ID: <4478b614$0$1599$636a55ce@news.free.fr> Paul Rubin a ?crit : > John D Salt <jdsalt_AT_gotadsl.co.uk> writes: > >>What exciting new ideas exist in software that are both important and >>cannot be traced back to 1986 or earlier? > > > Automated spamming tools? ;-) keyboard ! From bignose+hates-spam at benfinney.id.au Tue May 23 02:36:51 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Tue, 23 May 2006 16:36:51 +1000 Subject: Short and simple functions (was: Re: Dr. Dobb's Python-URL! - weekly Python news and links (May 22)) References: <e4sma5$msm$1@lairds.us> <e4t35c$7su$1@news.Stanford.EDU> Message-ID: <87bqtp2qnw.fsf_-_@benfinney.id.au> "Andy Salnikov" <a_salnikov at yahoo.com> writes: > "Peter Otten" <python-url at phaseit.net> wrote in message > news:e4sma5$msm$1 at lairds.us... > > QOTW: "It's hard to make a mistake by having too many short and simple > > functions. And much too easy to make them when you have too few ;-)" > > - Thomas Bartkus > > > And of course there is a mathematical proof of that provided > somewhere, isn't it? :) > > "Too many" is always opposite to "hard to make a mistake", at least > in my mind. I parsed the assertion as: (It's hard to (make a mistake (by having (too many (short and simple) functions)))) In other words, it's not that he's saying "having too many short and simple functions" is difficult, nor that it's not a mistake; he's saying that it's difficult to get into a situation where that is the cause of one's mistake. -- \ "I got an answering machine for my phone. Now when someone | `\ calls me up and I'm not home, they get a recording of a busy | _o__) signal." -- Steven Wright | Ben Finney From marco.herrn at sourcepark.de Tue May 16 11:46:35 2006 From: marco.herrn at sourcepark.de (Marco Herrn) Date: 16 May 2006 15:46:35 GMT Subject: simultaneous reading and writing a textfile Message-ID: <4469f3d6$0$11070$9b4e6d93@newsread4.arcor-online.net> Hi, I have a text file with some lines in it. Now I want to iterate over this file and exchange some lines with some others. I tried this approach: try: myfile= file('myfile', 'r+') while 1: line= myfile.readline() if not line: break l= line.strip().split() if len(l) == 1: hostname= l[0] myfile.write(hostname+' '+mac+'\n') break finally: if not myfile is None: myfile.close() This should inspect the file and find the first line, that can't be split into two parts (that means, which has only one word in it). This line should be exchanged with a line that contains some more info. Unfortunately (or how better python programmers than I am would say, "of course") this doesn't work. The line is exchanged, but also some more lines. Now how can I achieve, what I want? Really exchange one line with another, regardless of their length. Is this possible? If this is not possible, then what would be the best approach to do this? I do not want to read the whole file, exchange the line in memory and then write the whole file. This would be quite slow with large files. Regard1s Marco From swordsp at gmail.com Fri May 19 07:15:35 2006 From: swordsp at gmail.com (swordsp at gmail.com) Date: 19 May 2006 04:15:35 -0700 Subject: Encode exception for chinese text In-Reply-To: <1148036627.832162.321340@38g2000cwa.googlegroups.com> References: <1148036627.832162.321340@38g2000cwa.googlegroups.com> Message-ID: <1148037335.595690.49030@g10g2000cwb.googlegroups.com> Are you sure all the characters in original text are in "gb2312" charset? Encoding with "utf8" seems work for this character (u'\xa0'), but I don't know if the result is correct. Could you give a subset of str_data in unicode? From eoinrogers at gmail.com Sun May 14 13:05:13 2006 From: eoinrogers at gmail.com (Byte) Date: 14 May 2006 10:05:13 -0700 Subject: Starting/launching eric3 In-Reply-To: <1147624798.827349.286970@y43g2000cwc.googlegroups.com> References: <1147624798.827349.286970@y43g2000cwc.googlegroups.com> Message-ID: <1147626313.331126.90200@y43g2000cwc.googlegroups.com> OK, now I've managed to get it working, but when I run it the eric3 splash screen pops up, and then it says (in terminal): eoin at laptop:~$ eric3 Traceback (most recent call last): File "/usr/lib/site-python/eric3/eric3.py", line 147, in ? main() File "/usr/lib/site-python/eric3/eric3.py", line 132, in main mw = UserInterface(loc, splash) File "/usr/lib/site-python/eric3/UI/UserInterface.py", line 265, in __init__ self.sbv = SBVviewer(dbs, self.sbvDock, 1) File "/usr/lib/site-python/eric3/UI/SBVviewer.py", line 75, in __init__ self.stackComboBox.sizePolicy().hasHeightForWidth())) TypeError: argument 1 of QSizePolicy() has an invalid type Segmentation fault eoin at laptop:~$ Its not ment to do that... how to make it work right?? -- /usr/bin/byte From nobody at 127.0.0.1 Tue May 16 23:04:57 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 17 May 2006 03:04:57 GMT Subject: using target words from arrays in regex, pythons version of perls 'map' References: <44691fc2$0$61162$ae4e5890@news.nationwide.net> <41mi62hih1d3i53nnhdkfi9tpil77bfdp7@4ax.com> <1147760335.159838.146390@v46g2000cwv.googlegroups.com> <1147760591.524083.21330@j55g2000cwa.googlegroups.com> Message-ID: <tpwag.88668$dW3.8151@newssvr21.news.prodigy.com> John Machin wrote: > Would you believe "steps 3 & 4"? How about "two pops and a pass?" Quick! Lower the cone of silence! -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From devlai at gmail.com Fri May 26 01:01:06 2006 From: devlai at gmail.com (Devan L) Date: 25 May 2006 22:01:06 -0700 Subject: Creating instances of untrusted new-style classes In-Reply-To: <mailman.6218.1148619060.27775.python-list@python.org> References: <1148605569.607231.41640@j73g2000cwa.googlegroups.com> <mailman.6218.1148619060.27775.python-list@python.org> Message-ID: <1148619666.153118.5900@38g2000cwa.googlegroups.com> Michael Spencer wrote: > Devan L wrote: > > Is there any safe way to create an instance of an untrusted class > > without consulting the class in any way? With old-style classes, I can > > recreate an instance from another one without worrying about malicious > > code (ignoring, for now, malicious code involving attribute access) as > > shown below. > > [snip my example] > > > > I'm not sure how to do the same for new-style classes, if it's at all > > possible to do from within Python. Is there any way to accomplish this, > > or is there no practical way to do so? > > > > Thanks, > > - Devan > > > >>> class A(object): > ... def __init__(self, *args): > ... self.args = args > ... print "Calling __init__" > ... > >>> a = A("new","style") > Calling __init__ > >>> b = object.__new__(A) > >>> b.__dict__ = a.__dict__.copy() > >>> b.args > ('new', 'style') > >>> type(a) is type(b) > True > >>> > > HTH > > Michael Thanks, now I just have to figure out all the meddling small details I put off before! -Devan From onurb at xiludom.gro Fri May 5 06:54:59 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Fri, 05 May 2006 12:54:59 +0200 Subject: Subclassing array In-Reply-To: <1146824862.073573.82550@v46g2000cwv.googlegroups.com> References: <1146747096.623101.122510@j73g2000cwa.googlegroups.com> <1heszg6.1q17bgp1jwua35N%aleaxit@yahoo.com> <o5r*BDOfr@news.chiark.greenend.org.uk> <445a4845$0$21665$626a54ce@news.free.fr> <1146824862.073573.82550@v46g2000cwv.googlegroups.com> Message-ID: <445b2f61$0$2506$636a55ce@news.free.fr> TG wrote: > That's great, thanks ! > > To put it short, when I create a Stimulus object, it first seek > __new__() method. But if I don't define it, it looks for the one > defined in Vector. This raises a problem because the parameters passed > to Stimulus(params) aren't fitting with Vector parameters, raising an > exception. > > That's why I have to use this *arg **kw syntax in order to allow my > subclasses having any arguments without causing troubles. Am I right ? > To put it short : yes !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From email at christoph-haas.de Wed May 31 14:58:53 2006 From: email at christoph-haas.de (Christoph Haas) Date: Wed, 31 May 2006 20:58:53 +0200 Subject: Save data to a file thru a http connection In-Reply-To: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> References: <1149100667.391141.222280@i40g2000cwc.googlegroups.com> Message-ID: <20060531185853.GA5099@workaround.org> On Wed, May 31, 2006 at 11:37:47AM -0700, yinglcs at gmail.com wrote: > I am new to python. I read an example here about how to fetch data thru > a HTTP connection: > http://diveintopython.org/http_web_services/review.html, > > My question is how can i save the data to a file after reading it from > a http connection. Usually HTTP is read-only. There are extensions like WebDAV though that may do what you need. Google for "python webdav" and see how far you get. Kindly Christoph From bruno at modulix.org Fri May 26 07:10:50 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 26 May 2006 04:10:50 -0700 Subject: Can any body help me In-Reply-To: <1148621554.184942.155430@38g2000cwa.googlegroups.com> References: <1148621554.184942.155430@38g2000cwa.googlegroups.com> Message-ID: <1148641850.446762.156470@g10g2000cwb.googlegroups.com> 1. read this: www.catb.org/~esr/faqs/smart-questions.html 2. do the Python tutorial 3. do your homework 4. when stuck, post your code here HTH From fairwinds at eastlink.ca Sat May 13 10:05:35 2006 From: fairwinds at eastlink.ca (David Pratt) Date: Sat, 13 May 2006 11:05:35 -0300 Subject: Package that imports with name of dependent package Message-ID: <4465E7AF.5030006@eastlink.ca> Hi. I have code that currently depends on a particular package of a framework. I have decided I want to create my own package because I have made many changes and it is getting too difficult to maintain each time I retrieve an updated version of the framework from svn. The problem is, that there are all sorts of imports to the dependent package throughout my code and I just want to replace this module with something that will provide a reference to my own package without changing the original imports. So it just needs to point to the new package so that the original imports in my code will continue to work. For example, here is a package structure. dependentpackage | +---- __init__.py +---- somemodule.py +---- somefolder | +---- __init__.py +---- somesubmodule.py +---- someotherfolder etc .... I simply want the dependentpackage to point to the new package leaving no more than an init file or whatever would have to be minimally required to make this work dependentpackage | +---- __init__.py mypackage | +---- __init__.py +---- somemodule.py +---- somefolder | +---- __init__.py +---- somesubmodule.py +---- someotherfolder etc .... I my code I still need to have this work: from dependentpackage.somemodule import something - but I want the package to be getting the code from the new module. I'd appreciate hearing of what I can do in an __init__ file or what other strategy could make this work. Many thanks. Regards, David From osv at javad.com Thu May 4 08:50:11 2006 From: osv at javad.com (Sergei Organov) Date: Thu, 04 May 2006 16:50:11 +0400 Subject: Because of multithreading semantics, this is not reliable. References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <mailman.5280.1146690817.27775.python-list@python.org> <1146691613.911363.242620@e56g2000cwe.googlegroups.com> <4459c03b$0$2633$636a55ce@news.free.fr> <4459f1dd$1_2@newspeer2.tds.net> Message-ID: <e3cta3$s5a$1@sea.gmane.org> "Olaf Meding" <OlafMeding at noSpam.compuserve.com> writes: >> return result before that line, some other thread added a value ! > > Sure, but that is the nature of using threads and a mutex. I hope you are > you not saying that every function that uses a mutex should have a comment > saying this is not "reliable"? Strictly speaking, mutex has nothing to do about it, -- if there were no mutex there the problem would have been even worse, so this is the nature of accessing shared resources by multiple threads. Somewhat similar example is accessing a file after checking for its existence in a multi-tasking OS: if fileExists(fileName): openFile(fileName) has the same problem, -- at open_file time one can't rely on existence of the file, so the check for existence is useless. -- Sergei. From a.schmolck at gmail.com Sat May 6 08:42:50 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 06 May 2006 13:42:50 +0100 Subject: NaN handling References: <mailman.5272.1146675632.27775.python-list@python.org> <125hplqmppfeq29@corp.supernews.com> <mailman.5397.1146861407.27775.python-list@python.org> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> <mailman.5402.1146867973.27775.python-list@python.org> <125nlbgm8l1fi17@corp.supernews.com> <DE87348C-5BE0-4D55-B041-516FB72E7B04@mcmaster.ca> <mailman.5409.1146880569.27775.python-list@python.org> Message-ID: <yfsy7xfxr1x.fsf@oc.ex.ac.uk> Robert Kern <robert.kern at gmail.com> writes: > Ivan Vinogradov wrote: > > > It doesn't seem to be here under OSX either (universal Python install). > > It's not enabled by default. In the source distribution, it is > Modules/fpectlmodule.c . > > > Since numpy seems to be working on a variety of platforms/hardware, > > how hard would it be to extract this functionality from it to add to > > Python proper? > > Harder than just enabling fpectl. Last thing I heard fpectl was considered to be completely broken -- it's likely not disabled by default for no reason. A short google turned up this: Comment By: Michael Hudson (mwh) Date: 2006-02-20 12:59 Message: Logged In: YES user_id=6656 Waaa, the correct thing to is to remove the --with-fpectl from configure! I've been meaning to post to python-dev for a while now proposing the ripping out of this code. It's just not useful any more. At any rate, I am actively opposed to advertising its existence more widely. And in pep 356 (python 2.5 release schedule) we find: Possible features for 2.5 [...] - Remove the fpectl module? So "just enabling fpectl" doesn't look like a viable long term solution. 'as From fredrik at pythonware.com Fri May 12 07:01:12 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Fri, 12 May 2006 13:01:12 +0200 Subject: Python memory deallocate References: <1147345607.659659.123270@u72g2000cwu.googlegroups.com><-yy*V4mgr@news.chiark.greenend.org.uk><1147355266.189030.131420@y43g2000cwc.googlegroups.com><4463462a$0$297$626a54ce@news.free.fr><1147358549.473182.89950@i40g2000cwc.googlegroups.com> <44636843$0$278$626a54ce@news.free.fr> Message-ID: <e41pvs$h1p$1@sea.gmane.org> bruno at modulix" wrote: > *please* re-read carefully what I and Diez wrote earlier in this thread > before jumping to possibly erroneous conclusion. I didn't say that the > problem *actually* was with Python - just that it *may* have to do with > a memory management issue fixed in 2.5. the only thing that has changed is that Python 2.5 is slightly more likely to release memory areas held by the Python object allocator back to the C runtime memory allocator. if you have a leak in your application, changing to Python 2.5 won't change a thing. </F> From rdh at new.rr.com Mon May 15 09:41:57 2006 From: rdh at new.rr.com (DataSmash) Date: 15 May 2006 06:41:57 -0700 Subject: unzip zip files References: <1147470349.415553.324710@y43g2000cwc.googlegroups.com> <mailman.5649.1147474044.27775.python-list@python.org> Message-ID: <1147700516.933358.11540@i39g2000cwa.googlegroups.com> Thanks! I ended up using the "-d" parameter. I did try the zipfile module but I couldn't figure it out, nor could I find any examples using it. I also didn't have any luck changing the working dircectory and making it work. import subprocess, os # Get all the zip files in the current directory. for zip in os.listdir(''): if zip.endswith(".zip"): # Remove the first 3 and the last 4 characters # e.g. usa12345.zip becomes 12345 zipBase = zip[3:-4] # Make directory for unzipping os.mkdir(zipBase) # Make system call "unzip" print "\n unzip -d", zipBase, zip subprocess.Popen(["unzip", "-d", zipBase, zip]).wait() From lunz at falooley.org Thu May 25 23:26:31 2006 From: lunz at falooley.org (Jason Lunz) Date: Fri, 26 May 2006 03:26:31 +0000 (UTC) Subject: monkeypatching NamedTemporaryFile Message-ID: <e55sh7$n76$1@sea.gmane.org> Is there a better way to do this? def QuietNamedTemporaryFile(**kwargs): ''' Return a NamedTemporaryFile that doesn't complain when its file has already been unlinked at __del__ time. ''' tf = tempfile.NamedTemporaryFile(**kwargs) def quiet_del(): try: tf.close() except OSError: pass tf.__del__ = quiet_del return tf Jason From mensanator at aol.com Wed May 24 21:37:31 2006 From: mensanator at aol.com (mensanator at aol.com) Date: 24 May 2006 18:37:31 -0700 Subject: Compiling Python from Sources In-Reply-To: <1148518265.135570.39890@i39g2000cwa.googlegroups.com> References: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> <1148509057.542733.217230@i39g2000cwa.googlegroups.com> <1148509487.448417.294690@j33g2000cwa.googlegroups.com> <1148512998.732842.258430@j33g2000cwa.googlegroups.com> <1148518265.135570.39890@i39g2000cwa.googlegroups.com> Message-ID: <1148521050.907555.312320@j55g2000cwa.googlegroups.com> rwr wrote: > Due to my ignorance exactly what do you mean by "In my case, I had to > run configure over and over againeach time going through the log > finding a new missing file, re-install, > and repeat until the errors stopped." My In my case, my error log said it couldn't find the file "make". So I re-installed Cygwin and chose the custom rather than default install. I had to go through dozens of install options before finding the make file (it isn't with the compilers). The configure then got a little further and stopped, complaining that it couldn't find "m4". So I had to re-install Cygwin again, this time looking for make and m4. This process was repeated until the configure ran to completion. > > Why I ask is that I utilized "apt-get install gcc" to install gcc. Are > there additional options that are found by appending "--help"? I don't know, I don't actually use linux. It may be that what you installed was a default set of options. If so, I have no clue how you get it to do what you want, I'm suggesting that as a possible place to look. > > Curiously, > rwr > > Ps. Thank you for your help and for your time. :))) From johnjsal at NOSPAMgmail.com Mon May 8 13:17:51 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 17:17:51 GMT Subject: which is better, string concatentation or substitution? In-Reply-To: <e3nqo9$45o$1@reader1.panix.com> References: <445ec45e$0$1965$c3e8da3@news.astraweb.com> <IWH7g.2053$No6.45672@news.tufts.edu> <e3nnv0$jbm$1@reader1.panix.com> <aMJ7g.2058$No6.45704@news.tufts.edu> <e3nqo9$45o$1@reader1.panix.com> Message-ID: <33L7g.2059$No6.44800@news.tufts.edu> Roy Smith wrote: > In article <aMJ7g.2058$No6.45704 at news.tufts.edu>, > John Salerno <johnjsal at NOSPAMgmail.com> wrote: >> Roy Smith wrote: >> >>> OK, here's a quick tutorial to "big-oh" notation. >> Wow, that was fantastic (and interesting)! Did you just write that? That >> should be saved somewhere! Mind if I post it on my website? (don't >> worry, no one goes there anyway) :) > > Sure, feel free. Once you post something on usenet, anybody can > pretty much do anything they want with it. I do prefer if people > don't use what I write to line birdcages with, but have no control > over that either :-) > > Thanks! And don't worry about that last part, no birds here. :) From rajeeshrnair at gmail.com Wed May 3 01:27:11 2006 From: rajeeshrnair at gmail.com (raj) Date: 2 May 2006 22:27:11 -0700 Subject: what is the 'host' for SMTP? In-Reply-To: <pan.2006.05.03.03.42.28.745634@hastings.org> References: <44581205$0$25583$c3e8da3@news.astraweb.com> <pan.2006.05.03.03.42.28.745634@hastings.org> Message-ID: <1146634031.779762.297950@e56g2000cwe.googlegroups.com> If you've a gmail account, you can set it as smtp.gmail.com. From luis_lupe2XXX at netvisaoXXX.pt Tue May 9 14:27:10 2006 From: luis_lupe2XXX at netvisaoXXX.pt (Luis P. Mendes) Date: Tue, 09 May 2006 19:27:10 +0100 Subject: ascii to latin1 In-Reply-To: <1147180014.685659.325830@i39g2000cwa.googlegroups.com> References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> <mailman.5504.1147171291.27775.python-list@python.org> <4460831e$0$15794$14726298@news.sunsite.dk> <1147180014.685659.325830@i39g2000cwa.googlegroups.com> Message-ID: <4460dec2$0$15791$14726298@news.sunsite.dk> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 >> When I used the "NFD" option, I came across many errors on these and >> possibly other codes: \xba, \xc9, \xcd. > > What errors? normalize method is not supposed to give any errors. You > mean it doesn't work as expected? Well, I have to admit that using > normalize is a far from perfect way to implement search. The most > advanced algorithm is published by Unicode guys: > <http://www.unicode.org/reports/tr10/> If you read it you'll understand > it's not so easy. > >> I tried to use "NFKD" instead, and the number of errors was only about >> half a dozen, for a universe of 600000+ names, on code \xbf. >> It looks like I have to do a search and substitute using regular >> expressions for these cases. Or is there a better way to do it? > > Perhaps you can use unicode translate method to map the characters that > still give you problems to whatever you want. > Errors occur when I assign the result of ''.join(cp for cp in de_str if not unicodedata.category(cp).startswith('M')) to a variable. The same happens with de_str. When I print the strings everything is ok. Here's a short example of data: 115448,DA??O 117788,DA 1? DE MO N? 2 I used the following script to convert the data: # -*- coding: iso8859-15 -*- class Latin1ToAscii: def abreFicheiro(self): import csv self.reader = csv.reader(open(self.input_file, "rb")) def converter(self): import unicodedata self.lista_csv = [] for row in self.reader: s = unicode(row[1],"latin-1") de_str = unicodedata.normalize("NFD", s) nome = ''.join(cp for cp in de_str if not \ unicodedata.category(cp).startswith('M')) linha_ascii = row[0] + "," + nome # * print linha_ascii.encode("ascii") self.lista_csv.append(linha_ascii) def __init__(self): self.input_file = 'nome_latin1.csv' self.output_file = 'nome_ascii.csv' if __name__ == "__main__": f = Latin1ToAscii() f.abreFicheiro() f.converter() And I got the following result: $ python latin1_to_ascii.py 115448,DACAO Traceback (most recent call last): File "latin1_to_ascii.py", line 44, in ? f.converter() File "latin1_to_ascii.py", line 22, in converter print linha_ascii.encode("ascii") UnicodeEncodeError: 'ascii' codec can't encode character u'\xba' in position 11: ordinal not in range(128) The script converted the ?? from the first line, but not the ? from the second one. Still in *, I also don't get a list as [115448,DA??O] but a [u'115448,DA??O'] element, which doesn't suit my needs. Would you mind telling me what should I change? Luis P. Mendes -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (GNU/Linux) Comment: Using GnuPG with Mozilla - http://enigmail.mozdev.org iD8DBQFEYN7+Hn4UHCY8rB8RAjcTAKCgEkZwCURgp/VrtthM1MBba+d7KACfY9dj xcHVL1BuhyrPV8+9Z5Q2AJQ= =+AO0 -----END PGP SIGNATURE----- From larry.bates at websafe.com Mon May 8 09:46:00 2006 From: larry.bates at websafe.com (Larry Bates) Date: Mon, 08 May 2006 08:46:00 -0500 Subject: A better way to split up a list In-Reply-To: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> References: <1147092311.376020.55740@i39g2000cwa.googlegroups.com> Message-ID: <445F4B98.6010809@websafe.com> fidtz at clara.co.uk wrote: > The code below works fine, but it is less than nice to look at and > somewhat long winded. Is there a better way to do the docstring task? > This is the first working version, and can proabably be "compacted" a > bit (list comprehensions etc) but I am looking for a better basic > approach. Any help much appreciated :) > > from itertools import islice > def chopupmoves(movelist): > '''creates a list of 3 lists from one list, that should all have > (length of movelist)/3 length, with any remainder getting added to the > third list''' > outputlist = [[],[],[]] > > parlen = int(len(movelist)/3) > if parlen < 3: > parlen = 3 > > stoplist=[0];exit = 0 > while exit < len(movelist): > stoplist.append(exit+parlen) > exit = exit + parlen > while len(stoplist) > 4: > stoplist.pop(len(stoplist)-1) > stoplist[-1]=len(movelist) > > for x in range(len(stoplist)-1): > for i in islice(movelist,stoplist[x],stoplist[x+1],1): > outputlist[x].append(i) > return outputlist > movelist = [1,2,3,4,5,6,7,8,9,10,11] > print chopupmoves(movelist) > Try something like this: def chopupmoves(movelist): return [movelist[0:3], movelist[3:6], movelist[6:]] -Larry Bates From timr at probo.com Wed May 24 01:07:54 2006 From: timr at probo.com (Tim Roberts) Date: Wed, 24 May 2006 05:07:54 GMT Subject: newbie: windows xp scripting References: <1148228264.505752.83960@y43g2000cwc.googlegroups.com> <mailman.6032.1148231638.27775.python-list@python.org> <1148239856.998371.160700@u72g2000cwu.googlegroups.com> Message-ID: <pcq7725oei18c77hqgdo3rchctpou54vcr@4ax.com> "oscartheduck" <oscartheduck at gmail.com> wrote: > >It wasn't, but after seeing your success I discovered what was wrong. >My destination directory didn't exist, and for some reason windows >wasn't automatically creating it to dump the files in. Right. The "copy" command never creates directories. It will copy each individual file, in turn, to a file with whatever the last name in the list is. Not terribly useful, but it is a behavior inherited from DOS 1. On the other hand, the "xcopy" command will do it: xcopy /i C:\DIR1 C:\DIR2 That will create DIR2 if it does not already exist. >I could fix this with a nested if statement, but it "feels" like >windows should be creating this folder automatically if it doesn't >exist. What "feels" right is rarely a good reference for a command's behavior, especially on Windows. -- - Tim Roberts, timr at probo.com Providenza & Boekelheide, Inc. From bignose+hates-spam at benfinney.id.au Wed May 3 17:52:01 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 04 May 2006 07:52:01 +1000 Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <mailman.5175.1146483911.27775.python-list@python.org> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <xkv5g.529$fb2.114@newssvr27.news.prodigy.net> <44574481$0$18265$636a55ce@news.free.fr> <qGM5g.692$fb2.267@newssvr27.news.prodigy.net> <4457a78b$0$5171$626a54ce@news.free.fr> <qNO5g.11052$Lm5.5116@newssvr12.news.prodigy.com> <4457d83f$0$21106$626a54ce@news.free.fr> <TFR5g.66612$F_3.16905@newssvr29.news.prodigy.net> <mailman.5241.1146613795.27775.python-list@python.org> <44580270$0$4903$626a54ce@news.free.fr> Message-ID: <87fyjqdbem.fsf@benfinney.id.au> Bruno Desthuilliers <bdesth.quelquechose at free.quelquepart.fr> writes: > Ben Finney a ?crit : > > So now you're proposing that this be a special case when a > > function is declared by that particular syntax, and it should be > > different to when a function is created outside the class > > definition and added as a method to the object at run-time. > > > > Thus breaking not only "explicit is better than implicit", > > This one can be subject to discussion. All the assertions in 'import this' are subject to discussion. They're even contradictory. > > but also "special cases aren't special enough to break the rules". > > Yeps, I think this is what I don't like here. > > > Still -1. > > I'm not yet ready to vote for Edward's proposition - as you say, it > makes 'def statements into a class statement' a special case, and I > don't like special cases too much (OTOH, there actually *are* > special cases - __new__() being an example) - *but* it's not that > silly either IMHO, and I think this should not be dismissed on a > purely reactional basis. My basis for rejecting the proposal is that it claims to offer net simplicity, yet it breaks at least two of the admonishments that simplify Python. -- \ "My house is made out of balsa wood, so when I want to scare | `\ the neighborhood kids I lift it over my head and tell them to | _o__) get out of my yard or I'll throw it at them." -- Steven Wright | Ben Finney From exarkun at divmod.com Tue May 2 16:07:50 2006 From: exarkun at divmod.com (Jean-Paul Calderone) Date: Tue, 2 May 2006 16:07:50 -0400 Subject: Polling from keyboard In-Reply-To: <1146593098.744039.89340@u72g2000cwu.googlegroups.com> Message-ID: <20060502200750.22481.453527502.divmod.quotient.20698@ohm> On 2 May 2006 11:04:58 -0700, "sturnfie at gmail.com" <sturnfie at gmail.com> wrote: >I am trying to find a way to poll the keyboard. In my searching, I >have found that Windows users are given the msvcrt module. Is there an >equivilant for Unix systems? > >I am writing a p2p chat application, and would like to ideally approach >user input in a manner similar to the way I am using poll() to moniter >the sockets for events Twisted supports stdin just like any other transport. I have some screenshots of simple terminal-based apps I've developed with Twisted in my blog: http://jcalderone.livejournal.com/10572.html http://jcalderone.livejournal.com/10988.html You can find examples of using these APIs in Twisted Conch's examples: http://twistedmatrix.com/projects/conch/documentation/examples/ Jean-Paul From rune.strand at gmail.com Tue May 9 16:32:01 2006 From: rune.strand at gmail.com (Rune Strand) Date: 9 May 2006 13:32:01 -0700 Subject: Is Welfare Part of Capitalism? In-Reply-To: <1147200065.889769.76050@v46g2000cwv.googlegroups.com> References: <1147200065.889769.76050@v46g2000cwv.googlegroups.com> Message-ID: <1147206721.815900.309500@v46g2000cwv.googlegroups.com> Welfare is not a built-in, but in some distributions it's available as a module. Just type import Welfare. However, be aware of the Welfare.division() queerness. It won't be fixed until the Python 3000 is a fact. There is also some issues with the garbage collection. Under certain circumstances the dreaded Dutch disease may occur. From Bulkan at gmail.com Thu May 11 19:45:17 2006 From: Bulkan at gmail.com (placid) Date: 11 May 2006 16:45:17 -0700 Subject: Threads Message-ID: <1147391117.248113.297980@q12g2000cwa.googlegroups.com> Hi all, In Python, Threads cannot be paused, i remember reading this somewhere, so is there a way around this ? TIA From john at castleamber.com Sat May 20 18:44:32 2006 From: john at castleamber.com (John Bokma) Date: 20 May 2006 22:44:32 GMT Subject: python vs perl lines of code References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <e4fmkb$fn2$1@mlucom4.urz.uni-halle.de> <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <Xns97C7D8A0ABE54castleamber@130.133.1.4> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> <Xns97C9ADA375FCCcastleamber@130.133.1.4> <lFMbg.19879$Lm5.7431@newssvr12.news.prodigy.com> Message-ID: <Xns97C9B47CB9A1Bcastleamber@130.133.1.4> Edward Elliott <nobody at 127.0.0.1> wrote: > You lecturing people on pissing contests, that's rich. Nice way to > duck the issue and sound like a winner. Then you've missed what a discussion really is. It's not about winning, it's about learning. Sadly you missed that point. > Wake me when you decide to address the substance of my arguments. I have done so. If you don't consider it enough and think that code in a book based on 8+ year old modules is the current state of Perl programming, fine with me. As a final word, I quote from chapter 12.10 of Learning Perl Objects, References, & Modules [1]: "As seen earlier, *the normal means* of using an object-oriented module is to call class methods and then methods against instances resulting from constructors of that class. This means that an OO module *typically exports nothing*, ..." Which is in general recommended as the book one has to read after Learning Perl (IIRC it will be renamed in a next edition to reflect this). -- 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 merlyn at stonehenge.com Tue May 9 10:43:52 2006 From: merlyn at stonehenge.com (Randal L. Schwartz) Date: 09 May 2006 07:43:52 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1147106666.402541.114270@g10g2000cwb.googlegroups.com> <1hf1iq2.o3lae1fgte55N%aleax@mac.com> Message-ID: <86fyjjl0lz.fsf@blue.stonehenge.com> >>>>> "Alex" == Alex Martelli <aleax at mac.com> writes: Alex> The difference, if any, is that gurus of Java, C++ and Python get to Alex> practice and/or keep developing their respectively favorite languages Alex> (since those three are the "blessed" general purpose languages for Alex> Google - I say "general purpose" to avoid listing javascript for Alex> within-browser interactivity, SQL for databases, XML for data Alex> interchange, HTML for web output, &c, &c), while the gurus of Lisp, Alex> Limbo, Dylan and Smalltalk don't (Rob Pike, for example, is one of the Alex> architects of sawzall -- I already pointed to the whitepaper on that Alex> special-purpose language, and he co-authored that paper, too). That's crazy. Some of the key developers of Smalltalk continue to work on the Squeak project (Alan Kay, Dan Ingalls, and I'm leaving someone out, I know it...). So please remove Smalltalk from that list. -- Randal L. Schwartz - Stonehenge Consulting Services, Inc. - +1 503 777 0095 <merlyn at stonehenge.com> <URL:http://www.stonehenge.com/merlyn/> Perl/Unix/security consulting, Technical writing, Comedy, etc. etc. See PerlTraining.Stonehenge.com for onsite and open-enrollment Perl training! *** Posted via a free Usenet account from http://www.teranews.com *** From nobody at 127.0.0.1 Mon May 29 15:21:36 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 29 May 2006 19:21:36 GMT Subject: HTMLParser chokes on bad end tag in comment References: <8m3k72h9ghgarn1cfd970faos14cl6tfft@4ax.com> <mailman.6303.1148884549.27775.python-list@python.org> Message-ID: <4RHeg.103064$F_3.6208@newssvr29.news.prodigy.net> Fredrik Lundh wrote: >> Should it? The end tag it chokes on is in comment, isn't it? > > no. STYLE and SCRIPT elements contain character data, not parsed > character data, so comments are treated as characters, and the first > "</" ends the element. Rather than take your word for it, I checked the W3C HTML4 DTD and found this: http://www.w3.org/TR/html4/appendix/notes.html#notes-specifying-data Element content When script or style data is the content of an element (SCRIPT and STYLE), the data begins immediately after the element start tag and ends at the first ETAGO ("</") delimiter followed by a name start character ([a-zA-Z]); note that this may not be the element's end tag. Authors should therefore escape "</" within the content. Escape mechanisms are specific to each scripting or style sheet language. ILLEGAL EXAMPLE: The following script data incorrectly contains a "</" sequence (as part of "</EM>") before the SCRIPT end tag: <SCRIPT type="text/javascript"> document.write ("<EM>This won't work</EM>") </SCRIPT> In JavaScript, this code can be expressed legally by hiding the ETAGO delimiter before an SGML name start character: <SCRIPT type="text/javascript"> document.write ("<EM>This will work<\/EM>") </SCRIPT> Guess you learn something new every day. Too bad there's so much illegal code in the wild. :( -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From cvanarsdall at mvista.com Wed May 10 17:57:20 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 10 May 2006 14:57:20 -0700 Subject: design a Condition class In-Reply-To: <1147297217.372888.167960@v46g2000cwv.googlegroups.com> References: <1147297217.372888.167960@v46g2000cwv.googlegroups.com> Message-ID: <446261C0.5030003@mvista.com> joh12005 at yahoo.fr wrote: > Hello, > > i posted for suggestions a little idea even if it still needs further > thoughts but as i'm sure you could help :) > > if would like to implement some kind of Condition class which i coud > use to build bricks of more complex condition, conditions are based on > fields by using regexp > > I just wanted to make the comment that there already exists a Condition() class in the threading module. If you plan on using your class with the threading module you might wish to use another name. -carl -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From claird at lairds.us Tue May 9 07:59:11 2006 From: claird at lairds.us (Cameron Laird) Date: Tue, 9 May 2006 11:59:11 +0000 Subject: Python's DSLs References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <3mh4j3-9pm.ln1@lairds.us> <1hf1iaz.1qdpj4h1mj5f71N%aleax@mac.com> Message-ID: <fpc6j3-sne.ln1@lairds.us> In article <1hf1iaz.1qdpj4h1mj5f71N%aleax at mac.com>, Alex Martelli <aleax at mac.com> wrote: >Cameron Laird <claird at lairds.us> wrote: > ... >> On this one isolated matter, though, I'm confused, Alex: I sure >> think *I* have been writing DSLs as specializations of Python, >> and NOT as "a language in its own right". Have I been fooling >> myself, or are you making the point that Lisp-based DSLs live in >> a larger syntactic universe than Python's, or ...? > >With Lisp (or Scheme, for that matter), a DSL "lives" in exactly the >same world as the base language, while being able to add or tweak >whatever syntax it needs; with Python (or C++ or Java, for that matter), >a DSL is either a completely separate beast (parsed, compiled, perhaps >interpreted in the "host" language), or else it uses exactly the same >syntax as used in the host language. To rapidly build, experiment with, >and tweak, DSL's, a language with macros is thus advantaged. > >As to how crucial that is for _production_ (as opposed to _research_) >purposes, well, obviously I prefer having no macros (or else I'd use >some form of Lisp, or perhaps Dylan -- at least for my own private >purposes, such as my long-standing personal research into the >fundamentals of contract bridge -- while in fact I prefer to use Python >for those purposes just as for others). But that doesn't make me blind >to the advantages of macros for DSL-building purposes (if I was totally >sold on both Python AND macros, I think I might build a macro >preprocessor on top of Python -- the current ASL-based compiler probably >makes that task much more feasible than it used to be -- but, macros >would be somewhat complicated as in Dylan, not extremely easy as in >Scheme [[or, I guess, Common Lisp, though I have no real experience with >those -- on the surface they look murkier than Scheme's, but that may be >just an issue of habit on my part]]). > > >Alex Ah! I understand much better now. You correctly distinguish, say, Lisp, Dylan, ... from Python, C, Java, ... for their syntactic aptness at construction of DSLs. I don't want that to mislead readers, though, who might thus fail to see how Python *is* different from C, Java, ..., in its convenience for implementation of a particular kind of Python- looking DSL. As you know, it's easy (if heavy with security consequences) in Python to eval(), and it's not in C or Java. The Python run-time builds in a complete interpreter, and that's different from the base functionality of C or Java. A consequence is that, in Python, it's an exercise for a beginner to write, say an assembler whose syntax is a sequence of function calls (<URL: http://www.unixreview.com/documents/s=9133/ur0404e/ >). C or Java can't really boast the same. From gherron at islandtraining.com Tue May 30 18:30:38 2006 From: gherron at islandtraining.com (Gary Herron) Date: Tue, 30 May 2006 15:30:38 -0700 Subject: Strange behavior with iterables - is this a bug? In-Reply-To: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> References: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> Message-ID: <447CC78E.4060104@islandtraining.com> akameswaran at gmail.com wrote: >Ok, I am confused about this one. I'm not sure if it's a bug or a >feature.. but > > List comprehension is a great shortcut, but when the shortcut starts causing trouble, better to go with the old ways. You need to reopen each file each time you want to iterate through it. You should be able to understand the difference between these two bits of code. The first bit opens each file but uses (two of them) multiple times. Reading from a file at EOF returns an empty sequence. The second bit opened the file each time you want to reuse it. That works correctly. And that suggest the third bit of correctly working code which uses list comprehension. # Fails because files are opened once but reused f1 = open('word1.txt') f2 = open('word2.txt') f3 = open('word3.txt') for i1 in f1: for i2 in f2: for i3 in f3: print (i1.strip(),i2.strip(),i3.strip()) and # Works because files are reopened for each reuse: f1 = open('word1.txt') for i1 in f1: f2 = open('word2.txt') for i2 in f2: f3 = open('word3.txt') for i3 in f3: print (i1.strip(),i2.strip(),i3.strip()) and # Also works because files are reopened for each use: print [(i1.strip(),i2.strip(),i3.strip()) for i1 in open('word1.txt') for i2 in open('word2.txt') for i3 in open('word3.txt')] Hope that's clear! Gary Herron > > >>>>================================ RESTART >>>>f1 = open('word1.txt') >>>>f2 = open('word2.txt') >>>>f3 = open('word3.txt') >>>>print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in f1 for i2 in f2 for i3 in f3] >>>> >>>> >[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')] > > >>>>l1 = ['a\n','b\n','c\n'] >>>>l2 = ['a\n','b\n','c\n'] >>>> >>>>l3 = ['a\n','b\n','c\n'] >>>>print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for i3 in l3] >>>> >>>> >[('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), >('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), >('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), >('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), >('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), >('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), >('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')] > >explanation of code: the files word1.txt, word2.txt and word3.txt are >all identical conataining the letters a,b and c one letter per line. >The lists I've added the "\n" so that the lists are identical to what >is returned by the file objects. Just eliminating any possible >differences. > > >If you notice, when using the file objects I don't get the proper set >of permutations. I was playing around with doing this via recursion, >etc. But nothing was working so I made a simplest case nesting. Still >no go. >Why does this not work with the file objects? Or any other class I''ve >made which implements __iter__ and next? > >Seems like a bug to me, but maybe I am missing something. Seems to >happen in 2.3 and 2.4. > > > From kevin.bell at slcgov.com Fri May 26 10:09:07 2006 From: kevin.bell at slcgov.com (Bell, Kevin) Date: Fri, 26 May 2006 08:09:07 -0600 Subject: hide python window Message-ID: <2387F0EED10A4545A840B231BBAAC7226083B5@slcimail1.slcgov.com> When I run a script, how can I make it run in the background? I don't want to see the command window because it runs all day. I'm on windows... From percivall at gmail.com Tue May 9 17:06:53 2006 From: percivall at gmail.com (Simon Percivall) Date: 9 May 2006 14:06:53 -0700 Subject: elementtidy, \0 chars and parsing from a string In-Reply-To: <mNednUAIsJJHnfzZnZ2dnUVZ_tednZ2d@comcast.com> References: <mNednUAIsJJHnfzZnZ2dnUVZ_tednZ2d@comcast.com> Message-ID: <1147208813.267144.10080@i40g2000cwc.googlegroups.com> Well, it seems you can do: parser = elementtidy.TidyHTMLTreeBuilder.TidyHTMLTreeBuilder() parser.feed(your_str) tree = elementtree.ElementTree.ElementTree(element=parser.close()) Look at the parse() method in the ElementTree class. From "reverse[nepank.noot]" at fft.be Wed May 17 08:39:14 2006 From: "reverse[nepank.noot]" at fft.be (Toon Knapen) Date: Wed, 17 May 2006 14:39:14 +0200 Subject: CFLAGS are not taken into account properly In-Reply-To: <mailman.5798.1147865676.27775.python-list@python.org> References: <446ad377$0$438$6c56d894@reader0.news.be.easynet.net> <mailman.5798.1147865676.27775.python-list@python.org> Message-ID: <446B1972.4090107@fft.be> skip at pobox.com wrote: > I agree, the Python configure/Makefile combination doesn't conform very well > to current GNU style in this regard. Try setting EXTRA_CFLAGS instead of > CFLAGS. Thanks. But some other (but 'similar') functionality is broken. Now I succeeded in compiling python. But when using distutils (e.g. when installing numarray using the setup.py), python will compile the files using the '-xarch=v9' option but drops this option when linking dynamic libraries (although I defined LDFLAGS="-xarch=v9" before configuring python). Additionally python adds the option '-xcode=pic32' to the compile-command which will compile my numarray in 32bit instead of 64bit (while python itself is in 64bit) toon From lrasinen at iki.fi Tue May 16 13:12:10 2006 From: lrasinen at iki.fi (Lasse Rasinen) Date: 16 May 2006 20:12:10 +0300 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1hexdta.11ycihi11fhpp4N%aleaxit@yahoo.com> <ePb7g.334$pv7.229@fe08.lga> <1hexkds.1azsk81w2s9fjN%aleaxit@yahoo.com> <cee7g.543$RO4.202@fe12.lga> <d6l3bfc8nmr.fsf@vipunen.hut.fi> <i6T9g.228$qU1.90@fe08.lga> <d6lu07r7u0u.fsf@vipunen.hut.fi> <44681F95.9040400@gmail.com> <d6lpsif6sku.fsf@vipunen.hut.fi> <O15ag.337$RM1.120@fe12.lga> Message-ID: <d6l3bf97v2t.fsf@vipunen.hut.fi> Ken Tilton <kentilton at gmail.com> writes: > If you want to insist on how perfect your code is, please go find > ltktest-cells-inside.lisp in the source you downloaded and read the long > comment detailing the requirements I have identified for "data integrity". > Then (a) tell me how your code fails at integrity, (b) fix it, and (c) > tell me again how easy Cells is. :) Found it and read it; it was most enlightening. I claim my system fulfills the first three requirements(*), while most likely failing gloriously on the two last ones. I'll postpone (b) while I've had a chance to think it over(**), but in the face of the evidence I'm willing to admit my earlier work estimates (which should have had a smiley next to them anyway ;-) were in error. I won't admit to destroying Moscow, though. See (*). (*) All values depending on the changed cell are marked as invalid before anything else is done; trying to access an invalid value forces a recalculation which also marks the cell as valid again, and so on recursively down to cells that have already converged to a proper value. Setting input cells in callbacks will f*** that up, though. (**) Which probably doesn't occur until July or something ;( > > [Decorator example] > > Wow. I thought Python did not have macros. Calling decorators macros is an insult to CL macros ;-) All they do is make it a bit more convinent to apply transformations to functions, or as the abstract in the original spec[1] says: The current method for transforming functions and methods (for instance, declaring them as a class or static method) is awkward and can lead to code that is difficult to understand. Ideally, these transformations should be made at the same point in the code where the declaration itself is made. > This project is looking better all the time. Thx. In that case I have something else you might like: The "with" Statement[2] >From the abstract: This PEP adds a new statement "with" to the Python language to make it possible to factor out standard uses of try/finally statements. In practice one can use it implement some of the with-macros in a pretty straightforward manner, especially those that are expanded into (call-with-* (lambda () , at body)). I believe the previously advertised with-integrity macro could also be made to work in a satisfying manner. To quote from the examples: 2. A template for opening a file that ensures the file is closed when the block is left: @contextmanager def opened(filename, mode="r"): f = open(filename, mode) try: yield f finally: f.close() Used as follows: with opened("/etc/passwd") as f: for line in f: print line.rstrip() Does that last part look familiar to you?) The problem with this is that this is Python 2.5 syntax, which currently appears to be planned for release in late August, a bit late for SoC. Alpha(*) versions are available, so if you want to take a chance and live on the bleeding edge, you can probably gain from it. (*) I don't keep a very close eye on the alpha releases, which is why I didn't remember this yesterday. I like my programming tools steady and stable ;-) [1] http://www.python.org/dev/peps/pep-0318/#abstract [2] http://www.python.org/dev/peps/pep-0343/ -- Lasse Rasinen lrasinen at iki.fi From onurb at xiludom.gro Wed May 24 13:48:52 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 24 May 2006 19:48:52 +0200 Subject: Python keywords vs. English grammar In-Reply-To: <1148491495.794376.26920@38g2000cwa.googlegroups.com> References: <roy-CEC3E3.08573224052006@reader1.panix.com> <uC_cg.2166$No6.46848@news.tufts.edu> <1148491495.794376.26920@38g2000cwa.googlegroups.com> Message-ID: <44749cf1$0$11014$626a54ce@news.free.fr> defcon8 wrote: > 1. Does it matter? > 2. Is it affecting your productivity. > 3. Are you not trying to programme? > 4. It is open source, change it and stop whining. > What about trying emacs <alt>+x doctor <return> ? -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From martin at v.loewis.de Tue May 2 18:19:21 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Wed, 03 May 2006 00:19:21 +0200 Subject: xml-rpc and 64-bit ints? In-Reply-To: <fkM5g.71859$H71.21437@newssvr13.news.prodigy.com> References: <fkM5g.71859$H71.21437@newssvr13.news.prodigy.com> Message-ID: <4457DAE9.80504@v.loewis.de> Mark Harrison wrote: > I've got an API that deals with 64 bit int values. Is there > any way of handling this smoothly? Right now I'm casting > the values into and out of strings for the API. In XML-RPC, everything is transmitted as a string, so I don't think that choice is really that bad - except of course for the additional clumsiness for invoking explicit conversion functions. But no, XML-RPC doesn't have a data type that can represent integers above 2**32. If you can accept losing precision, you can use doubles (but you still would have to convert explicitly on the sender). > If not, are there any nice alternatives to XML-RPC that > support this? CORBA certainly supports 64-bit integers. Regards, Martin From cvanarsdall at mvista.com Wed May 17 12:59:33 2006 From: cvanarsdall at mvista.com (Carl J. Van Arsdall) Date: Wed, 17 May 2006 09:59:33 -0700 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: <slrne6mkt5.hoa.sybrenUSE@schuimige.stuvel.eu> References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <slrne6mkt5.hoa.sybrenUSE@schuimige.stuvel.eu> Message-ID: <446B5675.8040004@mvista.com> Sybren Stuvel wrote: > Andy Sy enlightened us with: > >> Like I said, you'll *NEVER* get that fancy shmancy 'semantic >> indentation' idea to work properly in the most basic utilities which >> have the 8-space tabs assumption hardcoded in them. >> > > Fair enough. How much code is viewed with less and cat, and how much > is viewed using smart viewers/editors? I think the majority is viewed > using the latter. > Really though, he's got a good point. I'm typically viewing code in vi. I don't know why so many people have so many issues with tabs, they really aren't that difficult to work with and I think make life a little easier when working on code with multiple people. You can setup your environment to make tabs look like you want your code to look, your team members can do tabs their way, and in the end the indentation levels all work out fine. People want to fight tooth and nail over this debate. But its really not worth it. Get an editor that doesn't completely suck and you won't have problems. .c -- Carl J. Van Arsdall cvanarsdall at mvista.com Build and Release MontaVista Software From sybrenUSE at YOURthirdtower.com.imagination Wed May 10 05:01:42 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Wed, 10 May 2006 11:01:42 +0200 Subject: Multi-line lambda proposal. References: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> <1147194852.528046.91560@y43g2000cwc.googlegroups.com> Message-ID: <slrne63avm.96g.sybrenUSE@schuimige.stuvel.eu> Kaz Kylheku enlightened us with: > In the case of if/elif/else, they have to be placed behind the > closest suite that follows the expression in the syntax of the > statement: > > if lambda(x)(4) < 0: > print "a" > lambda: > return x + 1 > elif y = 4: > print "b" > else: > print "foo" > > The overall rule is simple and uniform: each suite can have lambda: > clauses. These have to match lambda() occurences in the expression > (or expression list) immediately to the left in the same grammar > production. IMHO I think it's ugly and unreadable. If you use it in such a way, a much more elegant way would be to use an inner function: def increment(x): return x + 1 if increment(4) < 0: print "a" elif y = 4: print "b" else: print "foo" This also solves the readability issue when there are multiple multi-line lambdas involved. Just write a couple of inner functions neatly under each other, and call them by name. From my point of view, that's much more readable, and if there is any error, it'll be much easier to find due to proper tracebacks. > On the other hand, some people might find this compromise more > attractive: simply do not allow multi-line lambdas in compound > statements. I'm one of those people. I don't like multi-line lambdas at all, actually. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From jjl at pobox.com Wed May 3 17:51:33 2006 From: jjl at pobox.com (John J. Lee) Date: 03 May 2006 21:51:33 +0000 Subject: Python & SSL References: <e38c66$r2t$1@zinnia.noc.ucla.edu> <4457B74A.2000208@benjiyork.com> Message-ID: <874q064w0q.fsf@pobox.com> Benji York <benji at benjiyork.com> writes: > James Stroud wrote: > > I have been trying to make an https client with python > > You probably don't want to use the standard library for HTTPS; here's a > quote from the socket module docs about SSL: > > Warning: This does not do any certificate verification! [...] Of course, remembering that the first thing to ask in response to "is it secure?" is "against what?", for lots of purposes it just doesn't matter that it ignores certificates. John From Bulkan at gmail.com Sun May 7 19:28:17 2006 From: Bulkan at gmail.com (placid) Date: 7 May 2006 16:28:17 -0700 Subject: Can I use python for this .. ?? In-Reply-To: <mailman.5355.1146812024.27775.python-list@python.org> References: <1146771955.144672.147720@i39g2000cwa.googlegroups.com> <1146807680.232551.97460@y43g2000cwc.googlegroups.com> <mailman.5355.1146812024.27775.python-list@python.org> Message-ID: <1147044497.770831.130120@e56g2000cwe.googlegroups.com> Terry Reedy wrote: > "placid" <Bulkan at gmail.com> wrote in message > news:1146807680.232551.97460 at y43g2000cwc.googlegroups.com... > .) > > > > When you hibernate/boot up/hibernate for a long time without a clean > > reboot, Windows becomes unstable... > > This seems to depend on the system. I have gone at least a week, maybe > two, with nightly hibernations and no problems. Maybe you meant much > longer than that. But installs and updates often require reboots anyway. well, on my laptop its seems that if i hibernate more then a week, it becomes unstable > > tjr From LuciferLeo at gmail.com Sat May 20 08:35:47 2006 From: LuciferLeo at gmail.com (LuciferLeo at gmail.com) Date: 20 May 2006 05:35:47 -0700 Subject: misleading prefix ++ Message-ID: <1148128547.092479.231500@u72g2000cwu.googlegroups.com> given i = 0, I know i = i + 1 and i += 1 are all correct but when I type: >>> i++ the interpreter replies: File "<stdin>", line 1 i++ ^ SyntaxError: invalid syntax so I get the idea that suffix ++ is invalid in python but when I input: >>> ++i and the interpreter replies 0 Don't you think it is misleading when you expect a variable to increment? From nospam at foo.com Thu May 11 12:51:33 2006 From: nospam at foo.com (jayessay) Date: 11 May 2006 12:51:33 -0400 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <L4U6g.88$Ey5.52@fe12.lga> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <PV27g.16$pv7.11@fe08.lga> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <lr87g.502$SV1.253@fe10.lga> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <uHa7g.509$SV1.289@fe10.lga> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <m3vesdq0lp.fsf@rigel.goldenthreadtech.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <m3irodpxt9.fsf@rigel.goldenthreadtech.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: <m3d5ekpkru.fsf@rigel.goldenthreadtech.com> "Michele Simionato" <michele.simionato at gmail.com> writes: > jayessay wrote: > > I was saying that you are mistaken in that pep-0343 could be used to > > implement dynamically scoped variables. That stands. > > Proof by counter example: > > from __future__ import with_statement > import threading > > special = threading.local() > > def getvar(name): > return getattr(special, name) > > def setvar(name, value): > return setattr(special, name, value) > > class dynamically_scoped(object): > def __init__(self, name, value): > self.name = name > self.value = value > def __context__(self): > return self > def __enter__(self): > self.orig_value = getvar(self.name) > setvar(self.name, self.value) > def __exit__(self, Exc, msg, tb): > setvar(self.name, self.orig_value) > > if __name__ == '__main__': # test > setvar("*x*", 1) > print getvar("*x*") # => 1 > with dynamically_scoped("*x*", 2): > print getvar("*x*") # => 2 > print getvar("*x*") # => 1 > > If you are not happy with this implementation, please clarify. I can't get this to work at all - syntax errors (presumably you must have 2.5?, I only have 2.4). But anyway: This has not so much to do with WITH as relying on a special "global" object which you must reference specially, which keeps track (more or less) of its attribute values, which you use as "faked up" variables. Actually you probably need to hack this a bit more to even get that as it doesn't appear to stack the values beyond a single level. /Jon -- 'j' - a n t h o n y at romeo/charley/november com From jjl at pobox.com Tue May 2 22:07:43 2006 From: jjl at pobox.com (John J. Lee) Date: 03 May 2006 02:07:43 +0000 Subject: urllib2 not support proxy on SSL connection? References: <1146604944.658622.119860@u72g2000cwu.googlegroups.com> <200605022336.13609.me+python@modelnine.org> Message-ID: <87odyfrhcg.fsf@pobox.com> Heiko Wundram <me+python at modelnine.org> writes: > Am Dienstag 02 Mai 2006 23:22 schrieb itay_k: > > Is it possible that urllib2 doesnt support for proxy over https > > connections? > > Are you sure this a proxy which is accessed by https, or rather a proxy that > supports CONNECT, and thus allows you to access https-sites? I'd guess the > latter, which I haven't gotten to work with urllib2 so far. Also a recipe (maybe essentially the same as the SF patch, don't remember): http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/456195 John From nobody at 127.0.0.1 Sat May 13 19:26:26 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 13 May 2006 23:26:26 GMT Subject: distributing a app frozen by cx_freeze References: <1147482467.404798.187530@y43g2000cwc.googlegroups.com> <1147501391.800070.265860@g10g2000cwb.googlegroups.com> <1147536825.158172.73480@i40g2000cwc.googlegroups.com> Message-ID: <CWt9g.26722$4L1.20060@newssvr11.news.prodigy.com> Flavio wrote: > ImportError: /home/flavio/freeze/qt.so: undefined symbol: > _ZNK9QSGIStyle9classNameEv > So my question is: is there a way to find out exactly which lib is > missing ? yes - find the one with that symbol. wash, rinse, repeat. ;) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From russandheather at gmail.com Mon May 1 19:53:26 2006 From: russandheather at gmail.com (Russell Warren) Date: 1 May 2006 16:53:26 -0700 Subject: Popping from the middle of a deque + deque rotation speed In-Reply-To: <mailman.5120.1146281831.27775.python-list@python.org> References: <1146264164.488782.96770@g10g2000cwb.googlegroups.com> <mailman.5120.1146281831.27775.python-list@python.org> Message-ID: <1146527606.361060.211630@i39g2000cwa.googlegroups.com> > So does the speed of the remaining 0.001 cases really matter? Note > that even just indexing into a deque takes O(index) time. It doesn't matter as much, of course, but I was looking to make every step as efficient as possible (while staying in python). As to indexing into a deque being O(index)... I didn't realize that. It is certainly something to keep in mind, though... looping through the contents of a deque would obviously be a bad idea with this being the case! I wonder if the generator for the deque helps reduce this? Will check later. Proof of the O(n) for indexing into a deque (not that I doubted Tim #2! :)... >>> import timeit >>> s = "from collections import deque; d = deque(xrange(1000000))" >>> timeit.Timer(stmt="x=d[10000]", setup = s).timeit(number=100000) 0.14770257113683627 >>> timeit.Timer(stmt="x=d[100000]", setup = s).timeit(number=100000) 1.4016418287799155 Russ From skip at pobox.com Tue May 16 20:39:28 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 May 2006 19:39:28 -0500 Subject: For Large Dictionaries Could One Use Separate Dictionaries Where Each Dictionary Covers an Interval of the Input Range? In-Reply-To: <e4dbsm$b9q$1@reader1.panix.com> References: <1147657728.064817.214850@j73g2000cwa.googlegroups.com> <80sj621tskce4b18lqshe6ip7ihl0rqicm@4ax.com> <1147804326.793291.53410@j55g2000cwa.googlegroups.com> <mailman.5762.1147805604.27775.python-list@python.org> <e4dbsm$b9q$1@reader1.panix.com> Message-ID: <17514.28864.630233.832658@montanaro.dyndns.org> Roy> If you're getting long hash chains, you're either using a bad hash Roy> function, or your table isn't big enough. Sure. The original poster said something about 10 million keys I think. Unless the key distribution is amazingly fortuitous and the number of unique values is small, the dictionary is going to have a huge memory footprint. On my Mac laptop this code: >>> d = {} >>> for n in xrange(10**7): ... d[n] = hex(n) ... yields a process with 647MB of VM. If I trim that to 1000 unique values: >>> d = {} >>> for n in xrange(10**7): ... d[n] = hex(n % 1000) ... I still wind up with 647MB VM. The dictionary and its keys are what consume all the memory, and those keys are as simple as you can get. Skip From fredrik at pythonware.com Mon May 1 11:16:44 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Mon, 1 May 2006 17:16:44 +0200 Subject: returning none when it should be returning a list? References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com><4455A4A1.7020807@lexicon.net> <1146493188.096280.83040@y43g2000cwc.googlegroups.com> Message-ID: <e358ou$78n$1@sea.gmane.org> randomtalk at gmail.com wrote: > John Machin wrote: > > > > That's because it "falls off the end" of the function, which causes it > > to return None. However that's not your only problem. Major other > > problem is updating "seed" in situ. > > > I'm not sure what "falls off the end" of the function means, i searched > online, it seems to mean that the function has reached the end > prematurely and returned a default identifier to signal success or > not.. Can you please explain what that means? it means exactly what it says: that execution of the function body reaches the end of the function without seeing an explicit "return" statement. Python handles this by inserting an extra "return" statement at the end, to make sure there's always something to return (a plain "return" returns None to the caller). </F> From aisaac0 at verizon.net Mon May 1 12:50:26 2006 From: aisaac0 at verizon.net (David Isaac) Date: Mon, 01 May 2006 16:50:26 GMT Subject: list*list References: <1146497292.670742.43850@e56g2000cwe.googlegroups.com> <4bmotsF126gicU1@uni-berlin.de> Message-ID: <m%q5g.11251$Un3.9202@trnddc05> "Diez B. Roggisch" <deets at nospam.web.de> wrote in message news:4bmotsF126gicU1 at uni-berlin.de... > it's considered bad style to use range if all you want is a > enumeration of indices, as it will actually create a list of the size you > specified. Use xrange in such cases. I'm pretty sure this distinction goes away in 2.5. Cheers, Alan Isaac From sybrenUSE at YOURthirdtower.com.imagination Tue May 16 07:19:20 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Tue, 16 May 2006 13:19:20 +0200 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <GWR9g.22003$Gg.2175@twister.nyroc.rr.com> <xzS9g.76804$H71.22693@newssvr13.news.prodigy.com> <xqxac9jn7d6.fsf@cola3.ca.boeing.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <Xns97C558AB7C9B4duncanbooth@127.0.0.1> <slrne6j573.ecm.sybrenUSE@schuimige.stuvel.eu> <Xns97C5733407963duncanbooth@127.0.0.1> Message-ID: <slrne6jd9o.ejm.sybrenUSE@schuimige.stuvel.eu> Duncan Booth enlightened us with: > It could be, and for some keys (q, w, e, r, t, y, etc. spring to > mind) that is quite a reasonable implementation. For others 'tab', > 'backspace', 'enter', 'delete', etc. it is less reasonable, but it > is a quality of implementation issue. If I had an editor which > entered a control character for each of these I would simply move to > a better editor. Well, my editor *does* enter a control character when I press Enter, namely \n. It also enters a \t when I press TAB. That does not mean my editor is flawed. > The problem is that behaviour like this is useful, and mostly even > intuitive, but it's a long way from the definition of a tab or even > the little metal clips you used to stick on the back of a manual > typewriter. I understand what you are saying, but saying "an editor that insert a control character when pressing a key is flawed" is most incorrect. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From onurb at xiludom.gro Tue May 9 04:55:07 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 10:55:07 +0200 Subject: utility functions within a class? In-Reply-To: <1147062228.849272.225110@j73g2000cwa.googlegroups.com> References: <445e8992$0$9427$c3e8da3@news.astraweb.com> <1147049176.712585.205560@j73g2000cwa.googlegroups.com> <1147055211.899384.323190@v46g2000cwv.googlegroups.com> <445eb995$0$9381$c3e8da3@news.astraweb.com> <445ebacc$0$5345$c3e8da3@news.astraweb.com> <1147060713.875377.104640@y43g2000cwc.googlegroups.com> <445ec3d4$0$1965$c3e8da3@news.astraweb.com> <1147062228.849272.225110@j73g2000cwa.googlegroups.com> Message-ID: <4460594c$0$23806$626a54ce@news.free.fr> blair.bethwaite at gmail.com wrote: > John Salerno wrote: > >>What I originally meant was that they would not be called from an >>instance *outside* the class itself, i.e. they won't be used when >>writing another script, they are only used by the class itself. > > > Yep, so you want to encapsulate the functionality that those methods > provide, > > which is the whole point of building them in a class in the > first place. And you want them to be private to the class so that they > do not form part of the classes public/external interface. > > In python, as discussed earlier :), you can make them semi-private by > using the '__method_name' Blair, please, don't give bad advices. The 'double-leading-underscore' stuff has some side-effects (name-mangling), and is meant to protect an attribute from accidental overloading. The convention for 'protected' attributes (which should really be named 'implementation attributes') is a *single* leading underscore. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From invalidemail at aerojockey.com Sat May 20 04:52:28 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 20 May 2006 01:52:28 -0700 Subject: Exception style (was: calling python functions using variables) In-Reply-To: <tdsr625anu3r8hnknvegll0b6g8h83hfo7@4ax.com> References: <1148031553.574146.99130@j33g2000cwa.googlegroups.com> <mailman.5934.1148032680.27775.python-list@python.org> <446da180$0$10184$636a55ce@news.free.fr> <126rjus43k450df@corp.supernews.com> <9121k3-hjm.ln1@lairds.us> <tdsr625anu3r8hnknvegll0b6g8h83hfo7@4ax.com> Message-ID: <1148115148.141687.54450@i39g2000cwa.googlegroups.com> Dennis Lee Bieber wrote: > On Fri, 19 May 2006 14:41:13 +0000, claird at lairds.us (Cameron Laird) > declaimed the following in comp.lang.python: . > > Guys, I try--I try *hard*--to accept the BetterToAskForgiveness > > gospel, but this situation illustrates the discomfort I consistently > > feel: how do I know that the NameError means VARIABLE didn't resolve, > > rather than that it did, but that evaluation of commands.VARIABLE() > > I'd suggest that each of your "valid" commands should contain > whatever error checking is appropriate to it -- and if needed, raise > some custom "command failure" exception after handling the real failure > internally. That probably doesn't help when the exception is due to a bug and not bad input. If you have an AttributeError due to a bug, it would be wrong to raise a custom command failure exception. Carl Banks From NAIpt_lisasEXCHANGE at PLIPDECO.com Mon May 8 14:19:35 2006 From: NAIpt_lisasEXCHANGE at PLIPDECO.com (GroupShield for Exchange (EXCHANGE)) Date: Mon, 8 May 2006 14:19:35 -0400 Subject: ALERT - GroupShield ticket number OB20_1147112369_EXCHANGE_3 was generated Message-ID: <20138A39ED99DA1184A400065B01F90A838E74@EXCHANGE> Action Taken: The message was quarantined and replaced with a text informing the recipient of the action taken. To: python-list at python.org <python-list at python.org> From: Jorge Vargas <jorge.vargas at gmail.com> Sent: -235532672,29782731 Subject: help with Linker dependencies missing went compiling mysql-python on Windows without VisualStudio Attachment Details:- Attachment Name: N/A File: Infected.msg Infected? No Repaired? No Blocked? Yes Deleted? No Virus Name: -------------- next part -------------- A non-text attachment was scrubbed... Name: not available Type: application/ms-tnef Size: 1897 bytes Desc: not available URL: <http://mail.python.org/pipermail/python-list/attachments/20060508/d8b9e4df/attachment.bin> From duncan-news at grisby.org Wed May 31 11:44:35 2006 From: duncan-news at grisby.org (Duncan Grisby) Date: Wed, 31 May 2006 17:44:35 +0200 Subject: omniorbpy: problems sending float values References: <1148914432.514658.216050@38g2000cwa.googlegroups.com> Message-ID: <6233c$447db9e3$560eec15$12990@news.news-service.com> In article <1148914432.514658.216050 at 38g2000cwa.googlegroups.com>, Juergen <juergen.eckel at gmx.net> wrote: >I've got a problem sending floating point values to an corba server. >With other datatyes like short or string it works fine. Upgrade to the latest stable release, omniORB 4.0.7 and omniORBpy 2.7. The problem you are seeing is due to a conflict between some marshalling code in omniORB 4.0.6 and your compiler's use of strict aliasing. Cheers, Duncan. -- -- Duncan Grisby -- -- duncan at grisby.org -- -- http://www.grisby.org -- From vbgunz at gmail.com Wed May 24 00:58:31 2006 From: vbgunz at gmail.com (vbgunz) Date: 23 May 2006 21:58:31 -0700 Subject: Don't wish to give up on a Tkinter GUI Builder :( References: <1148369214.358531.74530@i40g2000cwc.googlegroups.com> <1148371674.932205.83160@j55g2000cwa.googlegroups.com> <1148382609.644438.267020@j55g2000cwa.googlegroups.com> <A6qdnQFPrLgDzO7ZnZ2dnUVZ_uidnZ2d@nmt.edu> <1148411169.830384.149330@g10g2000cwb.googlegroups.com> Message-ID: <1148446711.224119.53720@i39g2000cwa.googlegroups.com> > As for the code to actually make the application go, well, > if there is some automatic way to make that happen it hasn't dawned on > me yet. why not execute 'python -u /pathto/module.py' I could be wrong but hope I am not :) From robin at NOSPAMreportlab.com Mon May 1 05:44:03 2006 From: robin at NOSPAMreportlab.com (Robin Becker) Date: Mon, 01 May 2006 09:44:03 +0000 Subject: self modifying code In-Reply-To: <1146469385.334797.128930@i39g2000cwa.googlegroups.com> References: <445399A1.9020506@jessikat.plus.net> <slrne57r50.uh0.spamspam@bowser.marioworld> <44548536.7060409@jessikat.plus.net> <1146469385.334797.128930@i39g2000cwa.googlegroups.com> Message-ID: <4455D863.6070906@jessikat.plus.net> taleinat at gmail.com wrote: ........ > > What have we gained from this? Two major advantages: > * no ugly 'global' statement > * no reliance on the function's name I don't dispute either of the above, however, the actual overhead of your approach appears to be much higher (see below) probably because it has two function calls instead on one to get the answer. > > And now you can easily create such functions forever using this class > to abstract away the ugly implementation ;) ....... yes indeed ######file dingo.py class InitializingFunction(object): def __init__(self, init): def initializer(*args, **kw): self.func = init() return self(*args, **kw) self.func = initializer def __call__(self, *args, **kw): return self.func(*args, **kw) def init(): data = 42 def foo(arg): return arg+data return foo a = InitializingFunction(init) def b(arg): global b data = 42 def b(arg): return arg+data return b(arg) ###### Testing with timeit C:\Tmp>\Python\lib\timeit.py -s"from dingo import a;a(0)" a(1) 100000 loops, best of 3: 2.25 usec per loop C:\Tmp>\Python\lib\timeit.py -s"from dingo import b;b(0)" b(1) 1000000 loops, best of 3: 0.52 usec per loop so since the simple function is fairly trivial the overhead seems to be around 4 times that of the weird approach. The global naming stuff is pretty flaky and relies on the way names are looked up; in particular it seems as though references to the original global will be held at least throughout a single statement. If the first call is "print b(0),b(1)" then b is initialised twice. This 'masterpiece of obfuscation' ;) gets round that problem, but is pretty odd to say the least and still relies on knowing the class name. class Weird(object): @staticmethod def __call__(arg): data = 42 def func(arg): return arg+data Weird.__call__ = staticmethod(func) return func(arg) c = Weird() it is still more expensive than b, but not by much C:\Tmp>\Python\lib\timeit.py -s"from dingo import c;c(1)" c(1) 1000000 loops, best of 3: 0.709 usec per loop -- Robin Becker From diffuser78 at gmail.com Wed May 3 02:02:16 2006 From: diffuser78 at gmail.com (diffuser78 at gmail.com) Date: 2 May 2006 23:02:16 -0700 Subject: Wake on LAN and Shutdown for Windows and Linux In-Reply-To: <mailman.5234.1146606660.27775.python-list@python.org> References: <1146596569.987280.281870@i40g2000cwc.googlegroups.com> <mailman.5234.1146606660.27775.python-list@python.org> Message-ID: <1146636135.972523.30300@v46g2000cwv.googlegroups.com> because you can write scripts in python so easily as compared to other scripting languages. From DustanGroups at gmail.com Thu May 18 09:02:33 2006 From: DustanGroups at gmail.com (Dustan) Date: 18 May 2006 06:02:33 -0700 Subject: Which is More Efficient? Message-ID: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> I have a program that uses up a lot of CPU and want to make it is efficient as possible with what I have to work with it. So which of the following would be more efficient, knowing that l is a list and size is a number? l=l[:size] del l[size:] If it makes a difference, everything in the list is mutable. From "reverse[nepank.noot]" at fft.be Fri May 19 09:06:24 2006 From: "reverse[nepank.noot]" at fft.be (Toon Knapen) Date: Fri, 19 May 2006 15:06:24 +0200 Subject: CFLAGS are not taken into account properly In-Reply-To: <mailman.5818.1147881969.27775.python-list@python.org> References: <446ad377$0$438$6c56d894@reader0.news.be.easynet.net> <mailman.5798.1147865676.27775.python-list@python.org> <446B1972.4090107@fft.be> <mailman.5818.1147881969.27775.python-list@python.org> Message-ID: <446dc2d0$0$14605$6c56d894@reader0.news.be.easynet.net> skip at pobox.com wrote: > Toon> But some other (but 'similar') functionality is broken. Now I > Toon> succeeded in compiling python. But when using distutils (e.g. when > Toon> installing numarray using the setup.py), python will compile the > Toon> files using the '-xarch=v9' option but drops this option when > Toon> linking dynamic libraries (although I defined LDFLAGS="-xarch=v9" > Toon> before configuring python). Additionally python adds the option > Toon> '-xcode=pic32' to the compile-command which will compile my > Toon> numarray in 32bit instead of 64bit (while python itself is in > Toon> 64bit) > > That seems like a bug in distutils. Can you submit a help ticket? > > Skip Done From kairosenthal at tiscali.de Fri May 5 12:37:34 2006 From: kairosenthal at tiscali.de (kai) Date: 5 May 2006 09:37:34 -0700 Subject: ConfigParser: values with ";" and the value blank Message-ID: <1146847054.321520.296410@v46g2000cwv.googlegroups.com> Hello, I use the ConfigPaserver from Python. how can I use/save/read values with ";" (start comment) and the value blank? When I write (set) my config file often the part behind the ";" disappears. e.g. myKey = startMyValue ; endMyValue Thank's for your hints, Kai From fredrik at pythonware.com Thu May 18 09:39:39 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 15:39:39 +0200 Subject: Which is More Efficient? In-Reply-To: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> References: <1147957353.707903.278220@j73g2000cwa.googlegroups.com> Message-ID: <e4hteq$522$1@sea.gmane.org> Dustan wrote: > I have a program that uses up a lot of CPU and want to make it is > efficient as possible with what I have to work with it. So which of the > following would be more efficient, knowing that l is a list and size is > a number? > > l=l[:size] > del l[size:] since you have the program, it shouldn't that hard to test the two alternatives, should it ? (in theory, del should be faster in most cases, since it avoids creating another object. but the only way to tell for sure is to try it out). > If it makes a difference, everything in the list is mutable. the only difference between mutable and immutable objects in Python is that mutable objects have methods that let you modify the object contents, while immutable objects don't have such methods. </F> From johnjsal at NOSPAMgmail.com Wed May 10 10:29:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 10 May 2006 14:29:12 GMT Subject: reusing parts of a string in RE matches? Message-ID: <YMm8g.2077$No6.45935@news.tufts.edu> I probably should find an RE group to post to, but my news server at work doesn't seem to have one, so I apologize. But this is in Python anyway :) So my question is, how can find all occurrences of a pattern in a string, including overlapping matches? I figure it has something to do with look-ahead and look-behind, but I've only gotten this far: import re string = 'abababababababab' pattern = re.compile(r'ab(?=a)') m = pattern.findall(string) This matches all the 'ab' followed by an 'a', but it doesn't include the 'a'. What I'd like to do is find all the 'aba' matches. A regular findall() gives four results, but really there are seven. Is there a way to do this with just an RE pattern, or would I have to manually add the 'a' to the end of the matches? Thanks. From mikael at isy.liu.se Wed May 31 08:41:58 2006 From: mikael at isy.liu.se (Mikael Olofsson) Date: Wed, 31 May 2006 14:41:58 +0200 Subject: Running Python scripts under a different user In-Reply-To: <mailman.6249.1148659102.27775.python-list@python.org> References: <mailman.6246.1148657024.27775.python-list@python.org> <4dolv4F1b8m87U1@uni-berlin.de> <mailman.6249.1148659102.27775.python-list@python.org> Message-ID: <e5k2e0$m0r$1@news.lysator.liu.se> Laszlo Nagy wrote: > For Windows, you can use the 'runas.exe' program. But it requires a > password too. Or you can get a copy of the shareware program RunAsProfessional, which I use for my kids stupid games that necessarily has to be run by an admin. The price I paid was 10 Euro, which I still think was money well spent. IIRC you get a 30 days trial version for free. http://freedownloads.rbytes.net/cat/desktop/other3/runas-professional/ It does the same thing as RunAs, but you do not need to type the password every time you run your program. Instead the password is stored encrypted in the file you launch. I do not know what encryption is used, or how safe the encryption is. My needs are simply to make sure that my kids do not destroy anything by mistake. Sure, the stupid game may be designed to destroy, but that's another issue. /MiO From bitsandbytes88 at hotmail.com Tue May 30 11:03:56 2006 From: bitsandbytes88 at hotmail.com (bitsandbytes88 at hotmail.com) Date: 30 May 2006 08:03:56 -0700 Subject: sybase open client 15_0 In-Reply-To: <e5789d$dhg$1@gemini.csx.cam.ac.uk> References: <NPOdnbx8s-CdcejZRVn-iw@speakeasy.net> <BcmdnQxbloXocOjZRVn-rQ@speakeasy.net> <e5789d$dhg$1@gemini.csx.cam.ac.uk> Message-ID: <1149001436.520736.103260@g10g2000cwb.googlegroups.com> Hi, Thanks for the reply. I have tried that solution - adding syb like sybblk to setup.py, but it didn't change my end result, import sybase fails. I wonder if I need to start fresh. How would I be sure sybase-0.37 is gone? Also, I have 64-bit linux. I have libsybblk64.so for example. I don't have libsybcs.a or sybinsck, it didn't come with OCS-15_0. ~DjK From martin at v.loewis.de Mon May 22 00:39:29 2006 From: martin at v.loewis.de (=?ISO-8859-1?Q?=22Martin_v=2E_L=F6wis=22?=) Date: Mon, 22 May 2006 06:39:29 +0200 Subject: Python source sensitive to PyObject_HEAD layout? In-Reply-To: <1148254892.114251.45770@j55g2000cwa.googlegroups.com> References: <1148254892.114251.45770@j55g2000cwa.googlegroups.com> Message-ID: <44714081.2070308@v.loewis.de> Petter Haggholm wrote: > Any help, thoughts, or advice would be vastly appreciated. After changing PyObject_HEAD, I would run "make distclean". Most likely, some object files were not recompiled and still using the old layout. Regards, Martin From akameswaran at gmail.com Tue May 30 16:11:26 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 30 May 2006 13:11:26 -0700 Subject: Strange behavior with iterables - is this a bug? Message-ID: <1149019886.693900.126850@u72g2000cwu.googlegroups.com> Ok, I am confused about this one. I'm not sure if it's a bug or a feature.. but >>> ================================ RESTART >>> f1 = open('word1.txt') >>> f2 = open('word2.txt') >>> f3 = open('word3.txt') >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in f1 for i2 in f2 for i3 in f3] [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c')] >>> l1 = ['a\n','b\n','c\n'] >>> l2 = ['a\n','b\n','c\n'] >>> >>> l3 = ['a\n','b\n','c\n'] >>> print [(i1.strip(),i2.strip(),i3.strip(),) for i1 in l1 for i2 in l2 for i3 in l3] [('a', 'a', 'a'), ('a', 'a', 'b'), ('a', 'a', 'c'), ('a', 'b', 'a'), ('a', 'b', 'b'), ('a', 'b', 'c'), ('a', 'c', 'a'), ('a', 'c', 'b'), ('a', 'c', 'c'), ('b', 'a', 'a'), ('b', 'a', 'b'), ('b', 'a', 'c'), ('b', 'b', 'a'), ('b', 'b', 'b'), ('b', 'b', 'c'), ('b', 'c', 'a'), ('b', 'c', 'b'), ('b', 'c', 'c'), ('c', 'a', 'a'), ('c', 'a', 'b'), ('c', 'a', 'c'), ('c', 'b', 'a'), ('c', 'b', 'b'), ('c', 'b', 'c'), ('c', 'c', 'a'), ('c', 'c', 'b'), ('c', 'c', 'c')] explanation of code: the files word1.txt, word2.txt and word3.txt are all identical conataining the letters a,b and c one letter per line. The lists I've added the "\n" so that the lists are identical to what is returned by the file objects. Just eliminating any possible differences. If you notice, when using the file objects I don't get the proper set of permutations. I was playing around with doing this via recursion, etc. But nothing was working so I made a simplest case nesting. Still no go. Why does this not work with the file objects? Or any other class I''ve made which implements __iter__ and next? Seems like a bug to me, but maybe I am missing something. Seems to happen in 2.3 and 2.4. From ben at wintersun.org Tue May 2 19:40:27 2006 From: ben at wintersun.org (Ben Caradoc-Davies) Date: Wed, 03 May 2006 07:40:27 +0800 Subject: assignment in if In-Reply-To: <87iroodnqz.fsf@localhost.localdomain> References: <87iroodnqz.fsf@localhost.localdomain> Message-ID: <4457edf0$0$16966$5a62ac22@per-qv1-newsreader-01.iinet.net.au> Gary Wessle wrote: > is there a way to make an assignment in the condition of "if" No. > nx = re.compile('regex') > if x = nx.search(text): > funCall(text, x)) Use: nx = re.compile('regex') x = nx.search(text) if x: funCall(text, x) -- Ben Caradoc-Davies <ben at wintersun.org> http://wintersun.org/ "Those who deny freedom to others deserve it not for themselves." - Abraham Lincoln From mtobis at gmail.com Thu May 18 20:01:50 2006 From: mtobis at gmail.com (Michael Tobis) Date: 18 May 2006 17:01:50 -0700 Subject: python vs perl lines of code In-Reply-To: <Xns97C7BC8549BA0castleamber@130.133.1.4> References: <IRuag.28298$4L1.9158@newssvr11.news.prodigy.com> <S8vag.28302$4L1.6116@newssvr11.news.prodigy.com> <IzE7vM.8A4@news.boeing.com> <Atyag.72783$_S7.42376@newssvr14.news.prodigy.com> <e4g2lf$icl$1@panix2.panix.com> <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <mailman.5853.1147908610.27775.python-list@python.org> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <mailman.5857.1147914934.27775.python-list@python.org> <jGQag.73065$_S7.50305@newssvr14.news.prodigy.com> <mailman.5859.1147918811.27775.python-list@python.org> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <Xns97C7A4E344C7Dcastleamber@130.133.1.4> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> <Xns97C7BC8549BA0castleamber@130.133.1.4> Message-ID: <1147996910.404673.120340@j33g2000cwa.googlegroups.com> > According to your silly rule the shortest book on a subject would be the > best. Now why is that false? No, according to the rule, the shorter of two books **containing the same information** would be best. I don't think I'm a zealot. The original quote said "all else equal". Certainly legible code is better than, hence not equal to, illegible code. I would say that having played Python golf once, the complexity of the competitive keystroke-minimizing code is much higher than the complexity of the equivalent sane, readable, maintainable code. (Actually, it also turns out to involve a good deal of coding that isn't in the final source, but let's not go there.) The point is I did NOT say he programs best who *types* least, and I don't believe that. In fact, that's what makes the comparison interesting. I had always thought that Pythonistas type more than Perlists, though I prefer Python anyway. The presumption was based on the fact that Perl (as language and culture) takes delight in saving keystrokes at the expense of clarity ($_ and all that) while Python makes no special effort in that direction. If real world Python code is substantially more terse *despite* this cultural difference, it is a fact worthy of some note. Let me add my voice to those clamoring for Edward to release his code while I'm here, though. mt From tdelaney at avaya.com Wed May 17 19:16:12 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 18 May 2006 09:16:12 +1000 Subject: Test professionalism (was: count items in generator) Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6FA@au3010avexu1.global.avaya.com> Cameron Laird wrote: > Gulp. OK, you've got me curious: how many people habitually frame > their unit tests with resource constraints? I think I take testing > seriously, and certainly also am involved with resource limits often, > but I confess I've never aimed to write all my tests in terms of > bounds on time (and presumably memory and ...). You've got me > thinking, Tim. Generally we only do it when we actually discover a problem i.e. the test has been running forever ... which is precisely the problem. At least you don't have to specifically code tests for bounds on most other resources (such as memory) as eventually it will fail with a language with managed memory (Python, Java, etc). It definitely becomes an issue for C/C++ unit tests though - they don't fail nicely. I believe JUnit 4 includes the option to time out any test, but that you can vary the timeout using an annotation (for example, make any test fail if it takes longer than 30 seconds - but you may have one test that needs to run longer). We're only using JUnit 3 at my work at the moment though. The application I'm currently working on is very timing dependent (and the timings vary greatly across machines), so we've got loops like: while (test condition not met) and (timeout not exceeded): sleep assert test condition met Originally these were just: while (test condition not met): sleep and as a result turned into infinite loops. I think it's much better to have every test have a default timeout (at which point the test fails) and be able to change that default when needed. This protects against errors in both the code, and test cases. Tim Delaney From joel.hedlund at gmail.com Thu May 4 03:42:39 2006 From: joel.hedlund at gmail.com (Joel Hedlund) Date: Thu, 04 May 2006 09:42:39 +0200 Subject: Possibly dumb question about dicts and __hash__() In-Reply-To: <e3c7vt$8u4$01$1@news.t-online.com> References: <e3b0c0$g8o$1@news.lysator.liu.se> <e3c7vt$8u4$01$1@news.t-online.com> Message-ID: <e3caqb$nn2$1@news.lysator.liu.se> Hi! > Just the hash is not enough. You need to define equality, too: Thanks a million for clearing that up. Cheers! /Joel From python.list at tim.thechases.com Sun May 14 16:01:29 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Sun, 14 May 2006 15:01:29 -0500 Subject: Converting hex to char help In-Reply-To: <200605141933.57679.ognjen@mailshack.com> References: <mailman.3510.1143024593.27775.python-list@python.org> <slrne22k5n.31g.sybrenUSE@schuimige.unrealtower.org> <200605141933.57679.ognjen@mailshack.com> Message-ID: <44678C99.5020003@tim.thechases.com> > How can I convert a string "0x62" to int/hex without this problem? The call to int() takes an optional parameter for the base: >>> print int.__doc__ int(x[, base]) -> integer Convert a string or number to an integer, if possible. A floating point argument will be truncated towards zero (this does not include a string representation of a floating point number!) When converting a string, use the optional base. It is an error to supply a base when converting a non-string. If the argument is outside the integer range a long object will be returned instead. >>> int('0x62', 16) 98 -tkc From reinhold.strobl at gmail.com Fri May 19 05:05:05 2006 From: reinhold.strobl at gmail.com (reinsn) Date: 19 May 2006 02:05:05 -0700 Subject: Specific performance question - Python vs. Java Message-ID: <1148029505.407594.151900@i40g2000cwc.googlegroups.com> Hi, I have got a specific question on performance: Is the overhead of object creation in Python lower than in Java? I mean, I would argue, in Java by object creation, the complete class is the model and all methods and attributes are generated for the object. In Python, methods and objects are only generated, if reached: so could this represent a performance advantage for Python? Thanks! From johnjsal at NOSPAMgmail.com Wed May 24 10:52:57 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 24 May 2006 14:52:57 GMT Subject: Python Programming Books? In-Reply-To: <1148474872.218991.93460@j73g2000cwa.googlegroups.com> References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> <mn.c36f7d65ac4090ff.43626@yahoo.fr.invalid> <1148474872.218991.93460@j73g2000cwa.googlegroups.com> Message-ID: <dr_cg.2164$No6.46749@news.tufts.edu> herraotic at googlemail.com wrote: > Thanks, if you don't mind could I have a small <b>personal</b> > description on the quality of the books (pros, cons). > > I also am interested if anyone has used "Python Programming: An > Introduction to Computer Science" and if I could be given a detailes > evaluation about it. > I'm actually getting this book in the mail today. I'll let you know what I think of it if you're interested, but I say don't wait, go buy Learning Python (2nd ed.) now! From sendha_vin at yahoo.com Sat May 27 08:42:12 2006 From: sendha_vin at yahoo.com (sendhil kumar) Date: Sat, 27 May 2006 05:42:12 -0700 (PDT) Subject: TreeCtrl to TreeListCtrl Message-ID: <20060527124212.23272.qmail@web33101.mail.mud.yahoo.com> Hi all, whwn working with xml connectvity to python, i have a sash window, in which first window has a Tree Control that has 'n' parent fields preceded by + sign and on leftdown all the childs got from external xml file. when the particular parent field is selected and dragged, it must get posted to the other sash window which should in TreeList Control, bcoz iam displaying numerous xml attributes of the parent and following 'n' number of childs from xml. Now, iam facing a problem in implementing with TreeListCtrl, but it works fne with ListCtrl... any suggestions, would be of great value... cheers and thanx in advance... SendhilKumar B.Tech __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com From birchb at ozemail.com.au Tue May 9 11:37:08 2006 From: birchb at ozemail.com.au (birchb at ozemail.com.au) Date: 9 May 2006 08:37:08 -0700 Subject: Deferred Evaluation in Recursive Expressions? In-Reply-To: <e3qc7h$ats$01$1@news.t-online.com> References: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> <e3qc7h$ats$01$1@news.t-online.com> Message-ID: <1147189028.751527.157640@j73g2000cwa.googlegroups.com> How about mutual recursion? class LinkedListA(TypeDef): typedef = (int, LinkedListB) class LinkedListB(TypeDef): typedef = (int, LinkedListA) From phddas at yahoo.com Tue May 2 17:06:11 2006 From: phddas at yahoo.com (Gary Wessle) Date: 03 May 2006 07:06:11 +1000 Subject: data regex match Message-ID: <87r73cdtmk.fsf@localhost.localdomain> Hi I am having an issue with this match tx = "now 04/30/2006 then" data = re.compile('(\d{2})/\1/\1\1', re.IGNORECASE) d = data.search(tx) print d Nono I was expecting 04/30/2006, what went wrong? thanks From iddw at hotmail.com Tue May 2 15:18:41 2006 From: iddw at hotmail.com (Dave Hansen) Date: Tue, 02 May 2006 14:18:41 -0500 Subject: simultaneous assignment References: <8dM5g.2031$No6.43874@news.tufts.edu> <4bphvsF12acj1U1@uni-berlin.de> <tsM5g.2033$No6.43913@news.tufts.edu> <pan.2006.05.02.18.46.39.714313@hastings.org> <4UN5g.2038$No6.43609@news.tufts.edu> Message-ID: <imbf52doc8hop66o1idfb5amhjuu5to915@4ax.com> On Tue, 02 May 2006 18:52:48 GMT in comp.lang.python, John Salerno <johnjsal at NOSPAMgmail.com> wrote: [...] > >Yeah, after trying some crazy things, I just wrote it this way: > >def truth_test(seq): > truth = 0 > for item in seq: > if item: > truth += 1 > if truth == 1: > return True > else: > return False You could replace those last four lines with return truth == 1 > >Not sure I like having to keep a counter though, but the other stuff I Well, if you want something minimalist, you could try def truth_test(seq): return sum(1 for item in seq if item) == 1 Though I'm not sure it's really any clearer... >did was really convoluted, like checking to see if the first item was >True, and if it was, popping it from the list and iterating over the >rest of the items (needless to say, the in-place change wasn't helpful). Perhaps something like def truth_test(seq): found = False for item in seq: if item: if found: return False found = True return found Gets you an early exit, anyway... All code untested. Regards, -=Dave -- Change is inevitable, progress is not. From danb_83 at yahoo.com Mon May 1 04:33:07 2006 From: danb_83 at yahoo.com (Dan Bishop) Date: 1 May 2006 01:33:07 -0700 Subject: Converting floating point to string in non-scientific format In-Reply-To: <Pine.SOL.4.56.0605010352270.5230@pollux.cse.buffalo.edu> References: <Pine.SOL.4.56.0605010352270.5230@pollux.cse.buffalo.edu> Message-ID: <1146471023.468344.178050@i40g2000cwc.googlegroups.com> Madhusudhanan Chandrasekaran wrote: > Hi all: > > When I try to convert a float variable into string via repr() or str() > function, i get the value as is, i.e '0.1e-7' in IEEE 754 format. > Instead how can force the created string to represent the floating > point in non-scientific fashion (non IEEE 754 format)? i.e > something like 0.000000001 Use the % operator with the f format (e.g., '%.7f' % x). From rwrii at charter.net Wed May 24 20:07:35 2006 From: rwrii at charter.net (rwr) Date: 24 May 2006 17:07:35 -0700 Subject: Compiling Python from Sources In-Reply-To: <1148512998.732842.258430@j33g2000cwa.googlegroups.com> References: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> <1148509057.542733.217230@i39g2000cwa.googlegroups.com> <1148509487.448417.294690@j33g2000cwa.googlegroups.com> <1148512998.732842.258430@j33g2000cwa.googlegroups.com> Message-ID: <1148515655.391325.197480@j55g2000cwa.googlegroups.com> Thank you ever so much mensanator!!! Very much appreciated! rwr From sjmachin at lexicon.net Tue May 9 19:02:15 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 10 May 2006 09:02:15 +1000 Subject: PyExcelerator: How does one close a file? In-Reply-To: <1147211877.683702.272710@i40g2000cwc.googlegroups.com> References: <1147211877.683702.272710@i40g2000cwc.googlegroups.com> Message-ID: <44611F77.4090207@lexicon.net> On 10/05/2006 7:57 AM, tkpmep at hotmail.com wrote: > I use PyExcelerator to write data into Excel files, and repeatedly call > the function writeData with different filenames fn from my main > routine. Unfortunately, only one file - the last one - is created. The > problem seems to lie with the fact that I do not close the existing > file before calling the function again, If you needed to close a file that was opened in another module, that would be a very peculiar API design. You don't need to. > and the existing file is > therefore just saved with a new name. Your function creates a new instance of the Workbook class, as it should. The instance is abandoned when your function exits. One would not expect any carry-over between instances. Is there a way to close a > PyExcelerator Excel file so that each call to the function results in a > new file? There is no close() method as far as I can tell. > > def writeData(fn, Data): > """Write the data into an Excel file named fn using PyExcelerator > Data is a list of real numbers""" > w=PyExcelerator.Workbook() Last time I looked, the name was pyExcelerator -- that's a lower-case "p" at the front. How come you didn't get an exception here (or on earlier import)? Have you posted the actual code you executed??? > ws = w.add_sheet("Sheet1") > for i in range(len(Data)): > ws.write(i, 0, Data[i]) > w.save(fn) > pyExcelerator is open-source; you should read it. According to my reading of the version 0.6.3 source (which version are you using?), the Workbook.save method calls the CompoundDoc.save method, which opens a physical file with the supplied name, writes to it, and closes it. AFAICT, there is no hint of anything that could cause the symptoms you describe. I did a quick test using the following code and your function (with appropriate module name) on version 0.6.3. It worked as expected (Python 2.4.3 on Windows XP). Which Python version are you using? What OS? for k in range(3): writeData("zzz%d.xls" % k, range(k, k+10)) Perhaps the problem is closer to home; try inserting print repr(fn) before each call to your function, and os.system("ls -l " + fn) # or "dir " + fn, or whatever it takes after each call. HTH, John From ptmcg at austin.rr._bogus_.com Wed May 17 15:24:30 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Wed, 17 May 2006 19:24:30 GMT Subject: Pyparsing: Grammar Suggestion. 2nd thought References: <mailman.5827.1147889120.27775.python-list@python.org> Message-ID: <OLKag.41844$CH2.39146@tornado.texas.rr.com> "Khoa Nguyen" <khoa.coffee at gmail.com> wrote in message news:mailman.5827.1147889120.27775.python-list at python.org... > > for tokens,start,end in commaSeparatedList.scanString(data): > print tokens > > > This returns: > > ['f1', 'f2', 'f3', 'f4', 'f5', 'f6'] > ['f1', 'f2'] > ['f1', 'f2', '', 'f4', '', 'f6'] > <snip> > On 2nd thought, I don't think this will check for the correct order of > the fields. For example, the following would be incorrectly accepted: > > f1,f5,f2 END_RECORD > > Thanks, > Khoa Well, what are the rules for the comma-separated entries? Are they distinguished by type, or are they in ascending lexical or arithmetic order, or by ascending length? Two approaches you can take: - if at parse time you can determine if f5 is out of position because it is a specific type, then you can define your grammar like: Optional(f1SpecificFormat) + "," + Optional(f2SpecificFormat) + "," + ... and so on. Then f5 would only match if in the fifth position. Or, if even the commas are optional (as in f2,f5 END_RECORD), then you would need a grammar such as: Optional(f1SpecificFormat) + Optional(Optional(",") + f2SpecificFormat) + ... + "END_RECORD" - if f5 is out of order because it is followed by f2, but would have been ok if followed only by f6-fN values, then you'll need to read everything in, and then test for validity, most easily in a parse action. If the validation rule fails, then have the parse action raise a ParseException, so that the match would be rejected. -- Paul From Serge.Orlov at gmail.com Mon May 29 00:42:52 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 28 May 2006 21:42:52 -0700 Subject: iteration over non-sequence ,how can I resolve it? References: <1148822420.452617.79720@u72g2000cwu.googlegroups.com> <mailman.6293.1148825990.27775.python-list@python.org> <1148827650.075896.124970@g10g2000cwb.googlegroups.com> Message-ID: <1148877772.529750.34280@j55g2000cwa.googlegroups.com> python wrote: > To BJ?rn Lindqvist : > thank you . how to write the code specifically ?Could you give a > example? Use Queue module: import threading from Queue import Queue class PrintThread(threading.Thread): def __init__(self, urlList, results_queue): threading.Thread.__init__(self) urllist=[] self.urllist=urlList self.results_queue = results_queue def run(self): urllink=[self.urllist] * 2 self.results_queue.put(urllink) results = Queue() threadList = [] for i in range(0,2): thread=PrintThread("Thread"+str(i), results) threadList.append(thread) thread.start() for i in threadList: linkReturned = results.get() for j in linkReturned: print j From andrew.arobert at gmail.com Wed May 17 07:56:29 2006 From: andrew.arobert at gmail.com (Andrew Robert) Date: Wed, 17 May 2006 07:56:29 -0400 Subject: Option parser question - reading options from file as well as command line In-Reply-To: <1147851955.954641.180880@38g2000cwa.googlegroups.com> References: <126k3273j7kb28f@corp.supernews.com> <1147851955.954641.180880@38g2000cwa.googlegroups.com> Message-ID: <126m3ru1ql02m72@corp.supernews.com> Tim N. van der Leeuw wrote: > Andrew Robert wrote: >> Hi Everyone. >> >> >> I tried the following to get input into optionparser from either a file >> or command line. >> >> >> The code below detects the passed file argument and prints the file >> contents but the individual swithces do not get passed to option parser. >> > > After reading your post I decided to play around with optparse a bit, > to get acquainted with it. > > Experimenting with IDLE I found that the Values object returned by > parse_args has a method 'readfile', and this 'readfile' method allows > you to add options to the Values object. > > The syntax should be in the form: > > <option>=<value> > > <option> should not include the hyphens -- if your option is added as > '-x', then you should write: > > x=3 > > not: > > -x=3 > > If you have options with both long names and short names, then you > should use the long name -- if your option is added as '-f', '--file', > then you should write: > > file=foo.txt > > not: > > f=foo.txt > > > Also, you need the assignment-operator in your file. > > I didn't find any documentation on this, and I didn't try this with any > actions; only with options added to the parser like > op.add_option('-x', dest='x') > > Using this 2-step approach allows you to use optparse itself to get to > the command-line option with your command-line settings... > > > Out of pure personal interest, what queuing-system are you writing to > from Python? What libraries do you have for that? And is it commercial > software, or freely downloadable? > (I'd love to be able to write messages to IBM MQ Series from Python) > > Cheers, > > --Tim > Hi Tim, I am using the pymqi module which is freely available at http://pymqi.sourceforge.net/ . Documentation on the module can be found at http://pymqi.sourceforge.net/pymqidoc.html . I have a few python examples on my web site located at http://home.townisp.com/~arobert/ There are also a lot of good examples at http://www.koders.com/info.aspx?c=ProjectInfo&pid=TVM5FGBZMY4E5ZH7GC9AX54PAC . If you come up with anything, I would be glad to see what you have. Back to the original issue: I'm not sure exactly what you mean about the readfile option and format. Could you send me a code snippet so I can get a better feel for it? Thanks, Andy From 63q2o4i02 at sneakemail.com Tue May 16 15:17:30 2006 From: 63q2o4i02 at sneakemail.com (63q2o4i02 at sneakemail.com) Date: 16 May 2006 12:17:30 -0700 Subject: Using python for a CAD program References: <1147762143.076944.139600@j55g2000cwa.googlegroups.com> <xqxpsietsrf.fsf@cola3.ca.boeing.com> Message-ID: <1147807050.375537.297430@j73g2000cwa.googlegroups.com> Cool. thanks for the links. I've already looked around quite a bit, and am very hesitant to just write more shit on top of other shit. The idea behind this is it's completely mine. So yes, I have a tendency to want to reinvent a few wheels, but I think it'll give me greater satisfaction. The problem with geda, etc., is that it's taking the unix approach -- a buncha little command line tools that somehow make a "system", using text files as communication medium. I hate that, largely because it allows the infectious spread of little files all over your system, encourages people to write scripts from outside the system that probably won't work for you, and exposes the user unnecessarily to the implementation of where you keep files, directories, blabla. I'm more of the windows approach, where you have one integrated environment, and any text you type is from within the application itself, and most application-related data is hidden from the user unless he *really* wants to get at it. (disclosure: I've never actually installed geda, but I tried icarus once and couldn't get it to compile -- another bane of open source stuff I can't stand. I'm not a CS person, so when I download something, I just want it to work, and I don't get off trying to *make* it work...). Another reason for doing this on my own is that I'd like a general-purpose CAD/design framework, of which electrical/IC design is only one part. Also, I think geda simulations are spice-based, which is batch, which is sooo your-father's buick, which I hate as much as text files... aaand another thing is I'm very big on user-experience. I'd like my program to *look* slick, like it belongs in a movie or something. I think that means starting from scratch, since I've not seen any CAD program take any artistic/human/psychological approach to its design. From levub137 at wi.rr.com Sat May 6 11:25:25 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sat, 06 May 2006 15:25:25 GMT Subject: [ANN] clnum-1.2 Class Library For Numbers Python Binding Message-ID: <Fd37g.2685$WP5.495@tornado.rdc-kc.rr.com> The clnum package adds rational numbers and arbitrary precision floating point numbers in real and complex form to Python. Also provides arbitrary precision floating point replacements for the functions in the math and cmath standard library modules. Home page: http://calcrpnpy.sourceforge.net/clnum.html Changes in 1.2 * Make compatible with Python 2.5 on 64-bit platforms. * Windows installer now available. * Include documentation for building clnum on Windows. From onurb at xiludom.gro Tue May 16 12:22:53 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 16 May 2006 18:22:53 +0200 Subject: Help System For Python Applications In-Reply-To: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> References: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> Message-ID: <4469fcc4$0$7745$626a54ce@news.free.fr> redefined.horizons at gmail.com wrote: > I did some searching for this topic, but couldn't find anything. A > search of this list only turned up an old post from 2002. > > I'd like to add a comprehesive help system to my Python Application. By > "comprehensive" I mean regular "read-like-a-book" help and context > sensitive help that can be launched from the application. > > Is there an existing system in Python that would support this, or would > I need to start from scratch? This depends on the system and UI, so their can be no one-size-fits-all builtin solution. Hint : look at how other programs using the same system and UI solved the problem. > On a related note, is there a way to fire up Adobe's Acorbat Reader or > and Web Browser from Python and have the external application open a > specified PDF or HTML file? (For example, I want to open the file > "myhelp.pdf" in reader from Python code.) os.system() may be a good start. HTH -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From george.sakkis at gmail.com Sun May 21 04:20:08 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 21 May 2006 01:20:08 -0700 Subject: python vs perl lines of code In-Reply-To: <Xns97CA11C302CC1castleamber@130.133.1.4> References: <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <Xns97C8A4628E0EBcastleamber@130.133.1.4> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <t3sbg.10640$fb2.6437@newssvr27.news.prodigy.net> <Xns97C8B8D9E17C2castleamber@130.133.1.4> <Pxsbg.10647$fb2.8683@newssvr27.news.prodigy.net> <Xns97C8D420E22castleamber@130.133.1.4> <N2wbg.19102$Lm5.6969@newssvr12.news.prodigy.com> <Xns97C8F38DDC88Ecastleamber@130.133.1.4> <urJbg.73859$_S7.26899@newssvr14.news.prodigy.com> <Xns97C9ADA375FCCcastleamber@130.133.1.4> <lFMbg.19879$Lm5.7431@newssvr12.news.prodigy.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> <Xns97C9B5C01B657castleamber@130.133.1.4> <1148172321.824018.207540@j33g2000cwa.googlegroups.com> <Xns97C9EDC00DC96castleamber@130.133.1.4> <1148189521.803453.142860@j73g2000cwa.googlegroups.com> <Xns97CA11C302CC1castleamber@130.133.1.4> Message-ID: <1148199608.054443.110150@i39g2000cwa.googlegroups.com> John Bokma wrote: > Funny though, how you have a problem with a thread that side steps to Perl > only for 4 or 5 postings, but have no problem with a hit & run post in 5 > groups to spamvertize a site. > > Have fun with the pondering btw. > > -- > John MexIT: http://johnbokma.com/mexit/ > personal page: http://johnbokma.com/ > Experienced programmer available: http://castleamber.com/ > Happy Customers: http://castleamber.com/testimonials.html Oh, I think I get it now. Spamvertizing _one_ site is worth your host's subscription; doing it for _four_ sites at your signature is perfectly ok though. A rare case of irony deficit disorder I suppose. Have a nice day. George From nobody at 127.0.0.1 Wed May 17 20:34:15 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 00:34:15 GMT Subject: Tabs versus Spaces in Source Code ('semantic' vs. arbitrary indentation) References: <mailman.5794.1147861485.27775.python-list@python.org> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <mailman.5802.1147872927.27775.python-list@python.org> <slrne6mc12.hnp.sybrenUSE@schuimige.stuvel.eu> <mailman.5820.1147882817.27775.python-list@python.org> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <e4fofp$8sp$1@sea.gmane.org> <446B6AD1.4080104@mvista.com> <e4fqga$ep3$1@sea.gmane.org> <mailman.5836.1147892571.27775.python-list@python.org> <bvsm62tbdjq5pi7pti17qbukqicja6r985@4ax.com> <slrne6mv9k.ilm.sybrenUSE@schuimige.stuvel.eu> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <mailman.5846.1147904183.27775.python-list@python.org> <1147907634.532463.63730@u72g2000cwu.googlegroups.com> Message-ID: <biPag.18369$Lm5.14502@newssvr12.news.prodigy.com> We've finally hit the meta-discussion point. Instead of talking about tabs and spaces, we're talking about talking about tabs and spaces. Which frankly is a much more interesting conversation anyway. achates wrote: > Does it matter? Perhaps not if we can use tools which enable us to > bridge the divide, like indent auto-detection in emacs and vim. I'm > prepared to do that in cases where I have to work with an existing > group of coders uasing spaces. If you ask me, which of course you didn't, indentation is just one small part of the larger issue of code formatting. Unfortunately it's the only one that allows some semblance of flexibility. Formatting like brace/paren placement and inter-operator spacing greatly affect readability but are hard-coded into the source. And none of this matters a wit to the semantics of the code. What really should happen is that every time an editor reads in source code, the code is reformatted for display according to the user's settings. The editor becomes a parser, breaking the code down into tokens and emitting it in a personally preferred format. Comments are left untouched apart from initial indentation. On output back to a file, the code can be either written as-is (the next guy's editor will reformat it anyway) or put in some standard form (for the poor shlubs who code with cat/notepad). All this becomes completely transparent to the user, who sees every file he edits in exactly the format he's accustomed to. It's similar to the various pushes for syntactic code storage formats like abstract syntax trees or <shudder> xml, but works with the existing infrastructure built around processing plain text files. Meanwhile LISP has been storing code in paren-based ASTs since the 50s. vim and emacs can already do this today. It might not be perfect, but if people spent half as much time perfecting this as arguing about tabs vs spaces, we'd all be a lot better off (yes I'm guilty too). > It's a cruel irony that Python's creator > didn't appreciate the benefits that tab indentation would bring to his > own language - the only major language in which indentation levels > actually have semantic significance. Fate is a cruel mistress. Or maybe just a heartless bitch. Either way, watch your back. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From spohle at gmail.com Fri May 26 13:26:44 2006 From: spohle at gmail.com (spohle) Date: 26 May 2006 10:26:44 -0700 Subject: sort a dictionary by keys in specific order Message-ID: <1148664404.846062.146550@y43g2000cwc.googlegroups.com> hi i have a normal dictionary with key and value pairs. now i wanna sort by the keys BUT in a specific order i determine in a list !? any ideas dic = {'key1':'value1', 'key2':'value2', 'key3':'value3'} list = [key2, key3, key1] From eglez at ast.cam.ac.uk Fri May 26 11:53:17 2006 From: eglez at ast.cam.ac.uk (Eduardo Gonzalez-Solares) Date: Fri, 26 May 2006 16:53:17 +0100 Subject: sybase open client 15_0 In-Reply-To: <BcmdnQxbloXocOjZRVn-rQ@speakeasy.net> References: <NPOdnbx8s-CdcejZRVn-iw@speakeasy.net> <BcmdnQxbloXocOjZRVn-rQ@speakeasy.net> Message-ID: <e5789d$dhg$1@gemini.csx.cam.ac.uk> See: http://www.object-craft.com.au/pipermail/python-sybase/2006-May/000471.html Dan wrote: > I'm running SLES 9.3 on Tyan with 2 single core 64-bit Opteron & 8 GB of > memory and SWAP. > > OCS-15_0 > sybperl-2.18 > python 2.3.5 > > > > "Dan" <bitsandbytes88 at hotmail.com> wrote in message > news:NPOdnbx8s-CdcejZRVn-iw at speakeasy.net... >> I have compiled and installed sybase-.037 , the module to add sybase to >> python. However, when I try to use it I get Import error: >> /usr/local/lib/python2.3/site-packages/sybasect.so >> >> undefined symbol: cs_dt_info >> >> I've seen some posts on the internet with other people having this issue. >> But nothing they've suggested has resolved this issue. Maybe python just >> needs to be installed again or upgraded to support sybase Open Client. >> >> Thanks, >> ~DjK >> > > From rfmeraz at gmail.com Tue May 16 20:34:17 2006 From: rfmeraz at gmail.com (Richard Meraz) Date: Tue, 16 May 2006 17:34:17 -0700 Subject: advice modifying re library to support more than 100 named captures. Message-ID: <f98c79100605161734ia4d9ed2t84651c0ff6d4b9e9@mail.gmail.com> Dear group members, We need to capture more than 99 named groups using python regular expressions. From the docs and from this thread ( http://groups.google.com/group/comp.lang.python/browse_thread/thread/a39a91b4bf8e3df4/2ad4a7e01b60215d?lnk=st&q=python+regular+expression+group+limit&rnum=3#2ad4a7e01b60215d) its clear why the language designers have decided on this limitation. For our system, however, it is essential that we be able to capture an arbitrary number of groups. Could anyone on the list suggest what parts of the library code make assumptions about this restriction? We'd like to make some local changes to the core library to allow us to continue the development of our system (we don't want to switch to another language). We removed the condition in sre_compile.py that raises an exception for compiled regexps with more than 100 groups. This allowed us to compile a regular expression with more than 100 groups, but subsequent attempts to match or search with that regular expression resulted in segfaults. Thanks, Richard Meraz I realize this has been discussed before here: http://groups.google.com/group/comp.lang.python/browse_thread/thread/a39a91b4bf8e3df4/2ad4a7e01b60215d?lnk=st&q=python+regular+expression+group+limit&rnum=3#2ad4a7e01b60215d -- Never think there is anything impossible for the soul. It is the greatest heresy to think so. If there is sin, this is the only sin ? to say that you are weak, or others are weak. Swami Vivekananda -------------- next part -------------- An HTML attachment was scrubbed... URL: <http://mail.python.org/pipermail/python-list/attachments/20060516/e3ee04d6/attachment.html> From onurb at xiludom.gro Thu May 18 05:13:39 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Thu, 18 May 2006 11:13:39 +0200 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> Message-ID: <446c3b2b$0$17368$636a55ce@news.free.fr> glomde wrote: > i I would like to extend python so that you could create hiercical > tree structures (XML, HTML etc) easier and that resulting code would be > more readable than how you write today with packages like elementtree > and xist. > I dont want to replace the packages but the packages could be used with > the > new operators and the resulting IMHO is much more readable. > > The syntax i would like is something like the below: > > # Example creating html tree > '*!*' is an operator that creates an new node, > '*=*' is an operator that sets an attribute. > (snip) > > With syntactical sugar: > > # build a tree structure > root = ET.Element("html") > *!*root: > *!*head("head"): > *!*title("title): > *=*text = "Page Title" > *!*body("body"): > *=*bgcolor = "#ffffff" > *=*text = "Hello, World!" > What about using <XXX>data</XXX> for nodes and '=' for attributes ? Would look like: <html> <head> <title>Page Title Hello World > > I think that with the added syntax you get better view of the html > page. indeed !-) -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From jean.richelle at ulb.ac.be Sun May 14 23:06:11 2006 From: jean.richelle at ulb.ac.be (Jean Richelle) Date: Mon, 15 May 2006 05:06:11 +0200 Subject: Problem with Tkinter on Mac OS X Message-ID: <056074A2-8CDC-4743-AD70-C4ACAC0B0172@ulb.ac.be> Hello, I installed version 2.4.1 (and I tried also with 2.4.3) of Python under 10.3.9 (and 10.4.6), and I trying to use Tkinter. For simplicity I'm testing the "hello world" that I found in the documentation. I first launch IDLE, write (cut and paste from the web) the program in an editing window, save it, and then run it. The window with two buttons is displayed in the back of the IDLE window (and I cannot bring it to the front), and there nothing happening when I click either button. Did anybody do a fresh install recently and can run program using Tkinter ? Jean From invalidemail at aerojockey.com Sun May 21 19:13:01 2006 From: invalidemail at aerojockey.com (Carl Banks) Date: 21 May 2006 16:13:01 -0700 Subject: PEP-xxx: Unification of for statement and list-comp syntax In-Reply-To: References: <200605211711.25043.me+python@modelnine.org> <1148237544.579470.43420@i40g2000cwc.googlegroups.com> <1148247633.377696.157820@38g2000cwa.googlegroups.com> Message-ID: <1148253181.457948.143880@j73g2000cwa.googlegroups.com> Edward Elliott wrote: > Special cases aren't special enough to break the rules. (proposal eliminates > the current special case for comprehensions/generators) It really isn't a special case, though. It might seem like it is, but it's not at all when you remember the rules of equivalence between listcomps and regular statements. This listcomp: [ x for x in y ] is, by definition, semantically equivalent to this (except it's an expression instead of a statement): for x in y: _.append(x) If you have two fors in the listcomp, the second for is equivalent to a nested for. This: [ x for y in z for x in y ] is, by defintion, equivalent to this: for y in z: for x in y: _.append(x) Likewise, an if gets its own nested block in the equivalent statements. This: [ x for x in y if x is not None ] is, by definition, equivalent to this: for x in y: if x is not None: _.append(x) In other words, each for and if in a listcomp is equivalent to a nested block in a regular statement. There's a regular way to nest, and listcomp way, and they're separate. This PEP suggests we should mix them up--now *that's* a special case. Carl Banks From sjmachin at lexicon.net Thu May 25 08:40:19 2006 From: sjmachin at lexicon.net (John Machin) Date: Thu, 25 May 2006 22:40:19 +1000 Subject: a good explanation In-Reply-To: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> References: <1148556478.980423.269150@j55g2000cwa.googlegroups.com> Message-ID: <4475A5B3.6040101@lexicon.net> On 25/05/2006 9:27 PM, s99999999s2003 at yahoo.com wrote: > hi > my friend has written a loop like this > cnt = 0 > files = [a,b,c,d] > while cnt < len(files) : > do_something(files[cnt]) > > i told him using > for fi in files: > do_something(fi) > > is better, because the while loop method makes another call to > len..which is slower.. > am i partly right? or is there a better explanation for using the for > method.? You are partially right. More reasons: (1) It's more elegant; you don't have the "cnt" if you don't need it, there's no extraneous evaluation of len(files). (2) You don't get the chance to omit cnt += 1, like your friend did (ROTFLMAO). Cheers, John From nobody at 127.0.0.1 Thu May 18 19:35:01 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 23:35:01 GMT Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: Ben Finney wrote: > Until we get the code to examine independently, all we have is an > anecdote. Thus the comparison to UFO sightings. Except UFO sightings comprise a large body of data containing a vast number of known false reports and others that appear to be in the same vein with no verified positives despite many concerted efforts to produce such evidence. Here we have a single data point with no positive or negative corroborations. It's like a guy saying he saw a cloud that looks like a python. The cloud's gone now, but other people can watch other clouds and report what they see. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From pwatson at redlinepy.com Tue May 2 08:04:37 2006 From: pwatson at redlinepy.com (Paul Watson) Date: Tue, 02 May 2006 07:04:37 -0500 Subject: --version? Message-ID: <4bp06lF1276vvU1@individual.net> Is there any chance that Python would support the --version command line parameter? It seems that many open source programs use this switch to report their version number. From levub137 at wi.rr.com Sun May 7 12:35:41 2006 From: levub137 at wi.rr.com (Raymond L. Buvel) Date: Sun, 07 May 2006 16:35:41 GMT Subject: printing list In-Reply-To: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> References: <1147018510.282563.230760@j73g2000cwa.googlegroups.com> Message-ID: compboy wrote: > How do you print elements of the list in one line? > > alist = [1, 2, 5, 10, 15] > > so it will be like this: > 1, 2, 5, 10, 15 > > because if I use this code > > for i in alist: > print i > > the result would be like this > > 1 > 2 > 5 > 10 > 15 > > Thanks. > There are a number of ways to do it but if you want a one-liner: print repr(alist)[1:-1] will meet your spec. From birchb at ozemail.com.au Wed May 10 01:04:23 2006 From: birchb at ozemail.com.au (birchb at ozemail.com.au) Date: 9 May 2006 22:04:23 -0700 Subject: Deferred Evaluation in Recursive Expressions? In-Reply-To: References: <1147176742.310487.226720@e56g2000cwe.googlegroups.com> <1147189028.751527.157640@j73g2000cwa.googlegroups.com> Message-ID: <1147237463.261555.58640@y43g2000cwc.googlegroups.com> If we -are- limited to lambdas, I see two options. Either embed lambdas for each circular link, or have the whole expression in one lambda. ie LinkedList3 = (int, lambda: LinkedList3, lambda: TypeNameX) vs LinkedList2 = lambda: (int, LinkedList2, TypeNameX) The second option looks neater. Maybe both are OK? From mtobis at gmail.com Thu May 18 18:58:28 2006 From: mtobis at gmail.com (Michael Tobis) Date: 18 May 2006 15:58:28 -0700 Subject: python vs perl lines of code In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: <1147993108.475434.177030@j55g2000cwa.googlegroups.com> John Bokma wrote: > "akameswaran at gmail.com" wrote: > > Ok I'm going to end with a flamebait - but I would posit, ALL OTHER > > THINGS BEING EQUAL - that a smaller number of characters and lines in > > code is more maintainable than larger number of characters and lines in > > the code. > And I think that's why a lot of people posted very negative, in the hope > that people would not be tempted to make the above very dumb statement. Since it's too late to avoid such temptation, could you explain why you are willing to go so far as to call that statement "very dumb"? I, for one, consider it rather wise. When I am teaching programming, or advocating Python, I generally try to include the following advice, attributed to A. de St.-Exupery: "La perfection est atteinte non quand il ne reste rien ? ajouter, mais quand il ne reste rien ? enlever." The relevant corrolary is, "he programs best who programs least". I would have thought this was conventional wisdom among all dynamic language communities. Isn't that the whole point? By all means go back to C++ if you like to have three lines for each idea instead of the other way around. However, since I habitually make such a fuss about this, I'd hate to be wrong. Please do explain why you think this idea that terseness is a virtue is foolish. mt From Serge.Orlov at gmail.com Thu May 18 20:22:19 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 18 May 2006 17:22:19 -0700 Subject: WTF? Printing unicode strings References: <1147992722.970761.220840@j73g2000cwa.googlegroups.com> Message-ID: <1147998139.268318.315250@y43g2000cwc.googlegroups.com> Ron Garret wrote: > In article <1147992722.970761.220840 at j73g2000cwa.googlegroups.com>, > "Serge Orlov" wrote: > > > Ron Garret wrote: > > > In article , > > > Robert Kern wrote: > > > > > > > Ron Garret wrote: > > > > > > > > > I forgot to mention: > > > > > > > > > >>>>sys.getdefaultencoding() > > > > > > > > > > 'utf-8' > > > > > > > > A) You shouldn't be able to do that. > > > > > > What can I say? I can. > > > > > > > B) Don't do that. > > > > > > OK. What should I do instead? > > > > Exact answer depends on what OS and terminal you are using and what > > your program is supposed to do, are you going to distribute the program > > or it's just for internal use. > > I'm using an OS X terminal to ssh to a Linux machine. In theory it should work out of the box. OS X terminal should set enviromental variable LANG=en_US.utf-8, then ssh should transfer this variable to Linux and python will know that your terminal is utf-8. Unfortunately AFAIK OS X terminal doesn't set that variable and most (all?) ssh clients don't transfer it between machines. As a workaround you can set that variable on linux yourself . This should work in the command line right away: LANG=en_US.utf-8 python -c "print unichr(0xbd)" Or put the following line in ~/.bashrc and logout/login export LANG=en_US.utf-8 From dave at waveform.plus.com Mon May 1 16:49:01 2006 From: dave at waveform.plus.com (Dave Hughes) Date: 01 May 2006 20:49:01 GMT Subject: using ftplib References: Message-ID: <4456743d$0$2563$ed2619ec@ptn-nntp-reader02.plus.net> John Salerno wrote: > I'm experimenting with this now and I'm a little confused about > transferring commands. This might be more of an FTP question than > strictly Python, but it's still related to how to use the ftplib > methods. > > Anyway, if what I want to do is send a command to change the file > permission settings of a file (or files), I assume I would use > transfercmd() and the command would be something like SITE CHMOD 755 > name.py, for example. > > What I'm confused about is why the documentation says to send a PORT > or PASV command as well. Is this just something that must be done > before each command? > > Also, in order to figure out what the FTP commands are to begin with, > I did a little testing in FileZilla and I noted what was being > displayed at the top (things like PORT xxx, STOR xxx, SITE CHMOD, > etc. depending on what I was doing). So I assume these are the 'cmd' > parameter. So here are a couple of questions: > > 1. Are PORT/PASV necessary to start a transfer? Indeed. FTP is a tricky (and _very_ old) protocol that does things in a very different manner to the later (simpler) protocols like HTTP. Not sure how familiar you are with FTP, so my apologies if I wind up repeating stuff you know already: FTP sessions typically have *two* connections: the "control" connection, and the "data" connection. The control connection is from the client to the server (typically port 21 on the server side), and is used to send commands to the server and obtain responses. The PORT command tells the server to open a data connection to the client (yes, that's not a typo: from the server to the client) and the parameters tell the server the address and port to connect to. This is the "active" (or default) mode for FTP (although due to the heavy use of NAT these days, "passive" mode is probably as, or more common in practice). The PASV command is the reverse of the PORT command: it requests the server listen on a new port for a data connection from the client to the server. Data is never transferred over the control connection, it always goes over the separate data connection, hence why PORT or PASV are required before initiating a transfer. See RFC 959 for the full spec (gawd, it's been a long time since I read that ... amazed I still remember the number): http://www.faqs.org/rfcs/rfc959.html > > 2. Is the cmd parameter some kind of list, or is it just a string and > you have to call a separate transfercmd() for each command? Sorry, I haven't used ftplib yet, but a brief glance at the code suggests to me that it's just a string and you probably do need to call a separate transfercmd for each command. > 3. My burning question: also during every transfer I made in > FileZilla, I see that it sometimes sends a TYPE A or TYPE I command > as well. What are these, and are they also necessary when I'm using > transfercmd()? TYPE I indicates that an "Image" transfer is to take place (though this is more commonly referred to nowadays as a "binary" transfer). In an binary transfer the data is transferred verbatim with no transformations. TYPE A indicates that an ASCII transfer is to take place. An ASCII transfer is intended for use with text files and indicates that the data should be transformed from the native text format on the client platform to the native text format on the server platform. For example, transferring a file from a DOS/Windows client to a UNIX/Linux platform in ASCII mode would convert CRLF line endings (ASCII char 13 + ASCII char 10) to LF line endings (ASCII char 10). There are other transfer modes as well, though I forget exactly what they are (there's probably one for EBCDIC :-). Take a look at the storbinary, storlines, retrbinary and retrlines methods of the FTP object: looks like they perform the appropriate TYPE command for you, then pass the specified command to transfercmd. HTH, Dave. -- From harry.g.george at boeing.com Mon May 15 02:13:09 2006 From: harry.g.george at boeing.com (Harry George) Date: Mon, 15 May 2006 06:13:09 GMT Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> Message-ID: Edward Elliott writes: > Eli Gottlieb wrote: > > > Actually, spaces are better for indenting code. The exact amount of > > space taken up by one space character will always (or at least tend to > > be) the same, while every combination of keyboard driver, operating > > system, text editor, content/file format, and character encoding all > > change precisely what the tab key does. > > What you see as tabs' weakness is their strength. They encode '1 level of > indentation', not a fixed width. Of course tabs are rendered differently > by different editors -- that's the point. If you like indentation to be 2 > or 3 or 7 chars wide, you can view your preference without forcing it on > the rest of the world. It's a logical rather than a fixed encoding. > > [snip] This has been discussed repeatedly, and the answer is "If you only work alone, never use anyone else's code and no one ever uses your codes, then do as you please. Otherwise use tab-is-4-spaces." When you do Agile Programming with people using emacs, vim, nedit, xedit, wordpad, eclipse, and who knows what else, the 4-spaces rule is necessary for survival. The reason is simple: People get confused, and accidentally get the wrong tab indents when they move among editors or among settings on the same editor. In most languages this is an irritation, requiring some cleanup. In Python it is a disaster requiring re-inventing the coded algorithms. -- Harry George PLM Engineering Architecture From johnjsal at NOSPAMgmail.com Fri May 19 14:34:32 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Fri, 19 May 2006 18:34:32 GMT Subject: combining a C# GUI with Python code? In-Reply-To: <1148063303.620372.281600@j55g2000cwa.googlegroups.com> References: <3Dnbg.2135$No6.46516@news.tufts.edu> <1148063303.620372.281600@j55g2000cwa.googlegroups.com> Message-ID: Luis M. Gonz?lez wrote: > Now that I think about it, I'm not sure if Visual Studio can create > GUIs with ironpython already. I guess that at this moment, its > integration is as a text editor only (I may be wrong though). > > I almost forgot it, but someone was working in a little tool that > converts C# forms into python classes (for being used with ironpython). > > Check it out: http://www.digitalfanatics.org/e8johan/projects/cs2py/ > Thanks for the information! From micklee74 at hotmail.com Tue May 2 02:53:15 2006 From: micklee74 at hotmail.com (micklee74 at hotmail.com) Date: 1 May 2006 23:53:15 -0700 Subject: blank lines representation in python Message-ID: <1146552795.151721.25380@g10g2000cwb.googlegroups.com> hi what is the correct way to represent blank lines in python (while iterating a file) without regexp? I know one way is to use re.search((line,r'^$') to grab a blank line, but i wanna try not to use regexp... is it 1) if line == ''": dosomething() (this also means EOF right? ) 2) if line is None: dosomething() 3) if not line: dosomething() thanks From a.schmolck at gmail.com Fri May 12 16:06:29 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 12 May 2006 21:06:29 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> <1147418382.845693.253320@u72g2000cwu.googlegroups.com> Message-ID: Ken Tilton writes: > Alexander Schmolck wrote: > > jayessay writes: > > > > >>"Michele Simionato" writes: > >> > >> > >>>I was interested in a proof of concept, to show that Python can > >>>emulate Lisp special variables with no big effort. > >> > >>OK, but the sort of "proof of concept" given here is something you can > >> hack up in pretty much anything. > > > Care to provide e.g. a java equivalent? > > > I think the point is that, with the variable actually being just a string and > with dedicated new explicit functions required as "accessors", well, you could > hack that up in any language with dictionaries. Great -- so can I see some code? Can't be that difficult, it takes about 10-15 lines in python (and less in scheme). > It is the beginnings of an interpreter, not Python itself even feigning > special behavior. > > > perhaps the way to go is to take the Common Lisp: > > (DEFVAR *x*) > > *x* = special_var(v=42) ;; I made this syntax up > > that could make for cleaner code: > > *x*.v = 1 > > print *x*.v -> 1 > > (Can we hide the .v?) I'd presumably write special variable access as something like: with specials('x','y','z'): special.x = 3 + 4 special.y = special.x + 10 ... I haven't tested this because I haven't got the python 2.5 alpha and won't go through the trouble of installing it for this usenet discussion, but I'm pretty sure this would work fine (I'm sure someone else can post an implementation or prove me wrong). I also can't see how one could sensibly claim that this doesn't qualify as an implementation of dynamically scoped variables. Doesn't look any worse to me than (let (x y z) (declare (special x y z)) ...) -- in fact it looks better. > But there is still the problem of knowing when to revert a value to its > prior binding when the scope of some WITH block is left. Can you explain what you mean by this statement? I'm not quite sure but I've got the impression you're a possibly confused. Have you had a look at or some other explanation of the with statement? > Of course that is what indentation is for in Python, so... is that extensible > by application code? The meaning of indentation? No. > Or would this require Python internals work? From johnjsal at NOSPAMgmail.com Wed May 17 14:04:13 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Wed, 17 May 2006 18:04:13 GMT Subject: help with this simple DB script In-Reply-To: <4nkm62lael18tcj60uk4i7ka25n1t4vahc@4ax.com> References: <446a7849$0$1901$c3e8da3@news.astraweb.com> <446aa0cd$0$9395$c3e8da3@news.astraweb.com> <4nkm62lael18tcj60uk4i7ka25n1t4vahc@4ax.com> Message-ID: Dennis Lee Bieber wrote: > Out of curiosity, which SQL reference listed "number" as a data > type? I was taking the sqlcourse.com tutorial yesterday, and it shows it here: http://sqlcourse.com/create.html All the interactive examples in the tutorial seem to work with number(). But after work today I think I will go pick up a copy of the MySQL Pocket Reference, just to have something to easily consult from now on. From deets at nospam.web.de Fri May 5 06:36:14 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 12:36:14 +0200 Subject: Tuple assignment and generators? References: <1146821724.732068.268960@g10g2000cwb.googlegroups.com> <1146824577.242547.315600@y43g2000cwc.googlegroups.com> Message-ID: <4c0o60F13ut8cU1@uni-berlin.de> vdrab wrote: > That, I knew. What I did not know, nor get from this explanation, is > that this behaviour "may" differ > not only within the same implementation, but with instances of the same > class or type (in this case, 'int'). """ E.g., after "a = 1; b = 1", ? ? a and b may or may not refer to the same object with the value one, ? ? depending on the implementation, """ Diez From edreamleo at charter.net Thu May 11 10:00:04 2006 From: edreamleo at charter.net (Edward K. Ream) Date: Thu, 11 May 2006 09:00:04 -0500 Subject: ANN: Leo 4.4 Final released Message-ID: Leo 4.4 Final is now available at: http://sourceforge.net/project/showfiles.php?group_id=3458&package_id=29106 Leo is a text editor, data organizer, project manager and much more. See: http://webpages.charter.net/edreamleo/intro.html The highlights of Leo 4.4: -------------------------- - An Emacs-like mini-buffer: you can now execute any command by typing its long name, with tab completion. - Many new commands, including cursor and screen movement, basic character, word and paragraph manipulation, and commands to manipulate buffers, the kill ring, regions and rectangles. You can use Leo without using a mouse. - Flexible key bindings and input modes. You can emulate the operation of Emacs, Vim, or any other editor. - A tabbed log pane. The Find and Spell Check commands now use tabs instead of dialogs, making those commands much easier to use. Plugins or scripts can easily create new tabs. The Completion tab shows possible typing completions. - Autocompletion and calltips. To enable autocompletion, bind a key to the auto-complete command. - Dozens of other new features and bug fixes since Leo 4.3.3. Links: ------ Leo: http://webpages.charter.net/edreamleo/front.html Home: http://sourceforge.net/projects/leo/ Download: http://sourceforge.net/project/showfiles.php?group_id=3458 CVS: http://leo.tigris.org/source/browse/leo/ Quotes: http://webpages.charter.net/edreamleo/testimonials.html -------------------------------------------------------------------- Edward K. Ream email: edreamleo at charter.net Leo: http://webpages.charter.net/edreamleo/front.html -------------------------------------------------------------------- From steve at holdenweb.com Mon May 1 22:10:48 2006 From: steve at holdenweb.com (Steve Holden) Date: Tue, 02 May 2006 03:10:48 +0100 Subject: Can Python kill a child process that keeps on running? In-Reply-To: References: <1146532884.872505.154370@i40g2000cwc.googlegroups.com> Message-ID: <4456BFA8.30208@holdenweb.com> I. Myself wrote: > Serge Orlov wrote: > >>I. Myself wrote: >> >> >>>Suppose we spawn a child process with Popen. I'm thinking of an >>>executable file, like a compiled C program. >>>Suppose it is supposed to run for one minute, but it just keeps going >>>and going. Does Python have any way to kill it? >>> >>>This is not hypothetical; I'm doing it now, and it's working pretty >>>well, but I would like to be able to handle this run-on condition. I'm >>>using Windows 2000, but I want my program to be portable to linux. >>> >> >>On linux it's pretty easy to do, just setup alarm signal. On windows >>it's not so trivial to the point you cannot do it using python.org >>distribution, you will need to poke in low level C API using win32 >>extensions or ctypes. AFAIK twisted package >>has some code to help you. Also take a look at buildbot sources >> that uses twisted. Buildbot has the same >>problem as you have, it needs to kill run away or non-responding >>processes. >> > > That is bad news. Thanks anyway; bad news is better than no news. > Note, however, that ctypes is planned to be a part of the 2.5 distribution, so while there may not be a platform-independent way to achieve your goals you will at leats be able to do so without external extensions. regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC/Ltd http://www.holdenweb.com Love me, love my blog http://holdenweb.blogspot.com Recent Ramblings http://del.icio.us/steve.holden From robert.kern at gmail.com Wed May 24 17:40:27 2006 From: robert.kern at gmail.com (Robert Kern) Date: Wed, 24 May 2006 16:40:27 -0500 Subject: how to use matplotlib contour()? In-Reply-To: <1279j0o8va1fq12@corp.supernews.com> References: <1279j0o8va1fq12@corp.supernews.com> Message-ID: Grant Edwards wrote: > I downloaded examples/contour_demo.py, and it doesn't run. > > I've searched both the user guide and the Wiki for "contour" > and got zero hits. > > http://matplotlib.sourceforge.net/matplotlib.pylab.html#-contour > appears to be a good reference if you already know how to use > contour(), but I could glean zero clues from it on how to > actually use contour(). For example, it doesn't explain what > the actual formats/types of the parameters. It explains what > the parameters do, but not what they _are_ Yes, unfortunately, much of the documentation was written by people who were very familiar with the Matlab interfaces that these functions are emulating. > For example one parameter is specied as "an array". No clue as > to how many dimensions or what the axis are. > > In another place it says "the X,Y parameters specify the (x,y) > coordinates of a surface". _How_ do they specify the surface? > Are they just equal length lists of x and y coordinates that > specify len(X) points. Or do they specify a len(X) x len(Y) > grid of points? > Why would my Z values be a 2D array? contour() only does contouring on gridded data. If you want to handle scattered datapoints, you will have to do some interpolation. http://www.scipy.org/Cookbook/Matplotlib/Gridding_irregularly_spaced_data So X, Y, and Z are all 2-D arrays laid out corresponding to the grid that you have sampled. I thought the contour_demo.py example was reasonably clear on this, but if you didn't get it to run, then I can see why you wouldn't have read it. Talking about this on matplotlib-users will probably get these problems fixed faster: https://lists.sourceforge.net/lists/listinfo/matplotlib-users -- 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 thestever.net Tue May 2 19:26:53 2006 From: steve at thestever.net (Steve Quezadas) Date: Tue, 02 May 2006 16:26:53 -0700 Subject: Can subprocess point to file descriptor 5? Message-ID: <4457EABD.30002@thestever.net> Hello, I tried posting this to the web forums without much luck. I have some simple subprocess code here: output = subprocess.Popen([/usr/bin/program"], stdout=subprocess.PIPE).communicate()[0] However, /usr/bin/prgram also outputs not only to stdout and stderr but to file descriptor [5]. Can I redirect this output to either a file or a variable? - Steve From scott.daniels at acm.org Sat May 27 17:15:50 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Sat, 27 May 2006 14:15:50 -0700 Subject: Array? Please help. In-Reply-To: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> References: <8W0eg.348$eB3.14@newsread3.news.pas.earthlink.net> Message-ID: <4478bd43$1@nntp0.pdx.net> Dr. Pastor wrote: > I need a row of 127 bytes that I will use as a > circular buffer. Into the bytes (at unspecified times) > a mark (0 After some time the "buffer" will contain the last 127 marks. Sounds a lot like homework. -- --Scott David Daniels scott.daniels at acm.org From ptmcg at austin.rr._bogus_.com Tue May 16 15:18:30 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Tue, 16 May 2006 19:18:30 GMT Subject: round numbers in an array without importing Numeric or Math? - SOLVED, sort of References: <446a1748$0$61168$ae4e5890@news.nationwide.net> <446a2032$0$61167$ae4e5890@news.nationwide.net> Message-ID: "Lance Hoffmeyer" wrote in message news:446a2032$0$61167$ae4e5890 at news.nationwide.net... > The array comes out as unicode. This is probably because I am grabbing the numbers > from a Word Doc using regex's. > > So, before rounding I perform the following: > # Convert to String > Topamax = [str(x) for x in Topamax] > # Convert to floating > Topamax = [float(x) for x in Topamax] > # Finally, round the number > Topamax= [(x+0.5) for x in Topamax] > > Is there a shorter way? > > Lance > > > > Lance Hoffmeyer wrote: > > Is there an easy way to round numbers in an array? > > > > I have > > Test = [1.1,2.2,3.7] > > > > and want to round so the values are > > > > print Test [1,2,4] > > > > > > Lance (c.l.py people don't cotton to top-posting - when in Rome...) # Convert to String, convert to floating, and finally, round the number all in one swell foop Topamax= [int(float(str(x))+0.5) for x in Topamax] -- Paul From tdelaney at avaya.com Wed May 3 23:43:37 2006 From: tdelaney at avaya.com (Delaney, Timothy (Tim)) Date: Thu, 4 May 2006 13:43:37 +1000 Subject: Packet finding and clicking... Message-ID: <2773CAC687FD5F4689F526998C7E4E5FF1E6C2@au3010avexu1.global.avaya.com> Grant Edwards wrote: > On 2006-05-04, klauts wrote: > >> anyone have any help on this subjecT? > > I use tcpdump or ethereal for packet finding. > > For clicking, I use a logitech optical wheel mouse for desktops > or the integrated touchpoint/touchpad on my IBM ThinkPad. Or in other words ... http://www.catb.org/~esr/faqs/smart-questions.html Tim Delaney From ramen at lackingtalent.com Tue May 16 18:18:38 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 16 May 2006 15:18:38 -0700 Subject: Time to bundle PythonWin In-Reply-To: References: Message-ID: <9esag.99116$k%3.70060@dukeread12> Ten wrote: > Respectfully, that sounds like a reason for *you* to bundle pythonwin (and > python, to be honest :) ), not a reason for everyone else to have to download > an extra 40-50% of potentially superfluous cruft with their standard python > setup. Certainly, I could bundle Python and PythonWin myself. I'll even admit that my little office utilities would be better distributed as frozen .exe files with all the necessary libraries bundled inside. But my original problem as stated was this: 1. I release a Python script (a .py file) 2. My user upgrades or switches computers 3. They (logically) download and install Python 4. My script still doesn't work 5. They ask me for help At this point, I dig through four or five web sites to find where PythonWin is hosted these days, and it's obvious that my user never would have guessed to download it, or found the right place to retrieve it. If the windows installer for Python came with PythonWin, they might not have needed my help at all. I realize that other people's needs aren't the same as mine, but this scenario isn't contrived. This has happened numerous times. Bundling PythonWin myself wouldn't solve this particular problem as stated. > In more general terms I can see why it would be useful to some windows people > to have more winapi stuff available. I can still think of quite a few things > I'd rather be spending that extra download time on myself, though, like a > sexed-up tkinter or maybe even a new gui toolkit. I'd happily download a larger installer for any or all of these things. In the time it took me to write this, I'd probably already have finished the download anyway. > Still, it's not an either/or choice, I suppose. Yep. =) Cheers, Dave From nobody at 127.0.0.1 Mon May 22 13:15:42 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 22 May 2006 17:15:42 GMT Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> Message-ID: <2lmcg.90657$dW3.29599@newssvr21.news.prodigy.com> SamFeltus wrote: > 1. Loss of back button > Isn't this really a myth? A page with a time dimension, be it Flash, > HTML/JS or whatever, breaks the back button. A page without a time > dimension doesn't break the back button. Should we now and forever > more give up the time dimension to avoid breaking the back button. > Perhaps for non-text sites, the back button is an anachronism? A time-based push model of content delivery, that would be television. One of the web's defining features is it lets you retrieve information in your own order at your own pace. Pages with an unalterable 'time dimension' are nothing more than interactive tv at best. Flash is a fine technology, just not a good one for the web. It's appropriate for games and video clips embedded in a page and that's about it. Other content has no business being in Flash. Usability problems aren't just an artifact of the implementation, they're part of Flash's design. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From john at castleamber.com Wed May 24 11:29:19 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:29:19 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> <447479A1.8050809@hotORgooMAIL.invalid> Message-ID: Mitch wrote: > John Bokma wrote: > [...] >> You're mistaken. All you need to do is report it. After some time Xah >> will either walk in line with the rest of the world, or has found >> somewhere else to yell. As long as it's not my back garden and not >> around 4AM, I am ok with it. >> > > Walk in line with the rest of the world? Pah. > > This is no-ones back garden. Funny how people who always think they can "change Usenet" have no clue about what Usenet is and how it works in the first place. Usenet is just that, each server participating can be thought of as being the back yard of the news master. If you have no clue about how Usenet works, first read up a bit. What a Usenet server is, a feed, and how Usenet is distributed. And then come back if you finally have something to say that you can back up. -- 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 bborcic at gmail.com Tue May 2 16:22:46 2006 From: bborcic at gmail.com (Boris Borcic) Date: Tue, 02 May 2006 22:22:46 +0200 Subject: [SPOILER] Re: simultaneous assignment In-Reply-To: References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> Message-ID: <4457bf9e$1_6@news.bluewin.ch> John Salerno wrote: > bruno at modulix wrote: > >> Now if I may ask: what is your actual problem ? > > Ok, since you're so curious. :) > > Here's a scan of the page from the puzzle book: > http://johnjsalerno.com/spies.png > > Basically I'm reading this book to give me little things to try out in > Python. There's no guarantee that this puzzle is even conducive to (or > worthy of) a programming solution. def spyAreports(W,X,Y,Z) : return W+X+Y == X+Y+Z == W+Z == 1*True def spyBreports(W,X,Y,Z) : return W+X+Y == X+Y+Z == W+Y+Z == 1*True ft = (False,True) possibilities = [(W,X,Y,Z) for W in ft for X in ft for Y in ft for Z in ft] def testReport(report,name) : print name+"'s report", n=sum(report(*possibility) for possibility in possibilities) if n>0 : if n == len(possibilities) : print "must", else : print "may", else : print "can not", print "be true" testReport(spyAreports,"Spy A") testReport(spyBreports,"Spy B") From zhushenli at gmail.com Mon May 8 06:56:39 2006 From: zhushenli at gmail.com (Davy) Date: 8 May 2006 03:56:39 -0700 Subject: Python's regular expression? In-Reply-To: <1147085552.824265.128220@i39g2000cwa.googlegroups.com> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> <1147085552.824265.128220@i39g2000cwa.googlegroups.com> Message-ID: <1147085799.402161.86500@j73g2000cwa.googlegroups.com> By the way, is there any tutorial talk about how to use the Python Shell (IDE). I wish it simple like VC++ :) Regards, Davy From tim.peters at gmail.com Fri May 26 19:07:11 2006 From: tim.peters at gmail.com (Tim Peters) Date: Fri, 26 May 2006 23:07:11 +0000 Subject: Thread vs. generator problem In-Reply-To: <7xodxkmmzl.fsf_-_@ruckus.brouhaha.com> References: <7xodxkmmzl.fsf_-_@ruckus.brouhaha.com> Message-ID: <1f7befae0605261607r299032damda8316222629132d@mail.gmail.com> [Paul Rubin] > ... > When I try to do it in a separate thread: > > import time, itertools > def remote_iterate(iterator, cachesize=5): > # run iterator in a separate thread and yield its values > q = Queue.Queue(cachesize) > def f(): > print 'thread started' > for x in iterator: > q.put(x) > threading.Thread(target=f).start() > while True: > yield q.get() > > g = remote_iterate(itertools.count) You didn't run this code, right? itertools.count() was intended. In any case, as when calling any generator, nothing in the body of remote_iterate() is executed until the generator-iterator's next() method is invoked. Nothing here does that. So, in particular, the following is the _only_ line that can execute next: > print 'zzz...' And then this line: > time.sleep(3) And then this: > print 'hi' And then this: > for i in range(5): And then the first time you execute this line is the first time any code in the body of remote_iterate() runs: > print g.next() > > I'd expect to see 'thread started' immediately, then 'zzz...', then a 3 > second pause, then 'hi', then the numbers 0..4. Instead, the thread > doesn't start until the 3 second pause has ended. That's all as it must be. > When I move the yield statement out of remote_iterate's body and > instead have return a generator made in a new internal function, it > does what I expect: > > import time, itertools > def remote_iterate(iterator, cachesize=5): Note that remote_iterate() is no longer a generator, so its body is executed as soon as it's called. > # run iterator in a separate thread and yield its values > q = Queue.Queue(cachesize) > def f(): > print 'thread started' > for x in iterator: > q.put(x) > threading.Thread(target=f).start() And so the thread starts when remote_iterate() is called. > def g(): > while True: > yield q.get() > return g() > > Any idea what's up? Is there some race condition, where the yield > statement freezes the generator before the new thread has started? No. > Or am I just overlooking something obvious? No, but it's not notably subtle either ;-) From johnjsal at NOSPAMgmail.com Mon May 1 10:37:47 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 01 May 2006 14:37:47 GMT Subject: critique this little script, if you like In-Reply-To: References: <44554a32$0$11750$c3e8da3@news.astraweb.com> <874q0aa8em.fsf@localhost.localdomain> Message-ID: <%2p5g.2018$No6.43931@news.tufts.edu> Roel Schroeven wrote: > But watch out with leading backslashes, as in > > subdirs = [r'\cgi-bin', r'\images', r'\styles'] > > os.path.join will assume they are meant to be absolute paths, and will > discard all previous components: > > >>> os.path.join('base', 'subdomain', r'\images') > '\\images' > > In fact I think it's best to specify components without leading or > trailing backslashes (unless you really want an absolute path): > > >>> os.path.join('base', 'subdomain', 'images') > 'base\\subdomain\\images' Yeah, I made the list of subdirectories just strings, like 'cgi-bin' and took out the backslash. Then I used os.path.join to create those subdirectories on the end of the main directory. It always amazes me how posting here can lead to little tweaks that really clean up my code. :) From cjw at sympatico.ca Wed May 3 12:00:15 2006 From: cjw at sympatico.ca (cjw at sympatico.ca) Date: 3 May 2006 09:00:15 -0700 Subject: Numeric Python In-Reply-To: <1146670803.379440.19010@g10g2000cwb.googlegroups.com> References: <1146670803.379440.19010@g10g2000cwb.googlegroups.com> Message-ID: <1146672015.562567.281540@v46g2000cwv.googlegroups.com> Numeric => numarray => numpy is in a state of transition. It might be better if you installed the latest version of numpy. Colin W. From gene.tani at gmail.com Fri May 26 09:22:52 2006 From: gene.tani at gmail.com (gene tani) Date: 26 May 2006 06:22:52 -0700 Subject: Can any body help me In-Reply-To: <1148621554.184942.155430@38g2000cwa.googlegroups.com> References: <1148621554.184942.155430@38g2000cwa.googlegroups.com> Message-ID: <1148649772.730662.163680@i39g2000cwa.googlegroups.com> satish wrote: > how to write script for these > > 1.Given a test file containing lines of words such as (abc, abb, > abd,abb, etc), write a script that prints, in order of frequency, how > many times each word appears in the file. > > 2. > Write a script running in an endless loop that pings an IP (specified > on the command line) periodically. If the IP goes down n times in a row > 1. #include "We won't do your homework" and "don't you think your prof reads the list?" 2. #include link about asking smart questions 3. don't know where you are in your python learning, but all the code you need is in the online Python cookbook somewhere (search "ping IP address" and "heartbeat" http://aspn.activestate.com/ASPN/Cookbook/Python From nobody at 127.0.0.1 Sat May 20 22:39:00 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 02:39:00 GMT Subject: Feature request: sorting a list slice References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> <1147974696.448816.119100@i39g2000cwa.googlegroups.com> Message-ID: <8pQbg.79596$H71.75692@newssvr13.news.prodigy.com> John Machin wrote: > Use case? quicksort! :) -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From onurb at xiludom.gro Wed May 3 04:58:12 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Wed, 03 May 2006 10:58:12 +0200 Subject: simultaneous assignment In-Reply-To: <44580e23$0$5389$c3e8da3@news.astraweb.com> References: <8dM5g.2031$No6.43874@news.tufts.edu> <44579c58$0$23113$626a54ce@news.free.fr> <4457dadd$0$9654$636a55ce@news.free.fr> <44580e23$0$5389$c3e8da3@news.astraweb.com> Message-ID: <445870fe$0$479$626a54ce@news.free.fr> John Salerno wrote: > Bruno Desthuilliers wrote: > >> But my question (sorry, it may not have been clear) was more along the >> line of : "why do you worry about identity in the given snippet ?". > > > Actually, I kind of thought that maybe it *didn't* matter in this > particular example anyway, so my question was meant to be more general > than I might have written it. It seems like the identity issue can be a > problem in certain cases, although I can't think of a case right now! :) something a = b = [] a.append(1) print b -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From liuliuliu at gmail.com Sat May 20 17:08:55 2006 From: liuliuliu at gmail.com (liuliuliu at gmail.com) Date: 20 May 2006 14:08:55 -0700 Subject: 'error reading datastream' -- loading file only when transfer is complete? Message-ID: <1148159335.678868.22850@j73g2000cwa.googlegroups.com> hello -- i'm running python/pygame on maemo (nokia 770). my situation is that i'm continually scouring this one directory for incoming files. if i see if there's a new file (coming in via wireless scp), i proceed to load it and process it. however, i think i am running into the issue that my program starts to load the file after it recognises there is new data, but before the file has completely transferred, so at unpredictable times i get a pygame.error: Error reading from datastream. what is the easiest way to work out this issue? easy being the key word. :) thank you very much! christine From dongdonglove8 at hotmail.com Fri May 19 00:36:39 2006 From: dongdonglove8 at hotmail.com (dongdong) Date: 18 May 2006 21:36:39 -0700 Subject: how could I get all email address in a html page? Message-ID: <1148013399.715307.326120@j55g2000cwa.googlegroups.com> how could I get all email address in a html page? Have any modle can do this? like the htmldata.urlextract . From lepto.python at gmail.com Sun May 28 05:12:59 2006 From: lepto.python at gmail.com (oyster) Date: Sun, 28 May 2006 17:12:59 +0800 Subject: any advanced table module for wxpython? Message-ID: <6a4f17690605280212n4d5c64cct353fb249651d34ee@mail.gmail.com> Just like excel or vb does. A grid always looks like a normal grid, and can acts as a normal gird, where we can input some text. but when we click the right-most part, this grid becomes a choice widget, so we can choose some pre-defined gizmo; or it becomes a file-selector, and there is a button with "..." on it, the selected file name is filled; or it pops up a coluor/font choose dialog. It seems that wxpython supports the choice only. thank you -------------- next part -------------- An HTML attachment was scrubbed... URL: From r.pellegrini at gmail.com Sun May 28 17:22:55 2006 From: r.pellegrini at gmail.com (Rocco) Date: 28 May 2006 14:22:55 -0700 Subject: why not in python 2.4.3 In-Reply-To: References: <1148843825.610615.250830@y43g2000cwc.googlegroups.com> Message-ID: <1148851375.148311.320780@g10g2000cwb.googlegroups.com> This is the problem when I run the function this is the result from 2.3.5 >>> print rss NFE/1.0Google News ItaliaGoogle News ItaliaGoogle Inc.news-feedback at google.com&copy;2006 Google2006-05-28T19:09:13+00:00 Benedetto XVI: Wojtyla santo subito - Libert? tag:news.google.com,2005:cluster=41b535fbPrima pagina2006-05-28T11:05:00+00:002006-05-28T11:05:00+00:00<br><table border=0 align= cellpadding=5 cellspacing=0><tr><td width=80 align=center valign=top><a ..... >>> import sys >>> sys.getdefaultencoding() 'ascii' >>> this is the result with 2.4.3 >>> print rss ? >>> rss '\x1f\x8b\x08\x00\x00\x00\x00\x00\x02\xff\xe5}Ks\xe3F\xb6\xe6\xfeF\xdc\xff\x90\xd77\xba\xc3\x9e\x10D\xbc\x01\xcaU\xee\xa1\x9eM[\xa2\xd4$\xabl\xf7\x86\x93\x04\x93Tv\x81H\x1a\x0fV\xa9V\xfe\x0f3\x9b\x8e\x98\x89\xb8\xcb\x1b\xd1\xb3\x9a\xddD\xef\xec\x7f\xe2_2\xe7$\x00\x8a/\x11|\x93\xd6\xb4\xa3U"\x04\x02\x99\xe7d\x9e<\xdfy\xbe\xf9\xd3\xa7\xbeO\x86,\x8c\xb8\x08\xde~\xa1\x9d\xaa_\x10\x16x\xa2\xc3\x83\xde\xdb/\xde5\xaf\x15\xf7\x8b?}\xf3&\x8c\xa2\xe7\x9bt\xb8\xe9\x9b7\xde#\r\x02\xe6\x7f\xf3\xa6\xc7\x02\x16\xd2X\x84\xdf\xd4\xae\xafJ\xf0\x847\xa5\xe7Kob\x1e\xfb\xec\x9b\x1b!z>#5\xf61"\xd5\x98\xfa\x9c\xbe)\xa5\x7fy\xe3\xf3\xe0\xc37\x8fq<8+\x95\x02\xf8\xfbiO\xde{\xca\xe3\xd2\x9b\x92\xfc\xe3\x9b\x0e\x8b\xbc\x90\x0fbx\xfb\xdc\'\x8d\xff\xfd\x8dO\x83^B{\xec\x1b\x1e\xc3\xf7\xf3\x0fo>\xb2\xf6\x1d\x8db\x16~\x83/Q\xba\x8cu\xda\xd4\xfb\xf0_\xb3\xb7y\xa2\xff\xa6\xf4|\xcf\x1bO\x0c\x9eB\xde{\x8c\xbf\xf9#\xed\x0f\xbe\xc6\x8f_\xeb\xaaj\x93\xf4\xfdoJ\xcf7\xbc\x19$\xedK\x1a\xb3o\x1aIpBt\x97\xdc\xd1\'"\xef\xd5\xb53\xcd<3\x1crs\xd7|S\xcao\x83\x11F\xf1y\xc2\xfd\xce2\xdf\x9a\xbc\xf9_\xff\xe5\xcd\xbf)\n\xa9\x10O$\x03 C b\x16\x9d\xfd\xeb\xbf\x10\xfc\xdf\x7f!\xb4\xd3!4 _\x88$\x1e$\xf1[\xe0\xda\x17d at C\xda\'\xb1 =\x16\x93z\xa31\xba9b\x1eR\x0cn\xe8\xb1\x88<\xd2!#\x94|\x11\x8b\x01\xf7\xde\xfe)\xfb\xde\xd7\xd9\xdd\x84$\x11\xcb\xff\xf8\xf8\x05\xe9\x8a\x10nn\x8a\x01i\x00\x979|?{\xda\xe9\xbf\xfe\x8b\xa2|\xf3\x86\xf7%\xd1\x0b\x99\x9f\x84\xfe<\xde\x037J<\x88\xfd\x12\x8f[\xb0\x0e\xe4\xd3"yG+dp\x17\xef\xbe)\xe1W\x97Y<\xa5l,~\xfcx\xca\xfd\x18_\x82\x0f\xa1\x83A(\xba"\xe8\xf0>\x0bb\x0e\x04\xea\xb0O\xa74\x >>> import sys >>> sys.getdefaultencoding() 'latin_1' >>> No exception trace Thanks again From andychambers2002 at yahoo.co.uk Sun May 28 04:07:16 2006 From: andychambers2002 at yahoo.co.uk (andychambers2002 at yahoo.co.uk) Date: 28 May 2006 01:07:16 -0700 Subject: dynamic type changing References: <1148740408.226975.318050@u72g2000cwu.googlegroups.com> <44787bc6$0$19572$636a55ce@news.free.fr> Message-ID: <1148803636.370761.55540@j33g2000cwa.googlegroups.com> >> I'm working on a "TempFile" class that stores the data in memory until >> it gets larger than a specified threshold (as per PEP 42). Whilst >> trying to implement it, I've come across some strange behaviour. Can >> anyone explain this? >> The test case at the bottom starts a TempFile at size 50 and prints its >> type. It then increases the size to the threshold at which point >> "self" is changed to being a TemporaryFile. > Changed how ?-) Just by being assigned with a TemporaryFile object. I thought that if you do instance = TempFile() that "instance" and "self" defined in the Class were the same thing so that if you changed the class of self, the class of instance would also change. Thanks very much for your example. It has solved my problem and helped me understand a new pattern at the same time. From mumia.w.18.spam+fbi.gov at earthlink.net Sun May 21 20:01:35 2006 From: mumia.w.18.spam+fbi.gov at earthlink.net (Mumia W.) Date: Mon, 22 May 2006 00:01:35 GMT Subject: Software Needs Philosophers In-Reply-To: References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> <1148225181.251089.261160@j55g2000cwa.googlegroups.com> Message-ID: M Jared Finder wrote: > SamFeltus wrote: >> [...] >> Software needs philosophers is an interesting point, perhaps the most >> important function of Philosophers is exposing Sacred Cows as just >> Cattle. > > Finally, someone else who sees that Xah's posts consistently expose > valid problems! (Though his solutions are usually not well thought out.) > > -- MJF I agree, Xah's articles make you think. Although in this case, it's a blog article by Steve Yegge that Xah evidently got permission to post. Software *does* need philosophers, but the more I think about the implications of that, the more I think it's scary. From alf at merlin.fayauffre.org Wed May 31 15:49:01 2006 From: alf at merlin.fayauffre.org (Alexandre Fayolle) Date: Wed, 31 May 2006 19:49:01 +0000 (UTC) Subject: using import * with GUIs? References: Message-ID: Le 31-05-2006, John nous disait: > Hi all. Quick question (but aren't they all?) :) > > Do you think it's a good idea to use the 'from import *' > statement when using a GUI module? It seems on wxPython's site, they > recommend using import wx nowadays, but I wonder if that advice is > followed. Also, I'm still reading some Tkinter docs that seem to use > 'from Tkinter import *' a lot. > > I understand the danger of doing this, but is it safer in these cases, > given the more specific names that GUI frameworks tend to use > (sometimes!)? Or should you still qualify all your calls with the module? Don't overlook the "import module as shortname" construct, which is a real lifesaver for large modules when you'd rather avoid importing * Common idiom when using Numeric/numarray/numpy is import Numeric as N Importing Tkinter as tk is imo worth it. -- Alexandre Fayolle 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 sigzero at gmail.com Thu May 11 18:55:48 2006 From: sigzero at gmail.com (Robert Hicks) Date: 11 May 2006 15:55:48 -0700 Subject: Time to bundle PythonWin In-Reply-To: References: Message-ID: <1147388148.406918.76040@q12g2000cwa.googlegroups.com> No it isn't. It is a Windows only package. It needs to stay a separate download. Robert From nx13441a at net.vodafone.pt Thu May 4 08:00:04 2006 From: nx13441a at net.vodafone.pt (jonas) Date: 4 May 2006 05:00:04 -0700 Subject: pleac In-Reply-To: References: <1146740749.200368.173590@g10g2000cwb.googlegroups.com> Message-ID: <1146744004.881232.250760@y43g2000cwc.googlegroups.com> Thanks Fredrik, i'm going to buy the book. After all, there's nothing about the Python language power! thank you. From cablepuff at hotmail.com Sun May 7 03:31:20 2006 From: cablepuff at hotmail.com (chun ping wang) Date: Sun, 07 May 2006 00:31:20 -0700 Subject: python rounding problem. Message-ID: Hey i have a stupid question. How do i get python to print the result in only three decimal place... Example>>> round (2.995423333545555, 3) 2.9950000000000001 but i want to get rid of all trailing 0's..how would i do that? _________________________________________________________________ Express yourself instantly with MSN Messenger! Download today - it's FREE! http://messenger.msn.click-url.com/go/onm00200471ave/direct/01/ From nick at craig-wood.com Wed May 17 07:30:03 2006 From: nick at craig-wood.com (Nick Craig-Wood) Date: Wed, 17 May 2006 06:30:03 -0500 Subject: Tabs versus Spaces in Source Code References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147737979.892505.33010@i40g2000cwc.googlegroups.com> <1147800175.234540.279960@i40g2000cwc.googlegroups.com> <1147812497.596178.114500@38g2000cwa.googlegroups.com> <1147816939.467976.202120@j73g2000cwa.googlegroups.com> <1147853776.367091.254700@u72g2000cwu.googlegroups.com> Message-ID: Ant wrote: > I think Duncan has hit the nail on the head here really. I totally > agree that conceptually using tabs for indentation is better than using > spaces. As a programmer tabs appeal to our sense of neatness in python code. One tab for each level of indent - very nice. Back in the last century when I wrote nothing but assembler in a series of primitive text editors I would have agreed with you. Tabs rule! label TAB opcode TAB arguments TAB ; comment. > Pragmatically though, you can't tell in an editor where spaces > are used and where tabs are used. Now-a-days when I am writing Python, I just use emacs which indents perfectly. I press tab and emacs inserts the correct of indentation. Most of the time I don't have to press tab at all - emacs knows how much indentation I need. I don't actually care whether emacs inserts spaces or tabs (spaces actually), it works, looks nice and follows PEP 8. It's a lot less keystrokes than writing assember too ;-) If you are writing python using "cat" or "ed" then tabs might matter again, but for any modern editor with a python mode it really doesn't matter! > The following quote sums things up nicely I think: > > "In theory there is no difference between theory and practice, but in > practice there is." ;-) -- Nick Craig-Wood -- http://www.craig-wood.com/nick From kano.priv at gmail.com Tue May 16 09:23:14 2006 From: kano.priv at gmail.com (Lee Caine) Date: Tue, 16 May 2006 14:23:14 +0100 Subject: taking qoutes in arguments In-Reply-To: <87k68mrisa.fsf@benfinney.id.au> References: <98063b170605150748h3d0fffddibd6f8de28fff3d4f@mail.gmail.com> <87k68mrisa.fsf@benfinney.id.au> Message-ID: <98063b170605160623h2eca5a04xf106264d7909ef8f@mail.gmail.com> yea thanks alot for your help, gonna read up on 'Konsole' :) -------------- next part -------------- An HTML attachment was scrubbed... URL: From skip at pobox.com Tue May 16 13:05:18 2006 From: skip at pobox.com (skip at pobox.com) Date: Tue, 16 May 2006 12:05:18 -0500 Subject: [silly] Does the python mascot have a name ? In-Reply-To: <446A0363.5040205@mvista.com> References: <446A0363.5040205@mvista.com> Message-ID: <17514.1614.971362.276063@montanaro.dyndns.org> Carl> To be honest, Monty really makes the most sense to me for a mascot Carl> name... now if we can only get past all that damn copyright Carl> infringement ;) My dad's nickname was Monty. Some friends of my son, Chris, call him Monty as well. I doubt either of them would object. (Dad's gone, Chris does a little Python programming from time-to-time.) I say go for it... Skip (Montanaro) From mystilleef at gmail.com Mon May 8 10:54:03 2006 From: mystilleef at gmail.com (mystilleef) Date: 8 May 2006 07:54:03 -0700 Subject: Designing Plug-in Systems in Python References: <1146893983.268034.206080@e56g2000cwe.googlegroups.com> Message-ID: <1147100043.699412.79300@i39g2000cwa.googlegroups.com> Thanks for the pointers. From robert.kern at gmail.com Sun May 21 21:43:08 2006 From: robert.kern at gmail.com (Robert Kern) Date: Sun, 21 May 2006 20:43:08 -0500 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <44710145.6040603@serveisw3.net> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <44710145.6040603@serveisw3.net> Message-ID: Gonzalo Monz?n wrote: > sturlamolden escribi?: >>I don't think this is safe. MinGW links with msvcrt.dll whereas the >>main Python distribution links with msvcr71.dll (due to Visual C++ >>2003). It is not safe to mix and blend different C runtime libraries. >>If you are to build a C extension with MinGW, you also need to build >>Python against msvcrt.dll, i.e. you have to use a Python built with >>MinGW or Visual C++ 6.0. There other option is to make MinGW link >>against msvcr71.dll. I don't know if that is feasible. > > I use Python 2.4.3 (msvcrt71) and I succesfully installed the last > version of binutils, pyrex and MinGW, some weeks ago, using Julien Fiore > step-by-step guide, so "my" MinGW is linking with msvcrt71.dll, with the > default configuration. > > I don't understand why do you say MinGW links with msvcrt.dll... perhaps > you've got an older version than the ones Julien posted? Nope. He said it because it is true. Use Dependency Walker (http://www.dependencywalker.com) to see for yourself what DLLs are linked in. In fact, *both* DLLs are linked in. Sometimes this works fine, other times it does not. If you would like a more visceral demonstration, write a small C++ extension that uses std::cout. -- 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 Wed May 10 10:45:25 2006 From: michele.simionato at gmail.com (Michele Simionato) Date: 10 May 2006 07:45:25 -0700 Subject: New tail recursion decorator In-Reply-To: <1147253776.042505.34430@j73g2000cwa.googlegroups.com> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> Message-ID: <1147272325.625020.108840@y43g2000cwc.googlegroups.com> Kay Schluehr wrote: > for all those who already copied and pasted the original solution and > played with it I apologize for radical changes in the latest version ( > the recipe is on version 1.5 now ! ). The latest implementation is > again a lot faster than the previous one. It does not only get rid of > exceptions but also of stack-frame inspection. This is spectacular!! I would rewrite it as follows: CONTINUE = object() # sentinel value returned by iterfunc def tail_recursive(func): """ tail_recursive decorator based on Kay Schluehr's recipe http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/496691 """ var = dict(in_loop=False, cont=True, argkw='will be set later') # the dictionary is needed since Python closures are read-only def iterfunc(*args, **kwd): var["cont"] = not var["cont"] if not var["in_loop"]: # start looping var["in_loop"] = True while True: res = func(*args,**kwd) if res is CONTINUE: args, kwd = var["argkw"] else: var["in_loop"] = False return res else: if var["cont"]: var["argkw"] = args, kwd return CONTINUE else: return func(*args,**kwd) return iterfunc Using my decorator module 'tail_recursive' can even be turned in a signature-preserving decorator. I think I will add this great example to the documentation of the next version of decorator.py! Michele Simionato From aleax at mac.com Tue May 9 01:44:58 2006 From: aleax at mac.com (Alex Martelli) Date: Mon, 8 May 2006 22:44:58 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1147106666.402541.114270@g10g2000cwb.googlegroups.com> Message-ID: <1hf1iq2.o3lae1fgte55N%aleax@mac.com> Joe Marshall wrote: ... > Doesn't Google also employ such people as the inventor of Limbo > programming language, one of the inventors of Dylan, and a Smalltalk > expert? ...not to mention Lisp gurus (such as Peter Norvig), C++ gurus (such as Matt Austern) and Java ones (such as Josh Bloch) [[and I'm certainly forgetting many!]]. The difference, if any, is that gurus of Java, C++ and Python get to practice and/or keep developing their respectively favorite languages (since those three are the "blessed" general purpose languages for Google - I say "general purpose" to avoid listing javascript for within-browser interactivity, SQL for databases, XML for data interchange, HTML for web output, &c, &c), while the gurus of Lisp, Limbo, Dylan and Smalltalk don't (Rob Pike, for example, is one of the architects of sawzall -- I already pointed to the whitepaper on that special-purpose language, and he co-authored that paper, too). Alex From claird at lairds.us Thu May 11 16:21:19 2006 From: claird at lairds.us (Cameron Laird) Date: Thu, 11 May 2006 20:21:19 +0000 Subject: 2 books for me References: <87lkt9ytxx.fsf@localhost.localdomain> <4462f24d$0$311$636a55ce@news.free.fr> <1147375933.114803.40870@q12g2000cwa.googlegroups.com> Message-ID: In article , Ed Leafe wrote: >On May 11, 2006, at 3:32 PM, Robert Hicks wrote: > >> Wouldn't portability go with Tkinter since that is installed with >> every >> Python? > > Dunno about other platforms, but it's not on my Mac. . . . ? It's on mine ... While I invite someone to falsify this, I believe it's standard with Mac OS 10.4.X and above, for most values of X. From johnjsal at NOSPAMgmail.com Tue May 23 11:40:19 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 23 May 2006 15:40:19 GMT Subject: Valid SQL? In-Reply-To: <1148391055.270620.105920@u72g2000cwu.googlegroups.com> References: <1148383118.187847.197700@j33g2000cwa.googlegroups.com> <1148390464.318455.53750@u72g2000cwu.googlegroups.com> <1148391055.270620.105920@u72g2000cwu.googlegroups.com> Message-ID: Harlin Seritt wrote: > I am using the exact same query string generated and it works when i > type it in the MySQL client but doesn't work when using the MySQLdb > module. I've been messing around with mysqldb lately, and one reason I get your error message is if I'm not closing parentheses properly. Can you paste the exact Python code that you are using here, as well as the MySQL code used in the client window? I assume in the client you use a semicolon, but in Python you don't? I don't know if you'd get that particular error if the problem is something like the values not matching to their type, especially since you say it works on the client but not in Python. From maxerickson at gmail.com Fri May 5 10:43:30 2006 From: maxerickson at gmail.com (Max Erickson) Date: Fri, 5 May 2006 14:43:30 +0000 (UTC) Subject: cross platform libraries References: <1146761835.888206.148970@e56g2000cwe.googlegroups.com> <1146836899.678804.168000@g10g2000cwb.googlegroups.com> Message-ID: diffuser78 at gmail.com wrote in news:1146836899.678804.168000 at g10g2000cwb.googlegroups.com: > I went to this webpage > > http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/360649 > > Isn't it supposed to run on the network and close the connected > machine. That code uses the windows libraries on the machine it is run on to generate a request to the networked machine to shutdown. The code executes locally and sends the request over the network. > Every help is appreciate, > If you have some way of remotely running programs on the windows machine(ssh, telnet, etc.), you might try pstools: http://www.sysinternals.com/Utilities/PsTools.html specifically, psshutdown. max From claudio.grondi at freenet.de Wed May 17 15:30:02 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Wed, 17 May 2006 21:30:02 +0200 Subject: Large Dictionaries In-Reply-To: <1147874585.728471@teuthos> References: <1147699064.107490@teuthos> <1147772420.405097@teuthos> <1147818548.532882.94180@i39g2000cwa.googlegroups.com> <1147874585.728471@teuthos> Message-ID: Chris Foote wrote: > Klaas wrote: > >>> 22.2s 20m25s[3] >> >> >> 20m to insert 1m keys? You are doing something wrong. > > > Hi Mike. > > I've put together some simplified test code, but the bsddb > module gives 11m for 1M keys: > I have run your code for the bsddb on my P4 2.8 GHz and have got: Number generator test for 1000000 number ranges with a maximum of 3 wildcard digits. Wed May 17 16:34:06 2006 dictionary population started Wed May 17 16:34:14 2006 dictionary population stopped, duration 8.4s Wed May 17 16:34:14 2006 StorageBerkeleyDB population started Wed May 17 16:35:59 2006 StorageBerkeleyDB population stopped, duration 104.3s Surprising here, that the dictionary population gives the same time, but the BerkeleyDB inserts the records 6 times faster on my computer than on yours. I am running Python 2.4.2 on Windows XP SP2, and you? > Number generator test for 1000000 number ranges > with a maximum of 3 wildcard digits. > Wed May 17 22:18:17 2006 dictionary population started > Wed May 17 22:18:26 2006 dictionary population stopped, duration 8.6s > Wed May 17 22:18:27 2006 StorageBerkeleyDB population started > Wed May 17 22:29:32 2006 StorageBerkeleyDB population stopped, duration > 665.6s > Wed May 17 22:29:33 2006 StorageSQLite population started > Wed May 17 22:30:38 2006 StorageSQLite population stopped, duration 65.5s As I don't have SQLite installed, it is interesting to see if the factor 10 in the speed difference between BerkeleyDB and SQLite can be confirmed by someone else. Why is SQLite faster here? I suppose, that SQLite first adds all the records and builds the index afterwards with all the records there (with db.commit()). Can the same be done in BerkeleyDB, or does BerkeleyDB not support inserting of records without building an index each single insert command? If yes, how? Claudio > > test code is attached. > >> With bdb's it is crucial to insert keys in bytestring-sorted order. > > > For the bsddb test, I'm using a plain string. (The module docs list a > string being the only datatype supported for both keys & values). > >> Also, be sure to give it a decent amount of cache. > > > The bsddb.hashopen() factory seems to have a bug in this regard; if you > supply a cachesize argument, then it barfs: > > .... > File "bsddb-test.py", line 67, in runtest > db = bsddb.hashopen(None, flag='c', cachesize=8192) > File "/usr/lib/python2.4/bsddb/__init__.py", line 288, in hashopen > if cachesize is not None: d.set_cachesize(0, cachesize) > bsddb._db.DBInvalidArgError: (22, 'Invalid argument -- > DB->set_cachesize: method not permitted when environment specified') > > > I'll file a bug report on this if it isn't already fixed. > > Cheers, > Chris > > > ------------------------------------------------------------------------ > > import bsddb > import random > import time > import sqlite > > import psyco > psyco.full() > > class WallClockTimer(object): > '''Simple timer for measuring tests.''' > def __init__(self, msg): > self.start = time.time() > self.msg = msg > print time.ctime(self.start), self.msg, 'started' > > def stop(self): > end = time.time() > duration = end - self.start > print time.ctime(end), self.msg, 'stopped, duration %.1fs' % duration > > class NumberGen(object): > '''Phone number generator for testing different methods of storage.''' > def __init__(self, range_start, range_end, n, max_wildcards): > > print '''Number generator test for %d number ranges > with a maximum of %d wildcard digits.''' % (n, max_wildcards) > > wildcards = range(0, max_wildcards + 1) > # generate n unique numbers and store as keys in number_hash > timer = WallClockTimer('dictionary population') > self.number_hash = {} > > for i in xrange(0, n): > unique = False > while not unique: > wildcard_digits = self.gen_wildcard_digits(wildcards) > num = self.gen_number(range_start, range_end) > if wildcard_digits > 0: > num /= (10 ** wildcard_digits) > key = (num, wildcard_digits) > if self.number_hash.has_key(key): > unique = False > else: > unique = True > self.number_hash[key] = None > timer.stop() > > def gen_wildcard_digits(self, wildcards): > return random.choice(wildcards) > > def gen_number(self, start, end): > return int(random.uniform(start, end)) > > def storage_test(self, StorageTestClass): > test = StorageTestClass(self.number_hash) > > class StorageTest(object): > '''base class for testing storage. Derive a test > class and provide your own runtest() method.''' > def __init__(self, number_hash): > timer = WallClockTimer('%s population' % type(self).__name__) > self.runtest(number_hash) > timer.stop() > > class StorageBerkeleyDB(StorageTest): > def runtest(self, number_hash): > db = bsddb.hashopen(None, flag='c', cachesize=8192) > for (num, wildcard_digits) in number_hash.keys(): > key = '%d:%d' % (num, wildcard_digits) > db[key] = None > db.close() > > class StorageSQLite(StorageTest): > def runtest(self, number_hash): > db = sqlite.connect(':memory:') > cursor = db.cursor() > cursor.execute('CREATE TABLE numbers (num INTEGER, wd INTEGER)') > q = """insert into numbers (num, wd) values (%d, %d)""" > for (num, wildcard_digits) in number_hash.keys(): > cursor.execute(q, num, wildcard_digits) > db.commit() > db.close() > > > if __name__ == '__main__': > > test_vals = {'range_start' : 61880 * 10 ** 7, > 'range_end' : 61891 * 10 ** 7, > 'n' : 1 * 10 ** 4, > 'max_wildcards' : 3} > > ngen = NumberGen(test_vals['range_start'], test_vals['range_end'], > test_vals['n'], test_vals['max_wildcards']) > > ngen.storage_test(StorageBerkeleyDB) > ngen.storage_test(StorageSQLite) From johnjsal at NOSPAMgmail.com Tue May 9 15:26:12 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Tue, 09 May 2006 19:26:12 GMT Subject: multiline strings and proper indentation/alignment In-Reply-To: <4460d5b3$1@nntp0.pdx.net> References: <4460d5b3$1@nntp0.pdx.net> Message-ID: Scott David Daniels wrote: > John Salerno wrote: >> How do you make a single string span multiple lines, but also allow >> yourself to indent the second ... without causing the newlines and >> tabs or spaces to be added to the string as well? > > >> self.DTD = '''> "http://www.w3.org/TR/html4/strict.dtd">\n\n''' >> >> ..., but I don't want the extra newline or tabs to be a part of the >> string when it's printed. > > The easiest way: > > self.DTD = (' '"http://www.w3.org/TR/html4/strict.dtd">\n\n') > > Adjacent strings are combined at compile-time, and parens around allows > you to do a multi-line expression. > > --Scott David Daniels > scott.daniels at acm.org Thanks guys. Looks like both of your suggestions are pretty much the same thing, which is putting strings next to one another. Something about it looks wrong, but I guess it works!) From softwindow at gmail.com Wed May 24 05:52:17 2006 From: softwindow at gmail.com (softwindow) Date: 24 May 2006 02:52:17 -0700 Subject: hi,every body. a problem with PyQt. In-Reply-To: <1148463700.936915.279470@i40g2000cwc.googlegroups.com> References: <1148462180.457715.157360@i40g2000cwc.googlegroups.com> <1148463003.324183.279350@y43g2000cwc.googlegroups.com> <1148463700.936915.279470@i40g2000cwc.googlegroups.com> Message-ID: <1148464336.960828.199950@j55g2000cwa.googlegroups.com> but in my computer pyuic is not a valid commond may be i don't install something,but i have installed PyQt4. From bruno at modulix.org Fri May 26 08:25:28 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 26 May 2006 05:25:28 -0700 Subject: dict literals vs dict(**kwds) In-Reply-To: <1148480921.004282.134490@38g2000cwa.googlegroups.com> References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> <1148424591.982669.225430@i39g2000cwa.googlegroups.com> <447417c1$0$22094$626a54ce@news.free.fr> <1148480921.004282.134490@38g2000cwa.googlegroups.com> Message-ID: <1148646327.998387.294310@y43g2000cwc.googlegroups.com> > Hm, as far as I know shadowing the builtins is discouraged. *accidentally* shadowing builtins is a common Python gotcha - that's why it's comon here to raise *warnings* about this. Explicitly and knowingly rebinding a builtin (or any other name FWIW) *with a compatible object* is something else. Just google for "monkey-patching". And yes, it *is* an application of duck-typing. >In either case, I would guess that for the vast majority of cases the > builtin dicts are just fine That's probably why there are so many uses of dict-like objects (starting with the __dict__ attribute of classes, which is usually a DictProxy object) and so many helpers to build dict-like objects. > and there's no compelling reason for dict(**kwds). Yes there is : this *is* the ordinary Python syntax - calling a type to get an instance of it. The dict-litteral syntax is mostly syntactic sugar. > Perhaps it's something that should be reconsidered for Py3K Hopefully not. The fact that you fail to understand why a given feature exists and how it can be useful is not a reason to ask for arbitrary restrictions on the language. From me+python at modelnine.org Wed May 17 14:35:20 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 17 May 2006 20:35:20 +0200 Subject: Pyparsing: Grammar Suggestion. 2nd thought In-Reply-To: <200605172024.18470.me+python@modelnine.org> References: <3d00e6dc0605171105u3ff919ffke9e07b6b6f71dc08@mail.gmail.com> <200605172024.18470.me+python@modelnine.org> Message-ID: <200605172035.20801.me+python@modelnine.org> Am Mittwoch 17 Mai 2006 20:24 schrieb Heiko Wundram: > If I'm not completely mistaken, parsers written using PyParsing can accept > a small superset of all languages that an N/DFA can accept, Okay, forget what I said about PyParsing here; using Forward(), you can create recursion, but it took an O'Reilly article to find out about this. ;-) --- Heiko. From larswarholm at gmail.com Thu May 4 09:23:23 2006 From: larswarholm at gmail.com (Lars) Date: 4 May 2006 06:23:23 -0700 Subject: Problem building extension under Cygwin (ImportError: Bad address) In-Reply-To: References: <1146739813.157265.238320@i39g2000cwa.googlegroups.com> Message-ID: <1146749003.095894.281280@j73g2000cwa.googlegroups.com> Thanks Jason, it works now. There seems to be some sort of issue with ld in cygwin when compiling shared libraries (e.g. DLL's). This worked on my Cygwin installation also: ------------------------------ gcc hello.c -I/usr/include/python2.4/ -L/usr/lib/python2.4/config/ -lpython2.4 -shared -o hello.dll python hellouse.py (gives the right answer) -------------------------------- But first compiling hello.c with gcc, then linking it with gnu-ld just won't work. I only really need to compile one C-file to a shared library so it doesn't matter so much for me. But bigger projects will have a problem.. ------------------------------------------ gcc -c hello.c -I/usr/include/python2.4/ ld -shared hello.o -o hello.so -L /usr/lib/python2.4/config -lpython2.4 -lc python hellouse.py Traceback (most recent call last): File "hellouse.py", line 1, in ? import hello ImportError: Bad address ------------------------------------------- -Lars From mshelor at cpan.org.an.ism Sun May 21 08:49:04 2006 From: mshelor at cpan.org.an.ism (Mark Shelor) Date: Sun, 21 May 2006 05:49:04 -0700 Subject: Software Needs Philosophers In-Reply-To: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> Message-ID: <5lZbg.6992$KB.1650@fed1read08> Xah Lee wrote: > Programming languages are religions. For a long while now I've been > mildly uncomfortable calling it ?religion?, but I don't feel bad > about it anymore. They're similar enough. At the top of the language > religion is the language itself; it serves as the deity and the object > of worship. Programmers often display religious devotion to their chosen language(s). But that's a reflection of the programmer, not of the language. Programming languages are nothing more than instruments: a means for describing the process of computation. Any given language has no meaning or significance above and beyond its use as an instrument for describing and performing computations. What's the need for religion or mysticism, other than to impart false importance to problems that are already well-understood? There's no measurable value or progress in such an endeavor. Instrumentalism is a more constructive path. > Problem is, each time you switch religions, the next one has less > impact on you. Once a Catholic, always a Catholic, they say. I don't > know what that means for me, since I was raised by the > assembly-language wolf, but it appears to mean that I'm never going to > be enthralled with another programming language. And now that I've > swallowed the red pill, what choice do I have? I need to try to show > people what's out there. Is there really something new out there? I would argue that software needs innovation more than it needs philosophers. Mark From jonkje at gmail.com Thu May 25 17:22:50 2006 From: jonkje at gmail.com (jonkje at gmail.com) Date: 25 May 2006 14:22:50 -0700 Subject: Multi-dimensional list initialization trouble Message-ID: <1148592170.709560.307030@j55g2000cwa.googlegroups.com> Hello I found this very strange; is it a bug, is it a "feature", am I being naughty or what? >>> foo = [[0, 0], [0, 0]] >>> baz = [ [0]*2 ] * 2 >>> foo [[0, 0], [0, 0]] >>> baz [[0, 0], [0, 0]] >>> foo[0][0]=1 >>> baz[0][0]=1 >>> foo [[1, 0], [0, 0]] >>> baz [[1, 0], [1, 0]] Why on earth does foo and baz behave differently?? Btw.: Python 2.4.1 (#1, Apr 10 2005, 22:30:36) [GCC 3.3.5] on linux2 --- Jon ?yvind From mailper at gmail.com Fri May 5 07:37:04 2006 From: mailper at gmail.com (Per) Date: 5 May 2006 04:37:04 -0700 Subject: (question) How to use python get access to google search without query quota limit Message-ID: <1146829024.301402.282540@e56g2000cwe.googlegroups.com> I am doing a Natural Language processing project for academic use, I think google's rich retrieval information and query-segment might be of help, I downloaded google api, but there is query limit(1000/day), How can I write python code to simulate the browser-like-activity to submit more than 10k queries in one day? applying for more than 10 licence keys and changing them if query-quota-exception raised is not a neat idea... From me+python at modelnine.org Fri May 26 06:39:56 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Fri, 26 May 2006 12:39:56 +0200 Subject: getattr for modules not classes In-Reply-To: References: <5f56302b0605211252k79b642efl5ff4653fe7d17768@mail.gmail.com> Message-ID: <200605261239.56209.me+python@modelnine.org> Am Mittwoch 24 Mai 2006 15:43 schrieb Piet van Oostrum: > >>>>> Heiko Wundram (HW) wrote: > > > >HW> y.py > >HW> --- > >HW> from x import test > >HW> print test.one > >HW> print test.two > >HW> print test.three > >HW> --- > > Or even: > import x > x = x.test > print x.one > print x.two > print x.three Or even: --- from x import test as x print x.one print x.two print x.three --- --- Heiko. From akameswaran at gmail.com Thu May 18 19:49:29 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 16:49:29 -0700 Subject: python vs perl lines of code In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> <1147993108.475434.177030@j55g2000cwa.googlegroups.com> Message-ID: <1147996169.818933.252420@u72g2000cwu.googlegroups.com> John, Your hilarious... I mean it, and as a compliment. But seriously, I think your taking a discussion about trends and twisting them to be about absolutes. Maybe others are too. But, forgive the cheesy paraphrasing, but the solution should be as simple as possible, and no simpler. There is no real problem with choosing a set of coding principals and sticking with them. Honestly, I don't think there currently exists a good method of comparing true software quality. So most discussion on which coding principals are actually useful, is kinda like talkin to miss Cleo. Still there is some value in seeing how closely software can align with certain principals. Right now we are asking questions about terseness. The obvious follow up is what relation does terseness have to quality? We are in a better postition to answer the second question if we know the first. When our preconceived notions cause us to study something, they should be encouraged. When our preconceived notions cause us to say, "forget it, a waste of time", we should question them. I don't think anyone in this discussion has shown themselves to be a zealot. For the most part we've just been asking questions. From nobody at 127.0.0.1 Sat May 20 18:55:12 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sat, 20 May 2006 22:55:12 GMT Subject: python vs perl lines of code References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> <1148072317.975060.42970@j33g2000cwa.googlegroups.com> <1148073990.938267.320410@38g2000cwa.googlegroups.com> <1148164747.641393.68350@g10g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > Not trying to be as ass, but can you take this offline or at least in a > perl newsgroup ? Arguing on a particular fact or speculation about the > perl community is rather unproductive and offtopic for a python > newsgroup. No offense taken. It's definitely OT. I left it here because 1) comp.lang.python seems pretty lax about going OT when it's related to the thread, which in this case it was, and 2) the general discussion about what constitutes a community seemed kinda useful. That said, I definitely think the discussion has run its course. It's getting dangerously close to flaming at this point, which indicates it's time to go offline. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From stijndesaeger at gmail.com Fri May 5 05:09:31 2006 From: stijndesaeger at gmail.com (vdrab) Date: 5 May 2006 02:09:31 -0700 Subject: Tuple assignment and generators? In-Reply-To: <4c0hueF12dnv0U1@uni-berlin.de> References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <4c0hueF12dnv0U1@uni-berlin.de> Message-ID: <1146820171.032245.205870@i40g2000cwc.googlegroups.com> > beasts. It can get even worse: I can define an object (in C++ as well as in > python) that is not even equal to itself. Not that I felt the need for that > so far.... hehe... now you've picked my curiosity... how? ps. def __eq__(self, other): return False does not count ! From python.list at tim.thechases.com Thu May 25 21:24:13 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Thu, 25 May 2006 20:24:13 -0500 Subject: Speed up this code? In-Reply-To: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> Message-ID: <447658BD.8040307@tim.thechases.com> > def rmlist(original, deletions): > return [i for i in original if i not in deletions] > > original will be a list of odd numbers and deletions will be numbers > that are not prime, thus this code will return all items in original > that are not in deletions. For n > 100,000 or so, the program takes a > very long time to run, whereas it's fine for numbers up to 10,000. > > Does anybody know a faster way to do this? (finding the difference all > items in list a that are not in list b)? Testing for membership in an unsorted list is an O(n) sort of operation...the larger the list, the longer it takes. I presume order doesn't matter, or that the results can be sorted after the fact. If this is the case, it's quite efficient to use sets which provide intersection/difference/union methods. If you pass in sets rather than lists, you can simply return original.difference(deletions) It's almost not worth calling a function for :) There's also an in-place version called difference_update(). Once you've found all the results you want, and done all the set differences you want, you can just pass the resulting set to a list and sort it, if sorted results matter. -tkc From bearophileHUGS at lycos.com Wed May 3 08:32:53 2006 From: bearophileHUGS at lycos.com (bearophileHUGS at lycos.com) Date: 3 May 2006 05:32:53 -0700 Subject: ANN: ShedSkin 0.0.8 Message-ID: <1146659573.611592.104150@i39g2000cwa.googlegroups.com> Just released the version 0.0.8 of ShedSkin, the Python ==> C++ compiler. Blog, the last post contains some notes about Summer of Code and some open problems: http://shed-skin.blogspot.com/ Thesis about SS, with lot of info, useful for people that want to help this project too: http://kascade.org/optimizing_python.pdf The new site, just created: http://mark.dufour.googlepages.com/home To download it: http://shedskin.sourceforge.net/ Bye, bearophile From rwrii at charter.net Wed May 24 17:55:39 2006 From: rwrii at charter.net (rwr) Date: 24 May 2006 14:55:39 -0700 Subject: Compiling Python from Sources Message-ID: <1148507739.036611.216530@j55g2000cwa.googlegroups.com> As a newbie I am having problems/errors configuring Python after unpacking the Python archive: # ./configure checking MACHDEP... linux2 checking EXTRAPLATDIR... checking for --without-gcc... no checking for --with-cxx=... no checking for c++... no checking for g++... no checking for gcc... gcc checking for C++ compiler default output file name... configure: error: C++ compiler cannot create executables See `config.log' for more details. Any help on my current dilemma??? TIA, rwr From p4sync at yahoo.com Wed May 10 04:32:03 2006 From: p4sync at yahoo.com (- C Saha -) Date: Wed, 10 May 2006 01:32:03 -0700 (PDT) Subject: Error : 10053, 'Software caused connection abort' Message-ID: <20060510083203.38341.qmail@web38913.mail.mud.yahoo.com> Hi All I have a mail function in my pythin code and seems like due to that I am getting this error when ever I am running the pythin code. Any idea, how to resolve this? Error is = (10053, 'Software caused connection abort') My code is ============================================================================= "test.py" import os import sys import smtplib def df(): """ This function checks the Available space in each drive. """ #Command for C drive df -k | grep /cygdrive/c | awk '{print $5}' | awk -F"%" '{print $1}' cmd = "df -k | grep cygdrive"#| grep /cygdrive/c | awk '{print $5}' | awk -F"%" '{print $1}'") text = '' try: f = os.popen (cmd + " 2>&1") text = f.readlines() if len(text)!=0: drive=[] for i in range(0,len(text)): temp = text[i].split() if len(temp[0])==2: perct = int(temp[4].rstrip("%")) if perct>=20: drive.append((temp[0],perct)) if len(drive)>0: sendmailTo(drive) retval = f.close () if retval!= None: raise Exception(text + "\nCommand '%s' failed with return value:%d" % (command, retval)) except Exception, ex: print ex def sendmailTo(drv): """ """ fromaddr="sender at mail.com' toaddrs=['me at mail.com','you at mail.com'] msg = ("From: %s\r\nTo: %s\r\nSubject: %s\r\n\r\n" % (fromaddr, ", ".join(toaddrs),"Test mail")) server = smtplib.SMTP('mail.smtpmail.com') print "TESTSSS" server.sendmail(fromaddr, toaddrs, msg) server.quit() df() ============================================================================= Thanks a lot to all in advance ==================== Thanks & Regards CSaha __________________________________________________ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com -------------- next part -------------- An HTML attachment was scrubbed... URL: From akameswaran at gmail.com Thu May 18 18:44:10 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 18 May 2006 15:44:10 -0700 Subject: python vs perl lines of code In-Reply-To: References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> <1147986336.050431.51180@y43g2000cwc.googlegroups.com> Message-ID: <1147992249.990822.249450@g10g2000cwb.googlegroups.com> Thank you Ed for your eloquent statement. From now on I will avoid humor in posts on this thread , my previous attempts were not useful or productive - and I think there is something interesting in this discussion. It might be interesting to come up with a coding assignment for developers to attempt in both perl and python. Ask the developers to submit such items as length of time coding in each language, which they think is their "stronger" language, age, level of formal education in computer science and related, number of years programming all together, country of origni, Operating System perference, etc. Then perform analysis on the code an attempt to normalize for the above factors. In addtion to line/char counts we could look at execution time, memory consumption, number of detected bugs. Of course this means getting a bunch of developers interested in the task - and the words of Andrew Tannenbaum come to mind. But it would still be interesting - perhaps nothing could be proven - but that in itself might be useful. Physical beauty in humans is an area where some quantitifiable analysis can be performed (referring to a strong correlation between symmetry and percieved beauty). Beauty in poetry - to the best of my knowledge - has never been shown itself to be subject to quantitative analysis. Sometimes knowing what doesn't work - and proving it doesn't work - can be very useful. Don't believe me? Thgis is a bad example, but look at hidden variables theorems in quantum physics. Back the 40's Turing provided (a flawed) proof that no hidden variables theory could explain the quantum effects witnessed. Hence no viable hidden variable theories were even posited and this area of research nearly died out. It has had a slight resurgance, after Turing's proof was found to relate to specific subset of hidden variable theorems, rather than a truly generic proof. But I think it illustrates the value of proving a negative. From tim.golden at viacom-outdoor.co.uk Wed May 24 03:29:28 2006 From: tim.golden at viacom-outdoor.co.uk (Tim Golden) Date: 24 May 2006 00:29:28 -0700 Subject: No math module?? In-Reply-To: References: Message-ID: <1148455768.093063.170830@j73g2000cwa.googlegroups.com> Tim Roberts wrote: > WIdgeteye wrote: > > > >On Tue, 23 May 2006 12:40:49 +1000, Ben Finney wrote: > > > >Ok this is weird. I checked: > >/usr/local/lib/python2.3/lib-dynload/math.so > > > >Just as you have on your system and it's there. > >So why in the heck isn't it loading with: > >import math ???? > > > >This is strange. > > Is the Python that you are running actually 2.3? Some Linux systems have > both Python 1 and a Python 2 installed. Typing "python" at a command line > often gets Python 1, because the vendor's configuration scripts assume > that. Maybe he's running a UK-based distro which has renamed the math module to maths? (I have to work really hard to remember *not* to put the "s" on the end when I import it! ;-) TJG From george.sakkis at gmail.com Tue May 23 18:49:52 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 23 May 2006 15:49:52 -0700 Subject: dict literals vs dict(**kwds) References: <1148398779.586585.101000@u72g2000cwu.googlegroups.com> <447388e7$0$12284$626a54ce@news.free.fr> Message-ID: <1148424591.982669.225430@i39g2000cwa.googlegroups.com> Bruno Desthuilliers wrote: > George Sakkis a ?crit : > > Although I consider dict(**kwds) as one of the few unfortunate design > > choices in python since it prevents the future addition of useful > > keyword arguments (e.g a default value or an orderby function), I've > > been finding myself lately using it sometimes instead of dict literals, > > for no particular reason. Is there any coding style consensus on when > > should dict literals be preferred over dict(**kwds) and vice versa ? > > using dict literals means that you'll always have a builtin dict - you > cannot dynamically select another dict-like class. OTHO, you can only > use valid python identifiers as keys with dict(**kw). This is all good but doesn't answer my original question: under which circumstances (if any) would {'name':'Mike, 'age':23} be preferred over dict(name='Mike', age=23) and vice versa, or if it's just a matter of taste, similar to using single vs double quote for string literals (when both are valid of course). George From ilitzroth at gmail.com Wed May 24 07:00:47 2006 From: ilitzroth at gmail.com (ilitzroth at gmail.com) Date: 24 May 2006 04:00:47 -0700 Subject: John Bokma harassment In-Reply-To: <44-dnSw6EOzlqOnZRVny3g@bt.com> References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> Message-ID: <1148468447.577714.203450@j73g2000cwa.googlegroups.com> I agree there are limits to you right to free speech, but I believe Xah Lee is not crossing any boundaries. If he starts taking over newspapers and TV stations be sure to notify me, I might revise my position. Immanuel From nobody at 127.0.0.1 Sun May 21 18:35:41 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 22:35:41 GMT Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> Message-ID: <1X5cg.20478$Lm5.15710@newssvr12.news.prodigy.com> Roel Schroeven wrote: > SamFeltus schreef: >> Here is a visual argument, I would love to see a list of AJAX and SVG >> sites that display excellent graphics. [snip] > > In my humble opinion, those sites are an argument _against_ the use of > Flash on websites. They may look pretty (I don't think they do, but I > can imagine there are people out there who like the looks of those > sites), but they fail as websites: long load times and especially such > horrible navigation is a big no-no. A quote regarding web usability comes to mind: "If you're website starts winning design awards, be afraid. Be very afraid." Unfortunately I can't locate proper attribution. It may have been Jakob Nielsen. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From manstey at csu.edu.au Wed May 24 19:38:41 2006 From: manstey at csu.edu.au (manstey) Date: 24 May 2006 16:38:41 -0700 Subject: pickling multiple dictionaries In-Reply-To: References: <1148444653.078683.194750@u72g2000cwu.googlegroups.com> Message-ID: <1148513921.463640.60170@j55g2000cwa.googlegroups.com> Thanks very much. How large is *really* large for making pytables worthwhile. Our python script generates an xml file of about 450Mb. Is pytables worth using then? From scott.daniels at acm.org Wed May 31 12:45:10 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Wed, 31 May 2006 09:45:10 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <127ra71smt8mgd3@corp.supernews.com> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <447c8c6e$1@nntp0.pdx.net> <1149016823.214610.258930@r44g2000cwb.googlegroups.com> <447cadf6$1@nntp0.pdx.net> <127ra71smt8mgd3@corp.supernews.com> Message-ID: <447dc3b7$1@nntp0.pdx.net> Jim Segrave wrote: > In article <447cadf6$1 at nntp0.pdx.net>, > Scott David Daniels wrote: >> class FileReIterable2(object): >> ... >> def __iter__(self): >> self.file.seek(0) >> for line in self.file: >> nextpos = self.file.tell() >> yield line >> self.file.seek(nextpos) > > Hmm - I tried this with 'one.file' being ... letters, one per line: > > gen = FileReIterable2("one.file") > for a in gen: > for b in gen: > print a.strip(), b.strip() > > which didn't produce lines 'a a', 'a b', etc. It produced the single > line 'a a', then stopped.... Oops. This works in Python 2.5 (and later) because the file.tell and file.seek code are aware of the file iteration buffering. Since I am trying to test all of my stuff on 2.5, that is what I am using by default. > Rewriting the __iter__ method to not internally iterate over the file > object, as follows, works .... > > class FileReIterable2(object): > ... > def __iter__(self): > self.file.seek(0) > while True: > line = self.file.readline() > if line == '': raise StopIteration > nextpos = self.file.tell() > yield line > self.file.seek(nextpos) This fix does in fact provide working behavior for Pythons before 2.5. --Scott David Daniels scott.daniels at acm.org From bdesth.quelquechose at free.quelquepart.fr Wed May 3 20:31:58 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Thu, 04 May 2006 02:31:58 +0200 Subject: noob question: "TypeError" wrong number of args In-Reply-To: References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: <44591cc4$0$25304$626a54ce@news.free.fr> Marc 'BlackJack' Rintsch a ?crit : (snip) > > Okay, let's start with writing a simple text processor for this little > mess:: > > def b(c): > def d(r, *s, **t): > print '***' > c(r, *s, **t) > return d > > What a nice, readable, highly pythonic code... (snip) From harlinseritt at yahoo.com Tue May 23 09:21:04 2006 From: harlinseritt at yahoo.com (Harlin Seritt) Date: 23 May 2006 06:21:04 -0700 Subject: Valid SQL? In-Reply-To: References: <1148383118.187847.197700@j33g2000cwa.googlegroups.com> Message-ID: <1148390464.318455.53750@u72g2000cwu.googlegroups.com> Thanks for the help. I set up the SQL statement to be like: INSERT INTO tblFoo (field1, field2) VALUES ('value1', 'value2') I get this error: insert into Web1_DLTDS10_RootSite (dateTime, values) values('Sat Apr 15 08:58:13 2006', '0') Traceback (most recent call last): File "librarian.py", line 45, in ? Cursor.execute(InsertValuesSQL) File "C:\Python24\lib\site-packages\MySQLdb\cursors.py", line 137, in execute self.errorhandler(self, exc, value) File "C:\Python24\lib\site-packages\MySQLdb\connections.py", line 33, in defau lterrorhandler raise errorclass, errorvalue _mysql_exceptions.ProgrammingError: (1064, "You have an error in your SQL syntax ; check the manual that corresponds to your MySQL server version for the right s yntax to use near 'values) values('Sat Apr 15 08:58:13 2006', '0')' at line 1") Any idea why I'm getting this? Thanks, Harlin Seritt From wrstuden at wasabisystems.com Wed May 17 19:11:13 2006 From: wrstuden at wasabisystems.com (William Studenmund) Date: Wed, 17 May 2006 16:11:13 -0700 Subject: Tabs are EVIL *and* STUPID, end of discussion. (Re: Tabs versus Spaces in Source Code) In-Reply-To: References: <1147658680.357664.280170@g10g2000cwb.googlegroups.com> <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <_2Jag.88816$dW3.57801@newssvr21.news.prodigy.com> Message-ID: <8AB336BC-9D94-4DD7-B0CE-19BD5B2377A3@wasabisystems.com> -----BEGIN PGP SIGNED MESSAGE----- Hash: SHA1 On May 17, 2006, at 8:46 PM, Edward Elliott wrote: > Dave Hansen wrote: > >> On Wed, 17 May 2006 17:28:26 GMT in comp.lang.python, Edward Elliott >>> Just for the sake of completeness: >>> >>> cat file |sed 's/\t/ /g' >> >> That doesn't always work. If you don't see why, you don't understand >> my objection to TAB characters in text files. >> >>> less -x4 file >> >> That will work. As long as the creator of file used four-space TABs, >> anyway... > > I fail to see why less 'will work' but cat 'doesn't always work'. > The net > effect of both is the same. Unless you're in some weird place that > pipes > aren't allowed, these should be equivalent: I don't think that cat is the problem, it's sed. The problem is that tabs take you to the next tab stop, they don't expand to a fixed number of spaces. Consider the strings "\t\t", "\t \t", and "\t \t". With everything except one- or two-space tab settings (less -x1 or less -x2), the spaces haven't moved us past a tab stop, so the \t after them takes us to the same tab stop in all cases. Take care, Bill -----BEGIN PGP SIGNATURE----- Version: GnuPG v1.4.1 (Darwin) iD8DBQFEa62XDJT2Egh26K0RAhFUAJ0WWgTRS570DsHAUl0oij47qNoIfgCgiVyV 9vZQUBAOspWLfuom2Scy4MY= =wmWa -----END PGP SIGNATURE----- From lard at tardis.ed.ac.molar.uk Sun May 7 14:59:10 2006 From: lard at tardis.ed.ac.molar.uk (Alex Hunsley) Date: Sun, 07 May 2006 18:59:10 GMT Subject: algorithmic mathematical art In-Reply-To: <1146996866.280944.313050@y43g2000cwc.googlegroups.com> References: <1146996866.280944.313050@y43g2000cwc.googlegroups.com> Message-ID: <2sr7g.235940$8Q3.106391@fe1.news.blueyonder.co.uk> Xah Lee wrote: > i've long time been interested in algorithmic mathematical art. That > is, mathematical or algorithmic visual art works that are generated by > computer such that the program's source code reflects the algorithmic > essence of the visual quality in the art work. (for detail, see > Algorithmic Mathematical Art at > http://xahlee.org/Periodic_dosage_dir/t1/20040113_cmaci_larcu.html Oh, speaking of escher, try the following: http://occular.livejournal.com/89597.html Turns out it's in Wolfram's book. Interesting looking. From akameswaran at gmail.com Sat May 27 00:45:22 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 26 May 2006 21:45:22 -0700 Subject: iterator? way of generating all possible combinations? Message-ID: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> Ok, this is really irritating me. I'm sure there are different ways of doing this - I'm interested in the algo, not the practical solution, I'm more trying to play with iterators and recursion. I want to create a program that generates every possible combination of a set of a n dice, with s sides. so I started with an iterator class die(object): def __init__(self,sides): self.sides = range(1,sides+1) def __iter__(self): return self def next(self): self.sides = self.sides[1:] + [self.sides[0]] return self.sides[-1] now my thought was to create a recursive function to iterate through all the dice combinations. Unfortunately... I'm coming up with a dead end. I've tried working it out with different version of the die, ie one that doesn't loop infinitely, but instead takes a starting position. A vaiety of things, and yet I can't find a nice recursive function that falls out of the die class. Any ideas? or better terms to google? cuz I've tried. Thanks From nobody at 127.0.0.1 Sun May 21 14:23:51 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Sun, 21 May 2006 18:23:51 GMT Subject: dict!ident as equivalent of dict["ident"] References: Message-ID: Alexander Kozlovsky wrote: > With this suggestion, mapping!identifier > becomes fully equivalent to mapping["identifier"] Penny-wise, pound-foolish. Saves 3 character strokes at the cost of a new special-purpose operator which only works in limited circumstances. To avoid parsing ambiguity, identifier can only contain (as the name implies) alphanumerics and _. So your ! is limited not only to dicts but to certain keys in certain dicts. More complicated than it's worth. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From nobody at 127.0.0.1 Wed May 3 18:34:26 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Wed, 03 May 2006 22:34:26 GMT Subject: noob question: "TypeError" wrong number of args References: <1146481859.285752.34010@e56g2000cwe.googlegroups.com> <1146484803.498069.228480@v46g2000cwv.googlegroups.com> <44574481$0$18265$636a55ce@news.free.fr> <4457a78b$0$5171$626a54ce@news.free.fr> <4457d83f$0$21106$626a54ce@news.free.fr> Message-ID: Marc 'BlackJack' Rintsch wrote: > Edward Elliott wrote: >> I can prove that assertion too: make a simple text processor that reads >> Python source code and outputs the same source code with only one change: >> insert the string 'self" as the first parameter of every "def >> somemethod". Next run the output source code with the normal Python > > Okay, let's start with writing a simple text processor for this little > mess:: I didn't even try to wade through that morass of monocharacter variables. Anyone wanna summarize the point of that code? From scott.daniels at acm.org Thu May 11 12:36:45 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Thu, 11 May 2006 09:36:45 -0700 Subject: which windows python to use? In-Reply-To: References: Message-ID: <4463644e$1@nntp0.pdx.net> Brian Blais wrote: > Are there any recommendations for which Windows python version to use? Only if you have criteria. --Scott David Daniels scott.daniels at acm.org From george.sakkis at gmail.com Wed May 10 12:05:08 2006 From: george.sakkis at gmail.com (George Sakkis) Date: 10 May 2006 09:05:08 -0700 Subject: Decoupling fields from forms in Django Message-ID: <1147277108.105051.32960@g10g2000cwb.googlegroups.com> Didn't have much luck in the Django list, so I'm posting it here just in case anyone has come up with this problem. Django maintains two parallel hierarchies of field classes, one related to models that correspond to table columns and one that maps these fields to forms. This works ok for the admin interface and in many typical cases, but what if one wants to have an alternative or additional widget associated to a field ? For instance, say I have a "birthday" DateField that I want to render as a date range widget in a search form ("From - Up to"). What I did so far was a DateRangeField subclass of DateField and overrode the necessary methods. This works for rendering the form but breaks several other things (e.g. in the admin interface I still want to show the field as regular DateField widget, not a range; also the backend knows nothing about how to map a DateRangeField to a table column). Any ideas on how to decouple the field from its widget(s), even by tweaking/patching Django itself ? George From randomtalk at gmail.com Mon May 1 10:19:48 2006 From: randomtalk at gmail.com (randomtalk at gmail.com) Date: 1 May 2006 07:19:48 -0700 Subject: returning none when it should be returning a list? In-Reply-To: <4455A4A1.7020807@lexicon.net> References: <1146459167.992980.235410@v46g2000cwv.googlegroups.com> <4455A4A1.7020807@lexicon.net> Message-ID: <1146493188.096280.83040@y43g2000cwc.googlegroups.com> John Machin wrote: > > That's because it "falls off the end" of the function, which causes it > to return None. However that's not your only problem. Major other > problem is updating "seed" in situ. > I'm not sure what "falls off the end" of the function means, i searched online, it seems to mean that the function has reached the end prematurely and returned a default identifier to signal success or not.. Can you please explain what that means? Other than that, thanks alot for all those who posted! It's been very educational! From ericcngan at gmail.com Sat May 13 21:00:07 2006 From: ericcngan at gmail.com (vduber6er) Date: 13 May 2006 18:00:07 -0700 Subject: having trouble importing a module from local directory In-Reply-To: References: <1147465295.213844.284100@y43g2000cwc.googlegroups.com> Message-ID: <1147568407.477228.12260@y43g2000cwc.googlegroups.com> newbie reply, but how do i go about doing that? thanks! From softwindow at gmail.com Thu May 18 23:56:41 2006 From: softwindow at gmail.com (softwindow) Date: 18 May 2006 20:56:41 -0700 Subject: Script to make Windows XP-readable ZIP file In-Reply-To: References: <1148005379.476809.73500@j33g2000cwa.googlegroups.com> Message-ID: <1148011001.613000.294750@g10g2000cwb.googlegroups.com> aha we want to do it with python don't use ant From liuliuliu at gmail.com Sat May 20 18:59:47 2006 From: liuliuliu at gmail.com (liuliuliu at gmail.com) Date: 20 May 2006 15:59:47 -0700 Subject: 'error reading datastream' -- loading file only when transfer is complete? In-Reply-To: <126v3nsag5bcqdb@corp.supernews.com> References: <1148159335.678868.22850@j73g2000cwa.googlegroups.com> <126v3nsag5bcqdb@corp.supernews.com> Message-ID: <1148165987.760565.25670@j55g2000cwa.googlegroups.com> thanks - i'm looking, but i found this as well. actually, does this work? import os os.access(file, os.R_OK) # is it readable? is this valid: { i have my file identified } isFileAccessible = os.access(file, os.R_OK) while !isFileAccessible: isFileAccessible = os.access(file, os.R_OK) and then whenever it's true it can only then proceed to load the file? thanks, christine Andrew Robert wrote: > liuliuliu at gmail.com wrote: > > hello -- > > > > i'm running python/pygame on maemo (nokia 770). my situation is that > > i'm continually scouring this one directory for incoming files. if i > > see if there's a new file (coming in via wireless scp), i proceed to > > load it and process it. > > > > however, i think i am running into the issue that my program starts to > > load the file after it recognises there is new data, but before the > > file has completely transferred, so at unpredictable times i get a > > pygame.error: Error reading from datastream. > > > > what is the easiest way to work out this issue? easy being the key > > word. :) thank you very much! > > > > christine > > > > You might want to test for file locking before attempting to use From cyberco at gmail.com Wed May 31 16:50:51 2006 From: cyberco at gmail.com (cyberco) Date: 31 May 2006 13:50:51 -0700 Subject: OT: Search for python in Norway Message-ID: <1149108651.205786.99100@j55g2000cwa.googlegroups.com> Although the climate wouldn't make you think so, but searching for python is hot in Norway: http://www.google.com/trends?q=python&ctab=1&geo=all&date=all I wonder what the explanation could be. Btw: Java seems to be all the rage in India :) http://www.google.com/trends?q=java&ctab=1&geo=all&date=all From Steven.Watanabe at autodesk.com Thu May 4 14:08:30 2006 From: Steven.Watanabe at autodesk.com (Steven Watanabe) Date: Thu, 4 May 2006 14:08:30 -0400 Subject: Why does built-in set not take keyword arguments? Message-ID: I'm trying to do something like this in Python 2.4.3: class NamedSet(set): def __init__(self, items=(), name=''): set.__init__(self, items) self.name = name class NamedList(list): def __init__(self, items=(), name=''): list.__init__(self, items) self.name = name I can do: >>> mylist = NamedList(name='foo') but I can't do: >>> myset = NamedSet(name='bar') TypeError: set() does not take keyword arguments How come? How would I achieve what I'm trying to do? Thanks. -- Steven. From steven.bethard at gmail.com Fri May 12 15:19:23 2006 From: steven.bethard at gmail.com (Steven Bethard) Date: Fri, 12 May 2006 13:19:23 -0600 Subject: Broken essays on python.org In-Reply-To: References: Message-ID: Brian Cole wrote: > I'm not sure if this is the proper place to post this... > > A lot of the essays at http://www.python.org/doc/essays/ have a messed > up layout in Firefox and IE. The proper place to post this is to follow the "Report website bug" link at the bottom of the sidebar and post a tracker item. I was feeling generous today ;) so I did that for you: http://psf.pollenation.net/cgi-bin/trac.cgi/ticket/333 STeVe From gshepherd281281 at yahoo.com Wed May 3 13:29:55 2006 From: gshepherd281281 at yahoo.com (ProvoWallis) Date: 3 May 2006 10:29:55 -0700 Subject: NewB question on text manipulation References: <1146634624.622224.323010@u72g2000cwu.googlegroups.com> Message-ID: <1146677395.523919.319760@i39g2000cwa.googlegroups.com> Thanks very much for this I really appreciate it. I've pasted what I've got now thanks to you. I only have one issue that I can't figure out. When I print the new string I'm getting all of the values in the lt list rather than just the one that corresponds to the original entry. E.g., My original data looks like this: <1>FAM LAW ENF259-232-687 <1>APPEAL40-38; 40-44; 44-18; 45-151 I want my output to look like this: <1>FAM LAW ENF259-232-687 <1>APPEAL40-381 <1>APPEAL40-441 <1>APPEAL44-181 <1>APPEAL45-151 But istead I'm getting this -- all of the entries in the lt list are being added to my string when I just want one. I'm not sure how to select just the entry in the lt list that I want. <1>FAM LAW ENF259-232-6871 <1>APPEAL40-38-6871 <1>APPEAL40-44-6871 <1>APPEAL44-18-6871 <1>APPEAL45-15-6871 ### Here's what I've got so far: s_space = " " # a single space s_empty = "" # empty string pat = re.compile("\s*([^<]+)([^<]+)") lst = [] while True: m = pat.search(s) if not m: break title = m.group(1).strip() xc = m.group(2) xc = xc.replace(s_space, s_empty) tup = (title, xc) lst.append(tup) s = pat.sub(s_empty, s, 1) lt = s.strip() for title, xc in lst: lst_pp = xc.split(";") for pp in lst_pp: print "<1>%s%s%s" % (title, pp, lt) From python.list at tim.thechases.com Fri May 5 10:01:08 2006 From: python.list at tim.thechases.com (Tim Chase) Date: Fri, 05 May 2006 09:01:08 -0500 Subject: how to remove 50000 elements from a 100000 list? In-Reply-To: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> References: <1146836210.173092.150580@i40g2000cwc.googlegroups.com> Message-ID: <445B5AA4.4010902@tim.thechases.com> > but when a and b have many elements. such as: > >>>>a=range(100000) >>>>b=range(50000) >>>>for x in b: > > ... a.remove(x) > ... > it will very slowly. Well, your problem is rather ambiguous. In your examples, you're removing contiguous ranges. Thus, you should be able to do something like >>> a = range(100000) >>> del a[:50000] which may have a considerable speedup. However, if B contains a disjoint sets of entries, the simple solution will require A*B checks, making it dependant on the size of A and B (as you've discovered). Assuming the "del" method is considerably faster, you might be able to do some sort of optimization of the disjoint set, using the above-mentioned method. Break B into contiguous pieces, and then pass those as slices to delete. Or if B is a pattern of some sort, you could do >>> a = range(100000) >>> del a[::2] #delete even numbers >>> a = range(100000) >>> del a[1::2] #delete odd numbers >>> a = range(100000) >>> del a[2::5] # delete every 5th element beginning with the 3rd Another attempt might be to try >>> a = [x for x in a if x not in b] However, this is still doing A*B checks, and will likely degrade with as their sizes increase. Just a few ideas. -tkc From Serge.Orlov at gmail.com Tue May 9 09:06:01 2006 From: Serge.Orlov at gmail.com (Serge Orlov) Date: 9 May 2006 06:06:01 -0700 Subject: ascii to latin1 In-Reply-To: References: <445fdc6c$0$15793$14726298@news.sunsite.dk> <1147136835.481913.323510@v46g2000cwv.googlegroups.com> Message-ID: <1147179961.148432.157390@y43g2000cwc.googlegroups.com> Richie Hindle wrote: > [Serge] > > def search_key(s): > > de_str = unicodedata.normalize("NFD", s) > > return ''.join(cp for cp in de_str if not > > unicodedata.category(cp).startswith('M')) > > Lovely bit of code - thanks for posting it! Well, it is not so good. Please read my next message to Luis. > > You might want to use "NFKD" to normalize things like LATIN SMALL > LIGATURE FI and subscript/superscript characters as well as diacritics. IMHO It is perfectly acceptable to declare you don't interpret those symbols. After all they are called *compatibility* code points. I tried "a quater" symbol: Google and MSN don't interpret it. Yahoo doesn't support it at all. NFKD form is also more tricky to use. It loses semantic of characters, for example if you have character "digit two" followed by "superscript digit two"; they look like 2 power 2, but NFKD will convert them into 22 (twenty two), which is wrong. So if you want to use NFKD for search your will have to preprocess your data, for example inserting space between the twos. From auch-ich-m at g-kein-spam.com Fri May 5 13:16:26 2006 From: auch-ich-m at g-kein-spam.com (=?UTF-8?B?QW5kcsOp?= Malo) Date: Fri, 05 May 2006 19:16:26 +0200 Subject: ConfigParser: values with ";" and the value blank References: <1146847054.321520.296410@v46g2000cwv.googlegroups.com> Message-ID: <2391954.bby8049iTW@news.perlig.de> * kai wrote: > I use the ConfigPaserver from Python. > how can I use/save/read values with ";" (start comment) and the value > blank? > When I write (set) my config file often the part behind the ";" > disappears. > e.g. > myKey = startMyValue ; endMyValue You can't. The ConfigParser treats " ;" as inline comment delimiter. This is undocumented (afaik) and badly hardcoded into the module. The time I found this out, I simply hacked my own (way more simple) parser module replacement. Anyway, you might try http://www.voidspace.org.uk/python/configobj.html instead. I've never used it myself, though. nd -- Gib' mal folgendes in die Kommandozeile ein (und einen Moment warten): net send localhost "Buuuh!" Na, erschreckt? -- Markus Becker in mpdsh From pemboa at gmail.com Sun May 28 01:05:31 2006 From: pemboa at gmail.com (Arthur Pemberton) Date: Sun, 28 May 2006 00:05:31 -0500 Subject: Best way to check that a process is running on a Unix system? Message-ID: <16de708d0605272205m66cbadc9h25e699fe4f7b32ec@mail.gmail.com> Hello list, What is the best way to check that a process is running (or better yet number of instances) based on the name of the process? Would have to work on a unix/linux system. Thank you. -- To be updated... From tim.leeuwvander at nl.unisys.com Fri May 12 09:49:59 2006 From: tim.leeuwvander at nl.unisys.com (Tim N. van der Leeuw) Date: 12 May 2006 06:49:59 -0700 Subject: New tail recursion decorator In-Reply-To: <1147437656.779139.54840@d71g2000cwd.googlegroups.com> References: <1147242641.311804.161620@y43g2000cwc.googlegroups.com> <4cdnouF15dmjfU1@uni-berlin.de> <1147253776.042505.34430@j73g2000cwa.googlegroups.com> <1147436852.364490.99440@u72g2000cwu.googlegroups.com> <1147437656.779139.54840@d71g2000cwd.googlegroups.com> Message-ID: <1147441799.331677.88460@d71g2000cwd.googlegroups.com> Hi Michele, I'm sorry, but you misunderstood me. There are two definitions of the factorial() function, one given by the OP and the other given by Duncan. I tested both factorial() definitions with, and without the tail_recursion decorator (the version of the OP). So I had 4 factorial-functions defined in my test-file: @tail_recursion def factorial(n, acc=1): # do the stuff pass def factorial_r(n, acc=1): # do the stuff pass @tail_recursion def factorial2(n): # do the stuff pass def factorial2_r(n): # do the stuff pass All four functions give the same output for the tests I did (n=120, and n=1000). Using timeit, both factorial(1000) and factorial2(1000) are somewhat faster than factorial_r(1000) respectively factorial2_r(1000). However, factorial(1000) and factorial_r(1000) are both 10x faster than factorial2(1000) and factorial2_r(1000). It's the latter performance difference which I do not understand. The other thing I do not understand, due to my limited understanding of what is tail-recursion: factorial2 (Duncan's definition) is not proper tail-recursion. Why not? How does it differ from 'real' tail recursion? And if it's not proper tail-recursion and therefore should not work, then how comes that the tests I do show it to work? And I seemed to consistently get a slightly better performance from factorial2(1000) than from factorial2_r(1000). NB: Regarding the recursion limits, I don't know what would be the stacklimit on my system (Python 2.4.3 on WinXP SP2). I already calculated the factorial of 500000 using the recursive (non-decorated) function... Cheers, --Tim From nobody at 127.0.0.1 Wed May 17 20:51:11 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Thu, 18 May 2006 00:51:11 GMT Subject: python vs perl lines of code References: <1147906261.267292.122360@y43g2000cwc.googlegroups.com> Message-ID: <3yPag.18372$Lm5.13538@newssvr12.news.prodigy.com> Ben Finney wrote: > Those samples can be independently verified by any skilled observer at > another time. This is what distinguishes them from anecdotes, and > breaks your analogy. Anyone who has my source files can run the same tests. The measures are repeatable and reliable, even if at the moment few can perform them on my code. They don't just let anybody walk into the Louvre and cut off a piece of the Mona Lisa for spectral analysis. :) Before the days of cheap video, lots of scientific data was gathered by lone observers recording unrepeatable events. You build statistics by accumulating a vast number of such observations over time. In any case, I never asked for scientific-quality data in the first place. -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From jzgoda at o2.usun.pl Tue May 23 15:16:48 2006 From: jzgoda at o2.usun.pl (Jarek Zgoda) Date: Tue, 23 May 2006 21:16:48 +0200 Subject: how to change sys.path? In-Reply-To: <5aGcg.2150$No6.46806@news.tufts.edu> References: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> <4472c6b7$0$26894$626a54ce@news.free.fr> <1148399102.963320.129230@u72g2000cwu.googlegroups.com> <5aGcg.2150$No6.46806@news.tufts.edu> Message-ID: John Salerno napisa?(a): >> yes, I mean I want change the sys.path value and save it for next >> using. >> I can change the value of sys.path, but I can't "save" it permanently. >> There is no python_path environment on my pc, what the relationship >> between it and the sys.path? > > In Windows, at least, you can create the PYTHONPATH variable and assign > to it the paths of the directories you want Python to check for when > running a script. Setting Windows envvar by changing os.environ dict will work only for processes running in the same environment (i.e. in the same shell session). -- Jarek Zgoda http://jpa.berlios.de/ From songyi012133 at gmail.com Thu May 18 04:38:35 2006 From: songyi012133 at gmail.com (hankssong) Date: 18 May 2006 01:38:35 -0700 Subject: how to make the program notify me explicitly In-Reply-To: <1147939268.619806.147550@j73g2000cwa.googlegroups.com> References: <1147922004.345357.6360@i40g2000cwc.googlegroups.com> <1147939268.619806.147550@j73g2000cwa.googlegroups.com> Message-ID: <1147941515.759708.322920@y43g2000cwc.googlegroups.com> Ben Finney , Miki ,thanks a lot! may be message dialog is the best way to let me be informed! From deets at nospam.web.de Mon May 15 15:15:32 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Mon, 15 May 2006 21:15:32 +0200 Subject: OOP and Tkinter In-Reply-To: <1rjh629au1b5k1mk1trffnr97e2s61sqen@4ax.com> References: <7gih62p25k5krj9c5l9ot6tpt01c45e723@4ax.com> <4cs113F17n5m7U1@uni-berlin.de> <1rjh629au1b5k1mk1trffnr97e2s61sqen@4ax.com> Message-ID: <4cs2aeF172qs2U1@uni-berlin.de> Ronny Mandal schrieb: > Thanks, but the problem was my undentation, after making one indent, > it worked as expected. :) I seriously doubt that. I guess you didn't show us the real code. But there is no way that an instance variable can be accessed on type-level in a derived class (or from anywhere, for that matter). So I presume you have some misconceptions about pythons OO-model that will sooner or later bite you - for example if you want to have several Front-objects. Diez From miki.tebeka at gmail.com Thu May 18 03:55:50 2006 From: miki.tebeka at gmail.com (Miki) Date: 18 May 2006 00:55:50 -0700 Subject: getting the value of an attribute from pdb References: <87odxwt4kv.fsf@localhost.localdomain> Message-ID: <1147938950.200157.6530@i40g2000cwc.googlegroups.com> Hello Gary, > (Pdb) p root.title > > > (Pdb) p root.title[Tk.wm_title] Looks like "title" is a function, try "p root.title()" HTH, Miki http://pythonwise.blogspot.com/ From fredrik at pythonware.com Thu May 18 13:53:01 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Thu, 18 May 2006 19:53:01 +0200 Subject: Feature request: sorting a list slice In-Reply-To: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> References: <1147973268.404121.18520@g10g2000cwb.googlegroups.com> Message-ID: George Sakkis wrote: > It would be useful if list.sort() accepted two more optional > parameters useful for what? what's the use case ? From david.nospam.hopwood at blueyonder.co.uk Wed May 10 11:16:59 2006 From: david.nospam.hopwood at blueyonder.co.uk (David Hopwood) Date: Wed, 10 May 2006 15:16:59 GMT Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <1ZadnfwKY5_XG_zZRVn-sg@speakeasy.net> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1146996626.037365.304750@v46g2000cwv.googlegroups.com> <1heyu9a.1jijphh199wvh3N%aleaxit@yahoo.com> <1heznxs.1m1eqceeowwsrN%aleax@mac.com> <1147108421.090707.226700@i40g2000cwc.googlegroups.com> <1hf1c4j.1qms2xq1ws0aj4N%aleax@mac.com> <1hf1kf9.1ora26l1i4xsdzN%aleax@mac.com> <87ac9r1tem.fsf@snobis.de> <1hf26zk.1uqniari93h7fN%aleax@mac.com> <1ZadnfwKY5_XG_zZRVn-sg@speakeasy.net> Message-ID: M Jared Finder wrote: > Alex Martelli wrote: >> Stefan Nobis wrote: >>> aleax at mac.com (Alex Martelli) writes: >>> >>>> if anonymous functions are available, they're used in even more >>>> cases where naming would help >>> >>> Yes, you're right. But don't stop here. What about expressions? Many >>> people write very complex expression, that are hard to understand. A >>> good language should forbid these abuse and don't allow expressions >>> with more than 2 or maybe 3 operators! >> >> That would _complicate_ the language (by adding a rule). I repeat what >> I've already stated repeatedly: a good criterion for deciding which good >> practices a language should enforce and which ones it should just >> facilitate is _language simplicity_. If the enforcement is done by >> adding rules or constructs it's probably not worth it; if the >> "enforcements" is done by NOT adding extra constructs it's a double win >> (keep the language simpler AND push good practices). > > Your reasoning, taken to the extreme, implies that an assembly language, > by virtue of having the fewest constructs, is the best designed language > ever. Assembly languages don't have the fewest constructs; kernel languages such as Core ML or Kernel-Oz do. In any case, I didn't read Alex's point as being that simplicity was the only criterion on which to make decisions about what practices a language should enforce or facilitate; just "a good criterion". However, IMHO anonymous lambdas do not significantly increase the complexity of the language or of programs, and they can definitely simplify programs in functional languages, or languages that use them for control constructs. -- David Hopwood From bignose+hates-spam at benfinney.id.au Wed May 17 22:22:54 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Thu, 18 May 2006 12:22:54 +1000 Subject: MySQLdb - parameterised SQL - how to see resulting SQL ? References: <1147916515.511332.214660@j33g2000cwa.googlegroups.com> Message-ID: <87fyj8m5q9.fsf@benfinney.id.au> shearichard at gmail.com writes: > ... i would be interested in seeing what the actual SQL used by the > .execute looks like after the replacements have been done. Is there a > way of doing this ? I also think this would be a very useful feature for enabling logging, debugging, and other introspection. It surely is possible for the code to present that information (it must construct the final SQL statement to pass to the database engine), but I can't see a way to get at it with the current DB API. -- \ "Better not take a dog on the space shuttle, because if he | `\ sticks his head out when you're coming home his face might burn | _o__) up." -- Jack Handey | Ben Finney From a.schmolck at gmail.com Fri May 12 15:40:54 2006 From: a.schmolck at gmail.com (Alexander Schmolck) Date: 12 May 2006 20:40:54 +0100 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> <1hevo2w.1xdntgo1tsejf6N%aleaxit@yahoo.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Ken Tilton writes: > In Common Lisp we would have: > > (defvar *x*) ;; makes it special > (setf *x* 1) > (print *x*) ;;-> 1 > (let ((*x* 2)) > (print *x*)) ;; -> 2 > (print *x*) ;; -> 1 You seem to think that conflating special variable binding and lexical variable binding is a feature and not a bug. What's your rationale? 'as From peace.is.our.profession at gmx.de Mon May 8 03:49:56 2006 From: peace.is.our.profession at gmx.de (Mirco Wahab) Date: Mon, 08 May 2006 09:49:56 +0200 Subject: Python's regular expression? In-Reply-To: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> References: <1147072910.716624.299990@e56g2000cwe.googlegroups.com> Message-ID: Hi Davy wrote: > I am a C/C++/Perl user and want to switch to Python OK > (I found Python is more similar to C). ;-) More similar than what? > Does Python support robust regular expression like Perl? It supports them fairly good, but it's not 'integrated' - at least it feels not integrated for me ;-) If you did a lot of Perl, you know what 'integrated' means ... > And Python and Perl's File content manipulation, which is better? What is a 'file content manipulation'? Did you mean 'good xxx level file IO', where xxx means either 'low' or 'high'? > Any suggestions will be appreciated! Just try to start a small project in Python - from source that you already have in C or Perl or something. Regards Mirco From bdesth.quelquechose at free.quelquepart.fr Tue May 16 20:12:23 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Wed, 17 May 2006 02:12:23 +0200 Subject: calling upper() on a string, not working? In-Reply-To: References: Message-ID: <446a3b52$0$11000$626a54ce@news.free.fr> John Salerno a ?crit : > Can someone tell me what's happening here. This is my code: > > PUNCT_SPACE_SET = set(string.punctuation + string.whitespace) > > def filter_letters(original): > return ''.join(set(original) - PUNCT_SPACE_SET) > > 'original' is a string. The above works as expected, but when I change > it to > > return ''.join(set(original.upper()) - PUNCT_SPACE_SET) > > it doesn't seem to work. The full code is below if it helps to understand. > Don't assume str.upper() is broken !-) In fact, your problem is that you create the translation table based on uppercase letters, and apply it to a non uppercased string : > import string > import random > import itertools > > PUNCT_SPACE_SET = set(string.punctuation + string.whitespace) > > def convert_quote(quote): > return encrypt_quote(quote).split('|') > > def encrypt_quote(original): # Since it's here that we define that the new letters # will be uppercase only, it's our responsability # to handle any related conditions and problems # The other functions shouldn't have to even know this. original = original.upper() > original_letters = filter_letters(original) > new_letters = list(string.ascii_uppercase) > while True: > random.shuffle(new_letters) > trans_letters = ''.join(new_letters)[:len(original_letters)] > if test_code(original_letters, trans_letters): > trans_table = string.maketrans(original_letters, trans_letters) > break > return original.translate(trans_table) > > def filter_letters(original): # here, we *dont* have to do anything else than filtering # upper/lower case is *not* our problem. > return ''.join(set(original) - PUNCT_SPACE_SET) > > def test_code(original_letters, trans_letters): > for pair in itertools.izip(original_letters, trans_letters): > if pair[0] == pair[1]: > return False > return True > > if __name__ == '__main__': > print convert_quote("The past is not dead. In fact, it's not even > past.|William Faulkner") ["XCD ONKX AK IGX LDNL. AI WNBX, AX'K IGX DYDI ONKX.", 'UAEEANP WNREQIDS'] From fredrik at pythonware.com Tue May 9 15:58:37 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 9 May 2006 21:58:37 +0200 Subject: How to recast integer to a string References: <1147202254.367688.258160@v46g2000cwv.googlegroups.com> <1147203245.870258.64860@u72g2000cwu.googlegroups.com> Message-ID: James wrote: > > > How to recast an integer to a string? > > > > > > something like > > > n = 5 > > > str = str + char(n) > > > > str(n) > > > > Kindly > > Christoph > > In python2,4, I 've got > TypeError: 'str' object is not callable if you want to use a builtin function, you cannot use the same name for your own variables. From kay.schluehr at gmx.net Sat May 6 03:26:19 2006 From: kay.schluehr at gmx.net (Kay Schluehr) Date: 6 May 2006 00:26:19 -0700 Subject: A critic of Guido's blog on Python's lambda In-Reply-To: <6OS6g.78$Ey5.74@fe12.lga> References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <6OS6g.78$Ey5.74@fe12.lga> Message-ID: <1146900379.023190.164640@u72g2000cwu.googlegroups.com> Ken Tilton wrote: > Oh, my, you are preaching to the herd (?!) of lemmings?! Please tell me > you are aware that lemmings do not have ears. You should just do Lisp > all day and add to the open source libraries to speed Lisp's ascendance. > The lemmings will be liberated the day Wired puts John McCarthy on the > cover, and not a day sooner anyway. And then the 12th vanished Lisper returns and Lispers are not suppressed anymore and won't be loosers forever. The world will be united in the name of Lisp and Lispers will be leaders and honorables. People stop worrying about Lispers as psychpaths and do not consider them as zealots, equipped with the character of suicide bombers. No, Lisp means peace and paradise. From tbrkic at yahoo.com Thu May 18 02:44:23 2006 From: tbrkic at yahoo.com (glomde) Date: 17 May 2006 23:44:23 -0700 Subject: Proposal for new operators to python that add syntactic sugar for hierarcical data. In-Reply-To: <4d1l5nF188kcuU1@uni-berlin.de> References: <1147901086.947418.86810@g10g2000cwb.googlegroups.com> <4d1l5nF188kcuU1@uni-berlin.de> Message-ID: <1147934663.306885.220860@g10g2000cwb.googlegroups.com> There are some difference which are quite essential. First of all I dont se how you set attributes with that and then I dont see how you can mix python code with the creation. So how do you do this: root = ET.Element("html") *!*root: *!*head("head"): *!*title("title): for i in sections: !*! section(): *=*Text = section[i] From dingbat at codesmiths.com Mon May 22 12:49:40 2006 From: dingbat at codesmiths.com (dingbat at codesmiths.com) Date: 22 May 2006 09:49:40 -0700 Subject: Python - Web Display Technology In-Reply-To: <1148223307.073050.33710@y43g2000cwc.googlegroups.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> Message-ID: <1148316580.043077.76310@y43g2000cwc.googlegroups.com> SamFeltus wrote: > Here is a visual argument, > http://samfeltus.com/swf/contact_globes.swf Here's a text-based argument. If I search Golge for "gardener, Athens, GA" then Google's spiders won't have recorded your contact page. So I don't find you as a local gardener, so I don't hire you for my mansion in Athens. Your contact page is arguably pretty, but pretty just isn't selling for that particular sort of page. From ogahejini at yahoo.com Tue May 23 06:09:29 2006 From: ogahejini at yahoo.com (gen_tricomi) Date: 23 May 2006 03:09:29 -0700 Subject: A python problem about int to long promotion just see the idle session In-Reply-To: References: <1146676227.349286.280250@v46g2000cwv.googlegroups.com> Message-ID: <1148378969.740491.31030@i39g2000cwa.googlegroups.com> wow i think i was just been too paranoid. i thought it would affect some precision arithmetic in science. thanks for the reply From johnjsal at NOSPAMgmail.com Mon May 8 16:36:36 2006 From: johnjsal at NOSPAMgmail.com (John Salerno) Date: Mon, 08 May 2006 20:36:36 GMT Subject: i don't understand this RE example from the documentation Message-ID: Ok, I've been staring at this and figuring it out for a while. I'm close to getting it, but I'm confused by the examples: (?(id/name)yes-pattern|no-pattern) Will try to match with yes-pattern if the group with given id or name exists, and with no-pattern if it doesn't. |no-pattern is optional and can be omitted. For example, (<)?(\w+@\w+(?:\.\w+)+)(?(1)>) is a poor email matching pattern, which will match with '' as well as 'user at host.com', but not with ') mean that it has to end with a '>'? From rNOSPAMon at flownet.com Thu May 18 21:04:09 2006 From: rNOSPAMon at flownet.com (Ron Garret) Date: Thu, 18 May 2006 18:04:09 -0700 Subject: WTF? Printing unicode strings References: <1147992722.970761.220840@j73g2000cwa.googlegroups.com> <1147998139.268318.315250@y43g2000cwc.googlegroups.com> Message-ID: In article <1147998139.268318.315250 at y43g2000cwc.googlegroups.com>, "Serge Orlov" wrote: > Ron Garret wrote: > > In article <1147992722.970761.220840 at j73g2000cwa.googlegroups.com>, > > "Serge Orlov" wrote: > > > > > Ron Garret wrote: > > > > In article , > > > > Robert Kern wrote: > > > > > > > > > Ron Garret wrote: > > > > > > > > > > > I forgot to mention: > > > > > > > > > > > >>>>sys.getdefaultencoding() > > > > > > > > > > > > 'utf-8' > > > > > > > > > > A) You shouldn't be able to do that. > > > > > > > > What can I say? I can. > > > > > > > > > B) Don't do that. > > > > > > > > OK. What should I do instead? > > > > > > Exact answer depends on what OS and terminal you are using and what > > > your program is supposed to do, are you going to distribute the program > > > or it's just for internal use. > > > > I'm using an OS X terminal to ssh to a Linux machine. > > In theory it should work out of the box. OS X terminal should set > enviromental variable LANG=en_US.utf-8, then ssh should transfer this > variable to Linux and python will know that your terminal is utf-8. > Unfortunately AFAIK OS X terminal doesn't set that variable and most > (all?) ssh clients don't transfer it between machines. As a workaround > you can set that variable on linux yourself . This should work in the > command line right away: > > LANG=en_US.utf-8 python -c "print unichr(0xbd)" > > Or put the following line in ~/.bashrc and logout/login > > export LANG=en_US.utf-8 No joy. ron at www01:~$ LANG=en_US.utf-8 python -c "print unichr(0xbd)" Traceback (most recent call last): File "", line 1, in ? UnicodeEncodeError: 'ascii' codec can't encode character u'\xbd' in position 0: ordinal not in range(128) ron at www01:~$ rg From john.thingstad at chello.no Tue May 23 12:20:21 2006 From: john.thingstad at chello.no (John Thingstad) Date: Tue, 23 May 2006 18:20:21 +0200 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> Message-ID: On Tue, 23 May 2006 15:58:12 +0200, John D Salt wrote: > wrote in news:4dbartF19cb9rU1 at uni-berlin.de: > > [Snips] >> Wrong. We live in a paradise of ideas and possibilities well beyond the >> wildest dreams of only 20 years ago. > > What exciting new ideas exist in software that are both important and > cannot be traced back to 1986 or earlier? > > I'd like to believe that there are some, but I can't think of any at the > moment. > > All the best, > > John. Well most have to do with wireless nets and connectivity. One is that all compoters will be connected to the net all of the time. When you go out you will not bring a mobile phone you will bring a PDA (Personal data assistant). You can call people, listent to music, wach videoes. You can connect to the web cans at home and see that the children are ok or turn the oven on while on the way back from work, etc. As you move from sector to another the PDA aquites the closest transmitter and hooks on to it. Most use wireless networks to connect aplliances in their homes. Instead of tv stations you order movies and TV series from online servers. etc.. Also the AI part. AI will not consist of cumputers trying to pretend to be people. The will take vocal commands. The will remember your preferences. It will know when you are on vacation. Turn the alarm on, lower the house theperature and turn on lights periodically to make it look inhabited. It will know what movies and shows you like to watch and order them accordingly. It will know who you know and order incoming messages accordingly by priority, also block out those you do not what contact with. There is now a clear idea of how windows systems should behave. Windows interfaces have evolved accordingly. It is now far less tedious to connect systems to the net or make a windows interface.. etc, etc.. -- Using Opera's revolutionary e-mail client: http://www.opera.com/mail/ From bruno at modulix.org Fri May 26 08:32:51 2006 From: bruno at modulix.org (bruno de chez modulix en face) Date: 26 May 2006 05:32:51 -0700 Subject: Accessing object parent properties In-Reply-To: References: Message-ID: <1148646771.678232.161100@j55g2000cwa.googlegroups.com> > Are you sure you don't want to use a child class for this? Composition/delegation introduce far less coupling than implementation inheritance. Inheritance abuse is in fact a well-known OO antipattern. Since Python makes delegation easy as pie, I don't see any reason to go for inheritence when it's not really needed (FWIW, you'll notice that Python class hierarchies tend to be really flat when compared to Java or like). From claudio.grondi at freenet.de Mon May 22 07:27:18 2006 From: claudio.grondi at freenet.de (Claudio Grondi) Date: Mon, 22 May 2006 13:27:18 +0200 Subject: Pyrex installation on windows XP: step-by-step guide In-Reply-To: <1146153927.211618.180350@t31g2000cwb.googlegroups.com> References: <1145449777.731155.181600@i40g2000cwc.googlegroups.com> <1146076193.605314.70200@g10g2000cwb.googlegroups.com> <1146126507.086613.224070@j33g2000cwa.googlegroups.com> <1146153927.211618.180350@t31g2000cwb.googlegroups.com> Message-ID: sturlamolden wrote: > Julien Fiore wrote: > >>Thanks for your remark, Sturlamolden. >> >>Is there a free version of the "Visual C++ 2003" compiler available on >>the web? I have found "Visual C++ 2005 Express edition" >>(http://msdn.microsoft.com/vstudio/express/visualc/). According to >>Micrsoft, it replaces VC++2003 >>(http://msdn.microsoft.com/visualc/vctoolkit2003/). Is VC++2005ee the >>good compiler to compile a Pyrex module (or any Python extension) ? >>Does it link with msvcr71.dll ? > > > The bad news is that "Visual C++ 2005 Express" links with msvcr80.dll, > which incompatible with both msvcrt.dll and msvcr71.dll. What you need > is the "Microsoft .NET Framework SDK Version 1.1". It contains version > 7.1 of Microsoft's C/C++ compiler and links with the correct CRT. > > http://tinyurl.com/5flob > > I am not sure if this is an optimizing compiler. The free available Visual C++ 2003 compiler is the optimizing one. You have to get it separately downloading the Visual C++ Toolkit 2003 which comes with the Professional version of Microsoft Visual C++ .NET 2003 compiler and linker. Claudio > Microsoft did not give > away their optimizing compiler prior to "Visual C++ 2005 Express". Even > the standard version of Visual Studio did not have an optimizing > compiler, it only shipped with the professional and enterprise > versions. If this compiler does not optimize, you may try to make > "Visual C++ 2005 Express" use the import library for msvcr71.dll which > ships with the .NET SDK. > > Now you know the meaning of the word "DLL HELL". > From steven.klass at gmail.com Tue May 16 17:11:25 2006 From: steven.klass at gmail.com (rh0dium) Date: 16 May 2006 14:11:25 -0700 Subject: Beautiful parse joy - Oh what fun Message-ID: <1147813885.337318.141070@g10g2000cwb.googlegroups.com> Hi all, I am trying to parse into a dictionary a table and I am having all kinds of fun. Can someone please help me out. What I want is this: dic={'Division Code':'SALS','Employee':'LOO ABLE'} Here is what I have.. html="""
    Division Code: SALS
    Employee: LOO ABLE
    """ from BeautifulSoup import BeautifulSoup soup = BeautifulSoup() soup.feed(html) dic={} for row in soup('table')[0]('tr'): column = row('td') print column[1].findNext('font').string.strip(), column[2].findNext('font').string.strip() dic[column[1].findNext('font').string.strip()]= column[2].findNext('font').string.strip() for key in dic.keys(): print key, dic[key] The problem is I am missing the last name ABLE. How can I get "ALL" of the text. Clearly I have something wrong with my font string.. but what it is I am not sure of. Please and thanks!! From Nainto at gmail.com Wed May 3 07:33:58 2006 From: Nainto at gmail.com (Nainto) Date: 3 May 2006 04:33:58 -0700 Subject: Zope/Plone developer(s) needed to help build and finalize a fun project. Message-ID: <1146656038.903969.304230@v46g2000cwv.googlegroups.com> I am the lead developer of MacSuburb.com, a to-be-launched mac community. Unfortunatly, I am the only developer. If you are interested in helping please email me or reply with your contact information. Please leave atleast your email and/or IM name. I can be reached at zacim at jezajo.org. *Make sure you first read the list below!* We are looking for someone who... * is interested in working with me to further develop the existing MacSuburb software and ready it for the release. There is a lot of readying to be done. * knows Python and is familiar with Zope and Plone. We are using Zope and Plone to build the system on so keep that in mind. * uses a Mac or is a Mac enthusiast * Would like to be part of a grea group of people. (As I said, I'm the lead developer we have writers and other people too) * Has time to spend developing. On behalf of the MacSuburb Team, Thanks! From onurb at xiludom.gro Tue May 9 04:15:44 2006 From: onurb at xiludom.gro (bruno at modulix) Date: Tue, 09 May 2006 10:15:44 +0200 Subject: Is this a good use of __metaclass__? In-Reply-To: <1146936110.590076.295050@y43g2000cwc.googlegroups.com> References: <445baf1a$0$2386$626a54ce@news.free.fr> <1146936110.590076.295050@y43g2000cwc.googlegroups.com> Message-ID: <44605011$0$8317$626a54ce@news.free.fr> Joel.Hedlund at gmail.com wrote: > Hi! > > Thank you for a quick and informative response! > > >>I'd go for 'manually decorating' anyway. Metaclasses can be really handy >>for framework-like stuff, but for the use case you describe, I think the >>explicit decorator option is much more, well, explicit - and also more >>flexible - than metaclass black magic. > > > Yes, point taken. > > >>This may also help you distinguish 'published' API from implementation (which is what > CherryPy do) > > > Hmm... I'm not sure I understand how manually decorating would help me > do that? With SimpleXMLRPCServer.register_instance(obj) all public > methods of obj are published for XMLRPC, decorated or not. So it's effectively useless (disclaimer : I've never used SimpleXMLRPCServer). (snip) > >>You would then have a 'server' class that just provides common >>services and dispatch to specialized objects. > > Neat. It won't play nice with dir() or SimpleXMLRPCServer's > introspection functions though (system.listMethods(), > system.methodHelp()). That may be a showstopper, or do you know of any > fixes? Nope - well, at least not without digging into SimpleXMLRPCServer's internals, but if it (-> the solution I suggested) makes things more complicated, it's a bad idea anyway. -- bruno desthuilliers python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for p in 'onurb at xiludom.gro'.split('@')])" From sam at nuevageorgia.com Mon May 22 15:05:38 2006 From: sam at nuevageorgia.com (SamFeltus) Date: 22 May 2006 12:05:38 -0700 Subject: Python - Web Display Technology In-Reply-To: <2lmcg.90657$dW3.29599@newssvr21.news.prodigy.com> References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> <2lmcg.90657$dW3.29599@newssvr21.news.prodigy.com> Message-ID: <1148324738.039440.57700@j73g2000cwa.googlegroups.com> This has all been very helpful. I've been struggling for awhile on which direction to go with computer programming. I realize the problem with HTML and the P language family is that although it makes sense to me, it doesn't really resonate with my perspective. Flash definitely does. I finally realize what it is that bothers me about HTML/JS/Python/Perl/PHP... I am uncomfortable with the seperating of the code from the visual/time element, as well as the lack of emphasis on the visual/time element. Perhaps that is related to years of being a gardener? Anyways, this question no longer vexates me. HTML is for one ecosystem, Flash is for another. There is room for both. Next question... :) I am not a big Perl/PHP fan, I find Python with SimpleJSON, SQLObject and the included Python batteries pretty well does all I want to do server side. Is it correct to think that is gonna be a solid, simple solution for a Flash coder to use server side? Or, is there something better and easier? (In advance, I find XML irritating compared to JSON) From no at spam.please Thu May 25 17:12:43 2006 From: no at spam.please (D H) Date: Thu, 25 May 2006 16:12:43 -0500 Subject: Go "help" the perl list instead Fredrik Lundh In-Reply-To: References: <1148564940.107101.146320@i40g2000cwc.googlegroups.com> <1148567178.295878.305080@u72g2000cwu.googlegroups.com> Message-ID: Fredrik Lundh wrote: > vbgunz wrote: > >>> I have new a list , when it hava large number of values, I wonna to >>> delete all the values in it,how to do? >> >> something like this will probably help. >> >> x = [1,2,3,4,5,6,7,8,9] >> y = x >> >> list([x.pop() for z in xrange(len(x))]) >> >> print x, y # [] [] > > if you don't know how to do things, you don't need to post. > > if you know why this is about the dumbest way to do what you're doing, > and you're posted this on purpose, you really need to grow up. > > He already posted before your post that he made a mistake. You obviously ignored that and invented some argument that he posted with malicious intentions. That better describes most of your thousands of annoying posts. From scott.daniels at acm.org Tue May 30 16:59:59 2006 From: scott.daniels at acm.org (Scott David Daniels) Date: Tue, 30 May 2006 13:59:59 -0700 Subject: iterator? way of generating all possible combinations? In-Reply-To: <1149016823.214610.258930@r44g2000cwb.googlegroups.com> References: <1148705122.317512.294540@i40g2000cwc.googlegroups.com> <1148712466.299743.209350@j73g2000cwa.googlegroups.com> <1149009774.346691.294680@r44g2000cwb.googlegroups.com> <447c8c6e$1@nntp0.pdx.net> <1149016823.214610.258930@r44g2000cwb.googlegroups.com> Message-ID: <447cadf6$1@nntp0.pdx.net> akameswaran at gmail.com wrote: > Scott David Daniels wrote: > >> This works with "iterables" (and produces), rather than "iterators", >> which is vital to the operation. >> >> --Scott David Daniels >> scott.daniels at acm.org > > Sorry, it doesn't. It works with strings. It doesn't work with file, > it doesn't work with iterators I have created. Sorry, "re-iterables". A file re-iterable is: class FileReIterable(object): def __init__(self, file): if isinstance(file, basestring): self.file = open(file, 'rU') else: self.file = file def __iter__(self): self.file.seek(0) return iter(self.file) This works if-and-only-if it is only in use once at a time. If you have multiple simultaneous accesses, you need to do something like: class FileReIterable2(object): def __init__(self, file): if isinstance(file, basestring): self.file = open(file, 'rU') else: self.file = file def __iter__(self): self.file.seek(0) for line in self.file: nextpos = self.file.tell() yield line self.file.seek(nextpos) --Scott David Daniels scott.daniels at acm.org From nobody at 127.0.0.1 Tue May 2 04:50:08 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Tue, 02 May 2006 08:50:08 GMT Subject: Can Python kill a child process that keeps on running? References: <1146532884.872505.154370@i40g2000cwc.googlegroups.com> Message-ID: <43F5g.64465$_S7.31584@newssvr14.news.prodigy.com> Serge Orlov wrote: > I. Myself wrote: >> Suppose it is supposed to run for one minute, but it just keeps going >> and going. Does Python have any way to kill it? > > On linux it's pretty easy to do, just setup alarm signal. On windows > it's not so trivial to the point you cannot do it using python.org > distribution, you will need to poke in low level C API using win32 Can't you use a Timer thread and then send the runaway process a signal? Does Windows not have the equivalent of SIGHUP/SIGTERM/SIGKILL? From phpbird at gmail.com Tue May 23 03:38:46 2006 From: phpbird at gmail.com (Ju Hui) Date: 23 May 2006 00:38:46 -0700 Subject: how to change sys.path? Message-ID: <1148369925.919446.130470@i40g2000cwc.googlegroups.com> is python search module by paths in sys.path? how to change it manuallly? From pemboa at gmail.com Mon May 29 04:47:38 2006 From: pemboa at gmail.com (Arthur Pemberton) Date: Mon, 29 May 2006 03:47:38 -0500 Subject: Any other config parsing modules besides ConfigParser ? Message-ID: <16de708d0605290147p18a392qaf28102c0fbfe08e@mail.gmail.com> Are there any other good config parser modules for python? I am looking for something a bit more versatiles than ConfigParser. Thank you. -- To be updated... From __peter__ at web.de Wed May 10 04:02:23 2006 From: __peter__ at web.de (Peter Otten) Date: Wed, 10 May 2006 10:02:23 +0200 Subject: Redirecting unittest output to a Text widget References: <1147244476.396761.36600@i40g2000cwc.googlegroups.com> Message-ID: MrBlueSky wrote: > Morning! I'm writing my first Python program, so please have patience! > > I'd like to redirect the output from my application's unit tests > ("import unittest") to a Tkinter Text object. I found the magic to > redirect stdout and stderr: > sys.stdout = myTextWindow > sys.stderr = myTextWindow > where myTextWindow inherits from Text and implements write() and > writelines(). > > But the output from my UT still appears in the command window, not the > Text box. My own "print" statements *do* appear in the Text box. > > Can anyone suggest a way forward here? Provide your file-like object to an explicitly instantiated TextTestRunner: tr = unittest.TextTestRunner(stream=myTextWindow, verbosity=2) unittest.main(testRunner=tr) If you want to accept a verbosity option from the commandline you have to subclass unittest.TestProgram and override its runTests() method, unfortunately. Peter From sjmachin at lexicon.net Tue May 30 22:33:52 2006 From: sjmachin at lexicon.net (John Machin) Date: Wed, 31 May 2006 12:33:52 +1000 Subject: TIming In-Reply-To: References: Message-ID: <447d0091$1@news.eftel.com> On 31/05/2006 5:50 AM, WIdgeteye wrote: > > This PYTHON NG blows to high heaven. Whats worse, the answers I got were > most likely from people who know SQUAT about Python scripting. That's why > they gave me such lame [expletive deleted] answers. > > Idiots. Kindly refer back to your post of almost two years ago: http://groups.google.com/group/comp.lang.python/browse_frm/thread/46e15fb12e0f297a/d0e5efc00c1b5359?lnk=st&q=author%3A%09WIdgeteye&rnum=17&hl=en#d0e5efc00c1b5359 """Arg! That was it, now I really feel stupid. """ From akameswaran at gmail.com Fri May 19 16:58:38 2006 From: akameswaran at gmail.com (akameswaran at gmail.com) Date: 19 May 2006 13:58:38 -0700 Subject: python vs perl lines of code In-Reply-To: References: <1148002901.419641.326110@y43g2000cwc.googlegroups.com> Message-ID: <1148072317.975060.42970@j33g2000cwa.googlegroups.com> John Bokma wrote: > "akameswaran at gmail.com" wrote: > > > But if a 1 person, using 1 language, with the same set of tools withing > > a 3 month period implements the same algo without bugs - I'll bet you > > the shorter one was theone written second. > > You might lose that bet very often. I see often that additional checks are > added to algorithms to handle special cases overlooked, or documentation > added because a co-worker had problems with the notation. I am not the one generalizing my statement. Adding the things above, does not count as implementing the same thing. It would implementing a new thing. And what you describe could be just be more bloat - not indicating quality. > I rarely see my scripts shrink, they often grow. The only time they shrink > is when I factor one or more modules out of it :-) > > > The fact that you many ppl will state the shorter line count of > > rewrites is a sign of improving skill > > I disaprove if you want to make it a general rule. I have seen too many > exceptions. Two points here. I have since the beginning stating a HYPOTHESIS - a theory. One which my experince leads me think MIGHT be true. I am much more interested in figuring out a way to validly compare line counts (a distinct challenge in itself) Then we might be able to test the hypothesis. Two -I am not trying to declare an absolute rule. Would I advocate someone think about line count when implementing? No. Do I think there might be some useful analysis of code that includes line count and char count - yes. Is it proven - no. > > So while far from conclusive, the fact that I find my code gets > > shorter the second time - and it is usually done more skillfully, it > > seems there is a correlation of some sort between lines of code and > > quality. > > Yup, and this is exactly what frightens me the whole time in this thread. > People looking for quality rules based on line count. It's wrong. > Please note my original hypothesis was maintainability - not quality! important important distinction - and one I may have muddles myself as I got drawn into the conversation. And what frightens me are people who are so dogmatically convinced becasue of their long 10 years of experience - that they know exactly what does and doesn't matter, and have no intellectual curiosity anymore. There are no objective tests for maintainability that I am aware of. So neither of us is arguing from a position of evidence - just experience. From __peter__ at web.de Fri May 19 13:57:02 2006 From: __peter__ at web.de (Peter Otten) Date: Fri, 19 May 2006 19:57:02 +0200 Subject: how to suppress the "source code echo" output by warnings.warn("x")? References: <1148059191.067419.112040@38g2000cwa.googlegroups.com> Message-ID: funkyj wrote: > I've been googling around trying to find the answer to this question > but all I've managed to turn up is a 2 year old post of someone else > asking the same question (no answer though). > jh> In the following > jh> > jh> import warnings > jh> warnings.warn('change me') > jh> > jh> The warning is issued: > jh> > jh> hunter:~/python/test> python test.py > jh> test.py:3: UserWarning: change me > jh> warnings.warn('change me') > jh> > jh> I want to supress the line echo. Eg, I just want > jh> > jh> hunter:~/python/test> python test.py > jh> test.py:3: UserWarning: change me > jh> > jh> How do I configure warnings to do this? > > Perhaps this can't be done without rewriting the warning module? How about monkey-patching? import warnings def formatwarning(message, category, filename, lineno): return "%s:%s: %s: %s\n" % (filename, lineno, category.__name__, message) warnings.formatwarning = formatwarning warnings.warn("so what") Peter From claird at lairds.us Wed May 31 14:43:55 2006 From: claird at lairds.us (Cameron Laird) Date: Wed, 31 May 2006 18:43:55 +0000 Subject: Dr. Dobb's Python-URL! - weekly Python news and links (May 30) References: <1149028437.100527.240490@j55g2000cwa.googlegroups.com> Message-ID: In article <1149028437.100527.240490 at j55g2000cwa.googlegroups.com>, Fuzzyman wrote: . . . >> Fuzzyman advertises yet another convenience of Movable Python: >> http://groups.google.com/group/comp.lang.python/msg/35baaa3af891c12f . . . My apology, all. I'm still not sure how this happened, but the post to which I *intended* to draw attention was http://groups.google.com/group/comp.lang.python/msg/6a64800985655dce I'm utterly dumbfounded about how my processes could have allowed this mistake. From tim at pollenation.net Sat May 13 01:49:43 2006 From: tim at pollenation.net (Tim Parkin) Date: Sat, 13 May 2006 06:49:43 +0100 Subject: Broken essays on python.org In-Reply-To: References: Message-ID: <44657377.2050500@pollenation.net> Steven Bethard wrote: > Brian Cole wrote: > >>I'm not sure if this is the proper place to post this... >> >>A lot of the essays at http://www.python.org/doc/essays/ have a messed >>up layout in Firefox and IE. > > > The proper place to post this is to follow the "Report website bug" link > at the bottom of the sidebar and post a tracker item. I was feeling > generous today ;) so I did that for you: > http://psf.pollenation.net/cgi-bin/trac.cgi/ticket/333 > > STeVe Thanks for the report.. they're fixed now.. Tim From bencvt at gmail.com Fri May 26 01:23:02 2006 From: bencvt at gmail.com (Ben Cartwright) Date: 25 May 2006 22:23:02 -0700 Subject: genexp surprise (wart?) References: <7xpsi14drb.fsf@ruckus.brouhaha.com> Message-ID: <1148620982.393630.250970@i40g2000cwc.googlegroups.com> Paul Rubin wrote: > I tried to code the Sieve of Erastosthenes with generators: > > def sieve_all(n = 100): > # yield all primes up to n > stream = iter(xrange(2, n)) > while True: > p = stream.next() > yield p > # filter out all multiples of p from stream > stream = (q for q in stream if q%p != 0) > > # print primes up to 100 > print list(sieve_all(100)) > > but it didn't work. I had to replace > > stream = (q for q in stream if q%p != 0) > > with > > def s1(p): > return (q for q in stream if q%p != 0) > stream = s1(p) > > or alternatively > > stream = (lambda p,stream: \ > (q for q in stream if q%p != 0)) (p, stream) You do realize that you're creating a new level of generator nesting with each iteration of the while loop, right? You will quickly hit the maximum recursion limit. Try generating the first 1000 primes. > I had thought that genexps worked like that automatically, i.e. the > stuff inside the genexp was in its own scope. If it's not real > obvious what's happening instead, that's a sign that the current > behavior is a wart. (The problem is that p in my first genexp comes > from the outer scope, and changes as the sieve iterates through the > stream) I don't see how it's a wart. p is accessed (i.e., not set) by the genexp. Consistent with the function scoping rules in... http://www.python.org/doc/faq/programming/#what-are-the-rules-for-local-and-global-variables-in-python ...Python treats p in the genexp as a non-local variable. --Ben From lance at augustmail.com Tue May 16 22:09:10 2006 From: lance at augustmail.com (Lance Hoffmeyer) Date: Tue, 16 May 2006 21:09:10 -0500 Subject: help with a function Message-ID: <446a85c6$0$61170$ae4e5890@news.nationwide.net> Hey all, I'm new to python. I keep getting an error when running this. I'm sure there is an easy fix but I can't figure it out. What am I doing wrong? How do I fix it? def even_odd_round(num): if(round(num,2) + .5 == int(round(num,2)) + 1): if(int(num,0) % 2): #an odd number rounded_num = round(num,2) + .1 else: #an even number rounded_num = round(num,2) - .1 rounded_num = int(rounded_num) return rounded_num even_odd_round(5.5) Traceback (most recent call last): File "", line 1, in ? File "", line 3, in even_odd_round TypeError: int() can't convert non-string with explicit base >>> From nobody at 127.0.0.1 Mon May 22 01:42:02 2006 From: nobody at 127.0.0.1 (Edward Elliott) Date: Mon, 22 May 2006 05:42:02 GMT Subject: The ONE TRUE WAY to use tabs (if you must...) References: <1147863377.329823.162990@j73g2000cwa.googlegroups.com> <1147885294.044080.132570@38g2000cwa.googlegroups.com> <446B6AD1.4080104@mvista.com> <1147899701.004246.294580@g10g2000cwb.googlegroups.com> <1147907634.532463.63730@u72g2000cwu.googlegroups.com> Message-ID: Andy Sy wrote: [snipped 50 lines of previous message] > > Also... remember that the 'ONE TRUE WAY' essentially involves *mixing* > tabs and spaces for indentation with all the objections that that > entails... (although like mentioned above, it should work with Python, > at least in the simple cases i've tried) > > Frankly, the case for tab usage is not that compelling... Quoting usenet posts is like hunting buffalo: only take what you need. http://www.xs4all.nl/~wijnands/nnq/nquote.html#Q2 -- Edward Elliott UC Berkeley School of Law (Boalt Hall) complangpython at eddeye dot net From ramen at lackingtalent.com Tue May 16 18:20:25 2006 From: ramen at lackingtalent.com (Dave Benjamin) Date: Tue, 16 May 2006 15:20:25 -0700 Subject: Time to bundle PythonWin In-Reply-To: <1147467770.161050.321880@i39g2000cwa.googlegroups.com> References: <1hf737g.1oyxbs31plch4nN%aleax@mac.com> <1147467770.161050.321880@i39g2000cwa.googlegroups.com> Message-ID: jUrner at arcor.de wrote: > The ctypes.com package is no longer part of ctypes. > It has been split by Thomas Heller into a separate package comtypes. > See: http://sourceforge.net/projects/comtypes/ > > Still in its childhood but as easy as com can get, I guess, way easier > and better than pythonWin at least. What makes you say it's way easier? PythonWin is pretty darn easy, from my experience. If ctypes is going to be standard, and ctypes.com is pure-Python, I really have no reason left to complain. I do have to rewrite some scripts, but this isn't a big deal. Dave From frank at chagford.com Sat May 27 03:23:40 2006 From: frank at chagford.com (Frank Millman) Date: 27 May 2006 00:23:40 -0700 Subject: Speed up this code? In-Reply-To: <1148656566.089446.159470@y43g2000cwc.googlegroups.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <4476d3ac_2@newspeer2.tds.net> <1148647447.804097.228580@j33g2000cwa.googlegroups.com> <1148649951.816182.134210@g10g2000cwb.googlegroups.com> <1148656566.089446.159470@y43g2000cwc.googlegroups.com> Message-ID: <1148714620.909555.38700@j73g2000cwa.googlegroups.com> Gregory Petrosyan wrote: > # Paul Rubin's version > gregory at home:~$ python -mtimeit "import test2" "test2.primes(1000)" > 100 loops, best of 3: 14.3 msec per loop > > # version from the Cookbook > gregory at home:~$ python -mtimeit "import test1" "test1.primes(1000)" > 1000 loops, best of 3: 528 usec per loop You are quite right, Gregory, my timings are way off. I have figured out my mistake. Paul's function is a generator. Unlike a normal function, when you call a generator function, it does not actually run the entire function, it simply returns a generator object. It only runs when you iterate over it until it is exhausted. I was effectively measuring how long it took to *create* the generator, not iterate over it. Thanks for correcting me. Frank From rkern at enthought.com Tue May 23 19:30:24 2006 From: rkern at enthought.com (Robert Kern) Date: Tue, 23 May 2006 18:30:24 -0500 Subject: determining available space for Float32, for instance In-Reply-To: <519D71619DEB5348BFCBC6AEBC3F9A03014E1146@exchsrv2.cseresearch.cs.washington.edu> References: <519D71619DEB5348BFCBC6AEBC3F9A03014E1146@exchsrv2.cseresearch.cs.washington.edu> Message-ID: David Socha wrote: > I am looking for a way to determine the maxium array size I can allocate > for arrays of Float32 values (or Int32, or Int8, ...) at an arbitrary > point in the program's execution. This is needed because Python cannot > allocate enough memory for all of the data we need to process, so we > need to "chunk" the processing, as described below. > > Python's memory management process makes this more complicated, since > once memory is allocated for Float32, it cannot be used for any other > data type, such as Int32. Just for clarification, you're talking about Numeric arrays here (judging from the names, you still haven't upgraded to numpy), not general Python. Python itself has no notion of Float32 or Int32 or allocating chunks of memory for those two datatypes. > I'd like a solution that includes either > memory that is not yet allocated, or memory that used to be allocated > for that type, but is no longer used. > > We do not want a solution that requires recompiling Python, since we > cannot expect our end users to do that. OTOH, *you* could recompile Python and distribute your Python with your application. We do that at Enthought although for different reasons. However, I don't think it will come to that. > Does anyone know how to do this? With numpy, it's easy enough to change the datatype of an array on-the-fly as long as the sizes match up. In [8]: from numpy import * In [9]: a = ones(10, dtype=float32) In [10]: a Out[10]: array([ 1., 1., 1., 1., 1., 1., 1., 1., 1., 1.], dtype=float32) In [11]: a.dtype = int32 In [12]: a Out[12]: array([1065353216, 1065353216, 1065353216, 1065353216, 1065353216, 1065353216, 1065353216, 1065353216, 1065353216, 1065353216], dtype=int32) However, keeping track of the sizes of your arrays and the size of your datatypes may be a bit much to ask. > The following describes our application context in more detail. > > Our application is UrbanSim (www.urbansim.org), a micro-simulation > application for urban planning. It uses "datasets," where each dataset > may have millions of entities (e.g. households), and each entity (e.g. > household) may have dozens of attributes (e.g. number_of_cars, income, > etc.). Attributes can be any of the standard Python "base" types, > though most attributes are Float32 or Int32 values. Our models often > create a set of 2D arrays with one dimension being agents, and the > second dimention being choices from another dataset. For insances, the > agents may be households that choose a new gridcell to live in. For our > Puget Sound application, there are 1 to 2 million households, and 800K > gridcells. Each attribute of a dataset has such a 2D array. Given that > we may have dozens of attributes, they can eat up a lot of memory, > quickly. [snip] > First, we need to know how many attributes of each type (Float32, Int32, > etc.) will be used by this model. We can do that. > > Second, we need to know how much space is available for an array of a > particular type of values, e.g. for Float32 values. Is there a way to > get this information for Python? numpy arrays (not sure about Numeric) have an .itemsize attribute that tells you how many bytes each element has: In [13]: a.size * a.itemsize Out[13]: 40 numpy (definitely not Numeric) does have a feature called record arrays which will allow you to deal with your agents much more conveniently: http://www.scipy.org/RecordArrays Also, you will certainly want to look at using PyTables to store and access your data. With PyTables you can leave all of your data on disk and access arbitrary parts of it in a relatively clean fashion without doing the fiddly work of swapping chunks of memory from disk and back again: http://www.pytables.org/moin Doing the memory management yourself is tricky and probably not worthwhile given PyTables' existence. -- 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 kkylheku at gmail.com Mon May 8 20:10:07 2006 From: kkylheku at gmail.com (Kaz Kylheku) Date: 8 May 2006 17:10:07 -0700 Subject: Multi-line lambda proposal. Message-ID: <1147133407.746089.291680@i40g2000cwc.googlegroups.com> I've been reading the recent cross-posted flamewar, and read Guido's article where he posits that embedding multi-line lambdas in expressions is an unsolvable puzzle. So for the last 15 minutes I applied myself to this problem and come up with this off-the-wall proposal for you people. Perhaps this idea has been proposed before, I don't know. The solutions I have seen all assume that the lambda must be completely inlined within the expression: the expression is interrupted by the lambda, which is then completely specified (arguments and body) and the expression somehow continues (and this is where syntactic problems occur, giving rise to un-Python-like repugnancies). But suppose that the expression and the multi-line lambda body are reordered? That is to say, the expression is written normally, and the mlambda expressions in it serve as /markers/ indicating that body material follows. This results in the most Python-like solution. Suppose lambda() occurs without a colon a = lambda(x, y), lambda(s, t), lambda(u, w): u + w statement1 statement2 lambda: statement3 statement4 The first two lambdas do not have a colon after them. This means that they have multi-line bodies which follow this statement, and there must be as many bodies as there are lambdas. The third lambda is a regular one-expression lambda, entirely written right there. The bodies are made up of the statements which follow. If there is only one body, it's simply the indented material. If there are two or more lambdas in the expression, additional bodies are required, introduced by lambda: statements, which are at the same indentation level as the expression which contains the lambda markers. Of course, the bodies have their respective lambda parameters in scope. So statement1 and statement2 have access to x and y, and statement3 and statement4 have access to s and t. Problem solved, with no Python repugnancies. The way you can embed indented material in an expression is by not physically embedding it. If you want to be completely anally retentive, you can require that the expression which has lambda bodies after it has to be terminated by a colon: a = lambda(x, y), lambda(s, t), lambda(u, w): u + w: statement1 statement2 lambda: statement3 statement4 If we take out the last two lambdas, this reduces to: a = lambda(x, y): statement1 statement2 Here, the colon terminates the lambda-containing statement. It is not the colon which introduces the body of a one-expression lambda. E.g.: a = lambda(x, y): x + y a = lambda(x, y): return x + y The two are disambiguated by what follows. You get the picture. More examples: lambda defined in a function call argument a = foo(lambda (x, y)): return x + y Confusing? Not if you read it properly. "A lambda function is constructed with arguments x, y and passed to foo, and the result is assigned to a. Oh, and by the way, the body of the lambda is: return x + y." From grante at visi.com Fri May 5 18:45:04 2006 From: grante at visi.com (Grant Edwards) Date: Fri, 05 May 2006 22:45:04 -0000 Subject: NaN handling References: <125hplqmppfeq29@corp.supernews.com> <125neus2mkbgp51@corp.supernews.com> <53112E18-D624-47A2-AEE9-562F59429721@mcmaster.ca> Message-ID: <125nlbgm8l1fi17@corp.supernews.com> On 2006-05-05, Robert Kern wrote: >> Our programming expectations may differ, but an option to catch NaNs as >> an exception is a great idea. > [...] > Pure Python has a similar, but somewhat less flexible method, on UNIX platforms. > > http://docs.python.org/dev/lib/module-fpectl.html For which "Unix" platforms? It's not there under Linux: Python 2.4.2 (#1, Feb 14 2006, 07:55:13) [GCC 3.4.4 (Gentoo 3.4.4-r1, ssp-3.4.4-1.0, pie-8.7.8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import fpectl Traceback (most recent call last): File "", line 1, in ? ImportError: No module named fpectl >>> -- Grant Edwards grante Yow! Do I hear th' at SPINNING of various visi.com WHIRRING, ROUND, and WARM WHIRLOMATICS?! From gene.tani at gmail.com Fri May 19 18:18:47 2006 From: gene.tani at gmail.com (gene tani) Date: 19 May 2006 15:18:47 -0700 Subject: Daily python url archives In-Reply-To: References: Message-ID: <1148077127.433261.205800@u72g2000cwu.googlegroups.com> Bobert wrote: > Hi, > > Do you know by chance if someone has archives from the "daily python url" > feed (http://www.pythonware.com/daily/rss2.xml) ? An archive of the last 3 > or 6 months would be most useful to me. it gets picked up on Swik.net, with a bunch of other stuff: http://swik.net/Python?page=45 From redefined.horizons at gmail.com Tue May 16 12:32:16 2006 From: redefined.horizons at gmail.com (redefined.horizons at gmail.com) Date: 16 May 2006 09:32:16 -0700 Subject: Help System For Python Applications In-Reply-To: <4469fcc4$0$7745$626a54ce@news.free.fr> References: <1147794761.660137.82830@i40g2000cwc.googlegroups.com> <4469fcc4$0$7745$626a54ce@news.free.fr> Message-ID: <1147797136.023279.299860@j73g2000cwa.googlegroups.com> Thanks for the responses. I'll check out the web browser module, and I'll make sure that I release any work ona help system to the community. Scott Huey bruno at modulix wrote: > redefined.horizons at gmail.com wrote: > > I did some searching for this topic, but couldn't find anything. A > > search of this list only turned up an old post from 2002. > > > > I'd like to add a comprehesive help system to my Python Application. By > > "comprehensive" I mean regular "read-like-a-book" help and context > > sensitive help that can be launched from the application. > > > > Is there an existing system in Python that would support this, or would > > I need to start from scratch? > > This depends on the system and UI, so their can be no one-size-fits-all > builtin solution. Hint : look at how other programs using the same > system and UI solved the problem. > > > On a related note, is there a way to fire up Adobe's Acorbat Reader or > > and Web Browser from Python and have the external application open a > > specified PDF or HTML file? (For example, I want to open the file > > "myhelp.pdf" in reader from Python code.) > > os.system() may be a good start. > > HTH > -- > bruno desthuilliers > python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for > p in 'onurb at xiludom.gro'.split('@')])" From conor.robinson at gmail.com Thu May 11 15:48:47 2006 From: conor.robinson at gmail.com (py_genetic) Date: 11 May 2006 12:48:47 -0700 Subject: segmentation fault in scipy? In-Reply-To: References: <1147299683.463548.261310@g10g2000cwb.googlegroups.com> <1147303366.635169.305300@q12g2000cwa.googlegroups.com> <1147318499.764838.243020@u72g2000cwu.googlegroups.com> <1147373294.235202.188220@y43g2000cwc.googlegroups.com> Message-ID: <1147376927.857632.310430@j33g2000cwa.googlegroups.com> >No! matrix objects use matrix multiplication for *. You seem to need elementwise >multiplication. No! when you mult a vector with itself transposed, the diagonal of the resulting matrix is the squares of each error (albeit you do a lot of extra calc), then sum the squares, ie trace(). Its a nifty trick, if you don't have too much data 25000x25000 matrix in mem and youre using matricies ie. batch learning. The actual equation includes multiply by 1/2*(sum of the squares), but mean squared error can be more telling about error and cross entropy is even better, becuase it tells you how well youre predicting the posterior probabilies... From john at castleamber.com Wed May 24 11:14:32 2006 From: john at castleamber.com (John Bokma) Date: 24 May 2006 15:14:32 GMT Subject: John Bokma harassment References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <1148459377.384317.100730@j73g2000cwa.googlegroups.com> <1148463588.566212.36300@i39g2000cwa.googlegroups.com> <44-dnSw6EOzlqOnZRVny3g@bt.com> <1148468447.577714.203450@j73g2000cwa.googlegroups.com> <1148470149.596188.18500@j55g2000cwa.googlegroups.com> <44744962$0$11078$9b4e6d93@newsread4.arcor-online.net> Message-ID: Timo Stamm wrote: > Tim N. van der Leeuw schrieb: >> Perhaps he's not crossing boundaries of free speech, but he's >> repeatedly crossing boundaries on usenet nettiquette, even though >> repeatedly he's being asked not to do so. > > And repeatedly, others have encouraged him because they appreciate his > posts. Of which I am sure a large part are just in for the troll fest that follows. Some probably have also bumped into the netiquette. And instead of using their brains, they can't handle the dent in their ego, and what is not with them, must be shit, so they love stuff like this. Every Usenet kook has a group of pathetic followers and sock puppets. >> but since I've stopped following threads originated by him > > That's all you need to do if you are not interested in his posts. You're mistaken. All you need to do is report it. After some time Xah will either walk in line with the rest of the world, or has found somewhere else to yell. As long as it's not my back garden and not around 4AM, I am ok with it. -- John Bokma Freelance software developer & Experienced Perl programmer: http://castleamber.com/ From aahz at pythoncraft.com Thu May 25 13:45:05 2006 From: aahz at pythoncraft.com (Aahz) Date: 25 May 2006 10:45:05 -0700 Subject: Python Programming Books? References: <1148472688.990208.118420@y43g2000cwc.googlegroups.com> Message-ID: In article , Rony Steelandt wrote: > >1.Python for Dummies > Maruch Stef;Maruch Aahz - Hungry Minds Inc,U.S. - 408 pages - 08 2006 Possibly September if we get behind, but since Neal Norwitz is trying to accelerate the release of 2.5, that's not too likely. (This should be the first 2.5-specific book out.) >2.Programming Python > Lutz Mark - O Reilly - 1256 pages - 07 2006 > >3.Core Python Programming > Chun Wesley J - Peachpit Press - 07 2006 > >5.Python Essential Reference > Beazley David - Sams - 03 2006 > >8.Python Scripting for Computational Science > Langtangen Hans P. - Springer-Verlag Berlin and Heidelberg GmbH & Co. >K - 750 pages - 12 2005 > >9.WxPython in Action > Rappin Noel;Dunn Robin - O Reilly USA - 12 2005 Not sure why you suggested these books, they don't appear to be aimed at beginning programmers. -- Aahz (aahz at pythoncraft.com) <*> http://www.pythoncraft.com/ "I saw `cout' being shifted "Hello world" times to the left and stopped right there." --Steve Gonedes From cgreuter at csclub.uwaterloo.ca Tue May 16 11:30:48 2006 From: cgreuter at csclub.uwaterloo.ca (Chris Reuter) Date: Tue, 16 May 2006 11:30:48 -0400 Subject: spawnv throws exception under Windows XP Message-ID: <87rc4e.anl.ln@ceterneh.blit.ca> I've been trying to start a particular external program from Python using os.spawnv(). This works perfectly under Linux but under Windows, it first runs the program, then throws an OSError exception with the tuple (0, 'Error'): >>> spawnv(P_WAIT, 'c:/mctools/bin/mc', ['mc']) Archelon Tool Driver 3.09 2005/02/16 No input file was given. [correct output snipped] Traceback (most recent call last): File "", line 1, in ? OSError: (0, 'Error') >>> If I understand the error correctly, the zero is the errno value, so it's throwing an exception to warn me that the program worked correctly. Running a trivial program that was compiled with the same compiler (mingw) as "mc" worked fine. This is Python 2.4.3, the standard Windows binaries at python.org, BTW. Has anyone experienced this problem before? Does anyone know what's going on or if there's a workaround? Thanks in advance, --Chris -- Chris Reuter http://www.blit.ca "Fortunately, in my life, I have grown very good at convincing myself that horrified looks are actually looks of affection. This makes dates much easier." --Jeff Vogel, <20020806173519.11834.00002748 at mb-cu.aol.com> From chris.cavalaria at free.fr Wed May 3 05:29:35 2006 From: chris.cavalaria at free.fr (Christophe) Date: Wed, 03 May 2006 11:29:35 +0200 Subject: [Python-3000] bug in modulus? In-Reply-To: References: <1145807918.069455.241510@i40g2000cwc.googlegroups.com> <4450928c$0$21107$626a54ce@news.free.fr> <1f7befae0605021030r458a371fm54f263cfaf9c90cf@mail.gmail.com> Message-ID: <4458785c$0$27053$626a54ce@news.free.fr> Guido van Rossum a ?crit : > This is way above my head. :-) > > The only requirement *I* would like to see is that for floats that > exactly represent ints (or longs for that matter) the result ought of > x%y ought to have the same value as the same operation on the > corresponding ints (except if the result can't be represented exactly > as a float -- I don't know what's best then). Which is exactly the case at hand. As a proposed change, I would say that when the implementation of x%y returns y, then we should return 0 instead, or maybe the biggest possible number that is still < y. That way we would have a result that respects the "x%y < y" rule and still be as good as possible with the reduced float precision. And besides, mathematics say that "0 = y = 2y = 3y [y]" and so there is no problem for returning 0 instead of y :) From phddas at yahoo.com Tue May 9 07:43:50 2006 From: phddas at yahoo.com (Gary Wessle) Date: 09 May 2006 21:43:50 +1000 Subject: installing numpy References: <877j4v5ukc.fsf@localhost.localdomain> Message-ID: <873bfj5sp5.fsf@localhost.localdomain> Christoph Haas writes: > On Tue, May 09, 2006 at 09:03:31PM +1000, Gary Wessle wrote: > > I am trying to install NumPy in my debian/testing linux > > 2.6.15-1-686. > > > > with no numpy for debian/testing, I am left alone, since the > > experimental version available by debian will result in a dependency > > nightmares, > > What about "python-numeric"? Found through "apt-cache search numpy". is no longer maintained, notice my previous post titled "Numerical Python Tutorial errors" From wuwei23 at gmail.com Thu May 4 21:56:57 2006 From: wuwei23 at gmail.com (alex23) Date: 4 May 2006 18:56:57 -0700 Subject: Gettings subdirectories References: Message-ID: <1146794217.021766.184960@y43g2000cwc.googlegroups.com> Florian Lindner wrote: > how can I get all subdirectories of a given directories? If you're not adverse to a solution outside of the standard lib, I highly recommend the 'path' module: >>> from path import path >>> c = path("C:\\") >>> c.dirs() [path(u'C:\\cmdcons'), path(u'C:\\Config.Msi'), path(u'C:\\Logon'), path(u'C:\\Program Files'), path(u'C:\\Python24'), path(u'C:\\RECYCLER'), path(u'C:\\System Volume Information'), path(u'C:\\WINDOWS'), path(u'C:\\WINSRC')] http://www.jorendorff.com/articles/python/path/ Hope this helps. - alex23 From oliphant.travis at ieee.org Fri May 26 22:29:26 2006 From: oliphant.travis at ieee.org (Travis E. Oliphant) Date: Fri, 26 May 2006 20:29:26 -0600 Subject: Looking for triangulator/interpolator In-Reply-To: <127f313dbhl7gf4@corp.supernews.com> References: <127f313dbhl7gf4@corp.supernews.com> Message-ID: Grant Edwards wrote: > I need to interpolate an irregularly spaced set of sampled > points: Given a set of x,y,z points, I need to interpolate z > values for a much finer x,y grid. How many x,y,z points do you have? Did you try the fitpack function bisplrep in scipy? It can work well as long as you don't have too many starting points. Here is an example of how to use it from numpy import rand, exp, ogrid from scipy import interpolate x = 2*rand(20)-1 y = 2*rand(20)-1 z = (x+y)*exp(-6.0*(x*x+y*y)) tck = interpolate.bisplrep(x,y,z,s=0,xb=-1,xe=1,yb=-1,ye=1) xnew = r_[-1:1:70j] ynew = r_[-1:1:70j] znew = interpolate.bisplev(xnew,ynew,tck) There is a buglet that is fixed in SVN scipy that means you need to enter xb, xe, yb, and ye manually. -Travis From duane at franz.com Fri May 12 18:22:13 2006 From: duane at franz.com (Duane Rettig) Date: Fri, 12 May 2006 15:22:13 -0700 Subject: A critic of Guido's blog on Python's lambda References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> <1hew1wi.se8e521eylrb2N%aleaxit@yahoo.com> <87y7xf8swl.fsf@rpi.edu> <445c794e$0$31647$e4fe514c@news.xs4all.nl> <1hewvsx.11x9f301gbjrhqN%aleaxit@yahoo.com> <1hex8sg.1na8hsn1mkphy3N%aleaxit@yahoo.com> <1147160240.954015.181480@j73g2000cwa.googlegroups.com> <%F38g.16$RR.4@fe10.lga> <1147244842.745710.250560@j73g2000cwa.googlegroups.com> <1147277869.710723.43550@i39g2000cwa.googlegroups.com> <1147330449.102694.317200@i40g2000cwc.googlegroups.com> Message-ID: Alexander Schmolck writes: > Duane Rettig writes: > >> Alexander Schmolck writes: >> >> > Ken Tilton writes: >> > >> >> In Common Lisp we would have: >> >> >> >> (defvar *x*) ;; makes it special >> >> (setf *x* 1) >> >> (print *x*) ;;-> 1 >> >> (let ((*x* 2)) >> >> (print *x*)) ;; -> 2 >> >> (print *x*) ;; -> 1 >> > >> > You seem to think that conflating special variable binding and lexical >> > variable binding is a feature and not a bug. What's your rationale? >> >> A bug is a non-conformance to spec. > > There is a world beyond specs, you know. If copies of allegro CL accidently > sent out death-threats to the US president on a weekly basis, because someone > at franz accidently or purposefully left in some pranky debugging code the > fact that this behaviour would likely neither violate the ansi spec nor any > other specs that ACL officially purports to adhere to wouldn't make it any > less of a bug (or help to pacify your customers). It wouldn't be a bug in Allegro CL, because it would never happen in an Allegro CL that hasn't been enhanced with some kind of program. And although that program itself could have a bug whereby such a threat were accidental, I would tend not to call it accidental, I would tend to call it expicit, and thus not a bug but an intended consequence of such explicit programming. My reason for responding to you in the first place was due to your poor use of the often misused term "bug". You could have used many other words or phrases to describe the situation, and I would have left any of those alone. For example: >> Kenny's statement was specifically about Common Lisp > > No Kenny's statement was about contrasting the way something is done in python > and the way something is done in common lisp (with the implication that the > latter is preferable). Of course the way something is done in common lisp is > almost tautologically in closer agreement with the ansi common lisp spec than > the way it is done in python, so agreement with the clhs is not a useful > criterion when talking about design features and misfeatures when contrasting > languages. > > I thought it would have been pretty obvious that I was talking about language > design features and language design misfeatures (Indeed the infamously post > hoc, "It's a feature, not a bug" I was obviously alluding too doesn't make > much sense in a world were everything is tightly specified, because in it > nothing is post-hoc). Whether it is preferable is a matter of opinion, and whether Kenny meant it to infer preferability (I suspect so) or not has nothing to due with whether it is a bug. Instead, you should call it a "design misfeature", which would set the stage for a more cogent argumentation on the point, rather than on the hyperbole. By the way, if you do call it a design misfeature, I would be arguing against you, but that is another conversation. >>, which has a spec. > > Bah -- so does fortran. But scheme also has operational semantics. > >> Now, what was your rationale for it _being_ a bug? > > I just don't think the way special variable binding (or variable binding in > general[1]) is handled in common lisp is particularly well designed or > elegant. Then call it "misdesigned" or "inelegant". > Special variables and lexical variables have different semantics and using > convention and abusing[2] the declaration mechanism to differentiate between > special and lexical variables doesn't strike me as a great idea. Then call it a "bad idea". > I can certainly think of problems that can occur because of it (E.g. ignoring > or messing up a special declaration somewhere; setf on a non-declared variable > anyone? There are also inconsistent conventions for naming (local) special > variables within the community (I've seen %x%, *x* and x)). Then call it "not fully standardized or normative". > Thus I don't see having to use syntactically different binding and assignment > forms for special and lexical variables as inherently inferior. Then call it "inherently inferior". > But I might be wrong -- which is why was asking for the rationale of Kenny's > preference. But you _didn't_ ask him what rationale he had for his _preference_, you asked him his rationale for considering it not a _bug_. > I'd be even more interested in what you think (seriously; should > you consider it a design feature (for reasons other than backwards > compatiblity constraints), I'm pretty sure you would also give a justification > that would merrit consideration). Well, OK, let's change the conversation away from "bug"-ness and toward any of the other negatives we discussed above. I actually doubt that I can provide a justification in a small space without first understanding who you are and from what background you are coming, so let me turn it around and ask you instead to knock down a straw-man: You seem to be saying that pure lexical transparency is always preferable to statefulness (e.g. context). Can we make that leap? If not, set me straight. If so, tell me: how do we programmatically model those situations in life which are inherently contextual in nature, where you might get a small piece of information and must make sense of it by drawing on information that is _not_ given in that information, but is (globally, if you will) "just known" by you? How about conversations in English? And, by the way, how do you really know I'm writing to you in English, and not some coded language that means something entirely different? -- Duane Rettig duane at franz.com Franz Inc. http://www.franz.com/ 555 12th St., Suite 1450 http://www.555citycenter.com/ Oakland, Ca. 94607 Phone: (510) 452-2000; Fax: (510) 452-0182 From vmalloc at gmail.com Tue May 9 08:28:25 2006 From: vmalloc at gmail.com (Rotem) Date: 9 May 2006 05:28:25 -0700 Subject: import in execv after fork In-Reply-To: <1147176928.836116.17000@i40g2000cwc.googlegroups.com> References: <1147176928.836116.17000@i40g2000cwc.googlegroups.com> Message-ID: <1147177705.061658.87570@j33g2000cwa.googlegroups.com> Another workaround could be re-assigning a new lock to import_lock (such a thing is done with the global interpreter lock) at PyOS_AfterFork or pthread_atfork. From ptmcg at austin.rr._bogus_.com Fri May 19 12:28:00 2006 From: ptmcg at austin.rr._bogus_.com (Paul McGuire) Date: Fri, 19 May 2006 16:28:00 GMT Subject: who can give me the detailed introduction of re modle? References: <1148017824.774335.321590@j33g2000cwa.googlegroups.com> Message-ID: "softwindow" wrote in message news:1148017824.774335.321590 at j33g2000cwa.googlegroups.com... > the re module is too large and difficult to study > > i need a detaild introduction. > Sorry, but your post just sounds too much like it's in the "I'm too lazy to figure this out for myself, just spoon-feed me the answer" category. How do you know you need the re module? Is there a particular problem you are trying to solve? Have you made any effort on your own before just posting this open-ended request? How did it go? Is it possible that your problem could be solved with something less exotic, perhaps some combination of str.find() and str.split()? It may be simpler to wield a rapier string function than to haul out the chainsaw of re's. Yes, re's are mysterious and cryptic, and there is a whole cottage industry of books and websites out there to help you compose your own special re string, filled with '?'s, '.'s, '+'s, '*'s, and many, many '\'s. Are you familiar with Google? Try searching for, um, "Python re module" or "Python regular expressions". You are bound to find many pages of introductory, intermediate, expert, exemplary, and diabolical material. -- Paul From aomighty at gmail.com Thu May 25 22:33:57 2006 From: aomighty at gmail.com (aomighty at gmail.com) Date: 25 May 2006 19:33:57 -0700 Subject: Speed up this code? In-Reply-To: <7x8xopv95v.fsf@ruckus.brouhaha.com> References: <1148605930.830498.4990@j55g2000cwa.googlegroups.com> <7x8xopv95v.fsf@ruckus.brouhaha.com> Message-ID: <1148610837.762123.97260@g10g2000cwb.googlegroups.com> I got it working using difference() and sets, thanks all! 100,000 takes about 3 times the time of 10,000, which is what my math buddies told me I should be getting, rather than an exponential increase :). Thanks, all! From benji at benjiyork.com Tue May 2 15:47:22 2006 From: benji at benjiyork.com (Benji York) Date: Tue, 02 May 2006 15:47:22 -0400 Subject: Python & SSL In-Reply-To: References: Message-ID: <4457B74A.2000208@benjiyork.com> James Stroud wrote: > I have been trying to make an https client with python You probably don't want to use the standard library for HTTPS; here's a quote from the socket module docs about SSL: Warning: This does not do any certificate verification! I'd recommend M2Crypto instead: http://wiki.osafoundation.org/bin/view/Projects/MeTooCrypto -- Benji York From bugs at almad.net Thu May 11 15:24:19 2006 From: bugs at almad.net (Almad) Date: 11 May 2006 12:24:19 -0700 Subject: FTP filename escaping Message-ID: <1147375459.332757.212570@u72g2000cwu.googlegroups.com> Hello, I feel ashamed, but my google-fu betrayed me again. How do I escape filenames when using ftplib? I'd like to download it and upload on ftp again... toDown = self.ftpMaster.nlst() for fileDown in toDown: f = tmpfile() # download self.ftpMaster.retrbinary(''.join(['RETR ', fileDown]), f.write) f.seek(0) self.ftpMirror.storbinary(''.join(["STOR ", fileDown]), f, 1024) f.close() Problem is when fileDown contains special characters / spaces and so on. I hoped for some ftplib.quote(), urllib.quote() or quote_plus() is not functional either. Is there such a function in stdlib or do I have to read through specification and write it? Thank You, Almad From phddas at yahoo.com Tue May 2 06:42:54 2006 From: phddas at yahoo.com (Gary Wessle) Date: 02 May 2006 20:42:54 +1000 Subject: string.find first before location References: <87hd49m0xc.fsf@localhost.localdomain> Message-ID: <87zmi0emhd.fsf@localhost.localdomain> Peter Otten <__peter__ at web.de> writes: > Gary Wessle wrote: > > > I have a string like this > > > > text = "abc abc and Here and there" > > I want to grab the first "abc" before "Here" > > > > import string > > string.find(text, "Here") # > > > > I am having a problem with the next step. > > These days str methods are preferred over the string module's functions. > > >>> text = "abc abc and Here and there" > >>> here_pos = text.find("Here") > >>> text.rfind("abc", 0, here_pos) > 4 > > Peter and what about when python 3.0 is released and those depreciated functions like find and rfind are not supported. is there another solution which is more permanent? From bugs at almad.net Wed May 10 11:00:32 2006 From: bugs at almad.net (Almad) Date: 10 May 2006 08:00:32 -0700 Subject: PIL thumbnails unreasonably large In-Reply-To: <1147272829.719796.150680@y43g2000cwc.googlegroups.com> References: <1147272829.719796.150680@y43g2000cwc.googlegroups.com> Message-ID: <1147273232.709886.247200@i39g2000cwa.googlegroups.com> Forgot to add: I'm using PIL 1.1.5 with Python 2.4, expected on both Gentoo Linux and Windows XP. From sll_noSpamlicious_z_XXX_m at cc.usu.edu Sat May 6 16:10:19 2006 From: sll_noSpamlicious_z_XXX_m at cc.usu.edu (Luc The Perverse) Date: Sat, 6 May 2006 14:10:19 -0600 Subject: [Reported] (was Re: A critic of Guido's blog on Python's lambda) References: <1146875186.163084.93350@e56g2000cwe.googlegroups.com> Message-ID: "John Bokma" wrote in message news:Xns97BB7216CA9Acastleamber at 130.133.1.4... > Reported for excessive crossposting. Did u report yourself? -- LTP :) From telesphore4 at gmail.com Mon May 22 14:19:32 2006 From: telesphore4 at gmail.com (telesphore4 at gmail.com) Date: 22 May 2006 11:19:32 -0700 Subject: Using metaclasses to inherit class variables References: <1148073009.059300.290760@i40g2000cwc.googlegroups.com> <1148315581.385405.204750@i40g2000cwc.googlegroups.com> Message-ID: <1148321972.467689.148900@j73g2000cwa.googlegroups.com> Oops! This isn't working. As the sequence I'm trying for is.... >>> def set_classvars(**kwargs): ... def __metaclass__(name, bases, classdict): ... for name, value in kwargs.iteritems(): ... if name not in classdict: ... classdict[name] = value ... return type(name, bases, classdict) ... return __metaclass__ ... >>> class C(object): ... __metaclass__ = set_classvars(name='foo', desc='bar', list=[]) ... name = 'not foo' ... >>> C.name, C.desc, C.list ('not foo', 'bar', []) >>> class D(C): ... pass #<<<<<< Use Super's metaclass ... >>> D.name, D.desc, D.list, D.list is C.list ('not foo', 'bar', [], True) So... I just changed my stuff to be: import copy class ClassVars(type): classVars = {} def __init__(cls, name, bases, dict): for name, value in type(cls).classVars.iteritems(): if name not in dict: setattr(cls, name, copy.copy(value)) def are(**kwargs): return type('', (ClassVars,), {'classVars':kwargs}) Altho I'd like to see what you come up with too... if you persue this From http Fri May 19 14:24:35 2006 From: http (Paul Rubin) Date: 19 May 2006 11:24:35 -0700 Subject: newb: comapring two strings References: <1147992792.038103.151360@j55g2000cwa.googlegroups.com> <4d4chmF185ohoU1@uni-berlin.de> <1148038726.023455.145900@j73g2000cwa.googlegroups.com> <1148062114.800989.293270@j73g2000cwa.googlegroups.com> <1148062688.445501.30260@y43g2000cwc.googlegroups.com> Message-ID: <7xhd3lvpng.fsf@ruckus.brouhaha.com> bearophileHUGS at lycos.com writes: > > I have suggested C because if the words are all of the same length then > > you have 30000^2 = 90 000 000 000 pairs to test. > > Sorry, you have (n*(n-1))/2 pairs to test (~ 45 000 000 000). Still terrible. Use a better algorithm! From skip at pobox.com Fri May 19 10:05:10 2006 From: skip at pobox.com (skip at pobox.com) Date: Fri, 19 May 2006 09:05:10 -0500 Subject: how to read a list from python in C? In-Reply-To: <446D96C0.2010100@126.com> References: <446D96C0.2010100@126.com> Message-ID: <17517.53398.852197.414721@montanaro.dyndns.org> Lialie> I am writing a C extension with .Net. Now I have a list of Lialie> points, like [(0.0, 0.0), (2.0, 3.0), (random x, random y)....]. Lialie> Is there a better way to translate it to an array than doing it Lialie> one by one? Are you passing a list as an argument to one of the functions in your C extension module? If so, yup, you get the list argument and march through it element-by-element, then march through those tuples. For more detail on argument handling in C, read here: http://www.python.org/doc/api/arg-parsing.html Skip From me+python at modelnine.org Wed May 17 11:56:58 2006 From: me+python at modelnine.org (Heiko Wundram) Date: Wed, 17 May 2006 17:56:58 +0200 Subject: Pyparsing: Grammar Suggestion In-Reply-To: <200605171753.17467.me+python@modelnine.org> References: <3d00e6dc0605170824q6abe919dq49e72970baf46244@mail.gmail.com> <200605171753.17467.me+python@modelnine.org> Message-ID: <200605171756.58245.me+python@modelnine.org> Am Mittwoch 17 Mai 2006 17:53 schrieb Heiko Wundram: > If you're not limited to PyParsing, pyrr.ltk/ptk might be appropriate for > you here (if you're used to bison/flex). The following file implements a > small sample lexer/parser which does exactly what you need. pyrr.ltk (the > lexing toolkit) is stable, but pyrr.ptk isn't yet, but it's nevertheless > available under: > > http://hg.modelnine.org/hg/pyrr I know answering to oneself is bad, but forget that link. Use: http://dev.modelnine.org/hg/pyrr instead (I get mixed up between the name I use for pushing my trees and my development pages)... --- Heiko. From wahab at chemie.uni-halle.de Thu May 11 17:08:31 2006 From: wahab at chemie.uni-halle.de (Mirco Wahab) Date: Thu, 11 May 2006 23:08:31 +0200 Subject: reusing parts of a string in RE matches? In-Reply-To: References: <1147283334.610613.220770@j33g2000cwa.googlegroups.com> <1147287162.914661.237370@i39g2000cwa.googlegroups.com> <1147291197.423570.242440@g10g2000cwb.googlegroups.com> Message-ID: Hi John > Ah, I see the difference. In Python you get a list of > tuples, so there seems to be a little extra work to do > to get the number out. Dohh, after two cups of coffee ans several bars of chocolate I eventually mad(e) it ;-) In Python, you have to deconstruct the 2D-lists (here: long list of short lists [a,2] ...) by 'slicing the slice': char,num = list[:][:] in a loop and using the apropriate element then: import re t = 'a1a2a3Aa4a35a6b7b8c9c'; r = r'(\w)(?=(.)\1)' l = re.findall(r, t) for a,b in l : print b (l sould implicitly be decoded sequentially as l[:][->a : ->b] in the loop context.) In the moment, I find this syntax somehow hard to remember, but my mind should change if I'm adopted more to this in the end ;-) Regards, M. From vedranf at riteh.hr Tue May 2 11:14:21 2006 From: vedranf at riteh.hr (=?UTF-8?B?VmVkcmFuIEZ1cmHEjQ==?=) Date: Tue, 02 May 2006 17:14:21 +0200 Subject: Strange result with math.atan2() In-Reply-To: <1146581113.211223.244580@v46g2000cwv.googlegroups.com> References: <44575f1d$0$16971$5a62ac22@per-qv1-newsreader-01.iinet.net.au> <1146581113.211223.244580@v46g2000cwv.googlegroups.com> Message-ID: Serge Orlov wrote: >> So, you can convert -0 to 0, but you must multiply the result with sign of >> y, which is '-' (minus). > > But you miss the fact that 0 is an *integer*, not a float, and -0 > doesn't exist. Yes, you are right, I completely missed that 0 is integer in python, and I need a float. Regards, Vedran Fura? From OlafMeding at gmail.com Thu May 4 10:04:21 2006 From: OlafMeding at gmail.com (OlafMeding at gmail.com) Date: 4 May 2006 07:04:21 -0700 Subject: Because of multithreading semantics, this is not reliable. In-Reply-To: <445a014a$0$18281$636a55ce@news.free.fr> References: <1146686949.458427.83260@y43g2000cwc.googlegroups.com> <1146691613.911363.242620@e56g2000cwe.googlegroups.com> <4459c03b$0$2633$636a55ce@news.free.fr> <4459f1dd$1_2@newspeer2.tds.net> <445a014a$0$18281$636a55ce@news.free.fr> Message-ID: <1146751461.643033.119110@j33g2000cwa.googlegroups.com> Christophe > Same reason that there is a warning in the "os.access" manual I understand the if file exists open it code. I looked at the os.access documentation and see no "warning" or "not reliable" wording there. 6.1.4 Files and Directories access(path, mode) Olaf From bignose+hates-spam at benfinney.id.au Fri May 26 00:08:16 2006 From: bignose+hates-spam at benfinney.id.au (Ben Finney) Date: Fri, 26 May 2006 14:08:16 +1000 Subject: Creating instances of untrusted new-style classes References: <1148605569.607231.41640@j73g2000cwa.googlegroups.com> Message-ID: <87hd3d1l8v.fsf@benfinney.id.au> "Devan L" writes: > Is there any safe way to create an instance of an untrusted class Why are you instantiating classes you don't trust? > without consulting the class in any way? If you don't "consult the class", how can the instance be created properly? -- \ "It's easy to play any musical instrument: all you have to do | `\ is touch the right key at the right time and the instrument | _o__) will play itself." -- Johann Sebastian Bach | Ben Finney From jdsalt_AT_gotadsl.co.uk Tue May 23 09:58:12 2006 From: jdsalt_AT_gotadsl.co.uk (John D Salt) Date: Tue, 23 May 2006 08:58:12 -0500 Subject: Software Needs Philosophers References: <1148202931.643116.41150@j33g2000cwa.googlegroups.com> <4dbartF19cb9rU1@uni-berlin.de> Message-ID: wrote in news:4dbartF19cb9rU1 at uni-berlin.de: [Snips] > Wrong. We live in a paradise of ideas and possibilities well beyond the > wildest dreams of only 20 years ago. What exciting new ideas exist in software that are both important and cannot be traced back to 1986 or earlier? I'd like to believe that there are some, but I can't think of any at the moment. All the best, John. From fccoelho at gmail.com Sun May 14 07:17:25 2006 From: fccoelho at gmail.com (Flavio) Date: 14 May 2006 04:17:25 -0700 Subject: cx_freeze and matplotlib In-Reply-To: <1147575056.469276.156200@y43g2000cwc.googlegroups.com> References: <1147561396.641012.139940@y43g2000cwc.googlegroups.com> <1147575056.469276.156200@y43g2000cwc.googlegroups.com> Message-ID: <1147605445.671406.105140@g10g2000cwb.googlegroups.com> My application needs needs matplotlib. So cx_Freeze bundles it in. But it only bundles matplotlib python modules, not its data files! In the original machine I believe that the frozen executable is somehow finding those datafiles in their original locations, which is not desirable, ecause the bundle should be completely independent of external files. From vinu at hcl.in Fri May 12 04:06:21 2006 From: vinu at hcl.in (vinu) Date: Fri, 12 May 2006 13:36:21 +0530 Subject: New blog Message-ID: <446441FD.6070507@hcl.in> Hi all, http://pyadmin.blogspot.com/ THis is my blog and This is related to python utilities for system and network administration.plz comment on this regards Vineesh Kumar -------------- next part -------------- A non-text attachment was scrubbed... Name: vinu.vcf Type: text/x-vcard Size: 170 bytes Desc: not available URL: From bdesth.quelquechose at free.quelquepart.fr Thu May 4 18:11:35 2006 From: bdesth.quelquechose at free.quelquepart.fr (Bruno Desthuilliers) Date: Fri, 05 May 2006 00:11:35 +0200 Subject: Possible constant assignment operators ":=" and "::=" for Python In-Reply-To: <1146642072.934453.268870@e56g2000cwe.googlegroups.com> References: <1146251333.817862.94570@v46g2000cwv.googlegroups.com> <1146634135.469447.54670@j73g2000cwa.googlegroups.com> <1146642072.934453.268870@e56g2000cwe.googlegroups.com> Message-ID: <445a4d57$0$13242$626a54ce@news.free.fr> tsaar2003 at yahoo.com a ?crit : > Yes, I know that "constant" A will also be modified as the b[0] points > to A. Obviously the [] should be marked as immutable, as A is declared > to be constant thus immutable. If somebody tries to modify this > immutable object an error would occur. > > When I further thought about this problem with constant objects (and > values), I run into this scenario: What if I want to use a constant > object/value as a template (or predefined value/class) for a variable: > > constant A = ['1'] # let's declare A as immutable constant value/object > b = A # let's assign b some default value > b.append('2') # and let's play with b, but I wouldn't want to change A def A(): return ['1'] b = A() b.append('2') From me at privacy.net Sun May 21 08:52:53 2006 From: me at privacy.net (Dan Sommers) Date: Sun, 21 May 2006 08:52:53 -0400 Subject: dict!ident as equivalent of dict["ident"] References: Message-ID: On Sun, 21 May 2006 16:19:29 +0400, Alexander Kozlovsky wrote: > How about small syntactic sugar: > foo!bar!baz.x = y > With this suggestion, mapping!identifier > becomes fully equivalent to mapping["identifier"] Take a look at the "Bunch" recipe in the Python Cookbook: http://aspn.activestate.com/ASPN/Cookbook/Python/Recipe/52308 Regards, Dan -- Dan Sommers "I wish people would die in alphabetical order." -- My wife, the genealogist From deets at nospam.web.de Fri May 5 05:32:11 2006 From: deets at nospam.web.de (Diez B. Roggisch) Date: Fri, 05 May 2006 11:32:11 +0200 Subject: Tuple assignment and generators? References: <0KydnWcEJaVCtcfZnZ2dnUVZ_tmdnZ2d@comcast.com> <1vSdnRC7JP5K08fZRVn-rw@comcast.com> <1146803131.996632.207770@v46g2000cwv.googlegroups.com> <1146813639.825116.21780@g10g2000cwb.googlegroups.com> <1146814457.388702.263120@i39g2000cwa.googlegroups.com> <1146819662.519528.224530@e56g2000cwe.googlegroups.com> Message-ID: <4c0ke7F13i82oU1@uni-berlin.de> vdrab wrote: >> No. Why should you ever care about whether two integers representing >> values are the same object? Your tests should be with `==`, not `is`. > > Given this though, what other such beauties are lurking in the > interpreter, under the name of 'implementation accidents'? One of the > things that drew me to python is the claimed consistency and > orthogonality of both language and implementation, not sacrificing > clarity for performance, minimizing ad-hoc design hacks and weird > gotcha's, etc... > In fact, I think my code contains things like "if len(arg) is 0:" and > so on, and I feel I should be able to do so given the way python treats > (claims to treat?) constant objects, even if I don't care whether the > values actually represent the same object. Python doesn't claim that 0 is 0 == True. You are abusing the "is" operator. The only (or at least 99%) occasions I use "is" are if foo is None: ... as None is guaranteed to be a singleton object. The thing you observe as accident is that sometimes "0 is 0" is true just because of an optimization of number objects allocation. Such things happen in the "real" world - other examples are string-interning in e.g. the JVM (and I bet they have a similar scheme to boxed number object allocation as python has). Diez From no.offline.contact.please at nospam.com Sun May 21 18:43:49 2006 From: no.offline.contact.please at nospam.com (Rhino) Date: Sun, 21 May 2006 18:43:49 -0400 Subject: dynamic drawing in web page References: <1148245752.728480.238540@u72g2000cwu.googlegroups.com> Message-ID: <526cg.163$ho5.22351@news20.bellglobal.com> "barbaros" wrote in message news:1148245752.728480.238540 at u72g2000cwu.googlegroups.com... > Hello everybody, > > I need to put some dynamic drawings on my web page. More precisely, I > need to draw a number of geometric figures (circles, rectangles) which > evolve into a graphics windows according to some law (a little bit like > the solar system). I need also to have several fields aside the window, > where the visitor can change values for several significant parameters > (like the mass of each body). > > Could you please suggest a solution (preferably not involving hundreds > of lines of code) ? The computations should be performed on the client > machine. > Basically, it sounds like you're talking about writing an applet. An applet is a Java program that sits on a web page. You can write an applet so that it draws circles, arcs, etc. and you can give the user the ability to interact with an applet. If you look at the sample applets that Sun has written for Java - http://java.sun.com/applets/jdk/1.4/index.html - you'll see that a few applets are doing at least some of what you want to do. Each example includes source code so that you can get a rough idea of how much code is necessary to do what you want. In your case, you might want a single applet with several distinct canvases for drawing or a separate applet for each canvas; either way could probably work. -- Rhino From sybrenUSE at YOURthirdtower.com.imagination Mon May 22 15:25:00 2006 From: sybrenUSE at YOURthirdtower.com.imagination (Sybren Stuvel) Date: Mon, 22 May 2006 21:25:00 +0200 Subject: Python - Web Display Technology References: <1147935093.950609.111150@j55g2000cwa.googlegroups.com> <446c39b2$0$8047$636a55ce@news.free.fr> <20060519132452.7DF8.2.NOFFLE@dieschf.news.arcor.de> <1148193333.987704.16600@j33g2000cwa.googlegroups.com> <1148223307.073050.33710@y43g2000cwc.googlegroups.com> <1148251070.320923.65710@38g2000cwa.googlegroups.com> <1148310730.537959.265430@j55g2000cwa.googlegroups.com> <1148313166.202814.55680@j73g2000cwa.googlegroups.com> Message-ID: SamFeltus enlightened us with: > 1. Loss of back button > Isn't this really a myth? No, it isn't a myth. Pressing the back button is the action second most performed in a browser, clicking a link being the first. People want to go back from where they came. > A page with a time dimension, be it Flash, HTML/JS or whatever, > breaks the back button. No it doesn't. If something is interactive and lets the user go somewhere by performing an action, they expect to be able to go back using the back button. People want to be in control over their computer, their time, and their attention. If they aren't, they go away. > Fonts are problematic in Flash, this is a weakness of Flash. > Scaling Fonts is even more problematic, but, fonts are an issue in > any precise design on the web. Websites shouldn't be designed to be pixel-perfect. They should be designed to scale and stretch, and to accommodate a user's wishes. If you want something exactly like you envision it, go direct a movie. > I wouldn't argue Flash is better for text sites at the moment, due > to Search Engine shortcomings. And due to being incompatible with the browser's own search functionality. > As for the blind issue,that makes no sense to me. Is the suggestion > that we should give up using images in web sites since some people > can't see them. Might as well throw out the use of the img tag > while we are at it? Go and read some usability studies, and get acquainted with the HTML standards, before commenting on them. The 'alt' attribute is mandatory, and should describe the image for those who can only interpret text. Sybren -- The problem with the world is stupidity. Not saying there should be a capital punishment for stupidity, but why don't we just take the safety labels off of everything and let the problem solve itself? Frank Zappa From fredrik at pythonware.com Tue May 2 03:27:58 2006 From: fredrik at pythonware.com (Fredrik Lundh) Date: Tue, 2 May 2006 09:27:58 +0200 Subject: Using elementtree: replacing nodes References: <1146529455.411024.83020@j73g2000cwa.googlegroups.com> Message-ID: Andr? wrote: > I've started using elementtree and don't understand how to use it to > manipulate and replace nodes. I know how to do this using a simple, > but inefficient parser I wrote, but I'd rather learn to use a better > tool - especially as it is to be added to the standard library. > Now, I would like to find all
     tags of the "text" class and
    
        for pre in elem.getiterator("pre"):
    
    or
    
        for pre in elem.findall(".//pre"):
    
    > 1. change the class value
    
        pre.set("class", "value")
    
    > 2. append another node (